@tinkerlandai/indiana-sdk 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/README.md +11 -10
  3. package/README.zh-CN.md +16 -11
  4. package/dist/{ai-usage-BsrSG955.d.ts → ai-usage-Bigjb8MS.d.ts} +468 -274
  5. package/dist/chunk-2A6UYUFA.js +1 -0
  6. package/dist/chunk-3BQFJANQ.js +1 -0
  7. package/dist/chunk-3ENVRJE6.js +350 -0
  8. package/dist/chunk-A3N4ZZTM.js +7 -0
  9. package/dist/chunk-AE4CUTUE.js +1 -0
  10. package/dist/chunk-CXYOZSOF.js +1 -0
  11. package/dist/{chunk-4AWSZWZD.js → chunk-G2R56FKU.js} +1 -1
  12. package/dist/{chunk-6MO6Y24B.js → chunk-OVMNCZYC.js} +1 -1
  13. package/dist/{configuration-sync-Bvd956GL.d.ts → configuration-sync-VFbY1pCN.d.ts} +34 -35
  14. package/dist/content-K2HCZVC2.js +1 -0
  15. package/dist/{customer-page-B4LkIr5q.d.ts → customer-page-BrCZxcaQ.d.ts} +279 -6
  16. package/dist/funnel-runtime-host-HNZ47TZW.js +1 -0
  17. package/dist/{funnel-runtime-start-ChVYbLzV.d.ts → funnel-runtime-start-DKcTCRrd.d.ts} +1646 -1913
  18. package/dist/index.d.ts +13975 -13679
  19. package/dist/index.js +1 -1
  20. package/dist/native-shell.js +1 -1
  21. package/dist/openrouter.d.ts +3 -2
  22. package/dist/openrouter.js +1 -1
  23. package/dist/page.d.ts +9 -9
  24. package/dist/paywall-PD62B2AY.js +1 -0
  25. package/dist/popup.d.ts +3 -271
  26. package/dist/popup.js +1 -350
  27. package/dist/react-native.d.ts +8 -8
  28. package/dist/react-native.js +1 -1
  29. package/dist/{screen-iFngkxaL.d.ts → screen-BazUOjwM.d.ts} +168 -165
  30. package/dist/server.d.ts +5 -5
  31. package/dist/server.js +1 -1
  32. package/dist/src-4MRSESVS.js +1 -0
  33. package/dist/visual.d.ts +5 -2
  34. package/dist/visual.js +2 -2
  35. package/package.json +1 -7
  36. package/dist/chunk-3SONNXFG.js +0 -1
  37. package/dist/chunk-467Z5ISI.js +0 -11
  38. package/dist/chunk-4K25DELJ.js +0 -1
  39. package/dist/chunk-HD74AAFS.js +0 -1
  40. package/dist/chunk-J4RHVU3W.js +0 -1
  41. package/dist/chunk-NOFNOHUI.js +0 -1
  42. package/dist/chunk-QO4YQLZ4.js +0 -1
  43. package/dist/chunk-U6S6AZM6.js +0 -1
  44. package/dist/chunk-WCFVNF5D.js +0 -1
  45. package/dist/client-F6UPJMHR.js +0 -1
  46. package/dist/controls-XG46TKUU.js +0 -2
  47. package/dist/funnel-runtime-host-26QI2W3S.js +0 -1
  48. package/dist/iam.d.ts +0 -131
  49. package/dist/iam.js +0 -1
  50. package/dist/paywall-WKOHBYW7.js +0 -1
  51. package/dist/src-UHLPVD6E.js +0 -1
  52. package/dist/{errors-DrdTlPwf.d.ts → errors-BpCmukJr.d.ts} +1 -1
