@tinkerlandai/indiana-sdk 0.8.3 → 0.8.5
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 +16 -0
- package/README.md +73 -3
- package/README.zh-CN.md +40 -3
- package/dist/{ai-usage-BV-FlgWr.d.ts → ai-usage-DUlre7JC.d.ts} +1 -1
- package/dist/{api-B3FIE41b.d.ts → api-XDc4pRlN.d.ts} +63 -10
- package/dist/chunk-3KQHKRZJ.js +1 -0
- package/dist/chunk-6A5WWFNS.js +10 -0
- package/dist/{chunk-SHSNIJJM.js → chunk-A3XRIG53.js} +1 -1
- package/dist/chunk-BUDTHBFF.js +173 -0
- package/dist/{chunk-BNU6IG3F.js → chunk-FGIGKO7A.js} +1 -1
- package/dist/chunk-HEBQUICQ.js +4 -0
- package/dist/chunk-SSLZKIIU.js +1 -0
- package/dist/chunk-SUXAWRR6.js +1 -0
- package/dist/chunk-WWUUVURR.js +1 -0
- package/dist/{configuration-sync-DNvKXHk-.d.ts → configuration-sync-Ce3dShy7.d.ts} +6 -1
- package/dist/content-DDMDNRCV.js +1 -0
- package/dist/{customer-page-WUQVK_tp.d.ts → customer-page-9B97Qdt_.d.ts} +21 -1
- package/dist/{funnel-local-client-wbz-4gFx.d.ts → funnel-local-client-CUGavICI.d.ts} +43 -23
- package/dist/funnel-runtime-host-QK6WDRPS.js +1 -0
- package/dist/index.d.ts +76 -26
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +2 -2
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +1 -1
- package/dist/page.js +1 -1
- package/dist/paywall-4QT3JYD4.js +1 -0
- package/dist/popup.d.ts +14 -4
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-DLXDQQKK.js +1 -0
- package/dist/server.d.ts +13 -13
- package/dist/server.js +1 -1
- package/dist/src-EG7RWDDY.js +1 -0
- package/dist/visual.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-2QPETWDX.js +0 -1
- package/dist/chunk-ANOOBDW5.js +0 -350
- package/dist/chunk-EXCPE2XH.js +0 -1
- package/dist/chunk-X747SY26.js +0 -4
- package/dist/chunk-Y32NPIYY.js +0 -1
- package/dist/chunk-ZT66RIFU.js +0 -10
- package/dist/content-J3FKZTGT.js +0 -1
- package/dist/funnel-runtime-host-C5P5JTV3.js +0 -1
- package/dist/paywall-3GIRKSHN.js +0 -1
- package/dist/screen-renderer-5FPYVSPW.js +0 -1
- package/dist/src-BMJCIMIF.js +0 -1
package/dist/chunk-EXCPE2XH.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var t="https://api.tinker.cash";export{t as a};
|
package/dist/chunk-X747SY26.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{a as U}from"./chunk-EXCPE2XH.js";import{e as T,h as I,k as A}from"./chunk-KQCTDXVD.js";function L(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let r of document.cookie.split(";"))if(r.trim().startsWith(`${e}=`))try{t=decodeURIComponent(r.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function C(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function _(e=U){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var y=new Set,E;function $(e){if(y.add(e),!E){let t=history.pushState,r=history.replaceState,n=()=>{for(let c of y)c()},a=function(...c){t.apply(this,c),n()},d=function(...c){r.apply(this,c),n()};history.pushState=a,history.replaceState=d,addEventListener("popstate",n),addEventListener("hashchange",n),E=()=>{history.pushState===a&&(history.pushState=t),history.replaceState===d&&(history.replaceState=r),removeEventListener("popstate",n),removeEventListener("hashchange",n)}}return()=>{y.delete(e),y.size||(E?.(),E=void 0)}}var G=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function Y(e,t){let r=e,n=a=>Number.isInteger(a)&&a>=0;return!!r&&typeof r=="object"&&n(r.inserted)&&n(r.duplicates)&&n(r.skipped)&&Array.isArray(r.rejected)&&r.inserted+r.duplicates+r.skipped+r.rejected.length===t}function D(e){let t=[],r,n=(s,o)=>e.log?.(`${e.label} ${s}`,o);function a(s){r===void 0&&t.length&&(r=setTimeout(()=>{c()},s))}async function d(s){let o;try{o=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:s}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(g){return n("not sent",{error:g}),!1}if(o.status===408||o.status===429||o.status>=500)return n("not sent",{status:o.status}),!1;if(!o.ok)return n("rejected",{status:o.status,events:s.length}),!0;let l;try{l=await o.json()}catch{l=void 0}return Y(l,s.length)?(l.rejected.length&&n("rejected",{rejected:l.rejected}),!0):(n("not acknowledged",{status:o.status}),!1)}function c(){clearTimeout(r),r=void 0;let s=[];for(;t.length&&s.length<20&&(!s.length||G([...s,t[0]].map(o=>o.event))<=65536);)s.push(t.shift());return s.length?d(s.map(o=>o.event)).then(o=>{if(o)return a(1e3);let l=s.filter(g=>++g.attempts<5);l.length<s.length&&n("dropped after retries",{events:s.length-l.length}),t.unshift(...l),a(5e3)}):Promise.resolve()}return{push(s){t.push({event:s,attempts:0}),t.length>=20?c():a(1e3)},flush:c}}/*!
|
|
2
|
-
Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
|
|
3
|
-
plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
|
|
4
|
-
*/function J(e,t){let r,n;try{r=new URL(e),n=new URL(t)}catch{return t}return r.searchParams.forEach((a,d)=>{n.searchParams.has(d)||n.searchParams.set(d,a)}),n.toString()}function Q(e,t){let r=navigator.userAgent,n=new URLSearchParams(t.search),a={};for(let d of["source","medium","campaign","term","content"]){let c=n.get(`utm_${d}`);c!==null&&(a[`utm${d[0].toUpperCase()}${d.slice(1)}`]=c)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(r)?"edge":/Chrome/.test(r)?"chrome":/Firefox/.test(r)?"firefox":/Safari/.test(r)?"safari":"unknown",deviceType:/Mobi/.test(r)?"mobile":"desktop",...a}}function z(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(a=>Object.hasOwn(n,a))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(a=>!!a&&typeof a.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function ee(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=_(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=`${t}/api/v1/page-experiments/${e.environmentId}`,a=L(e.deviceIdCookie??"indiana_did"),d=C(),c=null,s={...e.attributes??{}},o="",l=!1,g=new Map,P=D({endpoint:`${n}/events`,fetch:r,log:e.log,label:"Exposure"}),x=P.flush,f={trackedExperiments:new Set,log:e.log,onExperimentViewed:(i,u)=>{e.trackExposures===!1||c?.trackExposures===!1||P.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:a,...d?{sessionId:d}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:u.key})}},j=()=>{f.url=location.href,f.attributes={...Q(a,location),...s}};function O(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let u=new URL(location.href);return i.variations.some(p=>{if(!p.urlRedirect)return!1;let v=new URL(p.urlRedirect);return v.protocol!==u.protocol||v.host!==u.host})}catch{return!0}}function N(i,u){let p=e.configuration?.snapshot?.generation;o=i;let v=e.navigate??(m=>location.replace(m)),M=e.navigateDelay??(e.navigate?0:100),V=e.maxNavigateDelay??1e3;Promise.all([Promise.race([u,new Promise(m=>setTimeout(m,V))]),new Promise(m=>setTimeout(m,M))]).then(()=>{!l&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===p)&&v(i)})}function h(){if(!(!c||l||e.configuration&&!e.configuration.fresh)){j();for(let i of c.experiments){if(O(i)){e.log?.("Auto experiment blocked",{id:i.key});continue}let u;try{u=A(i,f)}catch(p){e.log?.("Skipping page experiment",{id:i.key,error:String(p)});continue}if(g.set(i.key,u),!!u.inExperiment){if(u.value.urlRedirect){let p=i.persistQueryString?J(location.href,u.value.urlRedirect):u.value.urlRedirect;T(p,i.urlPatterns??[])?e.log?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):p!==o&&N(p,x())}break}}}}let b="",H=()=>{location.href!==b&&(b=location.href,o="",h())},R,S;function B(){R??=$(H),addEventListener("pagehide",k)}let k=()=>{x()};async function w(){let i=e.configuration?null:await r(n,{cache:"no-cache",credentials:"omit"});if(i&&!i.ok)throw new Error(`Page experiments unavailable (${i.status})`);let u=z(e.configuration?await e.configuration.pageExperiments():await i.json());if(u.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");c?.trackExposures===!1&&u.trackExposures&&f.trackedExperiments?.clear(),c=u,f.savedGroups=I(u.savedGroups)}return{async start(){await w(),S??=e.configuration?.subscribe(()=>{!l&&e.configuration?.fresh&&w().then(h).catch(i=>e.log?.("Page configuration unavailable",{error:String(i)}))}),B(),b=location.href,h()},async refresh(){await w(),o="",h()},setAttributes(i){s={...i},h()},getResults(){return new Map(g)},get generation(){return c?.generation??null},destroy(){l=!0,S?.(),R?.(),removeEventListener("pagehide",k),x()}}}export{L as a,C as b,_ as c,$ as d,J as e,Q as f,z as g,ee as h};
|
package/dist/chunk-Y32NPIYY.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as rn,b as on,c as an,d as sn}from"./chunk-GRLMT5PR.js";import{a as ge}from"./chunk-VVV3JNS3.js";import{a as te}from"./chunk-2QPETWDX.js";import{$g as Be,Hg as z,Ki as X,Me as ke,Ne as Ue,Qe as qe,Sg as Ge,Si as Qe,Ug as U,Uj as Xe,Vg as Je,Zg as Pe,Zi as pe,_g as x,ah as je,aj as Ye,bh as ze,ch as He,fh as $e,hh as Ke,kk as en,lj as Ze,lk as nn,mj as We,nk as tn,ue as Me}from"./chunk-ZT66RIFU.js";import{a as d}from"./chunk-SOQO2RDZ.js";import{b as xe,h as me}from"./chunk-OBYJWIRB.js";import{a as ne}from"./chunk-EXCPE2XH.js";import{b as Se}from"./chunk-RRII2DMC.js";import{h as Le,l as Ve}from"./chunk-KQCTDXVD.js";function Tn(n){let e=null,t=null,f=0,u=0,m=new Set,o=null,a=null,r=new Set,s=()=>{for(let i of r)try{i()}catch{}},p={attributes:Se.parse(n.attributes??{}),onFeatureUsage:n.onFeatureUsage?(i,v)=>{!m.has(i)&&(!e||!("analyticsConfig"in e)||e.analyticsConfig.featureUsageEnabled)&&n.onFeatureUsage(i,structuredClone(v))}:void 0,onExperimentViewed:n.onExperimentViewed?(i,v)=>(!e||!("analyticsConfig"in e)||e.analyticsConfig.experimentViewsEnabled)&&n.onExperimentViewed(structuredClone(i),structuredClone(v)):void 0,stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:n.saveStickyBucketAssignmentDoc?i=>n.saveStickyBucketAssignmentDoc(structuredClone(i)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function F(i,v=new Set){return m.has(i)?!o||!o.features[i]||["unknownFeature","cyclicPrerequisite"].includes(o.features[i].source):v.has(i)?!1:(v.add(i),(e?.features[i]?.rules??[]).some(P=>[...P.parentConditions??[],...(P.tracks??[]).flatMap(S=>S.experiment.parentConditions??[])].some(S=>F(S.id,v))))}let E=i=>{if(n.assertUsable?.(e?.generation),!e)throw new Error("Initialize the Feature client before evaluation");if(e.expiresAt&&Date.parse(e.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,p.features=e.features),m.has(i)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?w():structuredClone(o.features[i]??w()):F(i)?w():structuredClone(Ve(i,p))};async function O(){if(!e||!m.size)return;if(!n.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let i=u;if(a?.revision===i)return a.loading;let v=f,P=e,S=[...m],R=(async()=>{let N=qe.parse(await n.evaluateRemote({attributes:structuredClone(p.attributes),features:S}));if(!(v!==f||i!==u||P!==e)){if(n.assertUsable?.(P.generation),N.generation!==P.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(S.some(T=>!Object.hasOwn(N.features,T))||Object.keys(N.features).some(T=>!m.has(T)))throw new Error("Invalid remote Feature results");o=structuredClone(N),p.features={...P.features,...Object.fromEntries(Object.entries(o.features).map(([T,V])=>[T,{defaultValue:V.value}]))},s()}})();a={revision:i,loading:R};try{await R}finally{a?.loading===R&&(a=null)}}function l(){O().catch(i=>{try{n.onError?.(i)}catch{}})}async function y(){if(t)return t;let i=f,v=(async()=>{let P=await n.load(),S="remoteFeatures"in P?ke.parse(P):null,R=S??me.parse(P);if(R.scope.projectId!==n.scope.projectId||R.scope.environment!==n.scope.environment)throw new Error("Feature payload scope changed");if(i!==f)throw new Error("Feature client was reset");if(n.assertUsable&&e?.generation===R.generation){let{evaluatedAt:T,expiresAt:V,...J}=e,{evaluatedAt:B,expiresAt:Y,...q}=R;if(x(J)!==x(q))throw new Error("Immutable Feature generation changed content");return e.evaluatedAt=R.evaluatedAt,e.expiresAt=R.expiresAt,s(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&l(),structuredClone(e)}let N=new Set(S?.remoteFeatures??[]);if([...N].some(T=>Object.hasOwn(R.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return e&&"analyticsConfig"in e&&"analyticsConfig"in R&&!e.analyticsConfig.experimentViewsEnabled&&S?.analyticsConfig.experimentViewsEnabled&&p.trackedExperiments?.clear(),e=structuredClone(R),m=N,o=null,a=null,u++,p.features=e.features,p.savedGroups=Le(e.savedGroups),p.trackedFeatureUsage={},s(),l(),structuredClone(e)})();t=v;try{return await v}finally{t===v&&(t=null)}}return{init:y,refresh:y,refreshRemote:O,get generation(){return e?.generation??null},get expiresAt(){return e?.expiresAt??null},subscribe(i){return r.add(i),()=>{r.delete(i)}},setAttributes(i){p.attributes=Se.parse(i),u++,o=null,a=null,p.features=e?.features??{},p.trackedFeatureUsage={},s(),l()},evalFeature:E,isOn(i){return E(i).on},isOff(i){return E(i).off},getFeatureValue(i,v){let P=E(i).value;return structuredClone(P===null?v:P)},reset(){f++,u++,t=null,a=null,e=null,o=null,m.clear(),p.features={},p.savedGroups={},p.stickyBucketAssignmentDocs={},p.attributes={},p.trackedFeatureUsage={},p.trackedExperiments?.clear(),s()}}}function un(n){let e,t,f=()=>new d("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),u=Promise.resolve().then(async()=>{if(e=n.storage??globalThis.localStorage,t=n.locks??globalThis.navigator?.locks,!e||!t||!globalThis.crypto?.subtle)throw f();let a=new TextEncoder().encode(JSON.stringify([new URL(n.baseUrl??ne).href,n.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",a));return"indiana.funnel.commands.v1."+Array.from(r,s=>s.toString(16).padStart(2,"0")).join("")});u.catch(()=>{});async function m(a){try{let r=await u;return await t.request(r,{mode:"exclusive"},()=>a(r))}catch(r){throw r instanceof d?r:f()}}function o(a){let r=e.getItem(a);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw f();let s=JSON.parse(r);if(!s||typeof s!="object"||!("revision"in s)||!("entry"in s)||!Number.isSafeInteger(s.revision)||Number(s.revision)<0)throw f();return{revision:Number(s.revision),entry:s.entry}}return{read:()=>m(o),write:(a,r)=>m(s=>{if(o(s).revision!==a)return null;if(!Number.isSafeInteger(a+1))throw f();return e.setItem(s,JSON.stringify({revision:a+1,entry:r})),a+1})}}async function ye(n,e){let{funnelRuntimeDeliverySchema:t}=await import("./src-BMJCIMIF.js"),f=t.safeParse(e);if(!f.success)throw new d("INVALID_RESPONSE","Funnel response contract changed");let u=f.data;if(n.scope&&(u.scope.projectId!==n.scope.projectId||u.scope.environment!==n.scope.environment))throw new d("SCOPE_MISMATCH","Funnel scope changed");return u}async function be(n,e,t){if(Number(n.headers.get("content-length"))>e)throw t.error("limit");let f=n.body?.getReader();if(!f)throw t.error("missing");let u=[],m=0;try{for(;;){t.signal?.throwIfAborted();let r=await f.read();if(r.done)break;if(m+=r.value.length,m>e)throw t.error("limit");u.push(r.value)}}finally{await f.cancel().catch(()=>{})}t.signal?.throwIfAborted();let o=new Uint8Array(m),a=0;for(let r of u)o.set(r,a),a+=r.length;return o}async function ln(n,e,t){return new TextDecoder("utf-8",{fatal:!0}).decode(await be(n,e,t))}function we(n,e){let t=typeof n=="string"?new TextEncoder().encode(n):n;return t.byteLength===e.byteLength&&Be(t)===e.sha256}async function he(n,e){let t=$e.parse(e),{artifact:f,environmentId:u}=t.content,m=new URL(n.baseUrl??ne).origin,o=new URL(f.url,m);if(o.origin!==m||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${u}/artifacts/${f.sha256}`)throw new d("INVALID_RESPONSE","Public Paywall locator is not trusted");let a=new AbortController,r=setTimeout(()=>a.abort(),U.initializationMs);try{let s=await(n.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:a.signal});if(!s.ok||!s.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(s.headers.get("content-length"))>f.byteLength)throw new d("INVALID_RESPONSE","Public Paywall is unavailable");let p=await be(s,f.byteLength,{signal:a.signal,error:w=>new d("INVALID_RESPONSE",w==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!we(p,f))throw new d("INVALID_RESPONSE","Public Paywall digest or size changed");return Ke(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(p)))}finally{clearTimeout(r)}}var se=(n,e)=>new d(n,e);function $n(n){return en(n,se)}async function cn(n,e,{predict:t=!0}={}){let f=e.instruction;if(f?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!n)throw new d("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(n.scope.environmentId!==f.environmentId)throw new d("SCOPE_MISMATCH","Evaluation environment changed");let u=null,m;if(t)try{let o=await n.funnel(e.source.id,e.source.versionId);m=o.manifest.generation,u=Sn(n,e,o)}catch{u=null}return m??=n.snapshot?.generation??(await n.refresh()).generation,{advance:{policyRevision:f.policyRevision,generation:m},prediction:u}}function Sn(n,e,t){let f=e.instruction;if(f?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==f.policyRevision)return null;let{analyticsConfig:u,remoteFeatures:m,...o}=t.growth,a=Ze({scope:{projectId:n.scope.projectId,environment:n.scope.environment},funnelId:e.source.id,versionId:e.source.versionId,evaluationMode:"local",evaluationRevision:f.policyRevision,document:t.document,payload:me.parse(o)}),r=Pn(a,t.document,{...e,...f}),s=r.steps.at(-1),p=r.boundary??(s?.result.port==="value"?{nodeId:s.nodeId,visit:e.visit+r.steps.length-1}:null);return p?{runId:e.id,from:{nodeId:e.nodeId,visit:e.visit,revision:e.revision},nodeId:p.nodeId,visit:p.visit,terminal:!r.boundary}:null}function Pn(n,e,t){return tn(n,e,t,se)}import{z as G}from"zod";var dn=z.refine(n=>!["start","get","review"].includes(n.operation)&&!("customerToken"in n),"Persist only the original mutation, without credentials").transform(n=>{if(n.operation==="start"||n.operation==="get"||n.operation==="review")throw new d("COMMAND_STORAGE_INVALID","Stored mutation required");return n}),fn=G.strictObject({schemaVersion:G.literal(1),scope:xe,runId:G.uuid(),funnelId:G.uuid(),versionId:G.uuid(),command:dn.optional(),closeCommand:dn.refine(n=>n.operation==="close").optional(),purchase:G.strictObject({receiptId:G.uuid(),operationId:G.uuid(),generation:G.number().int().nonnegative()}).optional(),closed:G.literal(!0).optional()}).refine(n=>!n.closeCommand||n.command&&n.command.operation!=="close"&&n.command.requestId!==n.closeCommand.requestId,"Close requires a separate request identity").refine(n=>n.command!==void 0||n.purchase!==void 0,"A recovery record requires an original obligation"),M=()=>new d("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Ie=(n,e)=>JSON.stringify(n)===JSON.stringify(e);function mn(n){let e=0,t=null,f=r=>JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]),u=Promise.resolve();async function m(){let r=await n.read();if(!Number.isSafeInteger(r.revision)||r.revision<0)throw new d("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:r.revision,entry:r.entry===null?null:fn.parse(r.entry)}}function o(r){let s=u.then(r);return u=s.catch(()=>{}),s}async function a(r){for(let s=0;s<4;s++){let p=await m();if(p.entry&&t!==null&&f(p.entry)!==t)throw M();let w=r(p.entry,p.revision);if(Ie(p.entry,w)){e=p.revision;return}let F=await n.write(p.revision,w);if(F!==null){if(!Number.isSafeInteger(F)||F<=p.revision)throw M();e=F;return}}throw M()}return{bind(r){let s=JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]);if(t!==null&&t!==s)throw M();t=s},async load(){let r=await m();return e=r.revision,t=r.entry?f(r.entry):null,r.entry},retain(r){let s=fn.parse(r),p=s.command;return!p||t!==null&&f(s)!==t?Promise.reject(M()):(t??=f(s),o(()=>a((w,F)=>{if(w&&!Ie(f(w),f(s)))throw M();if(!w){if(F!==e&&p.operation!=="close")throw M();return s}if(!w.command)return{...w,command:p,...p.operation==="close"?{closed:!0}:{}};if(p.operation==="close"&&w.command.operation!=="close"){if(w.command.requestId===p.requestId||w.closeCommand&&!Ie(w.closeCommand,p))throw M();return{...w,closeCommand:p,closed:!0}}if(!Ie(w.command,p))throw M();return w})))},observePurchase(r,s,p){return o(()=>a((w,F)=>{if(!w&&F!==e||w&&f(w)!==f({...r,schemaVersion:1}))throw M();if(w?.purchase&&w.purchase.generation>s.generation)return w;if(w?.purchase&&w.purchase.generation===s.generation&&w.purchase.operationId!==s.operationId)throw M();return p?!w?.purchase||w.purchase.operationId!==s.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...r,...w,purchase:s}}))},settle(r){return o(()=>a(s=>s?s.command&&"requestId"in s.command&&s.command.requestId===r?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===r?{...s,closeCommand:void 0}:s:null))}}}function rt(n,e){return e.type==="id"?n.customerId===e.value:n.externalUserId===e.value}function re(n,e){if(n===e)return!0;if(Array.isArray(n)||Array.isArray(e))return Array.isArray(n)&&Array.isArray(e)&&n.length===e.length&&n.every((u,m)=>re(u,e[m]));if(!n||!e||typeof n!="object"||typeof e!="object")return!1;let t=Object.entries(n),f=Object.entries(e);return t.length===f.length&&t.every(([u,m])=>Object.hasOwn(e,u)&&re(m,Reflect.get(e,u)))}function pn(n){let e=null,t=0,f=!1,u,m=0,o=new Set;return{get view(){return e},get generation(){return t},get disposed(){return f},get customerToken(){return u},get readSequence(){return m},nextRead(){return++m},assertCurrent(a,r="Run identity changed during the request"){if(a!==t||f)throw new d("IDENTITY_CHANGED",r)},assertRun(a){if(e&&(a.id!==e.id||a.source.type!==e.source.type||a.source.id!==e.source.id||a.source.versionId!==e.source.versionId||a.locale!==e.locale||!re(a.parameters,e.parameters)))throw new d("INVALID_RESPONSE","Run version changed");if(n&&a.source.id!==n)throw new d("INVALID_RESPONSE","Run belongs to another Funnel")},publish(a,r,s,p,w){if(!(a.operation==="review"&&e&&e!==s&&r.run.revision<=e.revision)&&!(e&&r.run.revision===e.revision&&p!==void 0&&p<m)&&(a.operation==="review"&&!r.run.stopped&&["running","waiting"].includes(r.run.status)&&e&&r.run.nodeId===e.nodeId&&r.run.visit===e.visit&&r.run.revision===e.revision&&(r.run.screen=e.screen,(e.paywall?.quote?.operationId===r.review?.activeOperationId||!e.paywall?.quote&&r.review?.activeOperationId===null)&&(r.run.paywall=e.paywall)),!(e?.paywall&&r.run.paywall&&e.paywall.receiptId===r.run.paywall.receiptId&&(r.run.paywall.selectionGeneration??0)<(e.paywall.selectionGeneration??0)))){if(!e||r.run.revision>=e.revision)e=r.run;else if(!w)return;if(e)for(let F of o)try{F(structuredClone(e))}catch{}}},identify(a){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(a))throw new d("INVALID_TOKEN","Customer credential required");t++,u=a},subscribe(a){return o.add(a),()=>o.delete(a)},reset(){f=!0,t++,u=void 0,e=null,o.clear()}}}function K(n){let{customerToken:e,...t}=n;return t}var bn=n=>!(n instanceof d)||n.status===void 0||n.status>=500||[401,425].includes(n.status);function gn({options:n,journal:e,state:t,call:f}){let u=null,m=null,o=!1,a={command:null,close:null},r=!1,s,p=null,w=e?e.load().then(y=>{if(t.disposed)throw new d("IDENTITY_CHANGED","Controller was reset during command restoration");if(p=y,!y)return;if(n.scope&&(y.scope.projectId!==n.scope.projectId||y.scope.environment!==n.scope.environment))throw new d("SCOPE_MISMATCH","Pending command belongs to another scope");if(s=y.purchase,o=y.closed===!0,!y.command)return;let i=z.parse(y.command);if(i.operation==="start"||i.operation==="get"||i.operation==="review")throw new d("COMMAND_STORAGE_INVALID","Stored mutation required");u=i,y.closeCommand&&(m=y.closeCommand,o=!0),i.operation==="close"&&(o=!0),r=!0}):Promise.resolve();w.catch(()=>{});async function F(y=u){if(e&&await w,!y)throw new d("INVALID_REQUEST","No command is pending");let i=y,v=t.generation;if(e){if(!t.view||!n.scope)throw new d("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:K(i)})}if(v!==t.generation||u!==i&&m!==i)throw new d("IDENTITY_CHANGED","Run changed before command dispatch");let P={...i,...t.customerToken?{customerToken:t.customerToken}:{}},S=r;r=!0;try{return await f(P,R=>{if(!R.settlement)throw new d("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==i.requestId)throw new d("INVALID_RESPONSE","Command settlement identity changed");if(v===t.generation&&(u===i||m===i)&&R.run.pendingRequest?.requestId!==i.requestId&&R.settlement.state==="settled"&&(!o||i.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let N=()=>v!==t.generation||u!==i&&m!==i?!1:(u===i&&(u=null),m===i&&(m=null),r=u!==null,p=null,!0);return e?e.settle(i.requestId).then(N):N()}return!1})}catch(R){throw v===t.generation&&u===i&&!S&&!bn(R)&&(e&&await e.settle(i.requestId),v===t.generation&&u===i&&(u=null,r=!1,p=null)),R}}function E(y){let i=z.parse(y);if(i.operation==="start"||i.operation==="get"||i.operation==="review")throw new d("INVALID_REQUEST","Mutation required");if(o&&i.operation!=="close"){if(u?.requestId===i.requestId)return l(i.requestId);throw new d("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(i.operation==="close"&&u?.operation!=="close"){if(o=!0,m&&JSON.stringify(K(m))!==JSON.stringify(K(i)))throw new d("COMMAND_PENDING","Retry the original Close");return m??=i,a.close?a.close:O(m,"close")}if(u){if(JSON.stringify(K(u))!==JSON.stringify(K(i)))throw new d("COMMAND_PENDING","Retry the original command before sending another");if(a.command)return a.command}else u=i,r=!1;return O(u,"command")}function O(y,i){let v=F(y);a[i]=v;let P=()=>{a[i]===v&&(a[i]=null)};return v.then(P,P),v}async function l(y){let i=await f({operation:"get",settlementRequestId:y,...t.customerToken?{customerToken:t.customerToken}:{}});if(i.settlement?.requestId!==y)throw new d("INVALID_RESPONSE","Exact command settlement is missing");return i.settlement.state==="settled"&&(e&&await e.settle(y),u?.requestId===y&&(u=null,r=!1),m?.requestId===y&&(m=null)),i}return{ready:w,get pending(){return u},get closing(){return m},get closeRequested(){return o},get inFlight(){return a.command},get closeFlight(){return a.close},get purchase(){return s},assertBinding(y){if(p&&(y.run.id!==p.runId||y.run.source.id!==p.funnelId||y.run.source.versionId!==p.versionId))throw new d("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(y,i,v,P){e?.bind({scope:i.scope,runId:i.run.id,funnelId:i.run.source.id,versionId:i.run.source.versionId}),e&&!n.scope&&(n.scope=i.scope);let S=i.run.paywall,R=S??i.purchase,N=R?.operation,T=i.settlement&&(!S||S.purchaseRequestId===i.settlement.requestId)&&(!s||s.operationId===i.settlement.operationId)?i.settlement:void 0,V=N?.operationId??R?.quote?.operationId??T?.operationId,J=R?.receiptId??T?.receiptId,B=S?.selectionGeneration??s?.generation??0;if(e&&V&&J&&y.operation!=="review"&&(!t.view||i.run.revision>=t.view.revision)&&(P===void 0||P>=t.readSequence)&&(!s||B>=s.generation)){let Y={receiptId:J,operationId:V,generation:B},q=N?.status==="complete"||R?.canReselect===!0;return e.observePurchase({scope:i.scope,runId:i.run.id,funnelId:i.run.source.id,versionId:i.run.source.versionId},Y,q).then(()=>{t.assertCurrent(v),q?s?.operationId===Y.operationId&&(s=void 0):s=Y})}},stop(){o=!0},submit:E,executePending:F,settle:l,reset(){u=null,m=null,a.close=null,r=!1,a.command=null}}}function yn(n){if(n={...n},typeof n.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(n.runToken))throw new d("INVALID_TOKEN","Run credential required");if(n.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.serverKey)))throw new d("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let e=te({...n,...n.serverKey?{fetch:(l,y)=>{let i=new Headers(y?.headers),v=typeof y?.body=="string"?JSON.parse(y.body):null;return v!==null&&typeof v=="object"&&"customerToken"in v&&typeof v.customerToken=="string"&&v.customerToken.length>0||i.set(Ye,n.serverKey),(n.fetch??globalThis.fetch)(l,{...y,headers:i})}}:{},timeoutMs:n.timeoutMs??35e3});e.identify(n.runToken);let t=pn(n.funnelId),f=null,u=n.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?un(n):void 0),m=u&&mn(u),o=gn({options:n,journal:m,state:t,call:a});async function a(l,y,i){let v=t.generation,P=()=>t.assertCurrent(v);m&&await o.ready,P();let S=t.view,R=pe.parse(await ye(n,await e.request("funnels",z.parse(l))));if(l.operation==="review"&&!R.review)throw new d("INVALID_RESPONSE","Historical projection is missing");if(P(),R.runToken&&R.runToken!==n.runToken)throw new d("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&R.settlement?.requestId!==N)throw new d("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(R),t.assertRun(R.run);let T=o.observePurchase(l,R,v,i);if(T&&await T,!R.run.stopped&&["running","waiting"].includes(R.run.status)&&l.operation==="get"&&l.settlementRequestId)return R;let V=y?.(R),J=typeof V=="boolean"?V:V?await V:!1;return P(),["running","waiting"].includes(R.run.status)||o.stop(),t.publish(l,R,S,i,J),R}let r=o.submit,s=null,p=new WeakMap;function w(l){let y=p.get(l);if(y)return y;let i=E(l);return p.set(l,i),i}let F=!1;async function E(l){let y=await l;if(y.run.instruction?.type!=="evaluate_segment")return y;if(s)return s;F=!0;let i=t.generation,v=(async()=>{for(let P=0;P<32&&y.run.instruction?.type==="evaluate_segment";P++){if(o.pending||o.closeRequested)return y;let S=y.run;if(y.run.instruction?.type==="evaluate_segment"){let{advance:N,prediction:T}=await cn(n.configuration,S);if(i!==t.generation)throw new d("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return y;if(t.view&&(t.view.revision!==S.revision||t.view.visit!==S.visit||t.view.nodeId!==S.nodeId))return a({operation:"get",...t.customerToken?{customerToken:t.customerToken}:{}});f=T;try{y=await r({operation:"commit_segment",requestId:Qe(S.id,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,...N})}finally{f===T&&(f=null)}}}return y})();s=v;try{return await v}finally{s===v&&(s=null)}}let O={get configuration(){return F?n.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(K(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(K(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get prediction(){return f?structuredClone(f):null},settle:o.settle,get webViewUrl(){return"bundled"},resolvePaywall(l){return he(n,l)},review(l){return a({operation:"review",...l?{receiptId:l}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,t.nextRead())},async get(l,y){m&&await o.ready,y??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let i=t.nextRead();return w(a({operation:"get",...l?{data:l}:{},...y?{purchase:y}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,i))},resume(l=t.view?.pendingRequest?.requestId){return l?o.closeRequested?O.settle(l):o.pending?.requestId===l?w(r(o.pending)):w(r({operation:"resume",requestId:l})):Promise.reject(new d("INVALID_REQUEST","No interrupted command is available"))},submit(l){return w(r(l))},retry(){return o.closeFlight?o.closeFlight:o.closing?o.executePending(o.closing):o.closeRequested&&o.pending?O.settle(o.pending.requestId):o.inFlight?w(o.inFlight):o.pending?w(r(o.pending)):Promise.reject(new d("INVALID_REQUEST","No command is pending"))},identify(l){t.identify(l),e.identify(n.runToken)},subscribe:t.subscribe,reset(){t.reset(),o.reset(),f=null,e.reset()}};return O}async function Et(n,e){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(e.customerToken))throw new d("INVALID_TOKEN","A verified Customer credential is required");let t=te(n);t.identify(e.customerToken);let f=X.resolvePaywall.request.parse({funnelId:e.funnelId,funnelVersionId:e.funnelVersionId,selector:e.paywallVersionId?{type:"version",versionId:e.paywallVersionId}:{type:"paywall",paywallId:e.paywallId},commerce:e.commerce,locale:e.locale,...e.requirement?{requirement:e.requirement}:{}}),u=null,m=!1,o=null,a=null,r=null,s=null;async function p(){if(m)throw new d("IDENTITY_CHANGED","Paywall is closed");let E=X.resolvePaywall,O=await ge(t.request,E,{...f,selector:u?{type:"version",versionId:u.id}:f.selector}),l={paywall:await he(n,O.paywall)};if(m)throw new d("IDENTITY_CHANGED","Paywall is closed");if(e.paywallVersionId?l.paywall.id!==e.paywallVersionId:l.paywall.paywallId!==e.paywallId)throw new d("INVALID_RESPONSE","The requested Paywall changed");if(u&&(!rn(l.paywall,u)||l.paywall.paywallId!==u.paywallId))throw new d("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return u=l.paywall,structuredClone(u)}async function w(E){if(!o)throw new d("INVALID_REQUEST","A quoted purchase is required");let O=E==="read"?X.readSubscriptionOperation:X.attach,l=await ge(t.request,O,{operationId:o.operationId,...E==="read"?{}:{intent:E}});return on(l.operation,{operationId:o.operationId,currency:f.commerce.currency},"The purchase operation changed"),a=sn(a,l.operation),structuredClone(a)}let F={get view(){return u?structuredClone(u):null},get quote(){return o?structuredClone(o):null},get operation(){return a?structuredClone(a):null},get webViewUrl(){return"bundled"},refresh:p,async preview(E){if(!u)throw new d("INVALID_REQUEST","Load the Paywall first");let O=u.document.buttons[E.actionId];if(O?.type!=="checkout")throw new d("INVALID_REQUEST","Choose an authored purchase action");let l=Me(O.product,E.selection,u.capabilities);if(!l)throw new d("PRODUCT_UNAVAILABLE","Choose an available Product");let y=X.previewAttach.request.parse({funnelId:f.funnelId,funnelVersionId:f.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:l}],provider:f.commerce.provider,currency:f.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),i=JSON.stringify(y);if(r&&r!==i&&(!a||a.status==="pending"))throw new d("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(r===i){if(s)return s;if(o)return structuredClone(o)}r=i;let v=(async()=>{let P=X.previewAttach,S=await ge(t.request,P,y);return an(S.quote,{productVersionId:l,currency:f.commerce.currency,provider:f.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=S.quote,a=null,structuredClone(o)})();s=v;try{return await v}finally{s===v&&(s=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){m=!0,t.reset(),u=null,o=null,a=null,r=null}};return await p(),F}import{z as Nn}from"zod";import{z as ue}from"zod";var Fn=ue.record(ue.string().regex(/^[a-f0-9]{64}$/),ue.strictObject({at:ue.number(),text:ue.string()})),wn=2*1048576,En=100;function An(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function hn(n,e){let t=e===void 0?An():e,f=Promise.resolve();async function u(o){if(!t)return null;let a;try{return await Promise.race([Promise.resolve().then(()=>t.getItem(o)),new Promise(r=>{a=setTimeout(()=>r(null),En)})])}catch{return null}finally{clearTimeout(a)}}async function m(){try{let o=await u(`${n}:artifacts`);if(o&&o.length<=wn)return Fn.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return u(n)},writeManifest(o){Promise.resolve().then(()=>t?.setItem(n,o)).catch(()=>{})},async readArtifact(o){let a=(await m())[o];return a&&Date.now()>=a.at&&Date.now()-a.at<=U.retentionMs?a.text:void 0},writeArtifact(o,a){t&&(f=f.catch(()=>{}).then(async()=>{let r=await m(),s=Date.now();r[o]={at:s,text:a};let p={},w=2,F=0;for(let[E,O]of Object.entries(r).sort(([,l],[,y])=>y.at-l.at)){if(O.at>s||s-O.at>U.retentionMs)continue;let l=new TextEncoder().encode(JSON.stringify({[E]:O})).byteLength;w+l>wn||F>=128||(p[E]=O,w+=l,F++)}await t.setItem(`${n}:artifacts`,JSON.stringify(p))}).catch(()=>{}))}}}var C=(n,e)=>new d(n,e),Q=()=>performance.now(),In=n=>{typeof n=="object"&&"unref"in n&&n.unref()};function kt(n){let e=Je.parse(n.scope),t=new URL(n.origin??ne);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw C("INVALID_URL","Configuration requires a trusted HTTPS origin");let f=new Set([t.origin,...(n.assetOrigins??[]).map(g=>{let c=new URL(g);if(c.protocol!=="https:"||c.username||c.password||c.search||c.hash||c.pathname!=="/")throw C("INVALID_URL","Invalid configuration asset origin");return c.origin})]),u=n.fetch??globalThis.fetch.bind(globalThis),m=`/api/v1/configuration/${e.environmentId}`,o=`indiana:configuration:1:${t.origin}:${x(e)}`,a=hn(o,n.storage),r,s=0,p=0,w=!1,F=!1,E=0,O=0,l,y,i,v,P=0,S=new Set,R=new Set,N=new Map,T=new Map,V=0,J=!1;function B(){for(let g of S)try{g()}catch{}}function Y(g){try{n.onError?.(g)}catch{}}let q=()=>!F&&!w&&!!r&&Q()<s&&Date.now()<p;function oe(){if(!q())throw C("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Fe(g,c){let h=new TextEncoder().encode(c).byteLength;if(!N.has(g)){for(;N.size&&(N.size>=128||V+h>U.maxCacheBytes);){let I=N.entries().next().value;V-=new TextEncoder().encode(I[1]).byteLength,N.delete(I[0])}N.set(g,c),V+=h}}function Ee(g,c,h){return ln(g,c,{signal:h,error:I=>C("INVALID_RESPONSE",I==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Ae(g){let c=new URL(g,t);if(!f.has(c.origin)||c.username||c.password||c.hash||c.search)throw C("INVALID_URL","Configuration artifact origin is not trusted");return c.href}async function ve(g,c,h=!1){let I=await u(Ae(g),{method:"GET",credentials:"omit",redirect:"error",cache:h?"default":"no-cache",signal:c,headers:{}});if(I.status===429){let b=I.headers.get("retry-after")??"";P=/^\d+$/.test(b)?Number(b)*1e3:Math.max(0,Date.parse(b)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw C(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function Rn(g,c,h){let I=Date.parse(g.headers.get("x-indiana-config-validated-at")??""),b=Date.parse(g.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(g.headers.get("date")??""),A=g.headers.get("age"),k=A!==null&&/^\d+(\.\d+)?$/.test(A)?Number(A)*1e3:NaN;if(![I,b,_,k].every(Number.isFinite)||b<=I||b-I>U.maxControlAgeMs||I>_+1e3)throw C("INVALID_RESPONSE","Configuration freshness evidence is invalid");let D=Math.min(b-I,h.maxControlAgeSeconds*1e3,U.maxControlAgeMs)-Math.max(k,_-I,0)-(Q()-c);if(D<=0)throw C("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Q()+D}function Re(){if(clearTimeout(i),clearTimeout(v),F||!S.size)return;q()&&(v=setTimeout(()=>{q()?Re():B()},Math.max(1,s-Q())),In(v));let g=O?Math.min(15e3,1e3*2**Math.min(O-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);i=setTimeout(()=>{ee().catch(Y)},Math.max(P,g*(.8+Math.random()*.2))),In(i)}async function ee(){if(F)throw C("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(l)return l;let g=E,c=new AbortController;y=c;let h=(async()=>{if(!J){J=!0;try{let fe=await a.readManifest();if(fe&&!r){let j=Pe.parse(JSON.parse(fe));x(j.scope)===x(e)&&(r=j)}}catch{}}c.signal.throwIfAborted();let A=r,k=Q(),L=await ve(m,c.signal);L.status===304&&(!A||!L.headers.has("x-indiana-config-validated-at")||!L.headers.has("x-indiana-config-valid-until")||!L.headers.has("age"))&&(L=await ve(m,c.signal));let D=L.status===304?A:Pe.parse(JSON.parse(await Ee(L,U.maxManifestBytes,c.signal))),{generation:H,...$}=D,Z=L.headers.get("etag");if(x(D.scope)!==x(e)||je($)!==H||Z!==`"${H}"`&&Z!==`W/"${H}"`)throw C("INVALID_RESPONSE","Configuration scope or content identity changed");if(A&&(D.revision<A.revision||D.revision===A.revision&&D.generation!==A.generation))throw C("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[fe,j]of Object.entries(A?.funnels??{})){let W=D.funnels[fe];if(W&&(W.controlRevision<j.controlRevision||W.evaluationRevision<j.evaluationRevision||W.controlRevision===j.controlRevision&&W.state!==j.state||W.evaluationRevision===j.evaluationRevision&&W.evaluationMode!==j.evaluationMode))throw C("INVALID_RESPONSE","Funnel control revision changed identity")}let De=Rn(L,k,D.policy);if(c.signal.throwIfAborted(),g!==E)throw C("CONFIGURATION_DISPOSED","Configuration scope changed");return r=D,s=De,p=Date.now()+Math.max(0,De-Q()),w=!1,O=0,P=0,a.writeManifest(x(D)),B(),structuredClone(D)})(),I=setTimeout(()=>c.abort(C("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),U.initializationMs),b=new Promise((A,k)=>c.signal.addEventListener("abort",()=>k(c.signal.reason),{once:!0})),_=Promise.race([h,b]).catch(A=>{throw O++,(A instanceof Nn.ZodError||A instanceof SyntaxError||A instanceof d&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(A.code))&&(s=0,w=!0,B()),A}).finally(()=>{clearTimeout(I),l===_&&(l=void 0),Re()});return l=_,_}async function le(g){let c=g.sha256,h=H=>we(H,g);Ae(g.url);let I=N.get(c);if(I&&h(I))return N.delete(c),N.set(c,I),I;if(T.has(c))return T.get(c);let b=new AbortController;R.add(b);let _=E,A=(async()=>{try{let Z=await a.readArtifact(c);if(Z&&h(Z))return Fe(c,Z),Z}catch{}b.signal.throwIfAborted();let H=await ve(g.url,b.signal,!0),$=await Ee(H,g.byteLength,b.signal);if(!h($))throw C("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(F||_!==E)throw C("CONFIGURATION_DISPOSED","Configuration scope changed");return Fe(c,$),a.writeArtifact(c,$),$})(),k=setTimeout(()=>b.abort(C("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),U.initializationMs),L=new Promise((H,$)=>b.signal.addEventListener("abort",()=>$(b.signal.reason),{once:!0})),D=Promise.race([A,L]).finally(()=>{clearTimeout(k),R.delete(b),T.delete(c)});return T.set(c,D),D}async function ce(){return q()||await ee(),oe(),r}async function ie(g){let c,h=new Promise((I,b)=>{c=setTimeout(()=>b(C("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),U.initializationMs)});try{return await Promise.race([g(),h])}finally{clearTimeout(c)}}function ae(g,c){if(oe(),r?.generation!==g.generation)throw C("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(c&&r.funnels[c]?.state!=="active")throw C("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Ne(g){let c=g.gb.features;if(!c)throw C("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let h=g.artifacts[c];if(h.formatVersion!==1)throw C("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=Ue.parse(JSON.parse(await le(h)));if(x(I.scope)!==x({projectId:e.projectId,environment:e.environment})||I.generation!==h.generation||I.remoteFeatures.some(b=>Object.hasOwn(I.features,b)))throw C("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return ae(g),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,s-Q())).toISOString()}}async function Oe(g,c){let h=await ce(),I=h.funnels[g];c&&(!I||I.evaluationMode==="local"&&!I.versions[c])&&(l&&await l,h=await ee()),ae(h,g);let b=h.funnels[g];if(b.evaluationMode!=="local")throw C("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let _=c??b.currentVersionId,A=b.versions[_];if(!A)throw C("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(h.artifacts[A.artifact].formatVersion!==3)throw C("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[k,L]=await Promise.all([le(h.artifacts[A.artifact]).then(D=>He(JSON.parse(D))),b.evaluationMode==="local"?Ne(h):void 0]);if(L&&x(ze(k,L))!==x(A.dependencies))throw C("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return ae(h,g),{document:k,growth:L,versionId:_,control:structuredClone(b),manifest:structuredClone(h)}}async function Te(g,c){try{return await Oe(g,c)}catch(h){if(!(h instanceof d)||!(h.code==="CONFIGURATION_CHANGED"||h.code==="CONFIGURATION_HTTP_404"&&q()))throw h;let I=r?.generation;if(l&&await l,await ee(),h.code!=="CONFIGURATION_CHANGED"&&r?.generation===I)throw h;return Oe(g,c)}}function Ce(){w=!0,B(),ee().catch(Y)}let de=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ce()};function Cn(g){if(F)throw C("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return S.add(g),S.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ce),window.addEventListener("focus",de),document.addEventListener("visibilitychange",de)),Re()),()=>{S.delete(g),S.size||(clearTimeout(i),clearTimeout(v),_e())}}function _e(){typeof window<"u"&&(window.removeEventListener("online",Ce),window.removeEventListener("focus",de),document.removeEventListener("visibilitychange",de))}return{scope:Object.freeze({...e}),refresh:ee,subscribe:Cn,assertFresh:oe,assertFeatures(g){oe();let c=r.gb.features;if(!c)throw C("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(g!==void 0&&r.artifacts[c].generation!==g)throw C("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return q()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return q()?Math.max(0,s-Q()):0},async features(){return ie(async()=>Ne(await ce()))},pageExperiments:()=>ie(async()=>{let g=await ce(),c=g.gb.pageExperiments;if(!c)throw C("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let h=g.artifacts[c];if(h.formatVersion!==1)throw C("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=Xe.parse(JSON.parse(await le(h)));if(I.environmentId!==e.environmentId||I.generation!==h.generation)throw C("INVALID_RESPONSE","Page experiment scope or generation changed");return ae(g),I}),funnel:(g,c)=>ie(()=>Te(g,c)),paywall:(g,c)=>ie(async()=>{let h=await ce(),I=h.paywalls?.[g];if(!I||!c&&I.state!=="published")throw C("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let b=c??I.currentVersionId,_=I.versions[b],A=_&&h.artifacts[_.artifact];if(!A||A.kind!=="paywall"||A.formatVersion!==1)throw C("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let k=Ge.parse(JSON.parse(await le(A)));return ae(h),{document:k,versionId:b,version:_.version,control:structuredClone(I),manifest:structuredClone(h)}}),async localFunnel(g,c){let h=await ie(()=>Te(g,c));if(!h.growth)throw C("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:b,..._}=h.growth;return We({scope:{projectId:e.projectId,environment:e.environment},funnelId:g,versionId:h.versionId,evaluationMode:"local",evaluationRevision:h.control.evaluationRevision,document:h.document,payload:_})},assertFunnel(g,c,h){oe();let I=r.funnels[g];if(!I||I.state!=="active")throw C("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw C("EVALUATION_MODE","This Funnel now executes at Indiana");if(c!==void 0&&I.controlRevision!==c)throw C("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(h!==void 0&&!I.versions[h])throw C("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!F){F=!0,E++,s=0,y?.abort(C("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(i),clearTimeout(v),_e(),B(),S.clear();for(let g of R)g.abort(C("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));N.clear(),V=0}}}}function Jt(n,e,t){return nn(n,e,t,se)}function vn(n){let e=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey);if(typeof window<"u"&&!e)throw new d("SERVER_ONLY","Funnel starts are issued by your backend");if(!e&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new d("INVALID_TOKEN","A customer credential or server API key is required");let t=te({...n,timeoutMs:n.timeoutMs??35e3});return t.identify(n.apiKey),{async start(f){let u=z.safeParse({...f,operation:"start"});if(!u.success||u.data.operation!=="start"||(e?u.data.customer!==void 0:u.data.customer===void 0))throw new d("INVALID_REQUEST","Invalid current Funnel start");let m=u.data,o=pe.safeParse(await ye(n,await t.request("funnels",m)));if(!o.success||!o.data.runToken)throw new d("INVALID_RESPONSE","Funnel start credentials are missing");let a=o.data;if(a.run.source.id!==m.funnelId||a.run.locale!==(m.locale??"en")||!re(a.run.parameters,m.parameters??{})||(m.customer?!a.customerId||m.customer.type==="id"&&a.customerId!==m.customer.value:a.customerId!==void 0))throw new d("INVALID_RESPONSE","Funnel start contract changed");return{...a,runToken:a.runToken}}}}async function Xt(n){n={...n};let e=n.configuration;if(!e)throw new d("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:e.scope.projectId,environment:e.scope.environment};if(n.scope&&x(t)!==x(n.scope))throw new d("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await e.funnel(n.funnelId)).control.evaluationMode!=="local")throw new d("EVALUATION_MODE","This Funnel uses Remote evaluation");let u=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.credential);if(u?!n.customerId:n.customerId!==void 0)throw new d("INVALID_REQUEST","Only Server-Key starts name their Customer");let m=vn({...n,scope:t,apiKey:n.credential}),o=a=>{let r=yn({...n,scope:t,runToken:a,...u?{serverKey:n.credential}:{}});return u||r.identify(n.credential),r};return{async start(a){let r=await m.start({...a,funnelId:n.funnelId,...u?{customer:{type:"id",value:n.customerId}}:{}}),s=o(r.runToken),p=await s.get();return{...r,...p,controller:s}},async restore(a){let r=o(a),s=await r.get();if(s.run.source.id!==n.funnelId)throw r.reset(),new d("SCOPE_MISMATCH","Run belongs to another Funnel");return{...s,runToken:a,controller:r}}}}export{Tn as a,ye as b,se as c,$n as d,Pn as e,un as f,rt as g,re as h,yn as i,Et as j,kt as k,Jt as l,vn as m,Xt as n};
|