@tinkerlandai/indiana-sdk 0.6.0 → 0.6.1

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.
@@ -1 +1 @@
1
- import{a as e}from"./chunk-5TEZEOHX.js";import{a as j}from"./chunk-S5TVMQRC.js";import{kb as T,lb as P,ob as S}from"./chunk-HU2HIDVT.js";import{D as _,G as C,J as k,v as O}from"./chunk-RMJJOSVZ.js";import{b as E}from"./chunk-OHDY27EI.js";var L={name:"@tinkerlandai/indiana-sdk",version:"0.6.0",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.5"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var X=Symbol("IndianaNoContent");function Q(a,V){let v=a.webView??"hosted";if(!["hosted","embedded"].includes(v))throw new e("INVALID_REQUEST","Invalid Web View mode");let d=a.scope?E.parse(a.scope):void 0,s=new URL(a.baseUrl??j);if(s.username||s.password||s.search||s.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(s.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let U=a.fetch??globalThis.fetch.bind(globalThis),u=a.timeoutMs??1e4;if(!Number.isFinite(u)||u<=0||u>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,g,c=0,l=null,f=new Set;function R(){c+=1,p=null,l=null;for(let i of f)i.abort();f.clear()}async function M(i,H={},N="POST",q={}){if(!p)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let I=c,n=new AbortController;f.add(n);let m=()=>I!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),y,K=new Promise((t,o)=>{y=()=>o(m()),n.signal.addEventListener("abort",y,{once:!0})}),x=setTimeout(()=>n.abort(),u),F=async()=>{let t=await U(`${s.href.replace(/\/$/,"")}/api/v1/${i}`,{method:N,headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`,[T]:S.current,[P]:L.version,...d?{"X-Indiana-Project":d.projectId,"X-Indiana-Environment":d.environment}:{}},body:N==="POST"?JSON.stringify(H):void 0,signal:n.signal,credentials:"omit",cache:"no-store",redirect:"error",...q.keepalive?{keepalive:!0}:{}});if(n.signal.aborted)throw m();let o;try{o=t.status===204?X:await t.json()}catch{throw n.signal.aborted?m():new e(t.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",t.status,t.headers.get("X-Request-Id")??void 0)}if(n.signal.aborted)throw m();if(I!==c)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!t.ok){let r=C.safeParse(o),w=r.success&&(!O.safeParse(r.data.error.code).success||_(r.data.error.code,t.status)),A=w?r.data.error.code:"HTTP_ERROR",D=k(A,t.status,{retryAfter:t.headers.get("Retry-After"),recovery:w?r.data.error.recovery:void 0,reason:w?r.data.error.reason:void 0});throw new e(A,w?r.data.error.message:"Indiana request failed",t.status,t.headers.get("X-Request-Id")??(r.success?r.data.requestId:void 0),{...D,...r.success&&r.data.error.retryable===!1?{retryable:!1}:{},...D.retryAfterSeconds===void 0&&r.success&&r.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:r.data.error.retryAfterSeconds}:{}})}if(t.headers.get(T)!==S.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(d&&o&&typeof o=="object"&&"scope"in o){let r=E.safeParse(o.scope);if(!r.success||r.data.projectId!==d.projectId||r.data.environment!==d.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let b=t.headers.get("X-Indiana-Web-View");if(b){if(!/^\/web-view\/renderer\/[a-f0-9]{64}$/.test(b))throw new e("INVALID_RESPONSE","Invalid Web View renderer metadata");g=b}let h=t.headers.get("X-Indiana-Telemetry-Subject");if(h){if(!/^[a-f0-9]{64}$/.test(h))throw new e("INVALID_RESPONSE","Invalid telemetry identity");l!==h&&(l=h,V?.(l))}return o};try{return await Promise.race([F(),K])}catch(t){throw I!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):t instanceof e?t:new e(n.signal.aborted?"TIMEOUT":"NETWORK_ERROR",n.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(x),n.signal.removeEventListener("abort",y),f.delete(n)}}return{subjectKey:()=>l,webViewUrl(){if(v!=="embedded"){if(!g)throw new e("INVALID_RESPONSE","The gateway did not provide a hosted Web View renderer");return new URL(g,s).href}},identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");R(),p=i},reset:R,request:M}}export{Q as a};
1
+ import{a as e}from"./chunk-5TEZEOHX.js";import{a as j}from"./chunk-S5TVMQRC.js";import{kb as T,lb as P,ob as S}from"./chunk-46S4DTCD.js";import{D as _,G as C,J as k,v as O}from"./chunk-RMJJOSVZ.js";import{b as E}from"./chunk-OHDY27EI.js";var L={name:"@tinkerlandai/indiana-sdk",version:"0.6.1",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.5"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var X=Symbol("IndianaNoContent");function Q(a,V){let v=a.webView??"hosted";if(!["hosted","embedded"].includes(v))throw new e("INVALID_REQUEST","Invalid Web View mode");let d=a.scope?E.parse(a.scope):void 0,s=new URL(a.baseUrl??j);if(s.username||s.password||s.search||s.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(s.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let U=a.fetch??globalThis.fetch.bind(globalThis),u=a.timeoutMs??1e4;if(!Number.isFinite(u)||u<=0||u>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,g,c=0,l=null,f=new Set;function R(){c+=1,p=null,l=null;for(let i of f)i.abort();f.clear()}async function M(i,H={},N="POST",q={}){if(!p)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let I=c,n=new AbortController;f.add(n);let m=()=>I!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),y,K=new Promise((t,o)=>{y=()=>o(m()),n.signal.addEventListener("abort",y,{once:!0})}),x=setTimeout(()=>n.abort(),u),F=async()=>{let t=await U(`${s.href.replace(/\/$/,"")}/api/v1/${i}`,{method:N,headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`,[T]:S.current,[P]:L.version,...d?{"X-Indiana-Project":d.projectId,"X-Indiana-Environment":d.environment}:{}},body:N==="POST"?JSON.stringify(H):void 0,signal:n.signal,credentials:"omit",cache:"no-store",redirect:"error",...q.keepalive?{keepalive:!0}:{}});if(n.signal.aborted)throw m();let o;try{o=t.status===204?X:await t.json()}catch{throw n.signal.aborted?m():new e(t.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",t.status,t.headers.get("X-Request-Id")??void 0)}if(n.signal.aborted)throw m();if(I!==c)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!t.ok){let r=C.safeParse(o),w=r.success&&(!O.safeParse(r.data.error.code).success||_(r.data.error.code,t.status)),A=w?r.data.error.code:"HTTP_ERROR",D=k(A,t.status,{retryAfter:t.headers.get("Retry-After"),recovery:w?r.data.error.recovery:void 0,reason:w?r.data.error.reason:void 0});throw new e(A,w?r.data.error.message:"Indiana request failed",t.status,t.headers.get("X-Request-Id")??(r.success?r.data.requestId:void 0),{...D,...r.success&&r.data.error.retryable===!1?{retryable:!1}:{},...D.retryAfterSeconds===void 0&&r.success&&r.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:r.data.error.retryAfterSeconds}:{}})}if(t.headers.get(T)!==S.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(d&&o&&typeof o=="object"&&"scope"in o){let r=E.safeParse(o.scope);if(!r.success||r.data.projectId!==d.projectId||r.data.environment!==d.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let b=t.headers.get("X-Indiana-Web-View");if(b){if(!/^\/web-view\/renderer\/[a-f0-9]{64}$/.test(b))throw new e("INVALID_RESPONSE","Invalid Web View renderer metadata");g=b}let h=t.headers.get("X-Indiana-Telemetry-Subject");if(h){if(!/^[a-f0-9]{64}$/.test(h))throw new e("INVALID_RESPONSE","Invalid telemetry identity");l!==h&&(l=h,V?.(l))}return o};try{return await Promise.race([F(),K])}catch(t){throw I!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):t instanceof e?t:new e(n.signal.aborted?"TIMEOUT":"NETWORK_ERROR",n.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(x),n.signal.removeEventListener("abort",y),f.delete(n)}}return{subjectKey:()=>l,webViewUrl(){if(v!=="embedded"){if(!g)throw new e("INVALID_RESPONSE","The gateway did not provide a hosted Web View renderer");return new URL(g,s).href}},identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");R(),p=i},reset:R,request:M}}export{Q as a};
@@ -1 +1 @@
1
- import{a as u}from"./chunk-5TEZEOHX.js";import{$d as M,_d as E,ae as j,be as O,ce as T}from"./chunk-HU2HIDVT.js";import{h as w}from"./chunk-RMJJOSVZ.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
1
+ import{a as u}from"./chunk-5TEZEOHX.js";import{$d as M,_d as E,ae as j,be as O,ce as T}from"./chunk-46S4DTCD.js";import{h as w}from"./chunk-RMJJOSVZ.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
@@ -1 +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};
1
+ import{a as ge}from"./chunk-FRZNOXK6.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-46S4DTCD.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};
@@ -1,11 +1,11 @@
1
1
  import { z } from 'zod';
2
- import { S as StackNode } from './screen-16d-xADb.js';
2
+ import { S as StackNode } from './screen-BbLE1OMn.js';
3
3
 
4
4
  declare const configurationScopeSchema: z.ZodObject<{
5
5
  projectId: z.ZodString;
6
6
  environment: z.ZodEnum<{
7
- sandbox: "sandbox";
8
7
  live: "live";
8
+ sandbox: "sandbox";
9
9
  }>;
10
10
  environmentId: z.ZodUUID;
11
11
  }, z.core.$strict>;
@@ -15,8 +15,8 @@ declare const sdkConfigurationManifestSchema: z.ZodObject<{
15
15
  scope: z.ZodObject<{
16
16
  projectId: z.ZodString;
17
17
  environment: z.ZodEnum<{
18
- sandbox: "sandbox";
19
18
  live: "live";
19
+ sandbox: "sandbox";
20
20
  }>;
21
21
  environmentId: z.ZodUUID;
22
22
  }, z.core.$strict>;
@@ -90,7 +90,7 @@ type Listener = () => void;
90
90
  declare function createConfigurationSync(options: ConfigurationSyncOptions): {
91
91
  scope: Readonly<{
92
92
  projectId: string;
93
- environment: "sandbox" | "live";
93
+ environment: "live" | "sandbox";
94
94
  environmentId: string;
95
95
  }>;
96
96
  refresh: () => Promise<Manifest>;
@@ -103,7 +103,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
103
103
  schemaVersion: 1;
104
104
  scope: {
105
105
  projectId: string;
106
- environment: "sandbox" | "live";
106
+ environment: "live" | "sandbox";
107
107
  environmentId: string;
108
108
  };
109
109
  revision: number;
@@ -146,10 +146,6 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
146
146
  features(): Promise<{
147
147
  evaluatedAt: string;
148
148
  expiresAt: string;
149
- scope: {
150
- projectId: string;
151
- environment: "sandbox" | "live";
152
- };
153
149
  features: Record<string, {
154
150
  defaultValue?: z.core.util.JSONType | undefined;
155
151
  rules?: {
@@ -246,6 +242,10 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
246
242
  phase?: string | undefined;
247
243
  }[] | undefined;
248
244
  }>;
245
+ scope: {
246
+ projectId: string;
247
+ environment: "live" | "sandbox";
248
+ };
249
249
  generation: string;
250
250
  savedGroups: Record<string, {
251
251
  type: "hashed";
@@ -318,41 +318,41 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
318
318
  urlRedirect: string;
319
319
  }[];
320
320
  name?: string | undefined;
321
- coverage?: number | undefined;
322
- condition?: Record<string, z.core.util.JSONType> | undefined;
321
+ meta?: {
322
+ key?: string | undefined;
323
+ name?: string | undefined;
324
+ passthrough?: boolean | undefined;
325
+ }[] | undefined;
326
+ filters?: {
327
+ seed: string;
328
+ hashVersion: 2;
329
+ ranges: [number, number][];
330
+ attribute?: string | undefined;
331
+ }[] | undefined;
323
332
  seed?: string | undefined;
324
333
  hashVersion?: 2 | undefined;
325
334
  ranges?: [number, number][] | undefined;
326
- force?: number | undefined;
335
+ condition?: Record<string, z.core.util.JSONType> | undefined;
327
336
  urlPatterns?: {
328
337
  include: boolean;
329
338
  type: "regex" | "simple";
330
339
  pattern: string;
331
340
  }[] | undefined;
341
+ force?: number | undefined;
332
342
  persistQueryString?: boolean | undefined;
333
343
  hashAttribute?: string | undefined;
334
- phase?: string | undefined;
335
- filters?: {
336
- seed: string;
337
- hashVersion: 2;
338
- ranges: [number, number][];
339
- attribute?: string | undefined;
340
- }[] | undefined;
341
344
  parentConditions?: {
342
345
  id: string;
343
346
  condition: Record<string, z.core.util.JSONType>;
344
347
  gate?: boolean | undefined;
345
348
  }[] | undefined;
346
349
  weights?: number[] | undefined;
350
+ coverage?: number | undefined;
347
351
  fallbackAttribute?: string | undefined;
348
352
  disableStickyBucketing?: boolean | undefined;
349
353
  bucketVersion?: number | undefined;
350
354
  minBucketVersion?: number | undefined;
351
- meta?: {
352
- key?: string | undefined;
353
- name?: string | undefined;
354
- passthrough?: boolean | undefined;
355
- }[] | undefined;
355
+ phase?: string | undefined;
356
356
  }[];
357
357
  savedGroups: Record<string, {
358
358
  type: "hashed";
@@ -584,7 +584,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
584
584
  event: string;
585
585
  } | {
586
586
  type: "api";
587
- operation: "update" | "refund" | "setupPayment" | "readBalanceSource" | "adjustBalance" | "readUsage" | "setUsage" | "manageBalanceGrant" | "listBalanceGrants" | "restoreNativePurchase" | "readPaymentSetup" | "verifySubscriptions" | "previewAttach" | "attach" | "readSubscriptionOperation" | "previewUpdate" | "readSubscriptionUpdate" | "previewRefund" | "readRefund" | "readBillingControls" | "prepareBillingAuthorization" | "confirmBillingAuthorization" | "setBillingCoupons" | "revokeBillingAuthorization" | "listBillingInvoices" | "confirmBillingAdjustment" | "manageBillingLimits" | "manageUsageEntity" | "readUsageAnalytics" | "readCreditAnalytics" | "submitUsageBatch" | "readUsageBatch" | "checkEntitlement" | "resolveOffering" | "readHoldings" | "readLedger" | "readBillingInvoice" | "readCreditStatement" | "quoteBalance" | "trackUsage" | "mutateBalance" | "redeemReward" | "createReferralCode" | "claimRewardProduct" | "readSeats" | "manageSeat" | "redeemCoupon" | "listOffers" | "grantOffer";
587
+ operation: "update" | "attach" | "refund" | "readBalanceSource" | "adjustBalance" | "readUsage" | "setUsage" | "manageBalanceGrant" | "listBalanceGrants" | "restoreNativePurchase" | "setupPayment" | "readPaymentSetup" | "verifySubscriptions" | "previewAttach" | "readSubscriptionOperation" | "previewUpdate" | "readSubscriptionUpdate" | "previewRefund" | "readRefund" | "readBillingControls" | "prepareBillingAuthorization" | "confirmBillingAuthorization" | "setBillingCoupons" | "revokeBillingAuthorization" | "listBillingInvoices" | "confirmBillingAdjustment" | "manageBillingLimits" | "manageUsageEntity" | "readUsageAnalytics" | "readCreditAnalytics" | "submitUsageBatch" | "readUsageBatch" | "checkEntitlement" | "resolveOffering" | "readHoldings" | "readLedger" | "readBillingInvoice" | "readCreditStatement" | "quoteBalance" | "trackUsage" | "mutateBalance" | "redeemReward" | "createReferralCode" | "claimRewardProduct" | "readSeats" | "manageSeat" | "redeemCoupon" | "listOffers" | "grantOffer";
588
588
  inputs: Record<string, {
589
589
  source: "literal";
590
590
  value: z.core.util.JSONType;
@@ -627,7 +627,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
627
627
  } | undefined;
628
628
  } | {
629
629
  type: "end";
630
- outcome: "failed" | "completed" | "closed" | "ineligible";
630
+ outcome: "closed" | "failed" | "completed" | "ineligible";
631
631
  id: string;
632
632
  name: string;
633
633
  output?: {
@@ -692,7 +692,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
692
692
  primary: string;
693
693
  background: string;
694
694
  text: string;
695
- radius: "none" | "full" | "sm" | "md" | "lg";
695
+ radius: "sm" | "md" | "lg" | "none" | "full";
696
696
  font: "system" | "serif" | "rounded" | "mono";
697
697
  };
698
698
  pages: {
@@ -703,7 +703,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
703
703
  primary: string;
704
704
  background: string;
705
705
  text: string;
706
- radius: "none" | "full" | "sm" | "md" | "lg";
706
+ radius: "sm" | "md" | "lg" | "none" | "full";
707
707
  font: "system" | "serif" | "rounded" | "mono";
708
708
  } | undefined;
709
709
  editorPosition?: {
@@ -753,20 +753,20 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
753
753
  };
754
754
  publicData?: {
755
755
  couponDigests: Record<string, string>;
756
- variables: Record<string, Record<string, Partial<Record<"offer.headline" | "offer.name" | "offer.description" | "offer.eligibility" | "offer.validity" | "offer.terms" | "offer.discount" | "offer.months" | "offer.ends_at", string>>>>;
756
+ variables: Record<string, Record<string, Partial<Record<"offer.ends_at" | "offer.headline" | "offer.name" | "offer.description" | "offer.eligibility" | "offer.validity" | "offer.terms" | "offer.discount" | "offer.months", string>>>>;
757
757
  locales: Record<string, {
758
- plans: Record<string, never>;
759
758
  nodes: Record<string, {
760
759
  base: {
761
- couponId?: string | undefined;
762
- label?: string | undefined;
763
760
  text?: string | undefined;
761
+ label?: string | undefined;
764
762
  alt?: string | undefined;
765
763
  html?: string | undefined;
766
764
  countdownAt?: string | undefined;
765
+ couponId?: string | undefined;
767
766
  missing?: string[] | undefined;
768
767
  };
769
768
  }>;
769
+ plans: Record<string, never>;
770
770
  pickers: Record<string, never>;
771
771
  diagnostics: {
772
772
  nodeId: string;
@@ -846,10 +846,6 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
846
846
  growth: {
847
847
  evaluatedAt: string;
848
848
  expiresAt: string;
849
- scope: {
850
- projectId: string;
851
- environment: "sandbox" | "live";
852
- };
853
849
  features: Record<string, {
854
850
  defaultValue?: z.core.util.JSONType | undefined;
855
851
  rules?: {
@@ -946,6 +942,10 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
946
942
  phase?: string | undefined;
947
943
  }[] | undefined;
948
944
  }>;
945
+ scope: {
946
+ projectId: string;
947
+ environment: "live" | "sandbox";
948
+ };
949
949
  generation: string;
950
950
  savedGroups: Record<string, {
951
951
  type: "hashed";
@@ -1030,7 +1030,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1030
1030
  schemaVersion: 1;
1031
1031
  scope: {
1032
1032
  projectId: string;
1033
- environment: "sandbox" | "live";
1033
+ environment: "live" | "sandbox";
1034
1034
  environmentId: string;
1035
1035
  };
1036
1036
  revision: number;
@@ -1075,7 +1075,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1075
1075
  growth: {
1076
1076
  scope: {
1077
1077
  projectId: string;
1078
- environment: "sandbox" | "live";
1078
+ environment: "live" | "sandbox";
1079
1079
  };
1080
1080
  generation: string;
1081
1081
  evaluatedAt: string;
@@ -1236,7 +1236,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1236
1236
  }[]>;
1237
1237
  scope: {
1238
1238
  projectId: string;
1239
- environment: "sandbox" | "live";
1239
+ environment: "live" | "sandbox";
1240
1240
  };
1241
1241
  funnelId: string;
1242
1242
  versionId: string;
@@ -1246,7 +1246,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1246
1246
  entry: string;
1247
1247
  nodes: {
1248
1248
  id: string;
1249
- type: "output" | "action" | "condition" | "split" | "end" | "coupon" | "coupons" | "screen" | "offering" | "feature" | "entry" | "external_page" | "wait";
1249
+ type: "output" | "action" | "screen" | "end" | "coupon" | "feature" | "split" | "condition" | "offering" | "coupons" | "entry" | "external_page" | "wait";
1250
1250
  outputs: Record<string, string>;
1251
1251
  writes: Record<string, string>;
1252
1252
  resources: {
@@ -1291,7 +1291,7 @@ declare function createConfigurationSync(options: ConfigurationSyncOptions): {
1291
1291
  } | undefined;
1292
1292
  };
1293
1293
  terminals: Record<string, {
1294
- outcome: "failed" | "completed" | "closed" | "ineligible";
1294
+ outcome: "closed" | "failed" | "completed" | "ineligible";
1295
1295
  output: {
1296
1296
  type: "literal";
1297
1297
  value: z.core.util.JSONType;