@@ -0,0 +1 @@
1
+ import{a as ye}from"./chunk-CXYOZSOF.js";import{Bg as $e,Dg as Ke,Ej as We,Fj as Xe,Gj as en,Hi as Pe,Hj as nn,Ii as Ye,Qd as Ue,bg as se,ei as de,ge as ke,he as qe,ke as Ge,mg as je,mi as De,mj as Ze,og as H,pg as Je,tg as _e,ti as Ae,ug as G,vg as Ee,wg as Be,wi as Qe,xg as ze,yg as He}from"./chunk-A3N4ZZTM.js";import{a as u}from"./chunk-OVMNCZYC.js";import{b as xe,h as ge}from"./chunk-AE4CUTUE.js";import{a as we}from"./chunk-S5TVMQRC.js";import{b as Te}from"./chunk-RRII2DMC.js";import{h as Ve,l as Me}from"./chunk-KQCTDXVD.js";function An(e){let n=null,i=null,t=0,c=0,v=new Set,r=null,s=null,o=new Set,a=()=>{for(let y of o)try{y()}catch{}},f={attributes:Te.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,O)=>{!v.has(y)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(O))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,O)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(O)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function S(y,O=new Set){return v.has(y)?!r||!r.features[y]||["unknownFeature","cyclicPrerequisite"].includes(r.features[y].source):O.has(y)?!1:(O.add(y),(n?.features[y]?.rules??[]).some(_=>[..._.parentConditions??[],...(_.tracks??[]).flatMap(b=>b.experiment.parentConditions??[])].some(b=>S(b.id,O))))}let E=y=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return r?.expiresAt&&Date.parse(r.expiresAt)<=Date.now()&&(r=null,f.features=n.features),v.has(y)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?w():structuredClone(r.features[y]??w()):S(y)?w():structuredClone(Me(y,f))};async function T(){if(!n||!v.size)return;if(!e.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let y=c;if(s?.revision===y)return s.loading;let O=t,_=n,b=[...v],M=(async()=>{let L=Ge.parse(await e.evaluateRemote({attributes:structuredClone(f.attributes),features:b}));if(!(O!==t||y!==c||_!==n)){if(e.assertUsable?.(_.generation),L.generation!==_.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(b.some(k=>!Object.hasOwn(L.features,k))||Object.keys(L.features).some(k=>!v.has(k)))throw new Error("Invalid remote Feature results");r=structuredClone(L),f.features={..._.features,...Object.fromEntries(Object.entries(r.features).map(([k,Y])=>[k,{defaultValue:Y.value}]))},a()}})();s={revision:y,loading:M};try{await M}finally{s?.loading===M&&(s=null)}}function h(){T().catch(y=>{try{e.onError?.(y)}catch{}})}async function D(){if(i)return i;let y=t,O=(async()=>{let _=await e.load(),b="remoteFeatures"in _?ke.parse(_):null,M=b??ge.parse(_);if(M.scope.projectId!==e.scope.projectId||M.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(y!==t)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===M.generation){let{evaluatedAt:k,expiresAt:Y,...K}=n,{evaluatedAt:W,expiresAt:he,...z}=M;if(G(K)!==G(z))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=M.evaluatedAt,n.expiresAt=M.expiresAt,a(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&h(),structuredClone(n)}let L=new Set(b?.remoteFeatures??[]);if([...L].some(k=>Object.hasOwn(M.features,k)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in M&&!n.analyticsConfig.experimentViewsEnabled&&b?.analyticsConfig.experimentViewsEnabled&&f.trackedExperiments?.clear(),n=structuredClone(M),v=L,r=null,s=null,c++,f.features=n.features,f.savedGroups=Ve(n.savedGroups),f.trackedFeatureUsage={},a(),h(),structuredClone(n)})();i=O;try{return await O}finally{i===O&&(i=null)}}return{init:D,refresh:D,refreshRemote:T,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(y){return o.add(y),()=>{o.delete(y)}},setAttributes(y){f.attributes=Te.parse(y),c++,r=null,s=null,f.features=n?.features??{},f.trackedFeatureUsage={},a(),h()},evalFeature:E,isOn(y){return E(y).on},isOff(y){return E(y).off},getFeatureValue(y,O){let _=E(y).value;return structuredClone(_===null?O:_)},reset(){t++,c++,i=null,s=null,n=null,r=null,v.clear(),f.features={},f.savedGroups={},f.stickyBucketAssignmentDocs={},f.attributes={},f.trackedFeatureUsage={},f.trackedExperiments?.clear(),a()}}}async function be(e,n){let i=$e.parse(n),{artifact:t,environmentId:c}=i.content,v=new URL(e.baseUrl??we).origin,r=new URL(t.url,v);if(r.origin!==v||r.username||r.password||r.search||r.hash||r.pathname!==`/api/v1/configuration/${c}/artifacts/${t.sha256}`)throw new u("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,o=setTimeout(()=>s.abort(),H.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(r,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>t.byteLength)throw new u("INVALID_RESPONSE","Public Paywall is unavailable");let f=a.body?.getReader();if(!f)throw new u("INVALID_RESPONSE","Public Paywall body is missing");let w=[],S=0;try{for(;;){let h=await f.read();if(h.done)break;if(S+=h.value.length,S>t.byteLength)throw new u("INVALID_RESPONSE","Public Paywall exceeds its byte limit");w.push(h.value)}}finally{await f.cancel().catch(()=>{})}let E=new Uint8Array(S),T=0;for(let h of w)E.set(h,T),T+=h.length;if(S!==t.byteLength||Ee(E)!==t.sha256)throw new u("INVALID_RESPONSE","Public Paywall digest or size changed");return Ke(i,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(E)))}finally{clearTimeout(o)}}async function Ne(e,n){let{funnelRuntimeDeliverySchema:i}=await import("./src-4MRSESVS.js"),t=i.safeParse(n);if(!t.success)throw new u("INVALID_RESPONSE","Funnel response contract changed");let c=t.data;if(e.scope&&(c.scope.projectId!==e.scope.projectId||c.scope.environment!==e.scope.environment))throw new u("SCOPE_MISMATCH","Funnel scope changed");return c}function tn(e){let n,i,t=()=>new u("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),c=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,i=e.locks??globalThis.navigator?.locks,!n||!i||!globalThis.crypto?.subtle)throw t();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??we).href,e.runToken])),o=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(o,a=>a.toString(16).padStart(2,"0")).join("")});c.catch(()=>{});async function v(s){try{let o=await c;return await i.request(o,{mode:"exclusive"},()=>s(o))}catch(o){throw o instanceof u?o:t()}}function r(s){let o=n.getItem(s);if(o===null)return{revision:0,entry:null};if(o.length>1048576)throw t();let a=JSON.parse(o);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw t();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>v(r),write:(s,o)=>v(a=>{if(r(a).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw t();return n.setItem(a,JSON.stringify({revision:s+1,entry:o})),s+1})}}function Ln(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function Ie(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((c,v)=>Ie(c,n[v]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let i=Object.entries(e),t=Object.entries(n);return i.length===t.length&&i.every(([c,v])=>Object.hasOwn(n,c)&&Ie(v,Reflect.get(n,c)))}var fe=(e,n)=>new u(e,n);function Un(e){return We(e,fe)}function pn(e,n,i){return en(e,n,i,fe)}async function rn(e,n){let i=n.instruction;if(i?.type!=="evaluate")throw new Error("Evaluation instruction required");if(!e)throw new u("CONFIGURATION_UNAVAILABLE","Local conditions require the shared public configuration manager");let t=await e.funnel(n.source.id,n.source.versionId);if(!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==i.policyRevision)throw new u("EVALUATION_MODE","Refresh the original Funnel evaluation policy");let{analyticsConfig:c,remoteFeatures:v,...r}=t.growth,s=Pe({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:t.document,payload:ge.parse(r)});if(e.scope.environmentId!==i.environmentId)throw new u("SCOPE_MISMATCH","Evaluation environment changed");let o=pn(s,n.nodeId,i);return e.assertFunnel(n.source.id,void 0,n.source.versionId),{generation:t.manifest.generation,result:o}}async function on(e,n,{predict:i=!0}={}){let t=n.instruction;if(t?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new u("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==t.environmentId)throw new u("SCOPE_MISMATCH","Evaluation environment changed");let c=null,v;if(i)try{let r=await e.funnel(n.source.id,n.source.versionId);v=r.manifest.generation,c=gn(e,n,r)}catch{c=null}return v??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:t.policyRevision,generation:v},prediction:c}}function gn(e,n,i){let t=n.instruction;if(t?.type!=="evaluate_segment"||!i.growth||i.control.evaluationMode!=="local"||i.control.evaluationRevision!==t.policyRevision)return null;let{analyticsConfig:c,remoteFeatures:v,...r}=i.growth,s=Pe({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:t.policyRevision,document:i.document,payload:ge.parse(r)}),o=wn(s,i.document,{...n,...t}),a=o.steps.at(-1),f=o.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+o.steps.length-1}:null);return f?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:f.nodeId,visit:f.visit,terminal:!o.boundary}:null}function wn(e,n,i){return nn(e,n,i,fe)}import{z as Z}from"zod";var an=se.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new u("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),sn=Z.strictObject({schemaVersion:Z.literal(1),scope:xe,runId:Z.uuid(),funnelId:Z.uuid(),versionId:Z.uuid(),command:an.optional(),closeCommand:an.refine(e=>e.operation==="close").optional(),purchase:Z.strictObject({receiptId:Z.uuid(),operationId:Z.uuid(),generation:Z.number().int().nonnegative()}).optional(),closed:Z.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation");function yn(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let{command:n,closeCommand:i,...t}=e;return!!n&&typeof n=="object"&&n.operation==="commit_segment"&&("steps"in n||"boundary"in n)?i?{...t,command:i}:"purchase"in t?t:null:e}var In=e=>{let n=yn(e);return n===null?null:sn.parse(n)},B=()=>new u("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Fe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function un(e){let n=0,i=null,t=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),c=Promise.resolve();async function v(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new u("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:In(o.entry)}}function r(o){let a=c.then(o);return c=a.catch(()=>{}),a}async function s(o){for(let a=0;a<4;a++){let f=await v();if(f.entry&&i!==null&&t(f.entry)!==i)throw B();let w=o(f.entry,f.revision);if(Fe(f.entry,w)){n=f.revision;return}let S=await e.write(f.revision,w);if(S!==null){if(!Number.isSafeInteger(S)||S<=f.revision)throw B();n=S;return}}throw B()}return{bind(o){let a=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(i!==null&&i!==a)throw B();i=a},async load(){let o=await v();return n=o.revision,i=o.entry?t(o.entry):null,o.entry},retain(o){let a=sn.parse(o),f=a.command;return!f||i!==null&&t(a)!==i?Promise.reject(B()):(i??=t(a),r(()=>s((w,S)=>{if(w&&!Fe(t(w),t(a)))throw B();if(!w){if(S!==n&&f.operation!=="close")throw B();return a}if(!w.command)return{...w,command:f,...f.operation==="close"?{closed:!0}:{}};if(f.operation==="close"&&w.command.operation!=="close"){if(w.command.requestId===f.requestId||w.closeCommand&&!Fe(w.closeCommand,f))throw B();return{...w,closeCommand:f,closed:!0}}if(!Fe(w.command,f))throw B();return w})))},observePurchase(o,a,f){return r(()=>s((w,S)=>{if(!w&&S!==n||w&&t(w)!==t({...o,schemaVersion:1}))throw B();if(w?.purchase&&w.purchase.generation>a.generation)return w;if(w?.purchase&&w.purchase.generation===a.generation&&w.purchase.operationId!==a.operationId)throw B();return f?!w?.purchase||w.purchase.operationId!==a.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...o,...w,purchase:a}}))},settle(o){return r(()=>s(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===o?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===o?{...a,closeCommand:void 0}:a:null))}}}function me(e){let{customerToken:n,...i}=e;return i}var hn=e=>!(e instanceof u)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function ln(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new u("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.serverKey)))throw new u("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let n=ye({...e,...e.serverKey?{fetch:(l,m)=>{let F=new Headers(m?.headers),V=typeof m?.body=="string"?JSON.parse(m.body):null;return V!==null&&typeof V=="object"&&"customerToken"in V&&typeof V.customerToken=="string"&&V.customerToken.length>0||F.set(Qe,e.serverKey),(e.fetch??globalThis.fetch)(l,{...m,headers:F})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let i,t=null,c=0,v=0,r=null,s=null,o=null,a=!1,f=null,w=!1,S=null,E=new Set,T=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?tn(e):void 0),h=T&&un(T),D,y=null,O=!1,_=h?h.load().then(l=>{if(O)throw new u("IDENTITY_CHANGED","Controller was reset during command restoration");if(y=l,!l)return;if(e.scope&&(l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment))throw new u("SCOPE_MISMATCH","Pending command belongs to another scope");if(D=l.purchase,a=l.closed===!0,!l.command)return;let m=se.parse(l.command);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new u("COMMAND_STORAGE_INVALID","Stored mutation required");r=m,l.closeCommand&&(s=l.closeCommand,a=!0),m.operation==="close"&&(a=!0),w=!0}):Promise.resolve();_.catch(()=>{});async function b(l,m,F){let V=c,J=()=>{if(V!==c||O)throw new u("IDENTITY_CHANGED","Run identity changed during the request")};h&&await _,J();let A=t,p=Ae.parse(await Ne(e,await n.request("funnels",se.parse(l))));if(l.operation==="review"&&!p.review)throw new u("INVALID_RESPONSE","Historical projection is missing");if(J(),p.runToken&&p.runToken!==e.runToken)throw new u("INVALID_RESPONSE","Run credential changed");let X=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(X&&p.settlement?.requestId!==X)throw new u("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");if(y&&(p.run.id!==y.runId||p.run.source.id!==y.funnelId||p.run.source.versionId!==y.versionId))throw new u("SCOPE_MISMATCH","Stored command belongs to another Run or Version");if(t&&(p.run.id!==t.id||p.run.source.type!==t.source.type||p.run.source.id!==t.source.id||p.run.source.versionId!==t.source.versionId||p.run.locale!==t.locale||!Ie(p.run.parameters,t.parameters)))throw new u("INVALID_RESPONSE","Run version changed");if(e.funnelId&&p.run.source.id!==e.funnelId)throw new u("INVALID_RESPONSE","Run belongs to another Funnel");h?.bind({scope:p.scope,runId:p.run.id,funnelId:p.run.source.id,versionId:p.run.source.versionId}),T&&!e.scope&&(e.scope=p.scope);let Q=p.run.paywall,$=Q??p.purchase,re=$?.operation,oe=p.settlement&&(!Q||Q.purchaseRequestId===p.settlement.requestId)&&(!D||D.operationId===p.settlement.operationId)?p.settlement:void 0,ve=re?.operationId??$?.quote?.operationId??oe?.operationId,Ce=$?.receiptId??oe?.receiptId,pe=Q?.selectionGeneration??D?.generation??0;if(h&&ve&&Ce&&l.operation!=="review"&&(!t||p.run.revision>=t.revision)&&(F===void 0||F>=v)&&(!D||pe>=D.generation)){let ie={receiptId:Ce,operationId:ve,generation:pe},g=re?.status==="complete"||$?.canReselect===!0;await h.observePurchase({scope:p.scope,runId:p.run.id,funnelId:p.run.source.id,versionId:p.run.source.versionId},ie,g),J(),g?D?.operationId===ie.operationId&&(D=void 0):D=ie}if(!p.run.stopped&&["running","waiting"].includes(p.run.status)&&l.operation==="get"&&l.settlementRequestId)return p;let ee=m?.(p),Oe=typeof ee=="boolean"?ee:ee?await ee:!1;if(J(),["running","waiting"].includes(p.run.status)||(a=!0),l.operation==="review"&&t&&t!==A&&p.run.revision<=t.revision||t&&p.run.revision===t.revision&&F!==void 0&&F<v||(l.operation==="review"&&!p.run.stopped&&["running","waiting"].includes(p.run.status)&&t&&p.run.nodeId===t.nodeId&&p.run.visit===t.visit&&p.run.revision===t.revision&&(p.run.screen=t.screen,(t.paywall?.quote?.operationId===p.review?.activeOperationId||!t.paywall?.quote&&p.review?.activeOperationId===null)&&(p.run.paywall=t.paywall)),t?.paywall&&p.run.paywall&&t.paywall.receiptId===p.run.paywall.receiptId&&(p.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))return p;if(!t||p.run.revision>=t.revision)t=p.run;else if(!Oe)return p;if(t)for(let ie of E)try{ie(structuredClone(t))}catch{}return p}async function M(l=r){if(h&&await _,!l)throw new u("INVALID_REQUEST","No command is pending");let m=l,F=c;if(h){if(!t||!e.scope)throw new u("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await h.retain({schemaVersion:1,scope:e.scope,runId:t.id,funnelId:t.source.id,versionId:t.source.versionId,command:me(m)})}if(F!==c||r!==m&&s!==m)throw new u("IDENTITY_CHANGED","Run changed before command dispatch");let V={...m,...i?{customerToken:i}:{}},J=w;w=!0;try{return await b(V,A=>{if(!A.settlement)throw new u("INVALID_RESPONSE","Exact command settlement is missing");if(A.settlement.requestId!==m.requestId)throw new u("INVALID_RESPONSE","Command settlement identity changed");if(F===c&&(r===m||s===m)&&A.run.pendingRequest?.requestId!==m.requestId&&A.settlement.state==="settled"&&(!a||m.operation==="close"||A.settlement?.state==="settled"&&!["running","waiting"].includes(A.run.status))){let p=()=>F!==c||r!==m&&s!==m?!1:(r===m&&(r=null),s===m&&(s=null),w=r!==null,y=null,!0);return h?h.settle(m.requestId).then(p):p()}return!1})}catch(A){throw F===c&&r===m&&!J&&!hn(A)&&(h&&await h.settle(m.requestId),F===c&&r===m&&(r=null,w=!1,y=null)),A}}function L(l){let m=se.parse(l);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new u("INVALID_REQUEST","Mutation required");if(a&&m.operation!=="close"){if(r?.requestId===m.requestId)return z.settle(m.requestId);throw new u("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"&&r?.operation!=="close"){if(a=!0,s&&JSON.stringify(me(s))!==JSON.stringify(me(m)))throw new u("COMMAND_PENDING","Retry the original Close");if(s??=m,f)return f;let V=M(s);return f=V,V.then(()=>{f===V&&(f=null)},()=>{f===V&&(f=null)}),V}if(r){if(JSON.stringify(me(r))!==JSON.stringify(me(m)))throw new u("COMMAND_PENDING","Retry the original command before sending another");if(S)return S}else r=m,w=!1;let F=M();return S=F,F.then(()=>{S===F&&(S=null)},()=>{S===F&&(S=null)}),F}let k=null,Y=new WeakMap;function K(l){let m=Y.get(l);if(m)return m;let F=he(l);return Y.set(l,F),F}let W=!1;async function he(l){let m=await l;if(!["evaluate","evaluate_segment"].includes(m.run.instruction?.type??""))return m;if(k)return k;W=!0;let F=c,V=(async()=>{for(let J=0;J<32&&["evaluate","evaluate_segment"].includes(m.run.instruction?.type??"");J++){if(r||a)return m;let A=m.run,p=m.run.instruction;if(p?.type==="evaluate_segment"){let{advance:Q,prediction:$}=await on(e.configuration,A);if(F!==c)throw new u("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r||a)return m;if(t&&(t.revision!==A.revision||t.visit!==A.visit||t.nodeId!==A.nodeId))return b({operation:"get",...i?{customerToken:i}:{}});o=$;try{m=await L({operation:"commit_segment",requestId:De(A.id,A.visit,`segment:${A.revision}`),nodeId:A.nodeId,visit:A.visit,revision:A.revision,...Q})}finally{o===$&&(o=null)}continue}if(p?.type!=="evaluate")return m;let X=await rn(e.configuration,A);if(F!==c)throw new u("IDENTITY_CHANGED","Run identity changed during evaluation");if(r||a)return m;if(t&&(t.revision!==A.revision||t.visit!==A.visit||t.nodeId!==A.nodeId))return b({operation:"get",...i?{customerToken:i}:{}});m=await L({operation:"evaluate",requestId:De(A.id,A.visit,"evaluation"),nodeId:A.nodeId,visit:A.visit,revision:A.revision,receiptId:p.receiptId,policyRevision:p.policyRevision,...X})}return m})();k=V;try{return await V}finally{k===V&&(k=null)}}let z={get configuration(){return W?e.configuration:void 0},get configurationReady(){return!0},get view(){return t?structuredClone(t):null},get pendingCommand(){let l=s??r;return l?structuredClone(me(l)):null},get pendingCommands(){return[r,s].filter(l=>l!==null).map(l=>structuredClone(me(l)))},get pendingPurchase(){return D?structuredClone(D):null},get prediction(){return o?structuredClone(o):null},async settle(l){let m=await b({operation:"get",settlementRequestId:l,...i?{customerToken:i}:{}});if(m.settlement?.requestId!==l)throw new u("INVALID_RESPONSE","Exact command settlement is missing");return m.settlement.state==="settled"&&(h&&await h.settle(l),r?.requestId===l&&(r=null,w=!1),s?.requestId===l&&(s=null)),m},get webViewUrl(){return"bundled"},resolvePaywall(l){return be(e,l)},review(l){return b({operation:"review",...l?{receiptId:l}:{},...i?{customerToken:i}:{}},void 0,++v)},async get(l,m){h&&await _,m??=D&&{receiptId:D.receiptId,operationId:D.operationId};let F=++v;return K(b({operation:"get",...l?{data:l}:{},...m?{purchase:m}:{},...i?{customerToken:i}:{}},void 0,F))},resume(l=t?.pendingRequest?.requestId){return l?a?z.settle(l):r?.requestId===l?K(L(r)):K(L({operation:"resume",requestId:l})):Promise.reject(new u("INVALID_REQUEST","No interrupted command is available"))},submit(l){return K(L(l))},retry(){return f||(s?M(s):a&&r?z.settle(r.requestId):S?K(S):r?K(L(r)):Promise.reject(new u("INVALID_REQUEST","No command is pending")))},identify(l){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(l))throw new u("INVALID_TOKEN","Customer credential required");c++,i=l,n.identify(e.runToken)},subscribe(l){return E.add(l),()=>E.delete(l)},reset(){O=!0,c++,i=void 0,t=null,r=null,s=null,o=null,f=null,w=!1,S=null,n.reset(),E.clear()}};return z}async function dt(e,n){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(n.customerToken))throw new u("INVALID_TOKEN","A verified Customer credential is required");let i=ye(e);i.identify(n.customerToken);let t=de.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),c=null,v=!1,r=null,s=null,o=null,a=null;async function f(){if(v)throw new u("IDENTITY_CHANGED","Paywall is closed");let E=de.resolvePaywall,T=E.response.parse(await i.request(E.path,E.request.parse({...t,selector:c?{type:"version",versionId:c.id}:t.selector}))),h={paywall:await be(e,T.paywall)};if(v)throw new u("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?h.paywall.id!==n.paywallVersionId:h.paywall.paywallId!==n.paywallId)throw new u("INVALID_RESPONSE","The requested Paywall changed");if(c&&(h.paywall.id!==c.id||h.paywall.paywallId!==c.paywallId||h.paywall.offering.id!==c.offering.id||h.paywall.content?.artifact.sha256!==c.content?.artifact.sha256))throw new u("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return c=h.paywall,structuredClone(c)}async function w(E){if(!r)throw new u("INVALID_REQUEST","A quoted purchase is required");let T=E==="read"?de.readSubscriptionOperation:de.attach,h=T.response.parse(await i.request(T.path,T.request.parse({operationId:r.operationId,...E==="read"?{}:{intent:E}})));if(h.operation.operationId!==r.operationId||h.operation.currency!==t.commerce.currency)throw new u("INVALID_RESPONSE","The purchase operation changed");return s?.status==="complete"&&h.operation.status!=="complete"||s&&s.status!=="pending"&&h.operation.status==="pending"||(s=h.operation),structuredClone(s)}let S={get view(){return c?structuredClone(c):null},get quote(){return r?structuredClone(r):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:f,async preview(E){if(!c)throw new u("INVALID_REQUEST","Load the Paywall first");let T=c.document.buttons[E.actionId];if(T?.type!=="checkout")throw new u("INVALID_REQUEST","Choose an authored purchase action");let h=Ue(T.product,E.selection,c.capabilities);if(!h)throw new u("PRODUCT_UNAVAILABLE","Choose an available Product");let D=de.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:h}],provider:t.commerce.provider,currency:t.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),y=JSON.stringify(D);if(o&&o!==y&&(!s||s.status==="pending"))throw new u("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===y){if(a)return a;if(r)return structuredClone(r)}o=y;let O=(async()=>{let _=de.previewAttach,b=_.response.parse(await i.request(_.path,D));if(b.quote.currency!==t.commerce.currency||b.quote.provider!==t.commerce.provider||b.quote.lines.length!==1||b.quote.lines[0].productVersionId!==h)throw new u("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return r=b.quote,s=null,structuredClone(r)})();a=O;try{return await O}finally{a===O&&(a=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){v=!0,i.reset(),c=null,r=null,s=null,o=null}};return await f(),S}import{z as Sn}from"zod";import{z as Re}from"zod";var vn=Re.record(Re.string().regex(/^[a-f0-9]{64}$/),Re.strictObject({at:Re.number(),text:Re.string()})),cn=2*1048576,Cn=100;function Rn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function dn(e,n){let i=n===void 0?Rn():n,t=Promise.resolve();async function c(r){if(!i)return null;let s;try{return await Promise.race([Promise.resolve().then(()=>i.getItem(r)),new Promise(o=>{s=setTimeout(()=>o(null),Cn)})])}catch{return null}finally{clearTimeout(s)}}async function v(){try{let r=await c(`${e}:artifacts`);if(r&&r.length<=cn)return vn.parse(JSON.parse(r))}catch{}return{}}return{async readManifest(){return c(e)},writeManifest(r){Promise.resolve().then(()=>i?.setItem(e,r)).catch(()=>{})},async readArtifact(r){let s=(await v())[r];return s&&Date.now()>=s.at&&Date.now()-s.at<=H.retentionMs?s.text:void 0},writeArtifact(r,s){i&&(t=t.catch(()=>{}).then(async()=>{let o=await v(),a=Date.now();o[r]={at:a,text:s};let f={},w=2,S=0;for(let[E,T]of Object.entries(o).sort(([,h],[,D])=>D.at-h.at)){if(T.at>a||a-T.at>H.retentionMs)continue;let h=new TextEncoder().encode(JSON.stringify({[E]:T})).byteLength;w+h>cn||S>=128||(f[E]=T,w+=h,S++)}await i.setItem(`${e}:artifacts`,JSON.stringify(f))}).catch(()=>{}))}}}var R=(e,n)=>new u(e,n),ue=()=>performance.now(),fn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Ct(e){let n=Je.parse(e.scope),i=new URL(e.origin??we);if(i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!(i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw R("INVALID_URL","Configuration requires a trusted HTTPS origin");let t=new Set([i.origin,...(e.assetOrigins??[]).map(g=>{let d=new URL(g);if(d.protocol!=="https:"||d.username||d.password||d.search||d.hash||d.pathname!=="/")throw R("INVALID_URL","Invalid configuration asset origin");return d.origin})]),c=e.fetch??globalThis.fetch.bind(globalThis),v=`/api/v1/configuration/${n.environmentId}`,r=`indiana:configuration:1:${i.origin}:${G(n)}`,s=dn(r,e.storage),o,a=0,f=0,w=!1,S=!1,E=0,T=0,h,D,y,O,_=0,b=new Set,M=new Set,L=new Map,k=new Map,Y=0,K=!1;function W(){for(let g of b)try{g()}catch{}}function he(g){try{e.onError?.(g)}catch{}}let z=()=>!S&&!w&&!!o&&ue()<a&&Date.now()<f;function l(){if(!z())throw R("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function m(g,d){let C=new TextEncoder().encode(d).byteLength;if(!L.has(g)){for(;L.size&&(L.size>=128||Y+C>H.maxCacheBytes);){let I=L.entries().next().value;Y-=new TextEncoder().encode(I[1]).byteLength,L.delete(I[0])}L.set(g,d),Y+=C}}async function F(g,d,C){if(Number(g.headers.get("content-length"))>d)throw R("INVALID_RESPONSE","Configuration exceeds its byte limit");let I=g.body?.getReader();if(!I)throw R("INVALID_RESPONSE","Configuration body is missing");let P=[],x=0;try{for(;;){C.throwIfAborted();let U=await I.read();if(U.done)break;if(x+=U.value.length,x>d)throw R("INVALID_RESPONSE","Configuration exceeds its byte limit");P.push(U.value)}}finally{await I.cancel().catch(()=>{})}C.throwIfAborted();let N=new Uint8Array(x),q=0;for(let U of P)N.set(U,q),q+=U.length;return new TextDecoder("utf-8",{fatal:!0}).decode(N)}function V(g){let d=new URL(g,i);if(!t.has(d.origin)||d.username||d.password||d.hash||d.search)throw R("INVALID_URL","Configuration artifact origin is not trusted");return d.href}async function J(g,d,C=!1){let I=await c(V(g),{method:"GET",credentials:"omit",redirect:"error",cache:C?"default":"no-cache",signal:d,headers:{}});if(I.status===429){let P=I.headers.get("retry-after")??"";_=/^\d+$/.test(P)?Number(P)*1e3:Math.max(0,Date.parse(P)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw R(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function A(g,d,C){let I=Date.parse(g.headers.get("x-indiana-config-validated-at")??""),P=Date.parse(g.headers.get("x-indiana-config-valid-until")??""),x=Date.parse(g.headers.get("date")??""),N=g.headers.get("age"),q=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![I,P,x,q].every(Number.isFinite)||P<=I||P-I>H.maxControlAgeMs||I>x+1e3)throw R("INVALID_RESPONSE","Configuration freshness evidence is invalid");let j=Math.min(P-I,C.maxControlAgeSeconds*1e3,H.maxControlAgeMs)-Math.max(q,x-I,0)-(ue()-d);if(j<=0)throw R("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return ue()+j}function p(){if(clearTimeout(y),clearTimeout(O),S||!b.size)return;z()&&(O=setTimeout(()=>{z()?p():W()},Math.max(1,a-ue())),fn(O));let g=T?Math.min(15e3,1e3*2**Math.min(T-1,4)):Math.min(15e3,(o?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{X().catch(he)},Math.max(_,g*(.8+Math.random()*.2))),fn(y)}async function X(){if(S)throw R("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(h)return h;let g=E,d=new AbortController;D=d;let C=(async()=>{if(!K){K=!0;try{let Se=await s.readManifest();if(Se&&!o){let te=_e.parse(JSON.parse(Se));G(te.scope)===G(n)&&(o=te)}}catch{}}d.signal.throwIfAborted();let N=o,q=ue(),U=await J(v,d.signal);U.status===304&&(!N||!U.headers.has("x-indiana-config-validated-at")||!U.headers.has("x-indiana-config-valid-until")||!U.headers.has("age"))&&(U=await J(v,d.signal));let j=U.status===304?N:_e.parse(JSON.parse(await F(U,H.maxManifestBytes,d.signal))),{generation:ne,...ae}=j,le=U.headers.get("etag");if(G(j.scope)!==G(n)||Be(ae)!==ne||le!==`"${ne}"`&&le!==`W/"${ne}"`)throw R("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(j.revision<N.revision||j.revision===N.revision&&j.generation!==N.generation))throw R("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Se,te]of Object.entries(N?.funnels??{})){let ce=j.funnels[Se];if(ce&&(ce.controlRevision<te.controlRevision||ce.evaluationRevision<te.evaluationRevision||ce.controlRevision===te.controlRevision&&ce.state!==te.state||ce.evaluationRevision===te.evaluationRevision&&ce.evaluationMode!==te.evaluationMode))throw R("INVALID_RESPONSE","Funnel control revision changed identity")}let Le=A(U,q,j.policy);if(d.signal.throwIfAborted(),g!==E)throw R("CONFIGURATION_DISPOSED","Configuration scope changed");return o=j,a=Le,f=Date.now()+Math.max(0,Le-ue()),w=!1,T=0,_=0,s.writeManifest(G(j)),W(),structuredClone(j)})(),I=setTimeout(()=>d.abort(R("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs),P=new Promise((N,q)=>d.signal.addEventListener("abort",()=>q(d.signal.reason),{once:!0})),x=Promise.race([C,P]).catch(N=>{throw T++,(N instanceof Sn.ZodError||N instanceof SyntaxError||N instanceof u&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,w=!0,W()),N}).finally(()=>{clearTimeout(I),h===x&&(h=void 0),p()});return h=x,x}async function Q(g){let d=g.sha256,C=ne=>new TextEncoder().encode(ne).byteLength===g.byteLength&&Ee(ne)===d;V(g.url);let I=L.get(d);if(I&&C(I))return L.delete(d),L.set(d,I),I;if(k.has(d))return k.get(d);let P=new AbortController;M.add(P);let x=E,N=(async()=>{try{let le=await s.readArtifact(d);if(le&&C(le))return m(d,le),le}catch{}P.signal.throwIfAborted();let ne=await J(g.url,P.signal,!0),ae=await F(ne,g.byteLength,P.signal);if(!C(ae))throw R("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(S||x!==E)throw R("CONFIGURATION_DISPOSED","Configuration scope changed");return m(d,ae),s.writeArtifact(d,ae),ae})(),q=setTimeout(()=>P.abort(R("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),H.initializationMs),U=new Promise((ne,ae)=>P.signal.addEventListener("abort",()=>ae(P.signal.reason),{once:!0})),j=Promise.race([N,U]).finally(()=>{clearTimeout(q),M.delete(P),k.delete(d)});return k.set(d,j),j}async function $(){return z()||await X(),l(),o}async function re(g){let d,C=new Promise((I,P)=>{d=setTimeout(()=>P(R("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs)});try{return await Promise.race([g(),C])}finally{clearTimeout(d)}}function oe(g,d){if(l(),o?.generation!==g.generation)throw R("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(d&&o.funnels[d]?.state!=="active")throw R("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function ve(g){let d=g.gb.features;if(!d)throw R("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let C=g.artifacts[d];if(C.formatVersion!==1)throw R("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=qe.parse(JSON.parse(await Q(C)));if(G(I.scope)!==G({projectId:n.projectId,environment:n.environment})||I.generation!==C.generation||I.remoteFeatures.some(P=>Object.hasOwn(I.features,P)))throw R("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return oe(g),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-ue())).toISOString()}}async function Ce(g,d){let C=await $();oe(C,g);let I=C.funnels[g];if(I.evaluationMode!=="local")throw R("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let P=d??I.currentVersionId,x=I.versions[P];if(!x)throw R("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(C.artifacts[x.artifact].formatVersion!==3)throw R("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[N,q]=await Promise.all([Q(C.artifacts[x.artifact]).then(U=>He(JSON.parse(U))),I.evaluationMode==="local"?ve(C):void 0]);if(q&&G(ze(N,q))!==G(x.dependencies))throw R("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return oe(C,g),{document:N,growth:q,versionId:P,control:structuredClone(I),manifest:structuredClone(C)}}function pe(){w=!0,W(),X().catch(he)}let ee=()=>{(typeof document>"u"||document.visibilityState==="visible")&&pe()};function Oe(g){if(S)throw R("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return b.add(g),b.size===1&&(typeof window<"u"&&(window.addEventListener("online",pe),window.addEventListener("focus",ee),document.addEventListener("visibilitychange",ee)),p()),()=>{b.delete(g),b.size||(clearTimeout(y),clearTimeout(O),ie())}}function ie(){typeof window<"u"&&(window.removeEventListener("online",pe),window.removeEventListener("focus",ee),document.removeEventListener("visibilitychange",ee))}return{scope:Object.freeze({...n}),refresh:X,subscribe:Oe,assertFresh:l,assertFeatures(g){l();let d=o.gb.features;if(!d)throw R("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(g!==void 0&&o.artifacts[d].generation!==g)throw R("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return o?structuredClone(o):null},get remainingMs(){return z()?Math.max(0,a-ue()):0},async features(){return re(async()=>ve(await $()))},pageExperiments:()=>re(async()=>{let g=await $(),d=g.gb.pageExperiments;if(!d)throw R("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let C=g.artifacts[d];if(C.formatVersion!==1)throw R("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=Ze.parse(JSON.parse(await Q(C)));if(I.environmentId!==n.environmentId||I.generation!==C.generation)throw R("INVALID_RESPONSE","Page experiment scope or generation changed");return oe(g),I}),funnel:(g,d)=>re(()=>Ce(g,d)),paywall:(g,d)=>re(async()=>{let C=await $(),I=C.paywalls?.[g];if(!I||!d&&I.state!=="published")throw R("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let P=d??I.currentVersionId,x=I.versions[P],N=x&&C.artifacts[x.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw R("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let q=je.parse(JSON.parse(await Q(N)));return oe(C),{document:q,versionId:P,version:x.version,control:structuredClone(I),manifest:structuredClone(C)}}),async localFunnel(g,d){let C=await re(()=>Ce(g,d));if(!C.growth)throw R("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:P,...x}=C.growth;return Ye({scope:{projectId:n.projectId,environment:n.environment},funnelId:g,versionId:C.versionId,evaluationMode:"local",evaluationRevision:C.control.evaluationRevision,document:C.document,payload:x})},assertFunnel(g,d,C){l();let I=o.funnels[g];if(!I||I.state!=="active")throw R("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw R("EVALUATION_MODE","This Funnel now executes at Indiana");if(d!==void 0&&I.controlRevision!==d)throw R("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(C!==void 0&&!I.versions[C])throw R("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!S){S=!0,E++,a=0,D?.abort(R("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(O),ie(),W(),b.clear();for(let g of M)g.abort(R("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));L.clear(),Y=0}}}}function At(e,n,i){return Xe(e,n,i,fe)}function mn(e){let n=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey);if(typeof window<"u"&&!n)throw new u("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new u("INVALID_TOKEN","A customer credential or server API key is required");let i=ye({...e,timeoutMs:e.timeoutMs??35e3});return i.identify(e.apiKey),{async start(t){let c=se.safeParse({...t,operation:"start"});if(!c.success||c.data.operation!=="start"||(n?c.data.customer!==void 0:c.data.customer===void 0))throw new u("INVALID_REQUEST","Invalid current Funnel start");let v=c.data,r=Ae.safeParse(await Ne(e,await i.request("funnels",v)));if(!r.success||!r.data.runToken)throw new u("INVALID_RESPONSE","Funnel start credentials are missing");let s=r.data;if(s.run.source.id!==v.funnelId||s.run.locale!==(v.locale??"en")||!Ie(s.run.parameters,v.parameters??{})||(v.customer?!s.customerId||v.customer.type==="id"&&s.customerId!==v.customer.value:s.customerId!==void 0))throw new u("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function Vt(e){e={...e};let n=e.configuration;if(!n)throw new u("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let i={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&G(i)!==G(e.scope))throw new u("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new u("EVALUATION_MODE","This Funnel uses Remote evaluation");let c=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.credential);if(c?!e.customerId:e.customerId!==void 0)throw new u("INVALID_REQUEST","Only Server-Key starts name their Customer");let v=mn({...e,scope:i,apiKey:e.credential}),r=s=>{let o=ln({...e,scope:i,runToken:s,...c?{serverKey:e.credential}:{}});return c||o.identify(e.credential),o};return{async start(s){let o=await v.start({...s,funnelId:e.funnelId,...c?{customer:{type:"id",value:e.customerId}}:{}}),a=r(o.runToken),f=await a.get();return{...o,...f,controller:a}},async restore(s){let o=r(s),a=await o.get();if(a.run.source.id!==e.funnelId)throw o.reset(),new u("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:s,controller:o}}}}export{An as a,Ln as b,Ie as c,Ne as d,Un as e,pn as f,wn as g,tn as h,ln as i,dt as j,Ct as k,At as l,mn as m,Vt as n};
@@ -0,0 +1 @@
1
+ import{a as ue}from"./chunk-RRII2DMC.js";import{z as A}from"zod";var te=A.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),Sr=A.enum([...te.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),xr=A.enum([...te.options,"stale_revision"]),ot=A.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),at=A.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Ee={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};function _r(e){return[400,405,415,422].includes(e)?"INVALID_REQUEST":e===401?"UNAUTHENTICATED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":[409,412,425].includes(e)?"CONFLICT":e===413?"PAYLOAD_TOO_LARGE":e===429?"RATE_LIMITED":e===501?"NOT_CONFIGURED":[408,502,503,504].includes(e)?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR"}var Ie={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function st(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(Ie,e)){let i=Ie[e];return{retryable:i==="retry_same_request",recovery:i}}let n=te.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Ee[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Ir(e,t){let n=te.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):Ee[n.data].status===t;let i={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(i,e)&&(i[e]?.includes(t)??!1)}function ct(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let a=Number(n);return Number.isSafeInteger(a)?a:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let i=Date.parse(n);return Number.isFinite(i)?Math.max(0,Math.ceil((i-t)/1e3)):void 0}var Ae=A.object({retryable:A.boolean(),recovery:ot,reason:at.optional(),retryAfterSeconds:A.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),lt=A.object({requestId:A.uuid().optional(),error:A.object({code:A.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:A.string(),...Ae.partial().shape})}),Er=A.object({error:lt.shape.error.extend({requestId:A.uuid().optional()})}),Ar=A.object({error:A.string(),code:A.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:A.uuid(),...Ae.shape});function Nr(e,t,n={}){let i=st(e,t),a=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??i.recovery,c=i.retryable&&n.retryable!==!1&&a!=="recover_operation",l=c?ct(n.retryAfter??null):void 0;return{...i,retryable:c,recovery:a,...l===void 0?{}:{retryAfterSeconds:l},...n.reason?{reason:n.reason}:{}}}import{z as ut}from"zod";var pt=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],O=ut.enum(pt);function pe(e){let t=O.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function kr(e,t){let n=pe(t),i=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!i?.[1]||(i[2]?.length??0)>n)throw new Error("Amount has invalid currency precision");let a=BigInt(i[1])*BigInt(10**n)+BigInt((i[2]??"").padEnd(n,"0")||"0");if(a>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Amount exceeds the supported range");return Number(a)}function Cr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let n=pe(t),i=String(e).padStart(n+1,"0");return n?`${i.slice(0,-n)}.${i.slice(-n)}`:i}function Lr(e,t,n="en",i={}){let a=O.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:a,...i}).format(e/10**pe(a))}import{z as _}from"zod";var re=_.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),E=_.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),mt=_.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),me=E.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ne=_.string().min(1).max(64),V=_.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Re=_.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),L=_.record(Ne,_.union([_.string().max(120),_.number().finite(),_.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),Oe=_.record(Ne,_.union([_.string().max(120),_.number().finite(),_.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),q=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,i=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let a=BigInt(n)*BigInt("1000000")+BigInt(i.padEnd(6,"0"));return t?-a:a},ke=_.array(_.object({upTo:me.nullable(),cost:E}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let i=e[n-1]?.upTo;return t.upTo!==null&&(n===0||i!=null&&q(t.upTo)>q(i))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),dt=_.object({key:Re,match:Oe,priority:_.number().int().default(0),cost:E.optional(),tiers:ke.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),ft=_.object({key:Re,match:Oe,factor:me.optional(),add:mt.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),gt=_.object({units:me.default("1"),cost:E,tiers:ke.optional(),dimensions:_.array(dt).max(12).optional(),multipliers:_.array(ft).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],i=e.multipliers??[];(new Set(n.map(l=>l.key)).size!==n.length||new Set(i.map(l=>l.key)).size!==i.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[l,d]of n.entries())for(let g of n.slice(l+1))Object.keys(d.match).length===Object.keys(g.match).length&&d.priority===g.priority&&!Object.keys(d.match).some(s=>g.match[s]!==void 0&&g.match[s]!==d.match[s])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let a=[e.cost,...(e.tiers??[]).map(l=>l.cost),...n.flatMap(l=>[...l.cost===void 0?[]:[l.cost],...(l.tiers??[]).map(d=>d.cost)])],c=q(e.units);for(let l of a)for(let d=0;d<1<<i.length;d++){let g=i.filter((v,R)=>d&1<<R);if(g.some((v,R)=>g.slice(R+1).some(_e=>Object.keys(v.match).some(le=>_e.match[le]!==void 0&&_e.match[le]!==v.match[le]))))continue;let s=q(l),p=BigInt("1"),b=BigInt("0");for(let[v,R]of i.entries())d&1<<v&&(s*=q(R.factor??"1"),p*=BigInt("1000000"),b+=q(R.add??"0"));let h=(s+b*p)*BigInt("1000000"),w=p*c;(h<BigInt("0")||h%w!==BigInt("0")||h/w>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),Dr=gt.safeExtend({featureKey:V});import{z as bt}from"zod";var Le=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,M=bt.string().max(16).regex(Le,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");function de(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:n,script:i,region:a}=new Intl.Locale(t),c=[n,i,a].filter(Boolean).join("-");return Le.test(c)?c:null}catch{return null}}var yt=new Set(["TW","HK","MO"]);function Ce(e){let[t,n,i]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let a=n?.length===4?n:void 0,c=n?.length===4?i:n;return a?`zh-${a}`:c&&yt.has(c)?"zh-Hant":"zh-Hans"}function Te(e,t,n){let i=t.map(a=>({code:M.parse(a),normalized:a}));for(let a of e){let c=de(a);if(!c)continue;let l=i.find(p=>p.normalized===c);if(l)return l.code;let d=Ce(c),g=i.filter(p=>Ce(p.normalized)===d),s=g.find(p=>!p.normalized.includes("-")||p.normalized===d)??g[0];if(s)return s.code}return n}var ht=[{code:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{code:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u53F0\u7063\uFF09"},{code:"zh-HK",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u9999\u6E2F\uFF09"},{code:"en",label:"English"},{code:"ja",label:"\u65E5\u672C\u8A9E"},{code:"ko",label:"\uD55C\uAD6D\uC5B4"},{code:"es",label:"Espa\xF1ol"},{code:"fr",label:"Fran\xE7ais"},{code:"de",label:"Deutsch"},{code:"pt-BR",label:"Portugu\xEAs (Brasil)"},{code:"it",label:"Italiano"},{code:"ru",label:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"vi",label:"Ti\u1EBFng Vi\u1EC7t"},{code:"th",label:"\u0E44\u0E17\u0E22"},{code:"id",label:"Bahasa Indonesia"},{code:"ar",label:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629"}];function wr(e){return ht.find(t=>t.code===e)?.label??e}import{z as u}from"zod";var $=E.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),H=u.string().min(1).max(120),ne=u.enum(["cap","overflow"]),k=(e,t)=>{let[n,i=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(i.padEnd(t,"0"))},K=e=>{try{return e()}catch{return!1}},$r=u.discriminatedUnion("operation",[u.object({operation:u.literal("quote"),overageBehavior:ne.optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:$,properties:L}).strict(),u.object({operation:u.literal("consume"),overageBehavior:ne.optional(),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:E,properties:L,idempotencyKey:H}).strict(),u.object({operation:u.literal("reserve"),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:$,properties:L,idempotencyKey:H,expiresInSeconds:u.number().int().min(1).max(86400)}).strict(),u.object({operation:u.literal("confirm"),operationId:u.uuid(),quantity:$,properties:L.optional(),idempotencyKey:H}).strict(),u.object({operation:u.literal("refund"),operationId:u.uuid(),quantity:$,idempotencyKey:H}).strict(),u.object({operation:u.literal("release"),operationId:u.uuid(),idempotencyKey:H}).strict()]),St=u.object({internal_credit_feature_id:u.uuid().nullable(),internal_metered_feature_id:u.uuid(),dimension:u.string().min(1).max(64),counterKey:u.string().min(1).max(240),cycleStart:u.iso.datetime({offset:!0}),unitCost:E,units:$,amount:re,tier:u.number().int().min(1).max(12).nullable()}).strict(),Q=u.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function je(e,t){let n=e.reduce((i,a)=>i+k(a.units,12),0n)-k(t,12);return e.some(i=>i.funding==="balance")?n>=-100n&&n<=100n:n===0n}var De=u.discriminatedUnion("funding",[u.strictObject({funding:u.literal("balance"),sourceId:u.uuid(),rolloverId:u.uuid().nullable(),units:Q.refine(e=>/[1-9]/.test(e)),amount:re}),u.strictObject({funding:u.literal("unbilled"),units:Q.refine(e=>/[1-9]/.test(e))}),u.object({funding:u.literal("prepaid"),sourceId:u.uuid(),units:$,amount:re,pricing:u.array(St).min(1).max(12)}).strict().refine(e=>K(()=>e.pricing.reduce((t,n)=>t+k(n.units,6),0n)===k(e.units,6)&&e.pricing.reduce((t,n)=>t+k(n.amount,12),0n)===k(e.amount,12)&&e.pricing.every(t=>k(t.unitCost,6)*k(t.units,6)===k(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),u.object({funding:u.literal("postpaid"),invoiceLineId:u.uuid().nullable(),units:$,authorizationId:u.uuid()}).strict()]),ie=u.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Br=u.object({allowed:u.boolean(),internal_feature_id:u.uuid(),quantity:E,requestedQuantity:E.optional(),overageBehavior:ne.optional(),reason:ie.nullable(),allocations:u.array(De).max(500)}).strict().refine(e=>K(()=>e.allowed?e.reason===null&&je(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>K(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&k(e.requestedQuantity,6)>=k(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),qr=u.object({id:u.uuid(),internal_feature_id:u.uuid(),kind:u.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:u.uuid().nullable(),quantity:E,requestedQuantity:E.optional(),overageBehavior:ne.optional(),accepted:u.boolean(),reason:u.enum([...ie.options,"expired"]).nullable(),createdAt:u.iso.datetime({offset:!0}),reservationStatus:u.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:u.iso.datetime({offset:!0}).nullable(),allocations:u.array(De).max(500)}).strict().refine(e=>K(()=>e.accepted?e.reason===null&&je(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>K(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&k(e.requestedQuantity,6)>=k(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as T}from"zod";var xt=T.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),_t=T.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ze=T.strictObject({internal_feature_id:T.uuid(),entityId:T.uuid().nullable()}),Gr=ze.extend({quantity:E,expectedRevision:T.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:T.string().min(1).max(120),properties:L.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Pe=ze.extend({operationId:T.uuid().nullable(),usage:E,capacity:xt.nullable(),remaining:_t.nullable(),withinLimit:T.boolean(),revision:T.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:T.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=i=>{let a=i.startsWith("-"),[c,l=""]=(a?i.slice(1):i).split(".");if(c===void 0||c==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(c)*10n**12n+BigInt(l.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});import{z as o}from"zod";var P=o.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),j=o.iso.datetime({offset:!0}),It=o.enum(["access","metered","credit"]),W={internal_feature_id:o.uuid(),key:V,name:o.string().min(1).max(120),kind:It},Jr=o.object({customerId:o.uuid(),snapshotAt:j,memberships:o.array(o.object({id:o.uuid(),productId:o.string().min(1).max(255),productVersionId:o.uuid(),billingProductVersionId:o.uuid(),version:o.number().int().positive(),key:o.string().min(1).max(64),name:o.string().min(1).max(120),groupId:o.string().max(255).nullable(),membershipType:o.enum(["main","addon"]),status:o.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:o.boolean(),accessEnabled:o.boolean(),renewalChange:o.object({productVersionId:o.uuid(),name:o.string().min(1).max(120),version:o.number().int().positive(),effectiveAt:j,benefitsAppliedAt:j.nullable(),timing:o.enum(["immediate","renewal"]),changeKind:o.enum(["plan","seats","quantity"]),feature:o.strictObject({internal_feature_id:o.uuid(),name:o.string().min(1).max(80),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).optional(),seat:o.object({key:o.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).strict().nullable(),status:o.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:o.object({phase:o.enum(["paid","trial"]),startsAt:j,endsAt:j.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:o.boolean(),balances:o.array(o.object({...W,usageType:o.enum(["consumable","non_consumable"]).nullable(),accessible:o.boolean(),unlimited:o.boolean(),available:P,held:P,debt:P,nextExpiresAt:j.nullable(),usage:Pe.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:o.boolean()}).strict(),we=o.enum(["source","usage","transaction","invoice","debt","settlement"]),oe=o.object({at:j,id:o.uuid(),type:we}).strict(),en=o.object({type:we.nullable(),resourceKey:V.optional(),kind:o.enum(["purchase","refund"]).optional(),topup:o.boolean().optional(),from:o.iso.date().nullable(),to:o.iso.date().nullable(),after:oe.nullable(),limit:o.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),F={id:o.uuid(),occurredAt:j},Et=o.discriminatedUnion("type",[o.strictObject({...F,type:o.literal("invoice"),status:o.string().min(1).max(80),paid:P,refunded:P,currency:O,externalId:o.string().nullable()}),o.object({...F,...W,type:o.literal("source"),reason:o.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:P,unlimited:o.boolean(),status:o.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:j,expiresAt:j.nullable(),orderId:o.uuid().nullable(),parentSourceId:o.uuid().nullable()}).strict(),o.object({...F,type:o.literal("usage"),internal_feature_id:o.uuid(),name:o.string().min(1).max(120),kind:o.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:o.uuid().nullable(),quantity:E,accepted:o.boolean(),reason:o.enum([...ie.options,"expired"]).nullable(),properties:L,reservationStatus:o.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:j.nullable(),charges:o.array(o.discriminatedUnion("funding",[o.strictObject({funding:o.literal("balance"),sourceId:o.uuid(),rolloverId:o.uuid().nullable(),units:Q,amount:P}),o.strictObject({funding:o.literal("unbilled"),units:Q}),o.object({...W,funding:o.literal("prepaid"),amount:P}).strict(),o.object({funding:o.literal("postpaid"),invoiceId:o.uuid(),invoiceLineId:o.uuid(),authorizationId:o.uuid(),units:E,currency:O}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),o.object({...F,type:o.literal("transaction"),purpose:o.enum(["product","invoice"]),productVersionId:o.uuid().nullable(),productName:o.string().min(1).max(120).nullable(),productVersion:o.number().int().positive().nullable(),invoiceId:o.uuid().nullable(),orderId:o.uuid(),originalId:o.uuid().nullable(),kind:o.enum(["purchase","refund"]),amountMinor:o.number().int().nonnegative().max(2e8).nullable(),currency:O.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),o.object({...F,...W,type:o.literal("debt"),sourceId:o.uuid(),transactionId:o.uuid(),amount:P}).strict(),o.object({...F,...W,type:o.literal("settlement"),sourceId:o.uuid(),debtId:o.uuid(),kind:o.enum(["payment","usage_refund","payment_return"]),amount:P}).strict()]),tn=o.object({customerId:o.uuid(),rows:o.array(Et).max(50),nextCursor:oe.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as Z}from"zod";var ve=Z.enum(["stripe","apple","google"]),on=Z.enum(["membership","credit_pack","lifetime"]),an=Z.enum(["active","grace","suspended","inactive","revoked"]),sn=Z.strictObject({currency:Z.string().regex(/^[A-Z]{3}$/),micros:Z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as At}from"zod";var Ue=At.object({provider:ve,currency:O}).strict();import{z as x}from"zod";var Ve=x.strictObject({internal_feature_id:x.uuid(),quantity:E.refine(e=>/[1-9]/.test(e)),properties:L,entityId:x.uuid().optional()}),yn=x.strictObject({requirement:Ve,commerce:Ue.optional(),paywallId:x.uuid().optional()}),Nt=x.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Rt=x.strictObject({productId:x.string().min(1),productVersionId:x.string().min(1),name:x.string().min(1).max(120),action:x.enum(["purchase","upgrade","addon","topup"]),membershipId:x.string().min(1).nullable(),currency:O,amountMinor:x.string().regex(/^(0|[1-9]\d{0,8})$/),interval:x.enum(["free","week","month","year","one_time"]),intervalCount:x.number().int().min(1).max(156)}),$e=x.strictObject({internal_feature_id:x.string().min(1),name:x.string().min(1).max(120),kind:x.enum(["access","metered","credit"]),quantity:E,allowed:x.boolean(),reason:Nt.nullable(),preview:x.strictObject({scenario:x.enum(["feature_flag","usage_limit"]),candidates:x.array(Rt).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),hn=x.strictObject({paywallId:x.uuid(),requirement:Ve});import{z as f}from"zod";var Ot=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],fe=f.object({plan:f.string().min(1).max(200).optional(),coupon:f.uuid().optional(),promotionCode:f.uuid().optional(),picker:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Be=f.object({text:f.string().optional(),label:f.string().optional(),alt:f.string().optional(),html:f.string().max(32768).optional(),price:f.object({current:f.string(),original:f.string().nullable(),period:f.string()}).optional(),code:f.string().optional(),countdownAt:f.iso.datetime().optional(),planId:f.string().min(1).max(200).optional(),planVersionId:f.string().min(1).max(200).optional(),currency:O.optional(),couponId:f.uuid().optional(),offerId:f.uuid().optional(),unavailable:f.boolean().optional(),unavailableReason:f.string().optional(),missing:f.array(f.string()).optional()}).strict(),En=f.object({paywall:$e.optional(),nodes:f.record(f.string(),f.object({base:Be,picker:f.string().optional(),byPlan:f.record(f.string(),Be).optional()}).strict()),plans:f.record(f.string(),f.object({id:f.string().min(1).max(200),versionId:f.string().min(1).max(200),available:f.boolean(),name:f.string(),price:f.string(),period:f.string(),currency:O.optional()}).strict()),pickers:f.record(f.string(),f.object({options:f.array(f.string().min(1).max(200)).max(20),selected:f.string().min(1).max(200).nullable()}).strict()),diagnostics:f.array(f.object({nodeId:f.string(),message:f.string()}).strict())}).strict();function ae(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function se(e){let t=ae(e).filter(i=>!Ot.includes(i)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(i)),n=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(n.includes("{{")||n.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function An(e,t,n,i=!1){let a=ae(e).filter(c=>!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(c)&&t[c]===void 0);return a.length&&!i?{value:n,missing:a}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(c,l)=>t[l.trim()]??c),missing:a}}function Nn(e,t,n={}){let i=e?.nodes[t];if(!i)return;let a=i.picker?n[i.picker]??e?.pickers[i.picker]?.selected:void 0;return typeof a=="string"?i.byPlan?.[a]??i.base:i.base}function qe(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function ce(e){let t={};function n(i){if(qe(i)){let a=t[i.interaction.pickerId]??={ids:[],defaultId:null};for(let l of i.children){let d=l.type==="stack"?l.bind?.plan:void 0;d&&!a.ids.includes(d)&&a.ids.push(d)}let c=i.children[i.interaction.defaultIndex];!a.defaultId&&c?.type==="stack"&&(a.defaultId=c.bind?.plan??null)}i.type==="stack"&&i.children.forEach(n)}return e.pages.forEach(i=>n(i.root)),t}function Me(e,t,n){let i={};function a(g){if(g.hidden)return;if(g.type==="plan_picker"){let b=n.pickers[g.id];i[g.id]={ids:b?.options??[],defaults:b?.selected?[b.selected]:[],remembered:[]};return}if(g.type!=="stack")return;let s=g.children.filter(b=>!b.hidden),p=g.interaction;if(qe(g)){let b=i[g.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},h=n.pickers[g.interaction.pickerId]?.options??[];for(let v of s){let R=v.type==="stack"?v.bind?.plan:void 0;R&&h.includes(R)&&!b.ids.includes(R)&&b.ids.push(R),R&&v.id===t[g.id]&&b.remembered.push(R)}let w=g.children[g.interaction.defaultIndex];w?.type==="stack"&&!w.hidden&&w.bind?.plan&&b.defaults.push(w.bind.plan)}if(p?.type==="tabs"){let b=s.find(h=>h.id===t[g.id])??g.children[p.defaultIndex];b&&a(b)}else if(p?.type==="toggle"){let b=typeof t[g.id]=="boolean"?t[g.id]:p.defaultEnabled,h=g.children[b?0:1];h&&a(h)}else s.forEach(a)}let c=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,l=e.pages.find(g=>g.id===c);l&&a(l.root);let d={};for(let[g,s]of Object.entries(i)){let p=t[g],b=s.remembered[0]??(s.ids.includes(n.pickers[g]?.selected??"")?n.pickers[g]?.selected:s.defaults[0]);d[g]=typeof p=="string"?s.ids.includes(p)?p:"":b&&s.ids.includes(b)?b:""}for(let g of Object.keys(ce(e)))d[g]??="";return d}import{z as U}from"zod";var Fe=U.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ze=U.strictObject({tiers:U.array(U.strictObject({id:Fe,name:U.string().trim().min(1).max(80)})).min(1).max(8),assignments:U.array(U.strictObject({productVersionId:U.string().min(1).max(200),tierId:Fe,period:U.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(i=>i.id);(new Set(n).size!==n.length||new Set(e.assignments.map(i=>i.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(i=>`${i.tierId}:${i.period}`)).size!==e.assignments.length||e.assignments.some(i=>!n.includes(i.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Ge(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as m}from"zod";var kt=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],He=m.enum(kt),Ke=m.object({source:He,layout:m.enum(["full","compact"]),resourceKey:V.optional(),pageSize:m.number().int().min(1).max(50),showSources:m.boolean(),allowPurchase:m.boolean(),outputs:m.object({billing_adjustment:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),N=m.string().max(2e3),Qe=m.object({id:m.string().max(100),label:N,detail:m.array(N).max(12),value:N.optional(),status:N.optional(),facts:m.array(m.object({label:N,value:N}).strict()).max(1e3),purchaseId:m.uuid().optional(),invoiceUrl:m.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:m.array(m.strictObject({action:m.literal("invoice_open"),label:N})).max(1).optional(),membershipActions:m.array(m.object({value:m.string().max(100),label:N}).strict()).max(3).optional()}).strict(),Ct=m.object({key:V,name:N,spendable:N,reserved:N,available:N,expiry:N.nullable(),sources:m.array(Qe).max(50),sourceCount:m.number().int().nonnegative(),sourcePage:m.number().int().positive(),hasNextSources:m.boolean(),hasPreviousSources:m.boolean()}).strict(),Lt=m.object({source:He,status:m.enum(["idle","loading","ready","error"]),stale:m.boolean(),preview:m.boolean(),errorCode:m.string().max(80).optional(),errorMessage:N.optional(),resources:m.array(Ct).max(500),rows:m.array(Qe).max(50),hasNext:m.boolean(),hasPrevious:m.boolean(),page:m.number().int().positive(),filter:m.string().max(40),updatedAt:m.iso.datetime().optional(),buyingId:m.uuid().optional(),membershipBusy:m.boolean().optional(),billingBusy:m.boolean().optional(),membershipReview:m.object({title:N,note:N,facts:m.array(m.object({label:N,value:N}).strict()).max(100)}).strict().optional(),membershipResult:N.optional()}).strict(),jn=m.object({nodes:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Lt)}).strict(),Dn=m.object({nodeId:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:m.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:m.string().max(100).optional()}).strict();function zn(e){return{source:e,status:"idle",stale:!0,preview:!1,resources:[],rows:[],hasNext:!1,hasPrevious:!1,page:1,filter:"all"}}function ge(e){let t=se(e).map(n=>`\u672A\u77E5\u53D8\u91CF\uFF1A${n}`);for(let n=0;n<e.length;n++){if(e[n]!=="<"||!/[A-Za-z!/?{]/.test(e[n+1]??""))continue;let i=n;if(e.startsWith("<!--",n)){let a=e.indexOf("-->",n+4);n=a<0?e.length:a+2}else{let a="";for(n++;n<e.length;n++){let c=e[n];if(a)c===a&&(a="");else if(c==='"'||c==="'")a=c;else if(c===">")break}}/\{\{|\}\}/.test(e.slice(i,n+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}function We(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function vn(e,t,n,i=!1){let a=ge(e);if(a.length)throw new Error(a[0]);let c=[...new Set(ae(e).filter(l=>!l.startsWith("variables.")&&t[l]===void 0))];return c.length&&!i?{value:We(n),missing:c}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(l,d)=>t[d.trim()]===void 0?l:We(t[d.trim()])),missing:c}}import{z as r}from"zod";var Tt=4,z={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},X=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),S=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),jt=r.enum(["none","xs","sm","md","lg","xl"]),Dt=r.enum(["none","sm","md","lg","full"]),be=r.string().regex(/^#[0-9a-fA-F]{6}$/),Je=r.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),ye=r.union([Je,r.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),r.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),r.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Ye=r.object({primary:be,background:be,text:be,radius:Dt,font:r.enum(["system","serif","rounded","mono"])}).strict(),J=r.union([r.enum(["primary","text","muted","background","surface"]),r.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),y=(e,t)=>r.number().int().min(e).max(t),Xe=r.union([r.enum(["fit","fill"]),y(1,1200)]),zt=r.object({top:y(0,200),right:y(0,200),bottom:y(0,200),left:y(0,200)}).strict(),Pt=r.object({top:y(-100,200),right:y(-100,200),bottom:y(-100,200),left:y(-100,200)}).strict(),et=r.object({x:y(0,100),y:y(0,100)}).strict(),wt=r.discriminatedUnion("type",[r.object({type:r.literal("color"),color:J}).strict(),r.object({type:r.literal("linear"),angle:y(0,360),stops:r.array(r.object({color:J,at:y(0,100)}).strict()).min(2).max(4)}).strict(),r.object({type:r.literal("image"),src:ye,fit:r.enum(["cover","contain"]),position:et.optional()}).strict()]),vt=r.discriminatedUnion("type",[r.object({type:r.literal("rect"),radius:r.union([y(0,200),r.object({topLeft:y(0,200),topRight:y(0,200),bottomRight:y(0,200),bottomLeft:y(0,200)}).strict()])}).strict(),r.object({type:r.literal("pill")}).strict()]),Ut=r.object({width:y(0,12),color:J,style:r.enum(["solid","dashed"])}).strict(),Vt=r.object({x:y(-40,40),y:y(-40,40),blur:y(0,80),spread:y(-20,40),color:J}).strict(),$t=r.object({font:r.enum(["system","serif","rounded","mono"]),size:y(8,96),weight:r.number().int().min(100).max(900).multipleOf(100),lineHeight:r.number().min(.8).max(3),letterSpacing:r.number().min(-5).max(20),color:J,align:r.enum(["start","center","end"]),italic:r.boolean(),decoration:r.enum(["none","underline","line-through"]),transform:r.enum(["none","uppercase"])}).strict().partial(),B=r.object({width:Xe,height:Xe,padding:zt,margin:Pt,gap:y(0,120),grow:r.union([r.boolean(),r.number().min(0).max(12)]),background:wt,opacity:r.number().min(0).max(1),clipContent:r.boolean(),shape:vt,border:Ut,shadow:Vt,text:$t}).strict().partial(),C={id:X,name:r.string().trim().min(1).max(60).optional(),hidden:r.boolean().optional(),style:B.optional(),fallback:S.optional()},Bt=r.object({...C,type:r.literal("text"),productField:r.enum(["name","price","trial","period"]).optional(),feature:r.object({id:r.uuid(),field:r.enum(["name","allowance"])}).strict().optional(),text:S,variant:r.enum(["title","heading","body","caption"])}).strict(),qt=r.object({...C,type:r.literal("image"),src:ye,localizedSrc:r.record(M,ye).optional(),alt:S,aspect:r.enum(["auto","1:1","4:3","16:9","3:1"]),fit:r.enum(["cover","contain"]),position:et.optional()}).strict(),Mt=r.object({...C,type:r.literal("button"),label:S,variant:r.enum(["primary","secondary","link"]),action:S,purpose:r.enum(["purchase","navigation","close"]).optional(),bind:fe.optional()}).strict(),Ft=r.object({...C,type:r.literal("divider")}).strict(),Zt=r.object({...C,type:r.literal("customer_data"),title:S,data:Ke}).strict(),Gt=r.object({...C,type:r.literal("spacer"),size:jt}).strict(),Ht=r.object({...C,type:r.literal("custom_html"),html:r.record(M,r.string().max(z.customHtml)),css:r.string().max(z.customCss)}).strict(),Kt=r.object({...C,type:r.literal("price"),fallback:S,parts:r.object({current:B.optional(),original:B.optional(),period:B.optional()}).strict().optional()}).strict(),Qt=r.object({...C,type:r.literal("coupon_code"),label:S,fallback:S}).strict(),Wt=r.object({...C,type:r.literal("countdown"),source:r.enum(["offer.ends_at","offer.expires_at","fixed"]),at:r.iso.datetime().optional(),granularity:r.enum(["day","hour","minute","second"]),expired:S,fallback:S}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Yt=r.object({...C,type:r.literal("plan_picker"),label:S,fallback:S,planIds:r.array(r.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:r.string().min(1).max(200).optional(),grouping:Ze.safeExtend({monthLabel:S,yearLabel:S,unavailableLabel:S}).optional(),states:r.object({selected:B.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Ge(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Xt=r.discriminatedUnion("type",[r.object({type:r.literal("input"),label:S,keyboard:r.enum(["text","email","tel","url"]),maxLength:y(1,500)}).strict(),r.object({type:r.literal("multiselect"),label:S,min:y(0,50),max:y(1,50)}).strict(),r.object({type:r.literal("select"),label:S,defaultIndex:y(0,49),purpose:r.enum(["option","product","tier"]).optional(),pickerId:X.optional(),selectedStyle:B.optional()}).strict(),r.object({type:r.literal("tabs"),label:S,defaultIndex:y(0,49),purpose:r.literal("tier").optional()}).strict(),r.object({type:r.literal("toggle"),label:S,defaultEnabled:r.boolean()}).strict(),r.object({type:r.literal("carousel"),label:S}).strict()]),D={...C,type:r.literal("stack"),direction:r.enum(["vertical","horizontal","overlay"]),align:r.enum(["start","center","end","stretch"]),justify:r.enum(["start","center","end","between"]),productSlot:r.object({index:y(0,19),period:r.enum(["month","year"]).optional(),requireBinding:r.boolean().optional()}).strict().optional(),interaction:Xt.optional(),states:r.object({selected:B.optional()}).strict().optional(),purpose:r.literal("benefits").optional(),purchaseAction:S.optional(),buttonVariant:r.enum(["primary","secondary","link"]).optional(),bind:fe.optional()},tt=r.lazy(()=>r.object({...C,type:D.type,direction:D.direction,align:D.align,justify:D.justify,children:r.array(Jt).max(z.children),productSlot:D.productSlot,interaction:D.interaction,states:D.states,purpose:D.purpose,purchaseAction:D.purchaseAction,buttonVariant:D.buttonVariant,bind:D.bind}).strict()),Jt=r.lazy(()=>r.union([tt,Bt,qt,Mt,Ft,Gt,Ht,Kt,Qt,Wt,Yt,Zt])),er=r.union([r.string().max(500),r.number().finite(),r.boolean(),r.null()]),Y={id:S,event:S,properties:r.record(S,er).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},tr=r.discriminatedUnion("type",[r.object({...Y,type:r.literal("navigate"),close:r.literal(!1),pageId:X}).strict(),r.object({...Y,type:r.literal("event"),close:r.boolean()}).strict(),r.object({...Y,type:r.literal("close"),close:r.literal(!0)}).strict(),r.object({...Y,type:r.literal("open_url"),close:r.boolean(),url:Je}).strict(),r.object({...Y,type:r.literal("claim_offer"),close:r.boolean(),couponId:r.uuid()}).strict()]),rr=r.object({defaultLocale:M,locales:r.record(M,r.record(S,r.string().max(z.stringLength)))}).strict(),nr=r.enum(["popup","paywall","onboarding","page","banner"]),Gn={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages",banner:"/workspace/banners"},ir=r.discriminatedUnion("type",[r.object({type:r.literal("modal"),size:r.enum(["sm","md","lg"])}).strict(),r.object({type:r.literal("sheet"),size:r.enum(["sm","md","lg"])}).strict(),r.object({type:r.literal("fullscreen")}).strict(),r.object({type:r.literal("inline")}).strict()]),Hn={sm:360,md:420,lg:560},or=r.object({kind:r.literal("screen"),schemaVersion:r.literal(Tt),name:r.string().trim().min(1).max(80),surface:nr,initialPageId:X.optional(),presentation:ir,theme:Ye,pages:r.array(r.object({id:X,name:r.string().trim().min(1).max(60),root:tt,theme:Ye.optional(),editorPosition:r.object({x:r.number().finite().min(-1e5).max(1e5),y:r.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(z.pages),strings:rr,actions:r.array(tr).max(z.actions)}).strict();function G(e,t){for(let n of e.pages)ee(n.root,t)}function Kn(e,t){return{...e,pages:e.pages.map((n,i)=>i===0?{...n,root:t}:n)}}var ar=or.superRefine((e,t)=>{let n=z;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(p=>p.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let p of e.actions)p.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(b=>b.id===p.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let i=p=>t.addIssue({code:"custom",message:p}),a=Object.keys(e.strings.locales);a.includes(e.strings.defaultLocale)||i("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),a.length>z.locales&&i(`\u6700\u591A ${z.locales} \u79CD\u8BED\u8A00`);let c=new Set;for(let p of e.actions)c.has(p.id)&&i(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${p.id}`),c.add(p.id);let l=new Set;for(let p of e.pages)["next","back"].includes(p.id)&&i(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${p.id}`),l.has(p.id)&&i(`\u9875\u9762 id \u91CD\u590D\uFF1A${p.id}`),l.add(p.id);let d=new Set,g=0,s=!1;G(e,(p,b)=>{if(g++,b>z.depth&&(s=!0),d.has(p.id)&&i(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${p.id}`),d.add(p.id),p.type==="button"&&!c.has(p.action)&&i(`\u6309\u94AE ${p.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${p.action}`),p.type==="custom_html")for(let h of Object.keys(p.html))a.includes(h)||i(`\u81EA\u5B9A\u4E49 HTML ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`);if(p.type==="image")for(let h of Object.keys(p.localizedSrc??{}))a.includes(h)||i(`\u56FE\u7247 ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`)}),g>n.nodes&&i(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),s&&i(`\u5C42\u7EA7\u6700\u591A ${z.depth} \u5C42`)});function ee(e,t,n=1,i=null){if(t(e,n,i)!==!1&&e.type==="stack")for(let a of e.children)ee(a,t,n+1,e)}function Se(e){let t=[],n=new Set;return G(e,i=>{let a=(c,l,d)=>{n.has(c)||(n.add(c),t.push({key:c,nodeId:i.id,nodeType:i.type,field:l,required:d}))};i.type==="stack"&&i.interaction&&a(i.interaction.label,"label",!0),i.fallback&&a(i.fallback,"text",!0),i.type==="text"&&a(i.text,"text",!0),i.type==="customer_data"&&a(i.title,"title",!0),(i.type==="plan_picker"||i.type==="coupon_code")&&a(i.label,"label",!0),i.type==="plan_picker"&&i.grouping&&(a(i.grouping.monthLabel,"label",!0),a(i.grouping.yearLabel,"label",!0),a(i.grouping.unavailableLabel,"text",!0)),i.type==="countdown"&&a(i.expired,"text",!0),i.type==="button"&&a(i.label,"label",!0),i.type==="image"&&(a(`image:${i.id}`,"src",!1),a(i.alt,"alt",!1)),i.type==="custom_html"&&a(`html:${i.id}`,"html",!0)}),t}function sr(e,t,n){if(t.field==="html"){let i;return G(e,a=>{a.id===t.nodeId&&a.type==="custom_html"&&(i=a.html[n])}),i}if(t.field==="src"){let i=he(e,t.nodeId);return i?.type==="image"?i.localizedSrc?.[n]??(n===e.strings.defaultLocale?i.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function rt(e){let t=Se(e).filter(i=>i.required);return Object.keys(e.strings.locales).sort((i,a)=>i===e.strings.defaultLocale?-1:a===e.strings.defaultLocale?1:0).map(i=>{let a=t.filter(c=>!sr(e,c,i)?.trim()).map(c=>c.key);return{locale:i,total:t.length,filled:t.length-a.length,missing:a,complete:a.length===0}})}function Qn(e){return nt(e,!0)}function Wn(e){return nt(e,!1)}function nt(e,t){let n=[],i=t&&e.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"));i&&(!e.actions.some(s=>s.type==="claim_offer")||e.actions.some(s=>s.type==="event"&&typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-")))&&n.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u8BF7\u5C06\u9886\u53D6\u6309\u94AE\u8BBE\u4E3A\u300C\u9886\u53D6\u4F18\u60E0\u300D\u5E76\u9009\u62E9\u751F\u6548\u4E2D\u7684\u5238");function a(s,p){let b=s.type==="stack"||s.type==="button"?s.bind?.coupon??p:p;if(i&&s.type==="text"&&Object.values(e.strings.locales).some(h=>h[s.text]?.includes("{{offer."))&&!b&&n.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u52A8\u6001\u6587\u6848\u9700\u8981\u7EE7\u627F\u4F18\u60E0\u5238\u7ED1\u5B9A"),s.type==="button"){let h=e.actions.find(w=>w.id===s.action);h?.type==="claim_offer"&&b&&b!==h.couponId&&n.push(`\u9886\u53D6\u6309\u94AE ${s.id} \u4E0E\u5C55\u793A\u5185\u5BB9\u7ED1\u5B9A\u4E86\u4E0D\u540C\u7684\u4F18\u60E0\u5238`)}s.type==="stack"&&s.children.forEach(h=>a(h,b))}e.pages.forEach(s=>a(s.root));let c=[],l=ar.safeParse(e);l.success||n.push(...l.error.issues.map(s=>s.message));for(let s of Object.values(e.strings.locales))for(let p of Object.values(s))for(let b of se(p))n.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${b}`);G(e,s=>{if(s.type==="customer_data"&&Object.values(e.strings.locales).some(b=>/\{\{|\}\}/.test(b[s.title]??""))&&n.push(`\u6570\u636E\u7EC4\u4EF6 ${s.id} \u7684\u6807\u9898\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),(s.type==="text"?[s.text]:s.type==="button"?[s.label]:[]).some(b=>Object.values(e.strings.locales).some(h=>h[b]?.includes("{{")))&&!s.fallback&&n.push(`\u7EC4\u4EF6 ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),s.fallback&&Object.values(e.strings.locales).some(b=>b[s.fallback]?.includes("{{"))&&n.push(`\u7EC4\u4EF6 ${s.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),s.type==="custom_html"){for(let b of Object.values(s.html))n.push(...ge(b).map(h=>`HTML ${s.id}\uFF1A${h}`));Object.values(s.html).some(b=>b.includes("{{"))&&!s.fallback&&n.push(`HTML ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{/.test(s.css)&&n.push(`HTML ${s.id} \u7684 CSS \u4E0D\u652F\u6301\u53D8\u91CF`)}(s.type==="stack"||s.type==="button")&&s.bind?.picker&&he(e,s.bind.picker)?.type!=="plan_picker"&&!Object.hasOwn(ce(e),s.bind.picker)&&n.push(`\u5BB9\u5668 ${s.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});for(let s of Object.keys(ce(e)))he(e,s)||n.push(`Product selection scope ${s} must reference a UI node`);let d=rt(e);for(let s of d)s.complete||(s.locale===e.strings.defaultLocale?n.push(`\u9ED8\u8BA4\u8BED\u8A00 ${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):n.push(`${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u6CA1\u7FFB\u8BD1\uFF0C\u8BF7\u8865\u9F50\u6216\u5220\u9664\u8FD9\u79CD\u8BED\u8A00\u540E\u53D1\u5E03`));Se(e).length===0&&!e.pages.some(s=>cr(s.root))&&n.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let g=new Set;G(e,s=>{s.type==="button"&&g.add(s.action)});for(let s of e.actions)!g.has(s.id)&&!e.pages.some(p=>lr(p.root,s.id))&&c.push(`\u52A8\u4F5C ${s.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:n,warnings:c}}function cr(e){let t=!1;return ee(e,n=>{if(n.hidden)return!1;n.type==="image"&&(t=!0)}),t}function lr(e,t){let n=!1;return ee(e,i=>{if(i.type==="custom_html")for(let a of Object.values(i.html))a.includes(`data-grow-action="${t}"`)&&(n=!0)}),n}function ur(e){return rt(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Yn(e,t){return Te(t,ur(e),e.strings.defaultLocale)}function Xn(e,t){let n=e.strings.locales[t]??{},i=e.strings.locales[e.strings.defaultLocale]??{},a={};for(let l of Se(e)){if(l.field==="html"||l.field==="src")continue;let d=n[l.key]?.trim()?n[l.key]:i[l.key];d!==void 0&&(a[l.key]=d)}let c=l=>{if(l.type==="stack")return{...l,children:l.children.map(c)};if(l.type==="custom_html"){let d=l.html[t]?.trim()?l.html[t]:l.html[e.strings.defaultLocale];return{...l,html:d===void 0?{}:{[t]:d}}}if(l.type==="image"){let{localizedSrc:d,...g}=l;return{...g,src:d?.[t]??d?.[e.strings.defaultLocale]??l.src}}return l};return{...e,pages:e.pages.map(l=>({...l,root:c(l.root)})),strings:{defaultLocale:t,locales:{[t]:a}}}}function pr(e,t){let n=null;return ee(e,i=>{if(n)return!1;i.id===t&&(n=i)}),n}function he(e,t){for(let n of e.pages){let i=pr(n.root,t);if(i)return i}return null}function Jn(e){let t=de(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function ei(e,t,n){let i={};if(!t||typeof t!="object"||Array.isArray(t))return i;let a=t;if(G(e,c=>{if(c.type==="plan_picker"){let d=a[c.id];typeof d=="string"&&(i[c.id]=n?.pickers[c.id]?.options.includes(d)?d:"");return}if(c.type!=="stack"||!c.interaction)return;let l=Object.hasOwn(a,c.id)?a[c.id]:void 0;["select","tabs"].includes(c.interaction.type)&&typeof l=="string"&&c.children.some(d=>d.id===l)&&(i[c.id]=l),c.interaction.type==="toggle"&&typeof l=="boolean"&&(i[c.id]=l)}),e.surface==="paywall"&&typeof a.__page=="string"&&e.pages.some(c=>c.id===a.__page)&&(i.__page=a.__page),n){let c={...i};for(let[l,d]of Object.entries(a))(typeof d=="string"||typeof d=="boolean")&&(c[l]=d);Object.assign(i,Me(e,c,n))}return i}import{z as I}from"zod";var oi=I.discriminatedUnion("kind",[I.object({kind:I.literal("ledger"),cursor:oe}).strict(),I.object({kind:I.literal("billing"),cursor:I.uuid()}).strict()]),mr=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),dr=I.record(I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),I.union([I.string().max(500),I.boolean(),I.array(I.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),fr=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function xe(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>xe(n,t+1)):Object.entries(e).some(([n,i])=>["__proto__","constructor","prototype"].includes(n)||fr.test(n)||xe(i,t+1)))}var gr=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,br=I.record(mr,ue).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!xe(e)&&!gr.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function ai(e){let t=Object.create(null);for(let[n,i]of new URL(e).searchParams)I.string().max(500).parse(i),Object.hasOwn(t,n)||(t[n]=i);return br.parse(t),t}var it=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yr=I.array(I.object({variable:it,componentId:it,required:I.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),si=I.object({bindings:yr,answers:dr,values:I.record(I.string(),ue).optional()}).strict();export{te as a,Sr as b,xr as c,ot as d,at as e,Ee as f,_r as g,Ie as h,st as i,Ir as j,ct as k,Ae as l,lt as m,Er as n,Ar as o,Nr as p,pt as q,O as r,pe as s,kr as t,Cr as u,Lr as v,re as w,E as x,mt as y,V as z,L as A,ke as B,dt as C,ft as D,gt as E,Dr as F,M as G,de as H,Te as I,ht as J,wr as K,ne as L,$r as M,St as N,Q as O,De as P,ie as Q,Br as R,qr as S,ze as T,Gr as U,Pe as V,P as W,Jr as X,we as Y,oe as Z,en as _,Et as $,tn as aa,ve as ba,on as ca,an as da,sn as ea,Ue as fa,Ve as ga,yn as ha,Nt as ia,Rt as ja,$e as ka,hn as la,Ot as ma,fe as na,Be as oa,En as pa,ae as qa,se as ra,An as sa,Nn as ta,qe as ua,ce as va,Me as wa,Ze as xa,Ge as ya,kt as za,He as Aa,Ke as Ba,Lt as Ca,jn as Da,Dn as Ea,zn as Fa,ge as Ga,We as Ha,vn as Ia,Tt as Ja,z as Ka,X as La,S as Ma,jt as Na,Dt as Oa,ye as Pa,Ye as Qa,J as Ra,Xe as Sa,zt as Ta,Pt as Ua,et as Va,wt as Wa,vt as Xa,Ut as Ya,Vt as Za,$t as _a,B as $a,Bt as ab,qt as bb,Mt as cb,Ft as db,Zt as eb,Gt as fb,Ht as gb,Kt as hb,Qt as ib,Wt as jb,Yt as kb,Xt as lb,tt as mb,Jt as nb,tr as ob,rr as pb,nr as qb,Gn as rb,ir as sb,Hn as tb,G as ub,Kn as vb,ar as wb,ee as xb,Se as yb,sr as zb,rt as Ab,Qn as Bb,Wn as Cb,ur as Db,Yn as Eb,Xn as Fb,pr as Gb,he as Hb,Jn as Ib,ei as Jb,oi as Kb,dr as Lb,br as Mb,ai as Nb,yr as Ob,si as Pb};