@tinkerlandai/indiana-sdk 0.5.0 → 0.6.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.
- package/CHANGELOG.md +22 -1
- package/README.md +177 -8
- package/README.zh-CN.md +94 -6
- package/dist/{ai-usage-BzydP8eN.d.ts → ai-usage-B4W5m4Ie.d.ts} +21 -4
- package/dist/chunk-4JBIKJMU.js +4 -0
- package/dist/chunk-5TEZEOHX.js +1 -0
- package/dist/chunk-5WY3AXSS.js +1 -0
- package/dist/chunk-HU2HIDVT.js +11 -0
- package/dist/chunk-OHDY27EI.js +1 -0
- package/dist/chunk-OK2Q6IJD.js +1 -0
- package/dist/chunk-PCVQHHEE.js +1 -0
- package/dist/chunk-RMJJOSVZ.js +1 -0
- package/dist/chunk-S2MSIA57.js +17 -0
- package/dist/chunk-S5TVMQRC.js +1 -0
- package/dist/configuration-sync-Bnu8s4pc.d.ts +1314 -0
- package/dist/{customer-page-aZb5Twue.d.ts → customer-page-B4FGCVpt.d.ts} +3 -0
- package/dist/funnel-runtime-host-L3WILUHK.js +1 -0
- package/dist/funnel-runtime-start-Zbd5ro5r.d.ts +30920 -0
- package/dist/{growth-rules-D64pEvg9.d.ts → growth-rules-B4YYy64R.d.ts} +8 -1
- package/dist/index.d.ts +14950 -5193
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +6 -8
- package/dist/page.js +1 -1
- package/dist/paywall-TCE5DE5T.js +1 -0
- package/dist/popup.d.ts +5 -2
- package/dist/popup.js +6 -6
- package/dist/server.d.ts +4 -3
- package/dist/server.js +1 -1
- package/dist/src-VGIVVM27.js +1 -0
- package/dist/{visual-editor-agent-FDCV3BXP.js → visual-editor-agent-WW65CMKW.js} +1 -1
- package/dist/visual.d.ts +4 -2
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3OSMEG44.js +0 -17
- package/dist/chunk-GA6X57BO.js +0 -1
- package/dist/chunk-GTBD4BJ4.js +0 -11
- package/dist/chunk-QUW4UOKZ.js +0 -4
- package/dist/chunk-RMFH5TWV.js +0 -1
- package/dist/chunk-YNUVRZRQ.js +0 -1
- package/dist/funnel-runtime-host-RZRB2CY6.js +0 -1
- package/dist/funnel-runtime-start-JHA9ES24.d.ts +0 -9199
- package/dist/paywall-MYBEOVTQ.js +0 -1
- package/dist/src-E2GXK6WA.js +0 -1
- /package/dist/{chunk-ZT523F45.js → chunk-BIFEEVQO.js} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as ge}from"./chunk-OK2Q6IJD.js";import{a as l}from"./chunk-5TEZEOHX.js";import{a as Ne}from"./chunk-S5TVMQRC.js";import{Bf as Ge,Ck as xe,Dk as k,Ei as Qe,Ek as Xe,Fk as en,Gd as Me,Gk as nn,Hi as be,Hk as tn,Ig as Be,Ii as Ye,Ik as rn,Kg as Je,Kk as De,Lg as ze,Ng as He,Pk as on,Qh as _e,Rh as Te,Tg as Ke,Vf as ce,ag as je,ak as Ze,ni as te,xf as Ue,xi as Ae,xk as H,yf as qe,yi as $e,yk as We}from"./chunk-HU2HIDVT.js";import{b as ke,h as me}from"./chunk-OHDY27EI.js";import{f as Ce,j as Se,l as Oe,m as he}from"./chunk-S2MSIA57.js";function An(e){let n=null,i=null,o=0,d=0,p=new Set,r=null,a=null,t=new Set,s=()=>{for(let h of t)try{h()}catch{}},g={attributes:he.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(h,F)=>{!p.has(h)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(h,structuredClone(F))}:void 0,onExperimentViewed:e.onExperimentViewed?(h,F)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(h),structuredClone(F)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?h=>e.saveStickyBucketAssignmentDoc(structuredClone(h)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function R(h,F=new Set){return p.has(h)?!r||!r.features[h]||["unknownFeature","cyclicPrerequisite"].includes(r.features[h].source):F.has(h)?!1:(F.add(h),(n?.features[h]?.rules??[]).some(E=>[...E.parentConditions??[],...(E.tracks??[]).flatMap(x=>x.experiment.parentConditions??[])].some(x=>R(x.id,F))))}let A=h=>{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,g.features=n.features),p.has(h)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?w():structuredClone(r.features[h]??w()):R(h)?w():structuredClone(Se(h,g))};async function c(){if(!n||!p.size)return;if(!e.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let h=d;if(a?.revision===h)return a.loading;let F=o,E=n,x=[...p],_=(async()=>{let D=Ge.parse(await e.evaluateRemote({attributes:structuredClone(g.attributes),features:x}));if(!(F!==o||h!==d||E!==n)){if(e.assertUsable?.(E.generation),D.generation!==E.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(x.some(M=>!Object.hasOwn(D.features,M))||Object.keys(D.features).some(M=>!p.has(M)))throw new Error("Invalid remote Feature results");r=structuredClone(D),g.features={...E.features,...Object.fromEntries(Object.entries(r.features).map(([M,j])=>[M,{defaultValue:j.value}]))},s()}})();a={revision:h,loading:_};try{await _}finally{a?.loading===_&&(a=null)}}function N(){c().catch(h=>{try{e.onError?.(h)}catch{}})}async function b(){if(i)return i;let h=o,F=(async()=>{let E=await e.load(),x="remoteFeatures"in E?Ue.parse(E):null,_=x??me.parse(E);if(_.scope.projectId!==e.scope.projectId||_.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(h!==o)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===_.generation){let{evaluatedAt:M,expiresAt:j,...oe}=n,{evaluatedAt:X,expiresAt:ee,...f}=_;if(k(oe)!==k(f))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=_.evaluatedAt,n.expiresAt=_.expiresAt,s(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&N(),structuredClone(n)}let D=new Set(x?.remoteFeatures??[]);if([...D].some(M=>Object.hasOwn(_.features,M)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in _&&!n.analyticsConfig.experimentViewsEnabled&&x?.analyticsConfig.experimentViewsEnabled&&g.trackedExperiments?.clear(),n=structuredClone(_),p=D,r=null,a=null,d++,g.features=n.features,g.savedGroups=Ce(n.savedGroups),g.trackedFeatureUsage={},s(),N(),structuredClone(n)})();i=F;try{return await F}finally{i===F&&(i=null)}}return{init:b,refresh:b,refreshRemote:c,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(h){return t.add(h),()=>{t.delete(h)}},setAttributes(h){g.attributes=he.parse(h),d++,r=null,a=null,g.features=n?.features??{},g.trackedFeatureUsage={},s(),N()},evalFeature:A,isOn(h){return A(h).on},isOff(h){return A(h).off},getFeatureValue(h,F){let E=A(h).value;return structuredClone(E===null?F:E)},reset(){o++,d++,i=null,a=null,n=null,r=null,p.clear(),g.features={},g.savedGroups={},g.stickyBucketAssignmentDocs={},g.attributes={},g.trackedFeatureUsage={},g.trackedExperiments?.clear(),s()}}}function an(e){let n=new Map(e.topology.nodes.map(d=>[d.id,d])),i=Ce(e.growth.savedGroups);function o(d,p){if(!Object.hasOwn(e.growth.features,d))throw new l("INVALID_RESPONSE","Required GB Feature is unavailable");return Se(d,p).value}return{nodes:n,savedGroups:i,features:e.growth.features,feature:o,evaluate(d,p){let r=n.get(d);if(!r)throw new l("NOT_FOUND","Funnel node is unavailable");let a,t;if(r.type==="condition"){let g=e.conditions[r.id];if(!g)throw new l("INVALID_RESPONSE","Local condition rules are unavailable");a=_e({id:r.id,name:r.id,type:"condition",cases:g.map(w=>({condition:w.condition,target:r.outputs[w.port]})),default:r.outputs.default},p,e.growth.experiments).port}else if(r.type==="feature"){if(!r.resources.featureKey)throw new l("INVALID_RESPONSE","Feature reference is unavailable");t=o(r.resources.featureKey,p),a="next"}else if(r.type==="split"){if(!(r.resources.experimentId?e.growth.experiments[r.resources.experimentId]:void 0))throw new l("INVALID_RESPONSE","Experiment reference is unavailable");let w=_e({id:r.id,name:r.id,type:"split",experimentId:r.resources.experimentId,routes:r.outputs,notParticipating:r.outputs.notParticipating},p,e.growth.experiments);t=w.value,a=w.port}else if(["offering","end","output"].includes(r.type)&&r.resources.featureKey)t=o(r.resources.featureKey,p),a=r.type==="offering"?"next":"value";else throw new l("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let s=r.outputs[a]??(a==="value"?r.id:void 0);if(!s)throw new l("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:a,target:s,...t===void 0?{}:{value:t}}}}}function sn(e,n,i){let o=Qe.parse(e);if(o.evaluationMode!=="local")throw new l("EVALUATION_MODE","Remote nodes are evaluated by Grow");if(o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())throw new l("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition");let d=an(o),r={attributes:he.parse(i.attributes??{}),saveStickyBucketAssignmentDoc:i.saveStickyBucketAssignmentDoc?a=>i.saveStickyBucketAssignmentDoc(structuredClone(a)):void 0,onFeatureUsage:i.onFeatureUsage?(a,t)=>i.onFeatureUsage(a,structuredClone(t)):void 0,onExperimentViewed:i.onExperimentViewed?(a,t)=>i.onExperimentViewed(structuredClone(a),structuredClone(t)):void 0,features:d.features,savedGroups:d.savedGroups,stickyBucketAssignmentDocs:structuredClone(i.stickyBucketAssignmentDocs)};return d.evaluate(n,r)}function un(e){let n,i,o=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),d=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,i=e.locks??globalThis.navigator?.locks,!n||!i||!globalThis.crypto?.subtle)throw o();let a=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??Ne).href,e.runToken])),t=new Uint8Array(await crypto.subtle.digest("SHA-256",a));return"indiana.funnel.commands.v1."+Array.from(t,s=>s.toString(16).padStart(2,"0")).join("")});d.catch(()=>{});async function p(a){try{let t=await d;return await i.request(t,{mode:"exclusive"},()=>a(t))}catch(t){throw t instanceof l?t:o()}}function r(a){let t=n.getItem(a);if(t===null)return{revision:0,entry:null};if(t.length>1048576)throw o();let s=JSON.parse(t);if(!s||typeof s!="object"||!("revision"in s)||!("entry"in s)||!Number.isSafeInteger(s.revision)||Number(s.revision)<0)throw o();return{revision:Number(s.revision),entry:s.entry}}return{read:()=>p(r),write:(a,t)=>p(s=>{if(r(s).revision!==a)return null;if(!Number.isSafeInteger(a+1))throw o();return n.setItem(s,JSON.stringify({revision:a+1,entry:t})),a+1})}}function kn(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ye(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((d,p)=>ye(d,n[p]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let i=Object.entries(e),o=Object.entries(n);return i.length===o.length&&i.every(([d,p])=>Object.hasOwn(n,d)&&ye(p,Reflect.get(n,d)))}function Fe(e,n,i){let o=[],d=[],p=[],r=sn(e,n,{attributes:i.attributes,stickyBucketAssignmentDocs:i.sticky,saveStickyBucketAssignmentDoc(a){let t=a.attributeName+"||"+a.attributeValue,s=o.findIndex(w=>w.next.attributeName===a.attributeName&&w.next.attributeValue===a.attributeValue),g={expected:i.sticky[t]??null,next:a};s<0?o.push(g):o[s]=g},onExperimentViewed(a,t){t.inExperiment&&t.hashUsed&&!t.passthrough&&d.push(Oe.parse({key:a.key,variationId:t.variationId,keyUsed:t.key,hashAttribute:t.hashAttribute,hashValue:t.hashValue}))},onFeatureUsage(a,t){p.push(Oe.parse({feature:a,value:t.value,source:t.source,...t.ruleId?{ruleId:t.ruleId}:{}}))}});return{port:r.port,...r.value===void 0?{}:{value:r.value},sticky:o,exposures:d,features:p}}async function ln(e,n){let i=n.instruction;if(i?.type!=="evaluate")throw new Error("Evaluation instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require the shared public configuration manager");let o=await e.funnel(n.source.id,n.source.versionId);if(!o.growth||o.control.evaluationMode!=="local"||o.control.evaluationRevision!==i.policyRevision)throw new l("EVALUATION_MODE","Refresh the original Funnel evaluation policy");let{analyticsConfig:d,remoteFeatures:p,...r}=o.growth,a=be({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:o.document,payload:me.parse(r)});if(e.scope.environmentId!==i.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let t=Fe(a,n.nodeId,i);return e.assertFunnel(n.source.id,void 0,n.source.versionId),{generation:o.manifest.generation,result:t}}async function cn(e,n){let i=n.instruction;if(i?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");let o=await e.funnel(n.source.id,n.source.versionId);if(!o.growth||o.control.evaluationMode!=="local"||o.control.evaluationRevision!==i.policyRevision)throw new l("EVALUATION_MODE","Refresh the original Funnel evaluation policy");if(e.scope.environmentId!==i.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let{analyticsConfig:d,remoteFeatures:p,...r}=o.growth,a=be({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:o.document,payload:me.parse(r)}),t=hn(a,o.document,{...n,...i});return e.assertFunnel(n.source.id,void 0,n.source.versionId),{...t,generation:o.manifest.generation,policyRevision:i.policyRevision}}function hn(e,n,i){let o=i,d=new Map(n.graph.nodes.map(A=>[A.id,A])),p=structuredClone(i.variables),r=structuredClone(o.sticky),a=[],t=e.evaluationMode==="local"&&on(e.growth),s=i.nodeId,g=i.visit,w=!1;for(let A=0;A<rn;A++){let c=d.get(s);if(!c||!De(c))break;if(g>=n.execution.maxTransitions)throw new l("TRANSITION_LIMIT","Local Funnel transition budget exceeded");let N={attributes:c.type==="condition"?He({declarations:n.variables,attributes:o.attributes,parameters:i.parameters,answers:i.answers,results:p,savedGroups:{}}):{...o.attributes,parameters:i.parameters,answers:i.answers,results:p},sticky:r},b,h;if(["condition","feature","split"].includes(c.type)||c.type==="offering"&&c.configuration.source==="feature")b=Fe(e,c.id,N),c.type==="offering"&&(b.value={type:"offering_version",id:String(b.value)}),c.type==="condition"?h=b.port==="default"?c.default:c.cases[Number(b.port.slice(5))]?.target:c.type==="split"?h=b.port==="notParticipating"?c.notParticipating:c.routes[b.port]:(c.type==="feature"||c.type==="offering")&&(h=c.next);else if(b={port:"next",sticky:[],exposures:[],features:[]},(c.type==="entry"||c.type==="coupon"||c.type==="coupons")&&(h=c.next),c.type==="offering"&&c.configuration.source==="fixed"&&(b.value={type:"offering_version",id:c.configuration.versionId},h=c.next),c.type==="end"||c.type==="output"){let E=c.type==="end"?c.output:c.value;if(b=E?.type==="feature"?Fe(e,c.id,N):{...b,port:"value",value:E?.type==="literal"?E.value:E?.type==="variable"?Ke({source:"variable",key:E.key,...E.path?{path:E.path}:{}},{declarations:n.variables,answers:i.answers,results:p,parameters:i.parameters,attributes:o.attributes,savedGroups:{}}):null},E&&(b.value===void 0||!Be(n.outputSchema,b.value)))throw new l("INVALID_RESPONSE","Local terminal violates its declared output")}let F=[...a,{nodeId:s,result:b}];if(je({steps:F})>6e4){if(!a.length)throw new l("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:s,result:b}),c.type==="feature"||c.type==="offering"||c.type==="coupon"||c.type==="coupons"){let E=c.type==="coupons"?c.couponIds.map(_=>({type:"reward",id:_})):c.type==="coupon"?{type:"reward",id:c.couponId}:b.value;if(E===void 0)throw new l("INVALID_RESPONSE","Node output is missing");let x=Je(c,{value:E});ze(n.variables,c,x),Object.assign(p,x)}for(let E of b.sticky)r[`${E.next.attributeName}||${E.next.attributeValue}`]=structuredClone(E.next);if(c.type==="end"||c.type==="output"){w=!0;break}if(!h)throw new l("INVALID_RESPONSE","Local pure exit is unavailable");if(s=h,g++,t&&["feature","offering","coupon","coupons"].includes(c.type))break}let R=d.get(s);return{steps:a,...!w&&R&&!De(R)?{boundary:{nodeId:s,visit:g}}:{}}}import{z as Q}from"zod";var dn=te.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 l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),fn=Q.strictObject({schemaVersion:Q.literal(1),scope:ke,runId:Q.uuid(),funnelId:Q.uuid(),versionId:Q.uuid(),command:dn.optional(),closeCommand:dn.refine(e=>e.operation==="close").optional(),purchase:Q.strictObject({receiptId:Q.uuid(),operationId:Q.uuid(),generation:Q.number().int().nonnegative()}).optional(),closed:Q.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"),B=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Pe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function pn(e){let n=0,i=null,o=t=>JSON.stringify([t.scope,t.runId,t.funnelId,t.versionId]),d=Promise.resolve();async function p(){let t=await e.read();if(!Number.isSafeInteger(t.revision)||t.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:t.revision,entry:t.entry===null?null:fn.parse(t.entry)}}function r(t){let s=d.then(t);return d=s.catch(()=>{}),s}async function a(t){for(let s=0;s<4;s++){let g=await p();if(g.entry&&i!==null&&o(g.entry)!==i)throw B();let w=t(g.entry,g.revision);if(Pe(g.entry,w)){n=g.revision;return}let R=await e.write(g.revision,w);if(R!==null){if(!Number.isSafeInteger(R)||R<=g.revision)throw B();n=R;return}}throw B()}return{bind(t){let s=JSON.stringify([t.scope,t.runId,t.funnelId,t.versionId]);if(i!==null&&i!==s)throw B();i=s},async load(){let t=await p();return n=t.revision,i=t.entry?o(t.entry):null,t.entry},retain(t){let s=fn.parse(t),g=s.command;return!g||i!==null&&o(s)!==i?Promise.reject(B()):(i??=o(s),r(()=>a((w,R)=>{if(w&&!Pe(o(w),o(s)))throw B();if(!w){if(R!==n&&g.operation!=="close")throw B();return s}if(!w.command)return{...w,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&w.command.operation!=="close"){if(w.command.requestId===g.requestId||w.closeCommand&&!Pe(w.closeCommand,g))throw B();return{...w,closeCommand:g,closed:!0}}if(!Pe(w.command,g))throw B();return w})))},observePurchase(t,s,g){return r(()=>a((w,R)=>{if(!w&&R!==n||w&&o(w)!==o({...t,schemaVersion:1}))throw B();if(w?.purchase&&w.purchase.generation>s.generation)return w;if(w?.purchase&&w.purchase.generation===s.generation&&w.purchase.operationId!==s.operationId)throw B();return g?!w?.purchase||w.purchase.operationId!==s.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...t,...w,purchase:s}}))},settle(t){return r(()=>a(s=>s?s.command&&"requestId"in s.command&&s.command.requestId===t?s.closeCommand?{...s,command:s.closeCommand,closeCommand:void 0}:s.purchase?{...s,command:void 0}:null:s.closeCommand&&"requestId"in s.closeCommand&&s.closeCommand.requestId===t?{...s,closeCommand:void 0}:s:null))}}}function de(e){let{customerToken:n,...i}=e;return i}var vn=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function mn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let n=ge({...e,...e.serverKey?{fetch:(f,m)=>{let P=new Headers(m?.headers);return P.set($e,e.serverKey),(e.fetch??globalThis.fetch)(f,{...m,headers:P})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let i,o=null,d=0,p=0,r=null,a=null,t=!1,s=null,g=!1,w=null,R=new Set,A=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?un(e):void 0),c=A&&pn(A),N,b=null,h=!1,F=c?c.load().then(f=>{if(h)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(b=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(N=f.purchase,t=f.closed===!0,!f.command)return;let m=te.parse(f.command);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");r=m,f.closeCommand&&(a=f.closeCommand,t=!0),m.operation==="close"&&(t=!0),g=!0}):Promise.resolve();F.catch(()=>{});async function E(f,m,P){c&&await F;let U=d,Y=o,u=Ae.parse(await n.request("funnels",te.parse(f)));if(f.operation==="review"&&!u.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(U!==d)throw new l("IDENTITY_CHANGED","Run identity changed during the request");if(u.runToken&&u.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let J=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(J&&u.settlement?.requestId!==J)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");if(b&&(u.run.id!==b.runId||u.run.source.id!==b.funnelId||u.run.source.versionId!==b.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version");if(o&&(u.run.id!==o.id||u.run.source.type!==o.source.type||u.run.source.id!==o.source.id||u.run.source.versionId!==o.source.versionId||u.run.locale!==o.locale||!ye(u.run.parameters,o.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e.funnelId&&u.run.source.id!==e.funnelId)throw new l("INVALID_RESPONSE","Run belongs to another Funnel");c?.bind({scope:u.scope,runId:u.run.id,funnelId:u.run.source.id,versionId:u.run.source.versionId}),A&&!e.scope&&(e.scope=u.scope);let K=u.run.paywall,z=K??u.purchase,fe=z?.operation,pe=u.settlement&&(!K||K.purchaseRequestId===u.settlement.requestId)&&(!N||N.operationId===u.settlement.operationId)?u.settlement:void 0,ie=fe?.operationId??z?.quote?.operationId??pe?.operationId,ae=z?.receiptId??pe?.receiptId,we=K?.selectionGeneration??N?.generation??0;if(c&&ie&&ae&&f.operation!=="review"&&(!o||u.run.revision>=o.revision)&&(P===void 0||P>=p)&&(!N||we>=N.generation)){let $={receiptId:ae,operationId:ie,generation:we},Ee=fe?.status==="complete"||z?.canReselect===!0;await c.observePurchase({scope:u.scope,runId:u.run.id,funnelId:u.run.source.id,versionId:u.run.source.versionId},$,Ee),Ee?N?.operationId===$.operationId&&(N=void 0):N=$}if(!u.run.stopped&&["running","waiting"].includes(u.run.status)&&f.operation==="get"&&f.settlementRequestId)return u;let se=m?.(u),Ie=typeof se=="boolean"?se:se?await se:!1;if(["running","waiting"].includes(u.run.status)||(t=!0),f.operation==="review"&&o&&o!==Y&&u.run.revision<=o.revision||o&&u.run.revision===o.revision&&P!==void 0&&P<p||(f.operation==="review"&&!u.run.stopped&&["running","waiting"].includes(u.run.status)&&o&&u.run.nodeId===o.nodeId&&u.run.visit===o.visit&&u.run.revision===o.revision&&(u.run.screen=o.screen,(o.paywall?.quote?.operationId===u.review?.activeOperationId||!o.paywall?.quote&&u.review?.activeOperationId===null)&&(u.run.paywall=o.paywall)),o?.paywall&&u.run.paywall&&o.paywall.receiptId===u.run.paywall.receiptId&&(u.run.paywall.selectionGeneration??0)<(o.paywall.selectionGeneration??0)))return u;if(!o||u.run.revision>=o.revision)o=u.run;else if(!Ie)return u;if(o)for(let $ of R)try{$(structuredClone(o))}catch{}return u}async function x(f=r){if(c&&await F,!f)throw new l("INVALID_REQUEST","No command is pending");let m=f,P=d;if(c){if(!o||!e.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await c.retain({schemaVersion:1,scope:e.scope,runId:o.id,funnelId:o.source.id,versionId:o.source.versionId,command:de(m)})}if(P!==d||r!==m&&a!==m)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let U={...m,...i?{customerToken:i}:{}},Y=g;g=!0;try{return await E(U,u=>{if(!u.settlement)throw new l("INVALID_RESPONSE","Exact command settlement is missing");if(u.settlement.requestId!==m.requestId)throw new l("INVALID_RESPONSE","Command settlement identity changed");if(P===d&&(r===m||a===m)&&u.run.pendingRequest?.requestId!==m.requestId&&u.settlement.state==="settled"&&(!t||m.operation==="close"||u.settlement?.state==="settled"&&!["running","waiting"].includes(u.run.status))){let J=()=>P!==d||r!==m&&a!==m?!1:(r===m&&(r=null),a===m&&(a=null),g=r!==null,b=null,!0);return c?c.settle(m.requestId).then(J):J()}return!1})}catch(u){throw P===d&&r===m&&!Y&&!vn(u)&&(c&&await c.settle(m.requestId),P===d&&r===m&&(r=null,g=!1,b=null)),u}}function _(f){let m=te.parse(f);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(o?.recoveryRestricted&&m.operation!=="close"&&m.operation!=="resume"&&r?.requestId!==m.requestId)throw new l("PRECONDITION_FAILED","Original Run requires restricted recovery");if(t&&m.operation!=="close"){if(r?.requestId===m.requestId)return ee.settle(m.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"&&r?.operation!=="close"){if(t=!0,a&&JSON.stringify(de(a))!==JSON.stringify(de(m)))throw new l("COMMAND_PENDING","Retry the original Close");if(a??=m,s)return s;let U=x(a);return s=U,U.then(()=>{s===U&&(s=null)},()=>{s===U&&(s=null)}),U}if(r){if(JSON.stringify(de(r))!==JSON.stringify(de(m)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(w)return w}else r=m,g=!1;let P=x();return w=P,P.then(()=>{w===P&&(w=null)},()=>{w===P&&(w=null)}),P}let D=null,M=new WeakMap;function j(f){let m=M.get(f);if(m)return m;let P=X(f);return M.set(f,P),P}let oe=!1;async function X(f){let m=await f;if(m.run.recoveryRestricted||!["evaluate","evaluate_segment"].includes(m.run.instruction?.type??""))return m;if(D)return D;oe=!0;let P=d,U=(async()=>{for(let Y=0;Y<32&&["evaluate","evaluate_segment"].includes(m.run.instruction?.type??"");Y++){if(r||t)return m;let u=m.run,J=m.run.instruction;if(J?.type==="evaluate_segment"){let z=await cn(e.configuration,u);if(P!==d)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r||t)return m;if(o&&(o.revision!==u.revision||o.visit!==u.visit||o.nodeId!==u.nodeId))return E({operation:"get",...i?{customerToken:i}:{}});m=await _({operation:"commit_segment",requestId:Te(u.id,u.visit,`segment:${u.revision}`),nodeId:u.nodeId,visit:u.visit,revision:u.revision,...z});continue}if(J?.type!=="evaluate")return m;let K=await ln(e.configuration,u);if(P!==d)throw new l("IDENTITY_CHANGED","Run identity changed during evaluation");if(r||t)return m;if(o&&(o.revision!==u.revision||o.visit!==u.visit||o.nodeId!==u.nodeId))return E({operation:"get",...i?{customerToken:i}:{}});m=await _({operation:"evaluate",requestId:Te(u.id,u.visit,"evaluation"),nodeId:u.nodeId,visit:u.visit,revision:u.revision,receiptId:J.receiptId,policyRevision:J.policyRevision,...K})}return m})();D=U;try{return await U}finally{D===U&&(D=null)}}let ee={get configuration(){return oe?e.configuration:void 0},get configurationReady(){return!0},get view(){return o?structuredClone(o):null},get pendingCommand(){let f=a??r;return f?structuredClone(de(f)):null},get pendingCommands(){return[r,a].filter(f=>f!==null).map(f=>structuredClone(de(f)))},get pendingPurchase(){return N?structuredClone(N):null},async settle(f){let m=await E({operation:"get",settlementRequestId:f,...i?{customerToken:i}:{}});if(m.settlement?.requestId!==f)throw new l("INVALID_RESPONSE","Exact command settlement is missing");return m.settlement.state==="settled"&&(c&&await c.settle(f),r?.requestId===f&&(r=null,g=!1),a?.requestId===f&&(a=null)),m},get webViewUrl(){return n.webViewUrl()},review(f){return E({operation:"review",...f?{receiptId:f}:{},...i?{customerToken:i}:{}},void 0,++p)},async get(f,m){c&&await F,m??=N&&{receiptId:N.receiptId,operationId:N.operationId};let P=++p;return j(E({operation:"get",...f?{data:f}:{},...m?{purchase:m}:{},...i?{customerToken:i}:{}},void 0,P))},resume(f=o?.pendingRequest?.requestId){return f?t?ee.settle(f):r?.requestId===f?j(_(r)):j(_({operation:"resume",requestId:f})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(f){return j(_(f))},retry(){return s||(a?x(a):t&&r?ee.settle(r.requestId):w?j(w):r?j(_(r)):Promise.reject(new l("INVALID_REQUEST","No command is pending")))},identify(f){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(f))throw new l("INVALID_TOKEN","Customer credential required");d++,i=f,n.identify(e.runToken)},subscribe(f){return R.add(f),()=>R.delete(f)},reset(){h=!0,d++,i=void 0,o=null,r=null,a=null,s=null,g=!1,w=null,n.reset(),R.clear()}};return ee}async function ut(e,n){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");let i=ge(e);i.identify(n.customerToken);let o=ce.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}:{}}),d=null,p=null,r=null,a=null,t=null;async function s(){let R=ce.resolvePaywall,A=R.response.parse(await i.request(R.path,R.request.parse({...o,selector:d?{type:"version",versionId:d.id}:o.selector})));if(n.paywallVersionId?A.paywall.id!==n.paywallVersionId:A.paywall.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(d&&(A.paywall.id!==d.id||A.paywall.paywallId!==d.paywallId||A.paywall.offering.id!==d.offering.id))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return d=A.paywall,structuredClone(d)}async function g(R){if(!p)throw new l("INVALID_REQUEST","A quoted purchase is required");let A=R==="read"?ce.readSubscriptionOperation:ce.attach,c=A.response.parse(await i.request(A.path,A.request.parse({operationId:p.operationId,...R==="read"?{}:{intent:R}})));if(c.operation.operationId!==p.operationId||c.operation.currency!==o.commerce.currency)throw new l("INVALID_RESPONSE","The purchase operation changed");return r?.status==="complete"&&c.operation.status!=="complete"||r&&r.status!=="pending"&&c.operation.status==="pending"||(r=c.operation),structuredClone(r)}let w={get view(){return d?structuredClone(d):null},get quote(){return p?structuredClone(p):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return i.webViewUrl()},refresh:s,async preview(R){if(!d)throw new l("INVALID_REQUEST","Load the Paywall first");let A=d.document.buttons[R.actionId];if(A?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let c=Me(A.product,R.selection,d.capabilities);if(!c)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let N=ce.previewAttach.request.parse({funnelId:o.funnelId,funnelVersionId:o.funnelVersionId,requestId:R.requestId,plans:[{productVersionId:c}],provider:o.commerce.provider,currency:o.commerce.currency,...R.offerId?{offerId:R.offerId}:{},...R.nativeOffer?{nativeOffer:R.nativeOffer}:{}}),b=JSON.stringify(N);if(a&&a!==b&&(!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(a===b){if(t)return t;if(p)return structuredClone(p)}a=b;let h=(async()=>{let F=ce.previewAttach,E=F.response.parse(await i.request(F.path,N));if(E.quote.currency!==o.commerce.currency||E.quote.provider!==o.commerce.provider||E.quote.lines.length!==1||E.quote.lines[0].productVersionId!==c)throw new l("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return p=E.quote,r=null,structuredClone(p)})();t=h;try{return await h}finally{t===h&&(t=null)}},confirm:()=>g("confirm"),cancel:()=>g("cancel"),read:()=>g("read"),destroy(){i.reset(),d=null,p=null,r=null,a=null}};return await s(),w}import{z as Cn}from"zod";import{z as ve}from"zod";var En=ve.record(ve.string().regex(/^[a-f0-9]{64}$/),ve.strictObject({at:ve.number(),text:ve.string()})),gn=2*1048576;function Rn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function yn(e,n){let i=n===void 0?Rn():n,o=Promise.resolve();async function d(){try{let p=await i?.getItem(`${e}:artifacts`);if(p&&p.length<=gn)return En.parse(JSON.parse(p))}catch{}return{}}return{async readManifest(){try{return await i?.getItem(e)}catch{return}},writeManifest(p){Promise.resolve().then(()=>i?.setItem(e,p)).catch(()=>{})},async readArtifact(p){let r=(await d())[p];return r&&Date.now()>=r.at&&Date.now()-r.at<=H.retentionMs?r.text:void 0},writeArtifact(p,r){i&&(o=o.catch(()=>{}).then(async()=>{let a=await d(),t=Date.now();a[p]={at:t,text:r};let s={},g=2,w=0;for(let[R,A]of Object.entries(a).sort(([,c],[,N])=>N.at-c.at)){if(A.at>t||t-A.at>H.retentionMs)continue;let c=new TextEncoder().encode(JSON.stringify({[R]:A})).byteLength;g+c>gn||w>=128||(s[R]=A,g+=c,w++)}await i.setItem(`${e}:artifacts`,JSON.stringify(s))}).catch(()=>{}))}}}var S=(e,n)=>new l(e,n),re=()=>performance.now(),wn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function It(e){let n=We.parse(e.scope),i=new URL(e.origin??Ne);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 S("INVALID_URL","Configuration requires a trusted HTTPS origin");let o=new Set([i.origin,...(e.assetOrigins??[]).map(I=>{let y=new URL(I);if(y.protocol!=="https:"||y.username||y.password||y.search||y.hash||y.pathname!=="/")throw S("INVALID_URL","Invalid configuration asset origin");return y.origin})]),d=e.fetch??globalThis.fetch.bind(globalThis),p=`/api/v1/configuration/${n.environmentId}`,r=`indiana:configuration:1:${i.origin}:${k(n)}`,a=yn(r,e.storage),t,s=0,g=0,w=!1,R=!1,A=0,c=0,N,b,h,F,E=0,x=new Set,_=new Set,D=new Map,M=new Map,j=0,oe=!1;function X(){for(let I of x)try{I()}catch{}}function ee(I){try{e.onError?.(I)}catch{}}let f=()=>!R&&!w&&!!t&&re()<s&&Date.now()<g;function m(){if(!f())throw S("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function P(I,y){let C=new TextEncoder().encode(y).byteLength;if(!D.has(I)){for(;D.size&&(D.size>=128||j+C>H.maxCacheBytes);){let v=D.entries().next().value;j-=new TextEncoder().encode(v[1]).byteLength,D.delete(v[0])}D.set(I,y),j+=C}}async function U(I,y,C){if(Number(I.headers.get("content-length"))>y)throw S("INVALID_RESPONSE","Configuration exceeds its byte limit");let v=I.body?.getReader();if(!v)throw S("INVALID_RESPONSE","Configuration body is missing");let O=[],V=0;try{for(;;){C.throwIfAborted();let L=await v.read();if(L.done)break;if(V+=L.value.length,V>y)throw S("INVALID_RESPONSE","Configuration exceeds its byte limit");O.push(L.value)}}finally{await v.cancel().catch(()=>{})}C.throwIfAborted();let T=new Uint8Array(V),G=0;for(let L of O)T.set(L,G),G+=L.length;return new TextDecoder("utf-8",{fatal:!0}).decode(T)}function Y(I){let y=new URL(I,i);if(!o.has(y.origin)||y.username||y.password||y.hash||y.search)throw S("INVALID_URL","Configuration artifact origin is not trusted");return y.href}async function u(I,y,C=!1){let v=await d(Y(I),{method:"GET",credentials:"omit",redirect:"error",cache:C?"default":"no-cache",signal:y,headers:{}});if(v.status===429){let O=v.headers.get("retry-after")??"";E=/^\d+$/.test(O)?Number(O)*1e3:Math.max(0,Date.parse(O)-Date.now())||15e3}if(!v.ok&&v.status!==304)throw S(`CONFIGURATION_HTTP_${v.status}`,"Configuration synchronization failed");return v}function J(I,y,C){let v=Date.parse(I.headers.get("x-indiana-config-validated-at")??""),O=Date.parse(I.headers.get("x-indiana-config-valid-until")??""),V=Date.parse(I.headers.get("date")??""),T=I.headers.get("age"),G=T!==null&&/^\d+(\.\d+)?$/.test(T)?Number(T)*1e3:NaN;if(![v,O,V,G].every(Number.isFinite)||O<=v||O-v>H.maxControlAgeMs||v>V+1e3)throw S("INVALID_RESPONSE","Configuration freshness evidence is invalid");let q=Math.min(O-v,C.maxControlAgeSeconds*1e3,H.maxControlAgeMs)-Math.max(G,V-v,0)-(re()-y);if(q<=0)throw S("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return re()+q}function K(){if(clearTimeout(h),clearTimeout(F),R||!x.size)return;f()&&(F=setTimeout(()=>{f()?K():X()},Math.max(1,s-re())),wn(F));let I=c?Math.min(15e3,1e3*2**Math.min(c-1,4)):Math.min(15e3,(t?.policy.refreshIntervalSeconds??15)*1e3);h=setTimeout(()=>{z().catch(ee)},Math.max(E,I*(.8+Math.random()*.2))),wn(h)}async function z(){if(R)throw S("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(N)return N;let I=A,y=new AbortController;b=y;let C=(async()=>{if(!oe){oe=!0;try{let Re=await a.readManifest();if(Re&&!t){let W=xe.parse(JSON.parse(Re));k(W.scope)===k(n)&&(t=W)}}catch{}}y.signal.throwIfAborted();let T=t,G=re(),L=await u(p,y.signal);L.status===304&&(!T||!L.headers.has("x-indiana-config-validated-at")||!L.headers.has("x-indiana-config-valid-until")||!L.headers.has("age"))&&(L=await u(p,y.signal));let q=L.status===304?T:xe.parse(JSON.parse(await U(L,H.maxManifestBytes,y.signal))),{generation:Z,...ne}=q,ue=L.headers.get("etag");if(k(q.scope)!==k(n)||en(ne)!==Z||ue!==`"${Z}"`&&ue!==`W/"${Z}"`)throw S("INVALID_RESPONSE","Configuration scope or content identity changed");if(T&&(q.revision<T.revision||q.revision===T.revision&&q.generation!==T.generation))throw S("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Re,W]of Object.entries(T?.funnels??{})){let le=q.funnels[Re];if(le&&(le.controlRevision<W.controlRevision||le.evaluationRevision<W.evaluationRevision||le.controlRevision===W.controlRevision&&le.state!==W.state||le.evaluationRevision===W.evaluationRevision&&le.evaluationMode!==W.evaluationMode))throw S("INVALID_RESPONSE","Funnel control revision changed identity")}let Le=J(L,G,q.policy);if(y.signal.throwIfAborted(),I!==A)throw S("CONFIGURATION_DISPOSED","Configuration scope changed");return t=q,s=Le,g=Date.now()+Math.max(0,Le-re()),w=!1,c=0,E=0,a.writeManifest(k(q)),X(),structuredClone(q)})(),v=setTimeout(()=>y.abort(S("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs),O=new Promise((T,G)=>y.signal.addEventListener("abort",()=>G(y.signal.reason),{once:!0})),V=Promise.race([C,O]).catch(T=>{throw c++,(T instanceof Cn.ZodError||T instanceof SyntaxError||T instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(T.code))&&(s=0,w=!0,X()),T}).finally(()=>{clearTimeout(v),N===V&&(N=void 0),K()});return N=V,V}async function fe(I){let y=I.sha256,C=Z=>new TextEncoder().encode(Z).byteLength===I.byteLength&&Xe(Z)===y;Y(I.url);let v=D.get(y);if(v&&C(v))return D.delete(y),D.set(y,v),v;if(M.has(y))return M.get(y);let O=new AbortController;_.add(O);let V=A,T=(async()=>{try{let ue=await a.readArtifact(y);if(ue&&C(ue))return P(y,ue),ue}catch{}O.signal.throwIfAborted();let Z=await u(I.url,O.signal,!0),ne=await U(Z,I.byteLength,O.signal);if(!C(ne))throw S("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(R||V!==A)throw S("CONFIGURATION_DISPOSED","Configuration scope changed");return P(y,ne),a.writeArtifact(y,ne),ne})(),G=setTimeout(()=>O.abort(S("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),H.initializationMs),L=new Promise((Z,ne)=>O.signal.addEventListener("abort",()=>ne(O.signal.reason),{once:!0})),q=Promise.race([T,L]).finally(()=>{clearTimeout(G),_.delete(O),M.delete(y)});return M.set(y,q),q}async function pe(){return f()||await z(),m(),t}async function ie(I){let y,C=new Promise((v,O)=>{y=setTimeout(()=>O(S("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs)});try{return await Promise.race([I(),C])}finally{clearTimeout(y)}}function ae(I,y){if(m(),t?.generation!==I.generation)throw S("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(y&&t.funnels[y]?.state!=="active")throw S("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function we(I){let y=I.gb.features;if(!y)throw S("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let C=I.artifacts[y];if(C.formatVersion!==1)throw S("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let v=qe.parse(JSON.parse(await fe(C)));if(k(v.scope)!==k({projectId:n.projectId,environment:n.environment})||v.generation!==C.generation||v.remoteFeatures.some(O=>Object.hasOwn(v.features,O)))throw S("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return ae(I),{...v,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,s-re())).toISOString()}}async function se(I,y){let C=await pe();ae(C,I);let v=C.funnels[I];if(v.evaluationMode!=="local")throw S("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let O=y??v.currentVersionId,V=v.versions[O];if(!V)throw S("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(C.artifacts[V.artifact].formatVersion!==3)throw S("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let T=tn(JSON.parse(await fe(C.artifacts[V.artifact]))),G=v.evaluationMode==="local"?await we(C):void 0;if(G&&k(nn(T,G))!==k(V.dependencies))throw S("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return ae(C,I),{document:T,growth:G,versionId:O,control:structuredClone(v),manifest:structuredClone(C)}}function Ie(){w=!0,X(),z().catch(ee)}let $=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ie()};function Ee(I){if(R)throw S("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return x.add(I),x.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ie),window.addEventListener("focus",$),document.addEventListener("visibilitychange",$)),K()),()=>{x.delete(I),x.size||(clearTimeout(h),clearTimeout(F),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",Ie),window.removeEventListener("focus",$),document.removeEventListener("visibilitychange",$))}return{scope:Object.freeze({...n}),refresh:z,subscribe:Ee,assertFresh:m,assertFeatures(I){m();let y=t.gb.features;if(!y)throw S("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(I!==void 0&&t.artifacts[y].generation!==I)throw S("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return f()},get snapshot(){return t?structuredClone(t):null},get remainingMs(){return f()?Math.max(0,s-re()):0},async features(){return ie(async()=>we(await pe()))},pageExperiments:()=>ie(async()=>{let I=await pe(),y=I.gb.pageExperiments;if(!y)throw S("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let C=I.artifacts[y];if(C.formatVersion!==1)throw S("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let v=Ze.parse(JSON.parse(await fe(C)));if(v.environmentId!==n.environmentId||v.generation!==C.generation)throw S("INVALID_RESPONSE","Page experiment scope or generation changed");return ae(I),v}),funnel:(I,y)=>ie(()=>se(I,y)),async localFunnel(I,y){let C=await ie(()=>se(I,y));if(!C.growth)throw S("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:v,remoteFeatures:O,...V}=C.growth;return Ye({scope:{projectId:n.projectId,environment:n.environment},funnelId:I,versionId:C.versionId,evaluationMode:"local",evaluationRevision:C.control.evaluationRevision,document:C.document,payload:V})},assertFunnel(I,y,C){m();let v=t.funnels[I];if(!v||v.state!=="active")throw S("FUNNEL_STOPPED","Funnel is paused or unavailable");if(v.evaluationMode!=="local")throw S("EVALUATION_MODE","This Funnel now executes at Indiana");if(y!==void 0&&v.controlRevision!==y)throw S("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(C!==void 0&&!v.versions[C])throw S("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!R){R=!0,A++,s=0,b?.abort(S("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(h),clearTimeout(F),Ve(),X(),x.clear();for(let I of _)I.abort(S("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));D.clear(),j=0}}}}function In(e){let n=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");let i=ge({...e,timeoutMs:e.timeoutMs??35e3});return i.identify(e.apiKey),{async start(o){let d=te.safeParse({...o,operation:"start"});if(!d.success||d.data.operation!=="start"||(n?d.data.customer!==void 0:d.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let p=d.data,r=Ae.safeParse(await i.request("funnels",p));if(!r.success||!r.data.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");let a=r.data;if(a.run.source.id!==p.funnelId||a.run.locale!==(p.locale??"en")||!ye(a.run.parameters,p.parameters??{})||(p.customer?!a.customerId||p.customer.type==="id"&&a.customerId!==p.customer.value:a.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...a,runToken:a.runToken}}}}async function Ft(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let i={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&k(i)!==k(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let d=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.credential);if(d?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let p=In({...e,scope:i,apiKey:e.credential}),r=a=>{let t=mn({...e,scope:i,runToken:a,...d?{serverKey:e.credential}:{}});return d||t.identify(e.credential),t};return{async start(a){let t=await p.start({...a,funnelId:e.funnelId,...d?{customer:{type:"id",value:e.customerId}}:{}}),s=r(t.runToken),g=await s.get();return{...t,...g,controller:s}},async restore(a){let t=r(a),s=await t.get();if(s.run.source.id!==e.funnelId)throw t.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...s,runToken:a,controller:t}}}}export{An as a,kn as b,ye as c,an as d,sn as e,Fe as f,hn as g,un as h,mn as i,ut as j,It as k,In as l,Ft as m};
|