@tinkerlandai/indiana-sdk 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +5 -1
  2. package/README.md +2 -2
  3. package/README.zh-CN.md +2 -2
  4. package/dist/chunk-4K25DELJ.js +1 -0
  5. package/dist/chunk-CB63JLGT.js +1 -0
  6. package/dist/{chunk-N6UIDDAX.js → chunk-D7YHFS6B.js} +2 -2
  7. package/dist/chunk-FF3LWJ26.js +11 -0
  8. package/dist/chunk-FVUPV6YE.js +1 -0
  9. package/dist/chunk-ISUXYPYL.js +1 -0
  10. package/dist/{chunk-M3DG6ZCT.js → chunk-QG4GM4RI.js} +1 -1
  11. package/dist/chunk-U6S6AZM6.js +1 -0
  12. package/dist/chunk-VVSQKVE7.js +1 -0
  13. package/dist/chunk-YAMBRNJ2.js +1 -0
  14. package/dist/client-OYRHOMUQ.js +1 -0
  15. package/dist/{configuration-sync-Bnu8s4pc.d.ts → configuration-sync-C2mytNwU.d.ts} +18 -0
  16. package/dist/funnel-runtime-host-KPYLOYYN.js +1 -0
  17. package/dist/{funnel-runtime-start-Zbd5ro5r.d.ts → funnel-runtime-start-CVb2YonU.d.ts} +40 -3
  18. package/dist/iam.d.ts +131 -0
  19. package/dist/iam.js +1 -0
  20. package/dist/index.d.ts +40 -4
  21. package/dist/index.js +1 -1
  22. package/dist/native-shell.js +1 -1
  23. package/dist/openrouter.js +1 -1
  24. package/dist/page.d.ts +1 -1
  25. package/dist/page.js +1 -1
  26. package/dist/paywall-5WU6PX5C.js +1 -0
  27. package/dist/popup.d.ts +2 -5
  28. package/dist/popup.js +3 -14
  29. package/dist/server.d.ts +2 -2
  30. package/dist/server.js +1 -1
  31. package/dist/src-U7PBAUBN.js +1 -0
  32. package/dist/visual.d.ts +10 -1
  33. package/dist/visual.js +2 -1
  34. package/package.json +8 -2
  35. package/dist/chunk-BIFEEVQO.js +0 -1
  36. package/dist/chunk-ET4NANGB.js +0 -1
  37. package/dist/chunk-J7M7UH74.js +0 -1
  38. package/dist/chunk-OHDY27EI.js +0 -1
  39. package/dist/chunk-VMLGV5OS.js +0 -11
  40. package/dist/funnel-runtime-host-3STQUS6F.js +0 -1
  41. package/dist/paywall-LBDMGVWZ.js +0 -1
  42. package/dist/src-X6KT6WIH.js +0 -1
  43. package/dist/visual-editor-agent-WW65CMKW.js +0 -1
package/dist/server.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import 'zod';
2
- export { h as FeatureClient, e as FeatureClientOptions, s as FunnelDecisionInput, t as FunnelDecisionTimeoutError, u as FunnelDecisionUsedInput, v as FunnelLocalEvaluation, w as FunnelLocalEvaluator, x as FunnelLocalEvaluatorOptions, y as FunnelLocalSession, z as FunnelLocalSessionOptions, i as FunnelNodeEvaluationContext, A as FunnelSignalInput, g as FunnelStartInput, k as IndianaError, B as IndianaServerOptions, L as LocalFunnelClient, l as LocalFunnelClientOptions, o as createFeatureClient, C as createFunnelCampaignClient, D as createFunnelDecisionClient, E as createFunnelLocalEvaluator, G as createFunnelOrchestrationClient, H as createFunnelStartClient, J as createGuestToken, K as createIndianaServer, p as createLocalFunnelClient, M as createNativeReceiptClient, N as createPaywallStartClient, O as createSynchronizedFunnelLocalEvaluator, r as evaluateFunnelNode, Q as renewFunnelRun } from './funnel-runtime-start-Zbd5ro5r.js';
2
+ export { h as FeatureClient, e as FeatureClientOptions, s as FunnelDecisionInput, t as FunnelDecisionTimeoutError, u as FunnelDecisionUsedInput, v as FunnelLocalEvaluation, w as FunnelLocalEvaluator, x as FunnelLocalEvaluatorOptions, y as FunnelLocalSession, z as FunnelLocalSessionOptions, i as FunnelNodeEvaluationContext, A as FunnelSignalInput, g as FunnelStartInput, k as IndianaError, B as IndianaServerOptions, L as LocalFunnelClient, l as LocalFunnelClientOptions, o as createFeatureClient, C as createFunnelCampaignClient, D as createFunnelDecisionClient, E as createFunnelLocalEvaluator, G as createFunnelOrchestrationClient, H as createFunnelStartClient, J as createGuestToken, K as createIndianaServer, p as createLocalFunnelClient, M as createNativeReceiptClient, N as createPaywallStartClient, O as createSynchronizedFunnelLocalEvaluator, r as evaluateFunnelNode, Q as renewFunnelRun } from './funnel-runtime-start-CVb2YonU.js';
3
3
  export { f as AiPricingOptions, d as AiTokenQuote, b as AiTokenUsage, a as AiUsageContext, g as AiUsageMiddlewareOptions, h as AiUsageRecord, i as aiPriceSnapshotSchema, j as aiTokenQuoteSchema, c as createAiPricing, k as createAiUsageMiddleware, l as createConfiguredAiPricing } from './ai-usage-B4W5m4Ie.js';
4
4
  import './screen-16d-xADb.js';
5
- export { C as ConfigurationSync, c as createConfigurationSync } from './configuration-sync-Bnu8s4pc.js';
5
+ export { C as ConfigurationSync, c as createConfigurationSync } from './configuration-sync-C2mytNwU.js';
6
6
  import './growth-rules-B4YYy64R.js';
7
7
  import '@ai-sdk/provider';
8
8
  import 'zod/v4';
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import{a as j,b,c as pe,d as le,e as Se,f as de,g as me,j as fe,k as Ee,l as qe,m as Ae}from"./chunk-J7M7UH74.js";import{a as Ce,b as Re,c as Fe,d as Le}from"./chunk-M3DG6ZCT.js";import{a as q}from"./chunk-ET4NANGB.js";import{a as s}from"./chunk-5TEZEOHX.js";import"./chunk-S5TVMQRC.js";import{Fi as B,Gi as se,Ig as U,Ii as _,Ji as oe,Lg as X,Ng as Z,Qj as ie,Rh as M,Rj as ce,Tg as te,Vf as o,Wk as ue,ch as V,dh as ne,fh as re,qh as N,rh as R,sh as ae}from"./chunk-VMLGV5OS.js";import{Rb as ee}from"./chunk-RMJJOSVZ.js";import{b as Y,h as W}from"./chunk-OHDY27EI.js";import{B as $,b as H,m as J}from"./chunk-S2MSIA57.js";function p(n,r){try{return n.parse(r)}catch{throw new s("INVALID_RESPONSE","Invalid gateway response")}}function we(n){let r=le(n),t=i=>{throw new s("INVALID_RESPONSE",i)};r.nodes.size!==n.topology.nodes.length&&t("Duplicate local node identity"),r.nodes.get(n.topology.entry)?.type!=="entry"&&t("A local Funnel must start at Entry");let e=new Set(["entry","condition","feature","split","end","output"]);for(let i of r.nodes.values()){if(!e.has(i.type))throw new s("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(i.type==="entry"&&i.id!==n.topology.entry&&t("Unexpected Entry node"),["entry","feature"].includes(i.type)&&!i.outputs.next&&t("Local next exit is unavailable"),i.type==="feature"){let c=i.resources.featureKey;(!c||!Object.hasOwn(n.evaluation.variables,i.writes.value)||!Object.hasOwn(r.features,c))&&t("Local Feature definition or declaration is unavailable")}if(i.type==="condition"){let c=n.conditions[i.id];(!c||!i.outputs.default||c.some((f,m)=>f.port!==`case:${m}`||!i.outputs[f.port]))&&t("Local Condition exits are unavailable")}if(i.type==="split"&&(!i.resources.experimentId||!Object.hasOwn(n.growth.experiments,i.resources.experimentId)||!i.outputs.notParticipating)&&t("Local Experiment definition or exit is unavailable"),i.type==="end"||i.type==="output"){let c=n.evaluation.terminals[i.id];if(!c)throw new s("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(i.outputs).length&&t("A terminal cannot have outgoing edges"),c.output?.type==="feature"&&!Object.hasOwn(r.features,c.output.featureKey)&&t("Terminal Feature definition is unavailable")}for(let c of Object.values(i.outputs))r.nodes.has(c)||t("Local target is unavailable")}let a=new Set,u=new Set;function l(i){if(u.has(i)&&t("Local graph contains a cycle"),!a.has(i)){u.add(i);for(let c of Object.values(r.nodes.get(i).outputs))l(c);u.delete(i),a.add(i)}}return l(n.topology.entry),a.size!==r.nodes.size&&t("Local graph contains unreachable nodes"),{evaluate(i){let c={},f=i.context;f.features=r.features,f.savedGroups=r.savedGroups;let m=()=>{f.attributes=Z({declarations:n.evaluation.variables,attributes:i.attributes,parameters:i.parameters,answers:{},results:c,savedGroups:r.savedGroups})};m();let I=n.topology.entry,d=0;for(;;){let w=r.nodes.get(I);if(w.type==="end"||w.type==="output"){let y=n.evaluation.terminals[I],h=y.output,v=h?.type==="feature"?r.feature(h.featureKey,f):h?.type==="variable"?te({source:"variable",key:h.key,...h.path?{path:h.path}:{}},{declarations:n.evaluation.variables,answers:{},results:c,parameters:i.parameters,attributes:i.attributes,savedGroups:r.savedGroups}):h?.value??null;return U(n.evaluation.outputSchema,v)||t("Local output does not match its declaration"),{outcome:y.outcome,value:v}}if(d++>=n.evaluation.maxTransitions)throw new s("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(w.type==="entry")I=w.outputs.next;else{let y=r.evaluate(I,f);if(w.type==="feature"){let h=w.writes.value,v=y.value??null;U(n.evaluation.variables[h],v)||t("Local Feature value does not match its declaration"),X(n.evaluation.variables,{writes:w.writes},{[h]:v}),c[h]=v,m()}I=y.target}}}}}import{z as ye}from"zod";function Ie(n,r,t){let e=J.parse(n.attributes);if(["parameters","answers","results"].some(S=>Object.hasOwn(e,S)))throw new s("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let a=ee.parse(n.parameters??{}),u=ye.record(ye.string(),$).parse(n.stickyBucketAssignmentDocs??{});for(let[S,g]of Object.entries(u))if(S!==`${g.attributeName}||${g.attributeValue}`||!Object.hasOwn(e,g.attributeName)||H(e[g.attributeName])!==g.attributeValue)throw new s("INVALID_REQUEST","Sticky document identity does not match this session");let l=n.saveStickyBucketAssignmentDoc,i=n.onFeatureUsage,c=n.onExperimentViewed,f=n.onError,m=new Map,I=new Set,d={},w=Promise.resolve();function y(S){let g=w.then(()=>(t(),S()));return w=g.catch(()=>{}),g}function h(S){try{f?.(S)}catch{}}function v(S){try{let g=S();g&&typeof g.catch=="function"&&g.catch(h)}catch(g){h(g)}}async function L(){for(let[S,g]of m){if(t(),l)try{await l(structuredClone(g))}catch{throw new s("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}t(),m.delete(S)}}return{evaluate(S={}){let g=S.track===!0;return y(async()=>{let D=await r();t(D);let K=new Set(I),z={...d},Q=new Map,T=[],he={stickyBucketAssignmentDocs:structuredClone(u),saveStickyBucketAssignmentDoc(E){Q.set(`${E.attributeName}||${E.attributeValue}`,structuredClone(E))},...g?{trackedExperiments:K,trackedFeatureUsage:z,onExperimentViewed(E,C){let P=structuredClone(E),ve=structuredClone(C);c&&T.push(()=>c(structuredClone(P),structuredClone(ve)))},onFeatureUsage(E,C){let P=structuredClone(C);i&&T.push(()=>i(E,structuredClone(P)))}}:{}},ge=D.program.evaluate({attributes:e,parameters:a,context:he});t(D);for(let[E,C]of Q)u[E]=C,m.set(E,C);await L(),t(D),g&&(I=K,d=z);for(let E of T)v(E);let O=D.configuration;return structuredClone({evaluationMode:"local",scope:O.scope,funnelId:O.funnelId,versionId:O.versionId,evaluationRevision:O.evaluationRevision,generation:O.growth.generation,...ge})})},flush:()=>y(L),get stickyBucketAssignmentDocs(){return t(),structuredClone(u)}}}var De=6e4;function x(n){if(typeof window<"u")throw new s("SERVER_ONLY","Local Funnel sessions run on your backend");let r=Y.parse(n.scope),t=n.funnelId,e=n.load,a,u,l,i=0,c=I=>Date.now()>=I.expiresAt;async function f(){if(u)return u;let I=i;a=void 0;let d=(async()=>{let w=await e();if(I!==i)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(w&&typeof w=="object"&&"evaluationMode"in w&&w.evaluationMode==="remote")throw p(_,w),new s("EVALUATION_MODE","This Funnel requires remote decide");let y=p(oe,w);if(I!==i)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment||y.funnelId!==t)throw new s("SCOPE_MISMATCH","Local configuration scope changed");if(y.growth.scope.projectId!==r.projectId||y.growth.scope.environment!==r.environment||y.growth.expiresAt!==y.expiresAt)throw new s("INVALID_RESPONSE","GB configuration scope or expiry changed");let h=Math.min(Date.now()+De,y.expiresAt?Date.parse(y.expiresAt):1/0);if(Date.now()>=h)throw new s("CONFIGURATION_EXPIRED","Refresh expired local rules");let v=JSON.stringify([r.projectId,r.environment,t,y.versionId,y.evaluationRevision,y.growth.generation]),L=[y.topology,y.conditions,y.evaluation,y.growth.features,y.growth.experiments,y.growth.savedGroups];if(l?.key===v&&!pe(l.body,L))throw new s("INVALID_RESPONSE","Immutable local configuration identity changed");return l?.key!==v&&(l={key:v,body:L,program:we(y)}),a={key:v,configuration:y,expiresAt:h,program:l.program},a})();u=d;try{return await d}finally{u===d&&(u=void 0)}}function m(){return u??(a&&!c(a)?Promise.resolve(a):f())}return{session(I){let d=i;return Ie(I,m,w=>{if(n.assertUsable?.(),d!==i)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(w&&(c(w)||a?.key!==w.key))throw new s("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await f()).configuration)},reset(){i++,a=void 0,u=void 0,l=void 0}}}function Oe(n,r){let t=n.snapshot?.generation,e=x({scope:{projectId:n.scope.projectId,environment:n.scope.environment},funnelId:r,load:()=>n.localFunnel(r),assertUsable:()=>n.assertFunnel(r)}),a=n.subscribe(()=>{let l=n.snapshot?.generation;n.fresh&&l!==t&&(t=l,e.refresh().catch(()=>{}))}),u=e.session;return Object.assign(e,{session(l){let i=u(l),c=i.evaluate;return Object.assign(i,{async evaluate(...f){return n.fresh||await n.refresh(),c(...f)}})},destroy(){a(),e.reset()}})}function _e(n){if(typeof window<"u")throw new s("SERVER_ONLY","Secret API keys must stay on the backend");return{start:r=>fe(n,r)}}var F=class extends s{constructor(t,e){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,e);this.decisionId=t;this.decisionRequestId=e}decisionId;decisionRequestId};async function k(n,r,t,e){let{decisionId:a,requestId:u}=n,l=n,i=250;for(;;){if(l.decisionId!==a||l.requestId!==u||l.decision&&!b(l.decision,r))throw new s("INVALID_RESPONSE","Decision request or customer changed");if(l.decision)return l.decision;if(l.status==="failed")throw new s("DECISION_FAILED","Decision execution failed",503,u);if(Date.now()>=t)throw new F(a,u);if(await new Promise(c=>setTimeout(c,Math.min(i,t-Date.now()))),Date.now()>=t)throw new F(a,u);i=Math.min(1e3,i*2);try{l=await e(a,t)}catch(c){if(c instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(c.code))continue;throw c}}}function G(n){if("remoteEval"in n)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new s("SERVER_ONLY","Funnel decisions are requested by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new s("INVALID_TOKEN","A server API key is required");let r,t,e=new Map;async function a(c,f){let m=c;m.status!=="pending"&&e.delete(m.decisionId);for(let I=0;I<32&&m.evaluation;I++){let d=m.evaluation;if(d.runId!==m.decisionId)throw new s("INVALID_RESPONSE","Local evaluation Run changed");let w=e.get(m.decisionId);if(!w&&d.type==="evaluate_segment"){let h=ue.parse(await u({operation:"segment_configuration",funnelId:n.funnelId,versionId:d.versionId},f));if(h.configuration.scope.projectId!==n.scope.projectId||h.configuration.scope.environment!==n.scope.environment||h.configuration.funnelId!==n.funnelId||h.configuration.versionId!==d.versionId||h.configuration.evaluationRevision!==d.policyRevision)throw new s("SCOPE_MISMATCH","Original decision segment configuration changed");if(e.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding decisions first");w={operation:"commit_decision_segment",decisionId:m.decisionId,requestId:M(m.decisionId,d.visit,`segment:${d.revision}`),nodeId:d.nodeId,visit:d.visit,revision:d.revision,policyRevision:d.policyRevision,generation:h.configuration.growth.generation,...me(h.configuration,h.document,d)},e.set(m.decisionId,w)}if(!w){if(d.type!=="evaluate")throw new s("INVALID_RESPONSE","Unknown decision instruction");if((!t||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())&&(t=_.parse(await u({operation:"configuration",funnelId:n.funnelId,versionId:d.versionId},f))),t.scope.projectId!==n.scope.projectId||t.scope.environment!==n.scope.environment||t.funnelId!==n.funnelId)throw new s("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(t.evaluationMode!=="local"||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision)throw new s("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(e.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding Local decisions first");w={operation:"evaluate_decision",decisionId:m.decisionId,requestId:M(m.decisionId,d.visit,"evaluation"),nodeId:d.nodeId,visit:d.visit,revision:d.revision,receiptId:d.receiptId,policyRevision:d.policyRevision,generation:t.growth.generation,result:de(t,d.nodeId,d)},e.set(m.decisionId,w)}let y=R.parse(await u(w,f));if(y.decisionId!==c.decisionId||y.requestId!==c.requestId)throw new s("INVALID_RESPONSE","Decision identity changed during local evaluation");e.delete(m.decisionId),m=y}return m}async function u(c,f,m=!1){let I=q({...n,fetch:(d,w)=>{let y=new Headers(w?.headers);return y.set("Accept-Encoding","identity"),m&&y.set("Prefer","respond-async"),(n.fetch??globalThis.fetch)(d,{...w,headers:y})},timeoutMs:Math.min(n.timeoutMs??1e4,f?Math.max(1,f-Date.now()):12e4)});return I.identify(n.apiKey),I.request("funnels",c)}async function l(c,f){let m=R.parse(await u(N.parse({operation:"read_decision",decisionId:c}),f));if(m.decisionId!==c)throw new s("INVALID_RESPONSE","Decision identity changed");return a(m,f)}async function i(c,f,m=!1){let I=N.options[0].parse({...c,operation:"decide",funnelId:n.funnelId}),d;try{d=R.parse(await u(I,f,m))}catch(w){throw w instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(w.code)?new s("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",w.status,c.requestId):w}if(d.requestId!==c.requestId||d.decision&&!b(d.decision,I.customer))throw new s("INVALID_RESPONSE","Decision request or customer changed");return{response:await a(d,f),customer:I.customer}}return{local(){return r??=x({scope:n.scope,funnelId:n.funnelId,load:()=>u({operation:"local_configuration",funnelId:n.funnelId})})},async configuration(){let c=_.parse(await u({operation:"configuration",funnelId:n.funnelId}));if(c.scope.projectId!==n.scope.projectId||c.scope.environment!==n.scope.environment||c.funnelId!==n.funnelId)throw new s("SCOPE_MISMATCH","Configuration scope changed");return c},features(c={}){return j({...c,scope:n.scope,load:async()=>W.parse(await u({operation:"feature_config",funnelId:n.funnelId}))})},read:c=>l(c),async submit(c){return(await i(c,void 0,!0)).response},async decide(c){let f=Date.now()+3e4,m=await i(c,f);return k(m.response,m.customer,f,l)},async reportUsed(c){let f=ae.parse(await u(N.parse({...c,operation:"report_used"})));if(f.decisionId!==c.decisionId||f.eventId!==c.eventId)throw new s("INVALID_RESPONSE","Usage receipt identity changed");return f}}}function Ne(n){if(typeof window<"u")throw new s("SERVER_ONLY","Native receipts are verified by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new s("INVALID_TOKEN","Server API key required");let r=q({...n,timeoutMs:n.timeoutMs??35e3});return r.identify(n.apiKey),{async recover(t){let e=ie.parse(t);if(e.orderId!==e.receiptId)throw new s("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let a=e.nativeEvidence,u={requestId:e.requestId,customerToken:e.customerToken,purchaseIntentId:e.orderId,...a===null?{intent:"read"}:a.provider==="apple"?{provider:"apple",signedTransaction:a.signedTransaction}:{provider:"google",purchaseToken:a.purchaseToken}},l=o.restoreNativePurchase.response.parse(await r.request(o.restoreNativePurchase.path,u));if(l.operation.requestId!==e.requestId)throw new s("INVALID_RESPONSE","Native receipt request identity changed");let i=ce.parse({scope:l.scope,requestId:e.requestId,orderId:l.operation.orderId,receiptId:l.operation.orderId,orderStatus:l.operation.status,refunded:l.operation.refunded,...l.operation.completion===null?{}:{nativeCompletion:{orderId:l.operation.orderId,receiptId:l.operation.orderId,...l.operation.completion}}});if(i.requestId!==e.requestId||i.orderId!==e.orderId||i.receiptId!==e.receiptId||i.scope.projectId!==n.scope.projectId||i.scope.environment!==n.scope.environment)throw new s("INVALID_RESPONSE","Current order receipt scope changed");return i}}}import{z as be}from"zod";var A=be.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function xe(n,r){let t=A.parse(n.inputTokens.total),e=A.parse(n.outputTokens.total),a=A.parse(n.inputTokens.cacheRead??0),u=A.parse(n.inputTokens.cacheWrite??0),l=A.parse(n.outputTokens.reasoning??0);if(a+u>t||l>e||n.inputTokens.noCache!==void 0&&A.parse(n.inputTokens.noCache)!==t-a-u||n.outputTokens.text!==void 0&&A.parse(n.outputTokens.text)!==e-l)throw new s("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:t-a-u,cache_read:a,cache_write:u,output:r==="output"?e:e-l,reasoning:r==="separate"?l:0,input_audio:0,output_audio:0}}function ke(n){if(typeof window<"u")throw new s("SERVER_ONLY","AI usage belongs on the trusted backend");if(!n.modelId||!["output","separate"].includes(n.reasoning))throw new s("INVALID_REQUEST","Model ID and reasoning pricing are required");async function r(e){await n.persist({context:e,modelId:n.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function t(e,a){let u={context:e,modelId:n.modelId,usage:a,tokens:null,quote:null,receipt:null,phase:"captured"};await n.persist(u);let l=n.mapTokens?n.mapTokens(a):xe(a,n.reasoning),i=await n.pricing.quoteTokens({modelId:n.modelId,tokens:l});await n.persist({...u,tokens:l,quote:i,phase:"quoted"});let c=await n.pricing.trackTokens(n.client,{...e,quote:i});if(!c.receipt.accepted)throw new s("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await n.persist({...u,tokens:l,quote:i,receipt:c,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:e}){let a=await n.context(),u;try{u=await e()}catch(l){throw await r(a),l}return await t(a,u.usage),u},async wrapStream({doStream:e}){let a=await n.context(),u;try{u=await e()}catch(m){throw await r(a),m}let l=!1,i=!1,c=u.stream.getReader();async function f(){l||i||(i=!0,await r(a))}return{...u,stream:new ReadableStream({async pull(m){try{let{value:I,done:d}=await c.read();if(d){if(!l)throw await f(),new s("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");m.close();return}if(I.type==="finish"){if(l)throw new s("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");l=!0,await t(a,I.usage)}m.enqueue(I)}catch(I){try{await f()}finally{m.error(I),await c.cancel(I)}}},async cancel(m){try{await f()}finally{await c.cancel(m)}}})}}}}function Te(n){if(typeof window<"u")throw new s("SERVER_ONLY","Funnel receipts are sent by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new s("INVALID_TOKEN","A server API key is required");let r=q(n);return r.identify(n.apiKey),{async signal(t){let e=V.parse({...t,operation:"signal"}),a=ne.parse(await r.request("funnels",e));if(a.runId!==t.runId||a.eventId!==t.eventId||a.scope.projectId!==n.scope.projectId||a.scope.environment!==n.scope.environment)throw new s("INVALID_RESPONSE","Receipt identity changed");return a},async readResults(t){let e=V.parse({operation:"read_results",runId:t}),a=re.parse(await r.request("funnels",e));if(a.runId!==t||a.scope.projectId!==n.scope.projectId||a.scope.environment!==n.scope.environment)throw new s("INVALID_RESPONSE","Result identity changed");return a}}}function Pe(n){if("remoteEval"in n)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new s("SERVER_ONLY","Campaign entry requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new s("INVALID_TOKEN","A server API key is required");let r=q({...n,timeoutMs:n.timeoutMs??35e3});return r.identify(n.apiKey),{async decide(t){let e=Date.now()+(n.timeoutMs??3e4),a=B.parse({...t,funnelId:n.funnelId,operation:"campaign_decide"}),u=q({...n,timeoutMs:Math.min(n.timeoutMs??35e3,Math.max(1,e-Date.now()))});u.identify(n.apiKey);let l=R.parse(await u.request("funnels",a));if(l.scope.projectId!==n.scope.projectId||l.scope.environment!==n.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");return k(l,a.customer,e,(i,c)=>G({...n,timeoutMs:Math.min(n.timeoutMs??1e4,Math.max(1,c-Date.now()))}).read(i))},async start(t){let e=B.parse({...t,funnelId:n.funnelId,operation:"campaign_start"}),a=se.parse(await r.request("funnels",e));if(a.scope.projectId!==n.scope.projectId||a.scope.environment!==n.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in a)&&(a.run.source.id!==n.funnelId||!a.customerId||e.customer.type==="id"&&a.customerId!==e.customer.value))throw new s("INVALID_RESPONSE","Campaign Funnel or Customer changed");return a}}}function xt(){if(typeof window<"u")throw new s("SERVER_ONLY","Guest identity is issued by your backend");let n=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function kt(n){if(typeof window<"u")throw new s("SERVER_ONLY","Secret API keys must stay on your backend");let r=q(n);return r.identify(n.apiKey),{async listInvoiceTemplates(t={}){let e=o.listInvoiceTemplates;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewInvoice(t){let e=o.previewInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async createInvoice(t){let e=o.createInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageInvoice(t){let e=o.manageInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readInvoiceOperation(t){let e=o.readInvoiceOperation;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listInvoices(t){let e=o.listInvoices;return p(e.response,await r.request(e.path,e.request.parse(t)))},async getInvoice(t){let e=o.getInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async recordCouponRedemption(t){let e=o.recordCouponRedemption,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid Coupon redemption facts");return p(e.response,await r.request(e.path,a.data))},async getFeatures(t={}){let e=o.getFeatures;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async evaluateFeatures(t){let e=o.evaluateFeatures;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async trackEvents(t){let e=o.trackEvents;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async resolvePaywall(t){let e=o.resolvePaywall;return p(e.response,await r.request(e.path,e.request.parse(t)))},async resolveOffering(t){let e=o.resolveOffering;return p(e.response,await r.request(e.path,e.request.parse(t)))},async checkEntitlement(t){let e=o.checkEntitlement;return p(e.response,await r.request(e.path,e.request.parse(t)))},async setupPayment(t){let e=o.setupPayment;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readPaymentSetup(t){let e=o.readPaymentSetup;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewSubscriptionBatch(t){let e=o.previewSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async confirmSubscriptionBatch(t){let e=o.confirmSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionBatch(t){let e=o.readSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async abandonSubscriptionBatch(t){let e=o.abandonSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageSubscriptionTrial(t){let e=o.manageSubscriptionTrial;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionTrial(t){let e=o.readSubscriptionTrial;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listSubscriptions(t){let e=o.listSubscriptions;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listPurchases(t){let e=o.listPurchases;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listSubscriptionConflicts(t){let e=o.listSubscriptionConflicts;return p(e.response,await r.request(e.path,e.request.parse(t)))},async retrySubscriptionConflict(t){let e=o.retrySubscriptionConflict;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewRefund(t){let e=o.previewRefund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async refund(t){let e=o.refund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readRefund(t){let e=o.readRefund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewUpdate(t){let e=o.previewUpdate;return p(e.response,await r.request(e.path,e.request.parse(t)))},async update(t){let e=o.update;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionUpdate(t){let e=o.readSubscriptionUpdate;return p(e.response,await r.request(e.path,e.request.parse(t)))},async restoreNativePurchase(t){let e=o.restoreNativePurchase;return p(e.response,await r.request(e.path,e.request.parse(t)))},async verifySubscriptions(t){let e=o.verifySubscriptions;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewAttach(t){let e=o.previewAttach;return p(e.response,await r.request(e.path,e.request.parse(t)))},async attach(t){let e=o.attach;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionOperation(t){let e=o.readSubscriptionOperation;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readAiPricing(t){let e=o.readAiPricing;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsage(t){let e=o.readUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async setUsage(t){let e=o.setUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageBalanceGrant(t){let e=o.manageBalanceGrant;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readBalanceSource(t){let e=o.readBalanceSource;return p(e.response,await r.request(e.path,e.request.parse(t)))},async adjustBalance(t){let e=o.adjustBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listBalanceGrants(t){let e=o.listBalanceGrants;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageBillingLimits(t){let e=o.manageBillingLimits;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSeats(t){let e=o.readSeats;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageSeat(t){let e=o.manageSeat;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageUsageEntity(t){let e=o.manageUsageEntity;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsageAnalytics(t){let e=o.readUsageAnalytics;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readCreditAnalytics(t){let e=o.readCreditAnalytics;return p(e.response,await r.request(e.path,e.request.parse(t)))},async submitUsageBatch(t){let e=o.submitUsageBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsageBatch(t){let e=o.readUsageBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readHoldings(t){let e=o.readHoldings;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readLedger(t){let e=o.readLedger;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readBillingInvoice(t){let e=o.readBillingInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readCreditStatement(t){let e=o.readCreditStatement;return p(e.response,await r.request(e.path,e.request.parse(t)))},async quoteBalance(t){let e=o.quoteBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async trackUsage(t){let e=o.trackUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async mutateBalance(t){let e=o.mutateBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async getCustomer(t){let e=o.getCustomer,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid customer lookup");let u=e.response.safeParse(await r.request(e.path,a.data));if(!u.success)throw new s("INVALID_RESPONSE","Invalid customer response");return u.data},async listCustomers(t={}){let e=o.listCustomers,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid customer filters");let u=e.response.safeParse(await r.request(e.path,a.data));if(!u.success)throw new s("INVALID_RESPONSE","Invalid customer response");return u.data},async updateCustomer(t){let e=o.updateCustomer,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid customer patch");let u=e.response.safeParse(await r.request(e.path,a.data));if(!u.success)throw new s("INVALID_RESPONSE","Invalid customer response");return u.data},async createGuestCustomer(t){let e=o.createGuestCustomer;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async resumeGuestSession(t){let e=o.resumeGuestSession;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async claimGuestCustomer(t){let e=o.claimGuestCustomer;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async renewCustomerSession(t){let e=o.renewSession;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async revokeCustomerSessions(t){let e=o.revokeSessions;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async createCustomerSession(t){let e=o.createSession.request.safeParse({customerId:t});if(!e.success)throw new s("INVALID_REQUEST","A customer ID is required");let a=o.createSession.response.safeParse(await r.request("customer-sessions",e.data));if(!a.success)throw new s("INVALID_RESPONSE","Invalid customer session response");return a.data},async getOrCreateCustomer(t){let e=o.createCustomer.request.safeParse(t);if(!e.success)throw new s("INVALID_REQUEST","Invalid customer input");let a=o.createCustomer.response.safeParse(await r.request("customers",e.data));if(!a.success)throw new s("INVALID_RESPONSE","Invalid customer response");return a.data},async grantOffer(t){let e=o.grantOffer.request.safeParse({...t,requestId:t.requestId??crypto.randomUUID()});if(!e.success||!e.data.customerId)throw new s("INVALID_REQUEST","Invalid offer grant");let a=o.grantOffer.response.safeParse(await r.request("offers/grant",e.data));if(!a.success)throw new s("INVALID_RESPONSE","Invalid offer response");return a.data}}}async function Tt(n,r){if(typeof window<"u")throw new s("SERVER_ONLY","Renewal requires your backend");let{funnelCredentialCommandSchema:t,funnelCredentialResponseSchema:e}=await import("./src-X6KT6WIH.js"),a=q(n);return a.identify(n.apiKey),e.parse(await a.request("funnels",t.parse({...r,operation:"renew_run"})))}export{F as FunnelDecisionTimeoutError,s as IndianaError,Ce as aiPriceSnapshotSchema,Re as aiTokenQuoteSchema,Fe as createAiPricing,ke as createAiUsageMiddleware,Ee as createConfigurationSync,Le as createConfiguredAiPricing,j as createFeatureClient,Pe as createFunnelCampaignClient,G as createFunnelDecisionClient,x as createFunnelLocalEvaluator,Te as createFunnelOrchestrationClient,qe as createFunnelStartClient,xt as createGuestToken,kt as createIndianaServer,Ae as createLocalFunnelClient,Ne as createNativeReceiptClient,_e as createPaywallStartClient,Oe as createSynchronizedFunnelLocalEvaluator,Se as evaluateFunnelNode,Tt as renewFunnelRun};
1
+ import{a as j,b,c as pe,d as le,e as de,f as me,i as fe,j as Se,k as Ee,l as qe,m as Ae}from"./chunk-YAMBRNJ2.js";import{a as Ce,b as Re,c as Fe,d as Le}from"./chunk-QG4GM4RI.js";import{a as q}from"./chunk-FVUPV6YE.js";import{Ig as U,Ii as B,Ji as se,Lg as X,Li as _,Mi as oe,Ng as Z,Rh as M,Tg as te,Tj as ie,Uj as ce,Vf as o,ch as V,dh as ne,dl as ue,fh as re,qh as N,rh as R,sh as ae}from"./chunk-FF3LWJ26.js";import{a as s}from"./chunk-5TEZEOHX.js";import{Rb as ee}from"./chunk-RMJJOSVZ.js";import"./chunk-S5TVMQRC.js";import{b as Y,h as W}from"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import{B as $,b as H,m as J}from"./chunk-S2MSIA57.js";function p(n,r){try{return n.parse(r)}catch{throw new s("INVALID_RESPONSE","Invalid gateway response")}}function we(n){let r=le(n),t=i=>{throw new s("INVALID_RESPONSE",i)};r.nodes.size!==n.topology.nodes.length&&t("Duplicate local node identity"),r.nodes.get(n.topology.entry)?.type!=="entry"&&t("A local Funnel must start at Entry");let e=new Set(["entry","condition","feature","split","end","output"]);for(let i of r.nodes.values()){if(!e.has(i.type))throw new s("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(i.type==="entry"&&i.id!==n.topology.entry&&t("Unexpected Entry node"),["entry","feature"].includes(i.type)&&!i.outputs.next&&t("Local next exit is unavailable"),i.type==="feature"){let c=i.resources.featureKey;(!c||!Object.hasOwn(n.evaluation.variables,i.writes.value)||!Object.hasOwn(r.features,c))&&t("Local Feature definition or declaration is unavailable")}if(i.type==="condition"){let c=n.conditions[i.id];(!c||!i.outputs.default||c.some((f,m)=>f.port!==`case:${m}`||!i.outputs[f.port]))&&t("Local Condition exits are unavailable")}if(i.type==="split"&&(!i.resources.experimentId||!Object.hasOwn(n.growth.experiments,i.resources.experimentId)||!i.outputs.notParticipating)&&t("Local Experiment definition or exit is unavailable"),i.type==="end"||i.type==="output"){let c=n.evaluation.terminals[i.id];if(!c)throw new s("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(i.outputs).length&&t("A terminal cannot have outgoing edges"),c.output?.type==="feature"&&!Object.hasOwn(r.features,c.output.featureKey)&&t("Terminal Feature definition is unavailable")}for(let c of Object.values(i.outputs))r.nodes.has(c)||t("Local target is unavailable")}let a=new Set,u=new Set;function l(i){if(u.has(i)&&t("Local graph contains a cycle"),!a.has(i)){u.add(i);for(let c of Object.values(r.nodes.get(i).outputs))l(c);u.delete(i),a.add(i)}}return l(n.topology.entry),a.size!==r.nodes.size&&t("Local graph contains unreachable nodes"),{evaluate(i){let c={},f=i.context;f.features=r.features,f.savedGroups=r.savedGroups;let m=()=>{f.attributes=Z({declarations:n.evaluation.variables,attributes:i.attributes,parameters:i.parameters,answers:{},results:c,savedGroups:r.savedGroups})};m();let I=n.topology.entry,d=0;for(;;){let w=r.nodes.get(I);if(w.type==="end"||w.type==="output"){let y=n.evaluation.terminals[I],h=y.output,v=h?.type==="feature"?r.feature(h.featureKey,f):h?.type==="variable"?te({source:"variable",key:h.key,...h.path?{path:h.path}:{}},{declarations:n.evaluation.variables,answers:{},results:c,parameters:i.parameters,attributes:i.attributes,savedGroups:r.savedGroups}):h?.value??null;return U(n.evaluation.outputSchema,v)||t("Local output does not match its declaration"),{outcome:y.outcome,value:v}}if(d++>=n.evaluation.maxTransitions)throw new s("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(w.type==="entry")I=w.outputs.next;else{let y=r.evaluate(I,f);if(w.type==="feature"){let h=w.writes.value,v=y.value??null;U(n.evaluation.variables[h],v)||t("Local Feature value does not match its declaration"),X(n.evaluation.variables,{writes:w.writes},{[h]:v}),c[h]=v,m()}I=y.target}}}}}import{z as ye}from"zod";function Ie(n,r,t){let e=J.parse(n.attributes);if(["parameters","answers","results"].some(S=>Object.hasOwn(e,S)))throw new s("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let a=ee.parse(n.parameters??{}),u=ye.record(ye.string(),$).parse(n.stickyBucketAssignmentDocs??{});for(let[S,g]of Object.entries(u))if(S!==`${g.attributeName}||${g.attributeValue}`||!Object.hasOwn(e,g.attributeName)||H(e[g.attributeName])!==g.attributeValue)throw new s("INVALID_REQUEST","Sticky document identity does not match this session");let l=n.saveStickyBucketAssignmentDoc,i=n.onFeatureUsage,c=n.onExperimentViewed,f=n.onError,m=new Map,I=new Set,d={},w=Promise.resolve();function y(S){let g=w.then(()=>(t(),S()));return w=g.catch(()=>{}),g}function h(S){try{f?.(S)}catch{}}function v(S){try{let g=S();g&&typeof g.catch=="function"&&g.catch(h)}catch(g){h(g)}}async function L(){for(let[S,g]of m){if(t(),l)try{await l(structuredClone(g))}catch{throw new s("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}t(),m.delete(S)}}return{evaluate(S={}){let g=S.track===!0;return y(async()=>{let D=await r();t(D);let K=new Set(I),z={...d},Q=new Map,T=[],he={stickyBucketAssignmentDocs:structuredClone(u),saveStickyBucketAssignmentDoc(E){Q.set(`${E.attributeName}||${E.attributeValue}`,structuredClone(E))},...g?{trackedExperiments:K,trackedFeatureUsage:z,onExperimentViewed(E,C){let P=structuredClone(E),ve=structuredClone(C);c&&T.push(()=>c(structuredClone(P),structuredClone(ve)))},onFeatureUsage(E,C){let P=structuredClone(C);i&&T.push(()=>i(E,structuredClone(P)))}}:{}},ge=D.program.evaluate({attributes:e,parameters:a,context:he});t(D);for(let[E,C]of Q)u[E]=C,m.set(E,C);await L(),t(D),g&&(I=K,d=z);for(let E of T)v(E);let O=D.configuration;return structuredClone({evaluationMode:"local",scope:O.scope,funnelId:O.funnelId,versionId:O.versionId,evaluationRevision:O.evaluationRevision,generation:O.growth.generation,...ge})})},flush:()=>y(L),get stickyBucketAssignmentDocs(){return t(),structuredClone(u)}}}var De=6e4;function x(n){if(typeof window<"u")throw new s("SERVER_ONLY","Local Funnel sessions run on your backend");let r=Y.parse(n.scope),t=n.funnelId,e=n.load,a,u,l,i=0,c=I=>Date.now()>=I.expiresAt;async function f(){if(u)return u;let I=i;a=void 0;let d=(async()=>{let w=await e();if(I!==i)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(w&&typeof w=="object"&&"evaluationMode"in w&&w.evaluationMode==="remote")throw p(_,w),new s("EVALUATION_MODE","This Funnel requires remote decide");let y=p(oe,w);if(I!==i)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment||y.funnelId!==t)throw new s("SCOPE_MISMATCH","Local configuration scope changed");if(y.growth.scope.projectId!==r.projectId||y.growth.scope.environment!==r.environment||y.growth.expiresAt!==y.expiresAt)throw new s("INVALID_RESPONSE","GB configuration scope or expiry changed");let h=Math.min(Date.now()+De,y.expiresAt?Date.parse(y.expiresAt):1/0);if(Date.now()>=h)throw new s("CONFIGURATION_EXPIRED","Refresh expired local rules");let v=JSON.stringify([r.projectId,r.environment,t,y.versionId,y.evaluationRevision,y.growth.generation]),L=[y.topology,y.conditions,y.evaluation,y.growth.features,y.growth.experiments,y.growth.savedGroups];if(l?.key===v&&!pe(l.body,L))throw new s("INVALID_RESPONSE","Immutable local configuration identity changed");return l?.key!==v&&(l={key:v,body:L,program:we(y)}),a={key:v,configuration:y,expiresAt:h,program:l.program},a})();u=d;try{return await d}finally{u===d&&(u=void 0)}}function m(){return u??(a&&!c(a)?Promise.resolve(a):f())}return{session(I){let d=i;return Ie(I,m,w=>{if(n.assertUsable?.(),d!==i)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(w&&(c(w)||a?.key!==w.key))throw new s("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await f()).configuration)},reset(){i++,a=void 0,u=void 0,l=void 0}}}function Oe(n,r){let t=n.snapshot?.generation,e=x({scope:{projectId:n.scope.projectId,environment:n.scope.environment},funnelId:r,load:()=>n.localFunnel(r),assertUsable:()=>n.assertFunnel(r)}),a=n.subscribe(()=>{let l=n.snapshot?.generation;n.fresh&&l!==t&&(t=l,e.refresh().catch(()=>{}))}),u=e.session;return Object.assign(e,{session(l){let i=u(l),c=i.evaluate;return Object.assign(i,{async evaluate(...f){return n.fresh||await n.refresh(),c(...f)}})},destroy(){a(),e.reset()}})}function _e(n){if(typeof window<"u")throw new s("SERVER_ONLY","Secret API keys must stay on the backend");return{start:r=>fe(n,r)}}var F=class extends s{constructor(t,e){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,e);this.decisionId=t;this.decisionRequestId=e}decisionId;decisionRequestId};async function k(n,r,t,e){let{decisionId:a,requestId:u}=n,l=n,i=250;for(;;){if(l.decisionId!==a||l.requestId!==u||l.decision&&!b(l.decision,r))throw new s("INVALID_RESPONSE","Decision request or customer changed");if(l.decision)return l.decision;if(l.status==="failed")throw new s("DECISION_FAILED","Decision execution failed",503,u);if(Date.now()>=t)throw new F(a,u);if(await new Promise(c=>setTimeout(c,Math.min(i,t-Date.now()))),Date.now()>=t)throw new F(a,u);i=Math.min(1e3,i*2);try{l=await e(a,t)}catch(c){if(c instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(c.code))continue;throw c}}}function G(n){if("remoteEval"in n)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new s("SERVER_ONLY","Funnel decisions are requested by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new s("INVALID_TOKEN","A server API key is required");let r,t,e=new Map;async function a(c,f){let m=c;m.status!=="pending"&&e.delete(m.decisionId);for(let I=0;I<32&&m.evaluation;I++){let d=m.evaluation;if(d.runId!==m.decisionId)throw new s("INVALID_RESPONSE","Local evaluation Run changed");let w=e.get(m.decisionId);if(!w&&d.type==="evaluate_segment"){let h=ue.parse(await u({operation:"segment_configuration",funnelId:n.funnelId,versionId:d.versionId},f));if(h.configuration.scope.projectId!==n.scope.projectId||h.configuration.scope.environment!==n.scope.environment||h.configuration.funnelId!==n.funnelId||h.configuration.versionId!==d.versionId||h.configuration.evaluationRevision!==d.policyRevision)throw new s("SCOPE_MISMATCH","Original decision segment configuration changed");if(e.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding decisions first");w={operation:"commit_decision_segment",decisionId:m.decisionId,requestId:M(m.decisionId,d.visit,`segment:${d.revision}`),nodeId:d.nodeId,visit:d.visit,revision:d.revision,policyRevision:d.policyRevision,generation:h.configuration.growth.generation,...me(h.configuration,h.document,d)},e.set(m.decisionId,w)}if(!w){if(d.type!=="evaluate")throw new s("INVALID_RESPONSE","Unknown decision instruction");if((!t||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())&&(t=_.parse(await u({operation:"configuration",funnelId:n.funnelId,versionId:d.versionId},f))),t.scope.projectId!==n.scope.projectId||t.scope.environment!==n.scope.environment||t.funnelId!==n.funnelId)throw new s("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(t.evaluationMode!=="local"||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision)throw new s("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(e.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding Local decisions first");w={operation:"evaluate_decision",decisionId:m.decisionId,requestId:M(m.decisionId,d.visit,"evaluation"),nodeId:d.nodeId,visit:d.visit,revision:d.revision,receiptId:d.receiptId,policyRevision:d.policyRevision,generation:t.growth.generation,result:de(t,d.nodeId,d)},e.set(m.decisionId,w)}let y=R.parse(await u(w,f));if(y.decisionId!==c.decisionId||y.requestId!==c.requestId)throw new s("INVALID_RESPONSE","Decision identity changed during local evaluation");e.delete(m.decisionId),m=y}return m}async function u(c,f,m=!1){let I=q({...n,fetch:(d,w)=>{let y=new Headers(w?.headers);return y.set("Accept-Encoding","identity"),m&&y.set("Prefer","respond-async"),(n.fetch??globalThis.fetch)(d,{...w,headers:y})},timeoutMs:Math.min(n.timeoutMs??1e4,f?Math.max(1,f-Date.now()):12e4)});return I.identify(n.apiKey),I.request("funnels",c)}async function l(c,f){let m=R.parse(await u(N.parse({operation:"read_decision",decisionId:c}),f));if(m.decisionId!==c)throw new s("INVALID_RESPONSE","Decision identity changed");return a(m,f)}async function i(c,f,m=!1){let I=N.options[0].parse({...c,operation:"decide",funnelId:n.funnelId}),d;try{d=R.parse(await u(I,f,m))}catch(w){throw w instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(w.code)?new s("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",w.status,c.requestId):w}if(d.requestId!==c.requestId||d.decision&&!b(d.decision,I.customer))throw new s("INVALID_RESPONSE","Decision request or customer changed");return{response:await a(d,f),customer:I.customer}}return{local(){return r??=x({scope:n.scope,funnelId:n.funnelId,load:()=>u({operation:"local_configuration",funnelId:n.funnelId})})},async configuration(){let c=_.parse(await u({operation:"configuration",funnelId:n.funnelId}));if(c.scope.projectId!==n.scope.projectId||c.scope.environment!==n.scope.environment||c.funnelId!==n.funnelId)throw new s("SCOPE_MISMATCH","Configuration scope changed");return c},features(c={}){return j({...c,scope:n.scope,load:async()=>W.parse(await u({operation:"feature_config",funnelId:n.funnelId}))})},read:c=>l(c),async submit(c){return(await i(c,void 0,!0)).response},async decide(c){let f=Date.now()+3e4,m=await i(c,f);return k(m.response,m.customer,f,l)},async reportUsed(c){let f=ae.parse(await u(N.parse({...c,operation:"report_used"})));if(f.decisionId!==c.decisionId||f.eventId!==c.eventId)throw new s("INVALID_RESPONSE","Usage receipt identity changed");return f}}}function Ne(n){if(typeof window<"u")throw new s("SERVER_ONLY","Native receipts are verified by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new s("INVALID_TOKEN","Server API key required");let r=q({...n,timeoutMs:n.timeoutMs??35e3});return r.identify(n.apiKey),{async recover(t){let e=ie.parse(t);if(e.orderId!==e.receiptId)throw new s("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let a=e.nativeEvidence,u={requestId:e.requestId,customerToken:e.customerToken,purchaseIntentId:e.orderId,...a===null?{intent:"read"}:a.provider==="apple"?{provider:"apple",signedTransaction:a.signedTransaction}:{provider:"google",purchaseToken:a.purchaseToken}},l=o.restoreNativePurchase.response.parse(await r.request(o.restoreNativePurchase.path,u));if(l.operation.requestId!==e.requestId)throw new s("INVALID_RESPONSE","Native receipt request identity changed");let i=ce.parse({scope:l.scope,requestId:e.requestId,orderId:l.operation.orderId,receiptId:l.operation.orderId,orderStatus:l.operation.status,refunded:l.operation.refunded,...l.operation.completion===null?{}:{nativeCompletion:{orderId:l.operation.orderId,receiptId:l.operation.orderId,...l.operation.completion}}});if(i.requestId!==e.requestId||i.orderId!==e.orderId||i.receiptId!==e.receiptId||i.scope.projectId!==n.scope.projectId||i.scope.environment!==n.scope.environment)throw new s("INVALID_RESPONSE","Current order receipt scope changed");return i}}}import{z as be}from"zod";var A=be.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function xe(n,r){let t=A.parse(n.inputTokens.total),e=A.parse(n.outputTokens.total),a=A.parse(n.inputTokens.cacheRead??0),u=A.parse(n.inputTokens.cacheWrite??0),l=A.parse(n.outputTokens.reasoning??0);if(a+u>t||l>e||n.inputTokens.noCache!==void 0&&A.parse(n.inputTokens.noCache)!==t-a-u||n.outputTokens.text!==void 0&&A.parse(n.outputTokens.text)!==e-l)throw new s("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:t-a-u,cache_read:a,cache_write:u,output:r==="output"?e:e-l,reasoning:r==="separate"?l:0,input_audio:0,output_audio:0}}function ke(n){if(typeof window<"u")throw new s("SERVER_ONLY","AI usage belongs on the trusted backend");if(!n.modelId||!["output","separate"].includes(n.reasoning))throw new s("INVALID_REQUEST","Model ID and reasoning pricing are required");async function r(e){await n.persist({context:e,modelId:n.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function t(e,a){let u={context:e,modelId:n.modelId,usage:a,tokens:null,quote:null,receipt:null,phase:"captured"};await n.persist(u);let l=n.mapTokens?n.mapTokens(a):xe(a,n.reasoning),i=await n.pricing.quoteTokens({modelId:n.modelId,tokens:l});await n.persist({...u,tokens:l,quote:i,phase:"quoted"});let c=await n.pricing.trackTokens(n.client,{...e,quote:i});if(!c.receipt.accepted)throw new s("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await n.persist({...u,tokens:l,quote:i,receipt:c,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:e}){let a=await n.context(),u;try{u=await e()}catch(l){throw await r(a),l}return await t(a,u.usage),u},async wrapStream({doStream:e}){let a=await n.context(),u;try{u=await e()}catch(m){throw await r(a),m}let l=!1,i=!1,c=u.stream.getReader();async function f(){l||i||(i=!0,await r(a))}return{...u,stream:new ReadableStream({async pull(m){try{let{value:I,done:d}=await c.read();if(d){if(!l)throw await f(),new s("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");m.close();return}if(I.type==="finish"){if(l)throw new s("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");l=!0,await t(a,I.usage)}m.enqueue(I)}catch(I){try{await f()}finally{m.error(I),await c.cancel(I)}}},async cancel(m){try{await f()}finally{await c.cancel(m)}}})}}}}function Te(n){if(typeof window<"u")throw new s("SERVER_ONLY","Funnel receipts are sent by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new s("INVALID_TOKEN","A server API key is required");let r=q(n);return r.identify(n.apiKey),{async signal(t){let e=V.parse({...t,operation:"signal"}),a=ne.parse(await r.request("funnels",e));if(a.runId!==t.runId||a.eventId!==t.eventId||a.scope.projectId!==n.scope.projectId||a.scope.environment!==n.scope.environment)throw new s("INVALID_RESPONSE","Receipt identity changed");return a},async readResults(t){let e=V.parse({operation:"read_results",runId:t}),a=re.parse(await r.request("funnels",e));if(a.runId!==t||a.scope.projectId!==n.scope.projectId||a.scope.environment!==n.scope.environment)throw new s("INVALID_RESPONSE","Result identity changed");return a}}}function Pe(n){if("remoteEval"in n)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new s("SERVER_ONLY","Campaign entry requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new s("INVALID_TOKEN","A server API key is required");let r=q({...n,timeoutMs:n.timeoutMs??35e3});return r.identify(n.apiKey),{async decide(t){let e=Date.now()+(n.timeoutMs??3e4),a=B.parse({...t,funnelId:n.funnelId,operation:"campaign_decide"}),u=q({...n,timeoutMs:Math.min(n.timeoutMs??35e3,Math.max(1,e-Date.now()))});u.identify(n.apiKey);let l=R.parse(await u.request("funnels",a));if(l.scope.projectId!==n.scope.projectId||l.scope.environment!==n.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");return k(l,a.customer,e,(i,c)=>G({...n,timeoutMs:Math.min(n.timeoutMs??1e4,Math.max(1,c-Date.now()))}).read(i))},async start(t){let e=B.parse({...t,funnelId:n.funnelId,operation:"campaign_start"}),a=se.parse(await r.request("funnels",e));if(a.scope.projectId!==n.scope.projectId||a.scope.environment!==n.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in a)&&(a.run.source.id!==n.funnelId||!a.customerId||e.customer.type==="id"&&a.customerId!==e.customer.value))throw new s("INVALID_RESPONSE","Campaign Funnel or Customer changed");return a}}}function xt(){if(typeof window<"u")throw new s("SERVER_ONLY","Guest identity is issued by your backend");let n=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function kt(n){if(typeof window<"u")throw new s("SERVER_ONLY","Secret API keys must stay on your backend");let r=q(n);return r.identify(n.apiKey),{async listInvoiceTemplates(t={}){let e=o.listInvoiceTemplates;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewInvoice(t){let e=o.previewInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async createInvoice(t){let e=o.createInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageInvoice(t){let e=o.manageInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readInvoiceOperation(t){let e=o.readInvoiceOperation;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listInvoices(t){let e=o.listInvoices;return p(e.response,await r.request(e.path,e.request.parse(t)))},async getInvoice(t){let e=o.getInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async recordCouponRedemption(t){let e=o.recordCouponRedemption,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid Coupon redemption facts");return p(e.response,await r.request(e.path,a.data))},async getFeatures(t={}){let e=o.getFeatures;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async evaluateFeatures(t){let e=o.evaluateFeatures;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async trackEvents(t){let e=o.trackEvents;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async resolvePaywall(t){let e=o.resolvePaywall;return p(e.response,await r.request(e.path,e.request.parse(t)))},async resolveOffering(t){let e=o.resolveOffering;return p(e.response,await r.request(e.path,e.request.parse(t)))},async checkEntitlement(t){let e=o.checkEntitlement;return p(e.response,await r.request(e.path,e.request.parse(t)))},async setupPayment(t){let e=o.setupPayment;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readPaymentSetup(t){let e=o.readPaymentSetup;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewSubscriptionBatch(t){let e=o.previewSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async confirmSubscriptionBatch(t){let e=o.confirmSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionBatch(t){let e=o.readSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async abandonSubscriptionBatch(t){let e=o.abandonSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageSubscriptionTrial(t){let e=o.manageSubscriptionTrial;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionTrial(t){let e=o.readSubscriptionTrial;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listSubscriptions(t){let e=o.listSubscriptions;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listPurchases(t){let e=o.listPurchases;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listSubscriptionConflicts(t){let e=o.listSubscriptionConflicts;return p(e.response,await r.request(e.path,e.request.parse(t)))},async retrySubscriptionConflict(t){let e=o.retrySubscriptionConflict;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewRefund(t){let e=o.previewRefund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async refund(t){let e=o.refund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readRefund(t){let e=o.readRefund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewUpdate(t){let e=o.previewUpdate;return p(e.response,await r.request(e.path,e.request.parse(t)))},async update(t){let e=o.update;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionUpdate(t){let e=o.readSubscriptionUpdate;return p(e.response,await r.request(e.path,e.request.parse(t)))},async restoreNativePurchase(t){let e=o.restoreNativePurchase;return p(e.response,await r.request(e.path,e.request.parse(t)))},async verifySubscriptions(t){let e=o.verifySubscriptions;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewAttach(t){let e=o.previewAttach;return p(e.response,await r.request(e.path,e.request.parse(t)))},async attach(t){let e=o.attach;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionOperation(t){let e=o.readSubscriptionOperation;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readAiPricing(t){let e=o.readAiPricing;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsage(t){let e=o.readUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async setUsage(t){let e=o.setUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageBalanceGrant(t){let e=o.manageBalanceGrant;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readBalanceSource(t){let e=o.readBalanceSource;return p(e.response,await r.request(e.path,e.request.parse(t)))},async adjustBalance(t){let e=o.adjustBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listBalanceGrants(t){let e=o.listBalanceGrants;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageBillingLimits(t){let e=o.manageBillingLimits;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSeats(t){let e=o.readSeats;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageSeat(t){let e=o.manageSeat;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageUsageEntity(t){let e=o.manageUsageEntity;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsageAnalytics(t){let e=o.readUsageAnalytics;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readCreditAnalytics(t){let e=o.readCreditAnalytics;return p(e.response,await r.request(e.path,e.request.parse(t)))},async submitUsageBatch(t){let e=o.submitUsageBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsageBatch(t){let e=o.readUsageBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readHoldings(t){let e=o.readHoldings;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readLedger(t){let e=o.readLedger;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readBillingInvoice(t){let e=o.readBillingInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readCreditStatement(t){let e=o.readCreditStatement;return p(e.response,await r.request(e.path,e.request.parse(t)))},async quoteBalance(t){let e=o.quoteBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async trackUsage(t){let e=o.trackUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async mutateBalance(t){let e=o.mutateBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async getCustomer(t){let e=o.getCustomer,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid customer lookup");let u=e.response.safeParse(await r.request(e.path,a.data));if(!u.success)throw new s("INVALID_RESPONSE","Invalid customer response");return u.data},async listCustomers(t={}){let e=o.listCustomers,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid customer filters");let u=e.response.safeParse(await r.request(e.path,a.data));if(!u.success)throw new s("INVALID_RESPONSE","Invalid customer response");return u.data},async updateCustomer(t){let e=o.updateCustomer,a=e.request.safeParse(t);if(!a.success)throw new s("INVALID_REQUEST","Invalid customer patch");let u=e.response.safeParse(await r.request(e.path,a.data));if(!u.success)throw new s("INVALID_RESPONSE","Invalid customer response");return u.data},async createGuestCustomer(t){let e=o.createGuestCustomer;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async resumeGuestSession(t){let e=o.resumeGuestSession;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async claimGuestCustomer(t){let e=o.claimGuestCustomer;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async renewCustomerSession(t){let e=o.renewSession;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async revokeCustomerSessions(t){let e=o.revokeSessions;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async createCustomerSession(t){let e=o.createSession.request.safeParse({customerId:t});if(!e.success)throw new s("INVALID_REQUEST","A customer ID is required");let a=o.createSession.response.safeParse(await r.request("customer-sessions",e.data));if(!a.success)throw new s("INVALID_RESPONSE","Invalid customer session response");return a.data},async getOrCreateCustomer(t){let e=o.createCustomer.request.safeParse(t);if(!e.success)throw new s("INVALID_REQUEST","Invalid customer input");let a=o.createCustomer.response.safeParse(await r.request("customers",e.data));if(!a.success)throw new s("INVALID_RESPONSE","Invalid customer response");return a.data},async grantOffer(t){let e=o.grantOffer.request.safeParse({...t,requestId:t.requestId??crypto.randomUUID()});if(!e.success||!e.data.customerId)throw new s("INVALID_REQUEST","Invalid offer grant");let a=o.grantOffer.response.safeParse(await r.request("offers/grant",e.data));if(!a.success)throw new s("INVALID_RESPONSE","Invalid offer response");return a.data}}}async function Tt(n,r){if(typeof window<"u")throw new s("SERVER_ONLY","Renewal requires your backend");let{funnelCredentialCommandSchema:t,funnelCredentialResponseSchema:e}=await import("./src-U7PBAUBN.js"),a=q(n);return a.identify(n.apiKey),e.parse(await a.request("funnels",t.parse({...r,operation:"renew_run"})))}export{F as FunnelDecisionTimeoutError,s as IndianaError,Ce as aiPriceSnapshotSchema,Re as aiTokenQuoteSchema,Fe as createAiPricing,ke as createAiUsageMiddleware,Se as createConfigurationSync,Le as createConfiguredAiPricing,j as createFeatureClient,Pe as createFunnelCampaignClient,G as createFunnelDecisionClient,x as createFunnelLocalEvaluator,Te as createFunnelOrchestrationClient,qe as createFunnelStartClient,xt as createGuestToken,kt as createIndianaServer,Ae as createLocalFunnelClient,Ne as createNativeReceiptClient,_e as createPaywallStartClient,Oe as createSynchronizedFunnelLocalEvaluator,Ee as evaluateFunnelNode,Tt as renewFunnelRun};
@@ -0,0 +1 @@
1
+ import{$ as Xa,$a as Xb,$b as Cd,$c as Ge,$d as kh,$e as ki,$f as wj,$g as Ck,$h as Cl,$i as Cm,$j as Dn,$k as Lo,A as Q,Aa as wb,Ab as Lc,Ac as fe,Ad as nf,Ae as Lh,Af as Ri,Ag as Xj,Ah as bl,Ai as bm,Aj as bn,Ak as co,B as R,Ba as xb,Bb as Mc,Bc as ge,Bd as of,Be as Mh,Bf as Si,Bg as Yj,Bh as cl,Bi as cm,Bj as cn,Bk as eo,C as S,Ca as yb,Cb as Nc,Cc as he,Cd as pf,Ce as Nh,Cf as Ti,Cg as Zj,Ch as dl,Ci as dm,Cj as dn,Ck as fo,D as T,Da as zb,Db as Oc,Dc as ie,Dd as qf,De as Oh,Df as Ui,Dg as _j,Dh as el,Di as em,Dj as en,Dk as go,E as U,Ea as Ab,Eb as Pc,Ec as je,Ed as rf,Ee as Ph,Ef as Vi,Eg as $j,Eh as fl,Ei as fm,Ej as fn,Ek as oo,F as V,Fa as Bb,Fb as Qc,Fc as ke,Fd as uf,Fe as Qh,Ff as Wi,Fg as ak,Fh as gl,Fi as gm,Fj as gn,Fk as po,G as W,Ga as Cb,Gb as Rc,Gc as le,Gd as vf,Ge as Rh,Gf as Xi,Gg as bk,Gh as hl,Gi as hm,Gj as hn,Gk as qo,H as Z,Ha as Db,Hb as Sc,Hc as me,Hd as Sg,He as Sh,Hf as Yi,Hg as ck,Hh as il,Hi as im,Hj as jn,Hk as ro,I as _,Ia as Eb,Ib as Tc,Ic as ne,Id as Tg,Ie as Th,If as Zi,Ig as dk,Ih as jl,Ii as jm,Ij as kn,Ik as so,J as $,Ja as Fb,Jb as ad,Jc as oe,Jd as Ug,Je as Uh,Jf as _i,Jg as ek,Jh as kl,Ji as km,Jj as ln,Jk as to,K as aa,Ka as Gb,Kb as bd,Kc as pe,Kd as Vg,Ke as Vh,Kf as $i,Kg as fk,Kh as ll,Ki as lm,Kj as mn,Kk as uo,L as ba,La as Hb,Lb as cd,Lc as qe,Ld as Wg,Le as Wh,Lf as aj,Lg as gk,Lh as ml,Li as mm,Lj as nn,Lk as vo,M as ca,Ma as Ib,Mb as dd,Mc as re,Md as Xg,Me as Xh,Mf as bj,Mg as hk,Mh as nl,Mi as nm,Mj as on,Mk as wo,N as da,Na as Jb,Nb as ed,Nc as se,Nd as Yg,Ne as Yh,Nf as cj,Ng as ik,Nh as ol,Ni as om,Nj as pn,Nk as xo,O as ea,Oa as Kb,Ob as fd,Oc as te,Od as Zg,Oe as Zh,Of as dj,Og as jk,Oh as pl,Oi as pm,Oj as qn,Ok as yo,P as fa,Pa as Lb,Pb as gd,Pc as ue,Pd as _g,Pe as _h,Pf as ej,Pg as kk,Ph as ql,Pi as qm,Pj as rn,Pk as zo,Q as ga,Qa as Mb,Qb as hd,Qc as ve,Qd as $g,Qe as $h,Qf as fj,Qg as rk,Qh as rl,Qi as rm,Qj as sn,Qk as Ao,R as ha,Ra as Nb,Rb as id,Rc as we,Rd as ah,Re as ai,Rf as gj,Rg as sk,Rh as sl,Ri as sm,Rj as tn,Rk as Bo,S as ia,Sa as Ob,Sb as jd,Sc as xe,Sd as bh,Se as bi,Sf as hj,Sg as tk,Sh as tl,Si as tm,Sj as un,Sk as Co,T as ja,Ta as Pb,Tb as kd,Tc as ye,Td as ch,Te as ci,Tf as ij,Tg as uk,Th as ul,Ti as um,Tj as vn,Tk as Do,U as ka,Ua as Qb,Ub as ld,Uc as ze,Ud as dh,Ue as di,Uf as jj,Ug as vk,Uh as vl,Ui as vm,Uj as wn,Uk as Eo,V as Ra,Va as Rb,Vb as md,Vc as Ae,Vd as eh,Ve as ei,Vf as kj,Vg as wk,Vh as wl,Vi as wm,Vj as xn,Vk as Fo,W as Sa,Wa as Sb,Wb as nd,Wc as Be,Wd as fh,We as fi,Wf as lj,Wg as xk,Wh as xl,Wi as xm,Wj as yn,Wk as Go,X as Ta,Xa as Tb,Xb as yd,Xc as Ce,Xd as gh,Xe as gi,Xf as sj,Xg as yk,Xh as yl,Xi as ym,Xj as zn,Xk as Ho,Y as Ua,Ya as Ub,Yb as zd,Yc as De,Yd as hh,Ye as hi,Yf as tj,Yg as zk,Yh as zl,Yi as zm,Yj as An,Yk as Io,Z as Va,Za as Vb,Zb as Ad,Zc as Ee,Zd as ih,Ze as ii,Zf as uj,Zg as Ak,Zh as Al,Zi as Am,Zj as Bn,Zk as Jo,_ as Wa,_a as Wb,_b as Bd,_c as Fe,_d as jh,_e as ji,_f as vj,_g as Bk,_h as Bl,_i as Bm,_j as Cn,_k as Ko,a,aa as Ya,ab as Yb,ac as Dd,ad as He,ae as lh,af as li,ag as xj,ah as Dk,ai as Dl,aj as Dm,ak as En,al as Mo,b,ba as Za,bb as Zb,bc as Id,bd as Ie,be as mh,bf as mi,bg as yj,bh as Ek,bi as El,bj as Em,bk as Fn,bl as No,c,ca as _a,cb as _b,cc as Jd,cd as Je,ce as nh,cf as ni,cg as zj,ch as Fk,ci as Fl,cj as Fm,ck as Gn,cl as Oo,d,da as $a,db as $b,dc as Kd,dd as Ke,de as oh,df as oi,dg as Aj,dh as Gk,di as Gl,dj as Gm,dk as Hn,dl as Po,e,ea as ab,eb as ac,ec as Ld,ed as Le,ee as ph,ef as pi,eg as Bj,eh as Hk,ei as Hl,ej as Hm,ek as In,el as Qo,f,fa as bb,fb as bc,fc as Md,fd as Me,fe as qh,ff as qi,fg as Cj,fh as Ik,fi as Il,fj as Im,fk as Jn,fl as Ro,g,ga as cb,gb as cc,gc as Nd,gd as Ne,ge as rh,gf as ri,gg as Dj,gh as Jk,gi as Jl,gj as Jm,gk as Kn,h,ha as db,hb as dc,hc as Od,hd as Oe,he as sh,hf as si,hg as Ej,hh as Kk,hi as Kl,hj as Km,hk as Ln,i,ia as eb,ib as ec,ic as Pd,id as Pe,ie as th,if as ti,ig as Fj,ih as Lk,ii as Ll,ij as Lm,ik as Mn,j,ja as fb,jb as fc,jc as Qd,jd as Xe,je as uh,jf as ui,jg as Gj,jh as Mk,ji as Ml,jj as Mm,jk as Nn,k,ka as gb,kb as vc,kc as Rd,kd as Ye,ke as vh,kf as vi,kg as Hj,kh as Nk,ki as Nl,kj as Nm,kk as On,l,la as hb,lb as wc,lc as Sd,ld as Ze,le as wh,lf as wi,lg as Ij,lh as Ok,li as Ol,lj as Om,lk as Pn,m,ma as ib,mb as xc,mc as Td,md as _e,me as xh,mf as xi,mg as Jj,mh as Pk,mi as Pl,mj as Pm,mk as Qn,n,na as jb,nb as yc,nc as Ud,nd as $e,ne as yh,nf as yi,ng as Kj,nh as Qk,ni as Ql,nj as Qm,nk as Rn,o,oa as kb,ob as zc,oc as Vd,od as af,oe as zh,of as zi,og as Lj,oh as Rk,oi as Rl,oj as Rm,ok as Sn,p,pa as lb,pb as Ac,pc as Wd,pd as bf,pe as Ah,pf as Ai,pg as Mj,ph as Sk,pi as Sl,pj as Sm,pk as Tn,q,qa as mb,qb as Bc,qc as Xd,qd as cf,qe as Bh,qf as Bi,qg as Nj,qh as Tk,qi as Tl,qj as Tm,qk as Un,r,ra as nb,rb as Cc,rc as Yd,rd as df,re as Ch,rf as Ci,rg as Oj,rh as Uk,ri as Ul,rj as Um,rk as Vn,s,sa as ob,sb as Dc,sc as Zd,sd as ef,se as Dh,sf as Di,sg as Pj,sh as Vk,si as Vl,sj as Vm,sk as Wn,t as z,ta as pb,tb as Ec,tc as _d,td as ff,te as Eh,tf as Ei,tg as Qj,th as Wk,ti as Wl,tj as Wm,tk as Xn,u as A,ua as qb,ub as Fc,uc as $d,ud as gf,ue as Fh,uf as Fi,ug as Rj,uh as Xk,ui as Xl,uj as Xm,uk as Yn,v as B,va as rb,vb as Gc,vc as ae,vd as hf,ve as Gh,vf as Gi,vg as Sj,vh as Yk,vi as Yl,vj as Ym,vk as Zn,w as C,wa as sb,wb as Hc,wc as be,wd as jf,we as Hh,wf as Hi,wg as Tj,wh as Zk,wi as Zl,wj as Zm,wk as _n,x as D,xa as tb,xb as Ic,xc as ce,xd as kf,xe as Ih,xf as Oi,xg as Uj,xh as _k,xi as _l,xj as _m,xk as $n,y as E,ya as ub,yb as Jc,yc as de,yd as lf,ye as Jh,yf as Pi,yg as Vj,yh as $k,yi as $l,yj as $m,yk as ao,z as P,za as vb,zb as Kc,zc as ee,zd as mf,ze as Kh,zf as Qi,zg as Wj,zh as al,zi as am,zj as an,zk as bo}from"./chunk-FF3LWJ26.js";import{$ as xd,$a as ig,A as lc,Aa as Jf,Ab as Jg,B as mc,Ba as Kf,Bb as Kg,C as nc,Ca as Lf,Cb as Lg,D as oc,Da as Mf,Db as Mg,E as pc,Ea as Nf,Eb as Ng,F as qc,Fa as Of,Fb as Og,G as rc,Ga as Pf,Gb as Pg,H as sc,Ha as Qf,Hb as Qg,I as tc,Ia as Rf,Ib as Rg,J as uc,Ja as Sf,Jb as mj,K as Uc,Ka as Tf,Kb as nj,L as Vc,La as Uf,Lb as oj,M as Wc,Ma as Vf,Mb as pj,N as Xc,Na as Wf,Nb as qj,O as Yc,Oa as Xf,Ob as rj,P as Zc,Pa as Yf,Pb as lk,Q as _c,Qa as Zf,Qb as mk,R as $c,Ra as _f,Rb as nk,S as od,Sa as $f,Sb as ok,T as pd,Ta as ag,Tb as pk,U as qd,Ua as bg,Ub as qk,V as rd,Va as cg,W as sd,Wa as dg,X as td,Xa as eg,Y as ud,Ya as fg,Z as vd,Za as gg,_ as wd,_a as hg,a as t,aa as Ed,ab as jg,b as u,ba as Fd,bb as kg,c as v,ca as Gd,cb as lg,d as w,da as Hd,db as mg,e as x,ea as Qe,eb as ng,f as y,fa as Re,fb as og,g as F,ga as Se,gb as pg,h as G,ha as Te,hb as qg,i as H,ia as Ue,ib as rg,j as I,ja as Ve,jb as sg,k as J,ka as We,kb as tg,l as K,la as sf,lb as ug,m as L,ma as tf,mb as vg,n as M,na as wf,nb as wg,o as N,oa as xf,ob as xg,p as O,pa as yf,pb as yg,q as Ma,qa as zf,qb as zg,r as Na,ra as Af,rb as Ag,s as Oa,sa as Bf,sb as Bg,t as Pa,ta as Cf,tb as Cg,u as Qa,ua as Df,ub as Dg,v as gc,va as Ef,vb as Eg,w as hc,wa as Ff,wb as Fg,x as ic,xa as Gf,xb as Gg,y as jc,ya as Hf,yb as Hg,z as kc,za as If,zb as Ig}from"./chunk-RMJJOSVZ.js";import{a as X,b as Y,c as Ii,d as Ji,e as Ki,f as Li,g as Mi,h as Ni,j as ho,k as io,l as jo,m as ko,n as lo,o as mo,p as no}from"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import{A as Ia,B as Ja,C as Ka,D as La,a as la,b as ma,c as na,f as oa,g as pa,h as qa,i as ra,j as sa,l as ta,m as ua,n as va,o as wa,p as xa,q as ya,r as za,s as Aa,t as Ba,u as Ca,v as Da,w as Ea,x as Fa,y as Ga,z as Ha}from"./chunk-S2MSIA57.js";export{Yh as CODE_REFERENCE_LIMITS,Pa as COMMON_LOCALES,oo as CONFIGURATION_POLICY,Ra as COUPON_TERM_LOCALES,Hf as CUSTOMER_DATA_SOURCES,Td as CreateInvoiceParamsSchema,Sd as CreateInvoicePreviewSchema,Ym as DEFAULT_AUDIENCE_GROUP,Bk as DEFAULT_FUNNEL_EXECUTION_POLICY,dl as FUNNEL_API_CAPABILITIES,uj as FUNNEL_EXECUTION_LIMITS,sj as FUNNEL_LIMITS,rm as FUNNEL_PREVIEW_LIMITS,Qo as FUNNEL_READ_ONLY_OPERATIONS,vj as FUNNEL_RECORDING_LIMITS,Bo as FUNNEL_SEGMENT_BYTES,Ao as FUNNEL_SEGMENT_LIMIT,gm as FUNNEL_SERVER_KEY_HEADER,ql as FunnelCalculationError,Ko as FunnelLocalCalculationError,Qd as InvoiceModeParamsSchema,Rd as InvoiceTemplateSchema,Ze as OFFERING_MAX_DEPTH,$e as OFFERING_MAX_ITEMS,_e as OFFERING_MAX_PRODUCTS,Bg as POPUP_WIDTHS,Pd as ReissueInvoiceParamsSchema,Sf as SCREEN_LIMITS,mj as SCREEN_RENDER_PATH,Rf as SCREEN_SCHEMA_VERSION,zj as SCREEN_TEMPLATES,vc as SDK_PROTOCOL_HEADER,xc as SDK_SUPPORT_HEADER,yc as SDK_SUPPORT_POLICY,wc as SDK_VERSION_HEADER,zg as SURFACE_PATHS,zf as SURFACE_VARIABLES,Ec as SdkProtocolError,tj as UNBOUND_PRODUCT_VERSION_ID,mo as VISUAL_EDITOR_PARAM,Cc as addSupportMonths,j as aiCreditSystemConfigSchema,lh as aiMarkupSchema,kh as aiModelIdSchema,mh as aiModelRatesSchema,nh as aiPricingConfigurationSchema,jh as aiTokenPools,w as amountToMinor,Fi as analyticsConfigSchema,Hi as analyticsEventEnabled,lc as apiErrorCatalog,mc as apiErrorCodeForStatus,gc as apiErrorCodeSchema,kj as apiOperations,dj as apiPermissionSchema,rn as appResultsSchema,qn as appRevenueSchema,An as appendScreenTemplate,Yn as applyGrowthReleasePlan,_j as archiveSurfaceTemplateSchema,$m as audienceCustomerSchema,jn as audienceFunnelUsageSchema,kn as audienceFunnelUsagesSchema,an as audienceMembersSchema,Hc as audienceSchema,_m as audienceWriteSchema,Tm as auditFieldSchema,Wm as auditHistoryCursorSchema,Xm as auditHistorySchema,Sm as auditResourceSchema,qb as autoTopupPurchaseLimitSchema,Cb as autoTopupStateSchema,eo as autumnAmountToMinor,Hm as autumnCustomerAutoTopupSchema,Mm as autumnCustomerControlsSchema,Om as autumnCustomerMetadataSchema,Lm as autumnCustomerOverageAllowedSchema,Qm as autumnCustomerProductSummarySchema,Pm as autumnCustomerProfileRecordSchema,Im as autumnCustomerSpendLimitSchema,Km as autumnCustomerUsageAlertSchema,Jm as autumnCustomerUsageLimitSchema,Nm as autumnEntityControlsSchema,fo as autumnMinorToAmount,go as autumnUsageUnitAmountDecimal,eh as balanceAdjustmentCommandSchema,fh as balanceAdjustmentStateSchema,Yc as balanceAllocationSchema,Vc as balanceCommandSchema,bd as balanceGrantCommandSchema,ad as balanceGrantCreateSchema,ed as balanceGrantPageSchema,dd as balanceGrantReadSchema,cd as balanceGrantSchema,$c as balanceOperationSchema,Wc as balancePricingSegmentSchema,_c as balanceQuoteSchema,Xc as balanceReceiptUnitsSchema,Zc as balanceRejectionReasonSchema,Gn as balanceSourceReasonSchema,gh as balanceSourceStateSchema,Hn as balanceSourceStatusSchema,Jn as balanceSourcesPageSchema,In as balanceSourcesQuerySchema,jb as billingAccruedMinorSchema,ib as billingAmountMinorSchema,tb as billingAuthorizationSchema,sb as billingAuthorizationTermsSchema,kb as billingBudgetMinorSchema,Db as billingControlInputSchema,Eb as billingControlsSchema,Mb as billingCouponsSchema,z as billingCurrencies,Fb as billingInvoiceLineSchema,Gb as billingInvoiceSchema,Jb as billingInvoicesSchema,xb as billingLimitSchema,Wj as billingPortalInputSchema,Xj as billingPortalSchema,D as billingSettingsMutationSchema,B as billingSettingsSchema,C as billingSettingsScopeSchema,Bb as billingUsageWindowSchema,eg as borderSchema,kg as buttonNodeSchema,rl as calculateFunnelNode,No as calculateLocalFunnelEvaluation,Oo as calculateLocalFunnelSegment,Kc as campaignInputSchema,Ic as campaignOfferSchema,Lc as campaignSchema,Na as canonicalLocale,Af as capabilityBindingSchema,ob as cashPriceSchema,mb as cashPricingSchema,lb as cashPricingTiersSchema,hb as cashUnitAmountMinorSchema,Oh as claimRewardProductRequestSchema,$h as codeReferenceBranchSchema,fi as codeReferenceConfigRequestSchema,ei as codeReferenceConfigureSchema,li as codeReferenceFeatureSummarySchema,Zh as codeReferenceKeySchema,ai as codeReferencePathSchema,ii as codeReferenceReceiptSchema,_h as codeReferenceRepoSchema,hi as codeReferenceReportSchema,ci as codeReferenceRepositoryInputSchema,di as codeReferenceRepositorySchema,gi as codeReferenceScanConfigSchema,ji as codeReferenceScanSchema,ki as codeReferenceSettingsSchema,mi as codeReferenceSummarySchema,Gd as commerceAccessSchema,Qe as commerceContextSchema,De as commerceCursorSchema,Ee as commerceListQuerySchema,Hd as commerceMoneySchema,Cn as commerceProductKind,Fd as commerceProductKindSchema,Ed as commerceProviderSchema,Ea as compileGrowthFeatures,ro as configurationArtifactSchema,xo as configurationDependencies,qo as configurationDependenciesSchema,vo as configurationDigest,so as configurationFunnelSchema,wo as configurationGeneration,uo as configurationJson,po as configurationScopeSchema,Hb as confirmBillingAdjustmentInputSchema,vb as confirmBillingAuthorizationInputSchema,ic as consoleErrorCodeSchema,tc as consoleErrorResponseSchema,ao as consoleHasPermission,ne as consoleRefundRequestSchema,_n as consoleResources,$n as consoleRolePermissions,Zn as consoleRoleSchema,rg as countdownNodeSchema,Ya as couponAppliesToSchema,bb as couponChangeErrors,qg as couponCodeNodeSchema,tl as couponContentDigestSchema,Wa as couponDiscountSchema,bn as couponDisplaySchema,Ej as couponDistributionBatchSchema,Gj as couponDistributionDetailSchema,Dj as couponDistributionPreviewSchema,Fj as couponDistributionRecipientSchema,Hj as couponDistributionWriteSchema,Xa as couponDurationSchema,Za as couponEligibilitySchema,_a as couponInputSchema,Di as couponRedemptionCommandSchema,Ei as couponRedemptionReceiptSchema,Va as couponStatusSchema,Gm as couponTemplateExample,Em as couponTemplateKey,eb as couponWindow,en as createAccountOverviewPage,dn as createCreditCenterPage,gn as createCustomerPageTemplates,gj as createCustomerRequestSchema,hj as createCustomerResponseSchema,fn as createMembershipPage,Qh as createReferralCodeRequestSchema,F as creditAmountSchema,qh as creditAnalyticsFilterSchema,sh as creditAnalyticsPageSchema,rh as creditAnalyticsQuerySchema,oh as creditAnalyticsRangeSchema,ph as creditAnalyticsTimezoneSchema,L as creditDimensionSchema,M as creditMultiplierSchema,H as creditPriceAdjustmentSchema,N as creditPricingSchema,J as creditPropertiesSchema,G as creditQuantitySchema,O as creditRateSchema,Ob as creditResetCountSchema,Nb as creditResetSchema,I as creditResourceKeySchema,Pb as creditRolloverSchema,c as creditSchemaItemSchema,id as creditStatementInputSchema,jd as creditStatementSchema,i as creditSystemConfigSchema,K as creditTiersSchema,t as currencies,A as currencyAmountOptionsSchema,v as currencyDecimals,u as currencySchema,lj as currentApiOperations,kd as currentNotificationEventTypeSchema,og as customHtmlNodeSchema,ka as customerActivitySchema,oi as customerAttributesSchema,Zm as customerAudienceSchema,Jf as customerDataConfigSchema,Mf as customerDataIntentSchema,mg as customerDataNodeSchema,ui as customerDataReferenceMessage,ti as customerDataReferenced,si as customerDataSchema,If as customerDataSourceSchema,jj as customerEntitlementsSchema,Bi as customerFiltersSchema,pi as customerFingerprintSchema,sn as customerFunnelDecisionsSchema,zi as customerGetSchema,sd as customerHoldingsSchema,qi as customerInputSchema,wd as customerLedgerEntrySchema,xd as customerLedgerPageSchema,vd as customerLedgerQuerySchema,xi as customerLookupSchema,wi as customerMutationSchema,Lf as customerPageDataSchema,Kf as customerPageNodeStateSchema,Rm as customerPageSampleData,Ci as customerPageSchema,yi as customerPatchSchema,ec as customerPlanCreateSchema,fc as customerPlanCreatedSchema,ja as customerPlanSchema,vi as customerProfileSchema,ri as customerReferenceSchema,Vj as customerScheduledChangeCancelSchema,Tj as customerScheduledChangeSchema,Uj as customerScheduledChangesSchema,Mc as customerSchema,ni as customerTagsSchema,Ai as customerUpdateRequestSchema,bi as defaultCodeReferenceMethods,yj as defaultScreenTheme,yl as deliveredScreenDocument,cb as describeCoupon,_b as diffProductVariant,lg as dividerNodeSchema,Nf as emptyCustomerPageNode,Se as entitlementCheckInputSchema,Te as entitlementCheckReasonSchema,Ve as entitlementCheckResultSchema,Re as entitlementRequirementSchema,ga as entitlementSnapshotSchema,ij as entitlementStatusSchema,X as environmentSchema,Cd as environmentSettingsSchema,oc as errorCodeMatchesStatus,uc as errorMetadata,qc as errorMetadataSchema,nc as errorPolicy,kc as errorReasonSchema,jc as errorRecoverySchema,rc as errorResponseSchema,Pf as escapeHtmlText,pa as evalCondition,sa as evalFeature,Qi as evaluateFeaturesRequestSchema,Si as evaluateFeaturesResultSchema,Mo as evaluateLocalFunnelNode,dm as executionSourceSchema,Jo as expandFunnelSegment,Da as experimentConfigurationSchema,Ca as experimentPhaseSchema,Ha as experimentSnapshotSchema,n as featureCollectionSchema,g as featureConfigOverrideSchema,k as featureDefinitionSchema,Oi as featureDeliveryPayloadSchema,a as featureIdSchema,$ as featureInputSchema,f as featureMarkupsOverrideSchema,o as featureOptionsSchema,Ni as featurePayloadSchema,m as featureRecordSchema,aa as featureSchema,bo as featureTypes,co as featureUpdateBlockers,l as featureUpdateRulesSchema,od as featureUsageReadSchema,pd as featureUsageSetSchema,qd as featureUsageStateSchema,b as featureUsageTypeSchema,p as featureWriteSchema,Hg as fieldValue,cg as fillSchema,rd as financialAmountSchema,ud as financialCursorSchema,td as financialEntryTypeSchema,Pg as findDocumentNode,Og as findNode,Dm as formatCouponConditions,Ta as formatCouponDiscount,Sa as formatCouponMoney,Ua as formatCouponTerms,y as formatCurrencyMinor,Fn as formatProductBillingPeriod,db as formatUsd,el as funnelApiBindingSchema,bl as funnelApiProjectionSchema,Wk as funnelBundleDefinitionSchema,_k as funnelBundleLiterals,Zk as funnelBundleResultSchema,Xk as funnelBundleSelectionSchema,jm as funnelCampaignCommandSchema,km as funnelCampaignStartResponseSchema,fl as funnelCapabilitySchema,_l as funnelCollectionSchema,Xl as funnelCommandSchema,mm as funnelConfigurationSchema,Fl as funnelConsumedVariables,Io as funnelContextDelta,hm as funnelCredentialCommandSchema,im as funnelCredentialResponseSchema,Wl as funnelDataQueriesSchema,Sk as funnelDecideShape,Tk as funnelDecisionCommandSchema,Mk as funnelDecisionEvaluationSchema,Qk as funnelDecisionOutputSchema,Uk as funnelDecisionResponseSchema,Rk as funnelDecisionSchema,Pk as funnelDecisionSegmentEvaluationSchema,Vk as funnelDecisionUsedResponseSchema,Ol as funnelDocumentDraftSchema,Sl as funnelDocumentSchema,ik as funnelEvaluationAttributes,Lk as funnelEvaluationInstructionSchema,Jk as funnelEvaluationModeSchema,Kk as funnelEvaluationResultSchema,Ak as funnelExecutionPolicySchema,Ll as funnelExecutionStateSchema,hl as funnelExternalPageUrlSchema,zk as funnelExternalTaskSchema,kl as funnelGraphDraftSchema,jl as funnelGraphNodeSchema,ll as funnelGraphSchema,ml as funnelGraphTargets,hn as funnelGroupReferenceSchema,cm as funnelInstructionSchema,sl as funnelInvocationId,nm as funnelLocalConfigurationSchema,vl as funnelLocalScreenCommandSchema,wl as funnelLocalScreenResponseSchema,Ok as funnelLocalSegmentStepSchema,Ro as funnelNodeAcceptsEffect,Jl as funnelNodeInputSchema,Hl as funnelNodeKindSchema,fk as funnelNodeProjections,Kl as funnelNodeResultSchema,ck as funnelNodeWritesSchema,il as funnelOpenInSchema,Fk as funnelOrchestrationCommandSchema,ok as funnelParametersFromUrl,Vl as funnelPresentationSubmissionSchema,sm as funnelPreviewCommandSchema,vm as funnelPreviewDependencySchema,wm as funnelPreviewJournalSchema,tm as funnelPreviewOutcomeSchema,ym as funnelPreviewRequestSchema,zm as funnelPreviewResponseSchema,um as funnelPreviewScenarioSchema,Bm as funnelPreviewShareWriteSchema,Am as funnelPreviewSnapshotSchema,xm as funnelPreviewSourceSchema,$k as funnelProjectionFilterValueSchema,al as funnelProjectionWhereSchema,Ul as funnelPublicationDraftSchema,Ql as funnelPublicationRules,Tl as funnelPublicationSchema,Rl as funnelPublishableDraftSchema,Co as funnelPureNode,Zl as funnelRecordSchema,Il as funnelResourceReferenceSchema,ln as funnelResultsCursorSchema,mn as funnelResultsQuerySchema,Ik as funnelResultsResponseSchema,nn as funnelResultsSchema,em as funnelRunViewSchema,fm as funnelRuntimeResponseSchema,bm as funnelRuntimeStatusSchema,Cl as funnelScreenReads,Bl as funnelScreenTokens,Dl as funnelScreenValues,Po as funnelSegmentConfigurationSchema,Nk as funnelSegmentEvaluationInstructionSchema,Ho as funnelSegmentHasDynamicHash,Do as funnelSegmentPositionSchema,Fo as funnelSegmentSchema,Eo as funnelSegmentStepSchema,Gk as funnelSignalResponseSchema,Cm as funnelStatisticsSchema,Go as funnelStepId,yk as funnelTaskBindingSchema,wk as funnelTaskDataSchema,xk as funnelTaskOutputsSchema,Ck as funnelTaskResponseSchema,Hk as funnelTaskResultsSchema,zn as funnelTemplateDraft,xn as funnelTemplateSchema,om as funnelTopology,lm as funnelTopologySchema,Ml as funnelTraceEventSchema,sk as funnelValueBindingSchema,$j as funnelValueDeclarationSchema,dk as funnelValueMatches,rk as funnelValuePathSchema,hk as funnelValueSchema,ak as funnelVariableDeclarationSchema,bk as funnelVariableDeclarationsSchema,Al as funnelVariableRead,ek as funnelVariableValues,wj as funnelVisitAllowed,Gl as funnelWaitKindSchema,$l as funnelWriteSchema,Ji as gbRuntimeExperimentResultSchema,Ii as gbRuntimeExperimentSchema,Ki as gbRuntimeFeatureRuleSchema,Li as gbRuntimeFeatureSchema,Mi as gbRuntimeSavedGroupsSchema,la as getQueryStringOverride,Xn as getRecommendedRolloutData,qa as getStickyBucketAttributes,Pn as growthAttributeSchema,ua as growthAttributesSchema,Rn as growthCatalogSchema,xa as growthConditionGroupIds,kk as growthConditionPaths,va as growthConditionSchema,Tn as growthDryRunSchema,Un as growthExperimentInspectionSchema,Fa as growthExperimentStop,Ga as growthFeatureExpiry,za as growthFeatureRuleSchema,Aa as growthFeatureSchema,Ba as growthFeaturesSchema,Vn as growthGroupReferenceCursorSchema,Wn as growthGroupReferencesSchema,wa as growthGroupSchema,Qn as growthNamespaceSchema,Sn as growthResourceWriteSchema,Ka as growthRuleContextSchema,ya as growthSavedGroupsSchema,Ia as growthSnapshotSchema,La as growthSplitResultSchema,Of as htmlVariableErrors,Uf as identifierSchema,jg as imageNodeSchema,bg as imagePositionSchema,$f as insetsSchema,Zi as invoiceCommandSchema,fd as invoiceDetailInputSchema,hd as invoiceDetailSchema,aj as invoiceOperationSchema,gd as invoiceProductItemSchema,me as invoiceRefundsSchema,Yi as invoiceTemplateCommandSchema,Xi as invoiceTemplatePageSchema,Vi as invoiceTemplateValuesSchema,pb as isInvoiceCreditPrice,wf as isProductGroup,Bn as isRecurringMembership,Qg as isRtlLocale,Bc as isStableSdkProtocol,na as isURLTargeted,nb as itemBillingCycleSchema,xj as jsonStorageBytes,ta as jsonValueSchema,E as licenseOfferSchema,Ib as listBillingInvoicesInputSchema,Qa as localeLabel,Ma as localeSchema,Ig as localeStatuses,Ng as localizeScreen,zb as manageBillingLimitsInputSchema,yb as manageOveragePolicyInputSchema,$i as managedInvoiceDetailSchema,bj as managedInvoicePageSchema,_i as managedInvoiceSchema,Wi as managedInvoiceTemplateSchema,hc as managementErrorCodeSchema,sc as managementErrorResponseSchema,ag as marginSchema,Oa as matchLocale,jk as matchesGrowthCondition,T as membershipActionSchema,Dn as membershipBillingCount,U as membershipChangeSchema,V as membershipHoldingSchema,R as membershipRulesSchema,W as membershipStateSchema,S as membershipTimingSchema,Um as mergeAuditSchema,_ as metadataSchema,h as meteredConfigSchema,x as minorToAmount,e as modelMarkupsSchema,un as nativeCompletionSchema,Id as nativeCouponStoreOfferLinkWriteSchema,Jd as nativeCouponStoreOfferLinksSchema,Rc as nativeProductBindingSchema,Tc as nativeProductBindingWriteSchema,Sc as nativeProductBindingsPageSchema,tn as nativeProofSchema,Od as nativePurchaseInstructionSchema,vn as nativeReceiptCommandSchema,wn as nativeReceiptResponseSchema,Oe as nativeRestoreCommandSchema,Pe as nativeRestoreResultSchema,Md as nativeStoreOfferForProduct,Kd as nativeStoreOfferSelectionSchema,Ld as nativeStoreOfferSelectionsSchema,Nd as nativeStoreSelectionMatches,ee as nativeSubscriptionUpdatePreviewSchema,fe as nativeSubscriptionUpdateResultSchema,Cj as newBlankSurface,ab as newCouponInput,Gi as newEnvironmentAnalyticsConfig,am as newFunnelDocument,Aj as newScreenFromTemplate,Bj as newSurfaceFromTemplate,Tf as nodeIdSchema,Vm as objectAuditSchema,Pl as offerCopyUnscoped,on as offerFlowInputSchema,pn as offerFlowResultSchema,fb as offerSchema,gb as offerUnavailableReasonSchema,ff as offeringAuthorSchema,kf as offeringCollectionSchema,ef as offeringDocumentSchema,af as offeringItemSchema,bf as offeringItemsSchema,Ye as offeringMetadataSchema,gf as offeringProductEvidenceSchema,Xe as offeringProductIdSchema,cf as offeringProductIds,of as offeringProductOptionSchema,df as offeringProductPaths,qf as offeringPublicationIssues,hf as offeringRecordSchema,nf as offeringSelectorSchema,rf as offeringValueSchema,jf as offeringVersionSchema,pf as offeringWorkspaceSchema,mf as offeringWriteResultSchema,lf as offeringWriteSchema,Uc as overageBehaviorSchema,Ab as overagePolicySchema,Nl as ownedFunnelScreenSchema,Mn as pageExperimentEventSchema,Nn as pageExperimentEventsRequestSchema,On as pageExperimentEventsResponseSchema,Ln as pageExperimentPayloadSchema,Kn as pageExperimentSchema,Zf as paintColorSchema,yo as parsePublicFunnel,pc as parseRetryAfter,qj as parseScreenRenderPath,xe as paymentSetupCommandSchema,ye as paymentSetupReadSchema,Ae as paymentSetupSchema,Ue as paywallCandidateSchema,Ug as paywallClientActionSchema,_g as paywallCollectionSchema,Vg as paywallDocumentDraftSchema,Wg as paywallDocumentSchema,Yg as paywallFlowIssues,bh as paywallLibrarySchema,Xg as paywallProductIssues,uf as paywallProductsSchema,Zg as paywallRecordSchema,We as paywallRequestSchema,dh as paywallResolutionSchema,ch as paywallResolveInputSchema,$g as paywallSummarySchema,ah as paywallWriteSchema,da as planConfigSchema,ea as planInputSchema,ca as planItemSchema,sg as planPickerNodeSchema,fa as planSchema,ha as planVersionSchema,Jc as popupSchema,dc as prepaidAllowanceAmount,r as prepaidPriceAmount,s as prepaidQuantityAmount,Nc as prepaidQuantitySchema,q as prepaidTierPricingSchema,rb as prepareBillingAuthorizationInputSchema,Fm as prepareCouponTemplate,Lo as prepareLocalFunnelNodes,oa as prepareSavedGroups,ub as preparedBillingAuthorizationSchema,Ag as presentationSchema,pg as priceNodeSchema,ba as priceSchema,Sb as productAllowanceSchema,Oc as productBindingSchema,Qc as productBindingWriteSchema,Pc as productBindingsPageSchema,bc as productCollectionSchema,Vb as productConfigurationSchema,Yb as productDefinitionSchema,cc as productEditorOptionsSchema,tf as productGroupingMatches,sf as productGroupingSchema,Ub as productLicenseSchema,Ij as productMigrationBlockReasonSchema,Pj as productMigrationDetailSchema,Jj as productMigrationErrorCodeSchema,Oj as productMigrationItemSchema,Mj as productMigrationItemStatusSchema,Qj as productMigrationListSchema,Kj as productMigrationPreviewSchema,Sj as productMigrationQuerySchema,Lj as productMigrationRunStatusSchema,Nj as productMigrationSchema,Rj as productMigrationWriteSchema,$b as productOptionsSchema,Rb as productPrepaidPriceSchema,Qb as productPricesSchema,ac as productRecordSchema,Sg as productSelectionSchema,Tb as productTrialSchema,Wb as productVariantOverridesSchema,Xb as productVariantSchema,cl as projectFunnelApiOutputs,pm as projectFunnelConfiguration,qm as projectFunnelLocalConfiguration,Bd as projectSettingsSchema,$a as promotionCodeInputSchema,Ac as protocolForSdkVersion,d as providerMarkupsSchema,ul as publicCouponScreenDataSchema,Pi as publicFeatureConfigurationSchema,zo as publicFunnelDocument,zl as publicScreenDocument,xl as publicScreenIssues,Jg as publishChecks,Ge as purchaseListItemSchema,Me as purchaseListPageSchema,Wf as radiusSchema,tk as readFunnelValuePath,Nh as redeemRewardRequestSchema,Rh as referralCodeSchema,Th as referralProgramCollectionSchema,Gh as referralProgramInputSchema,Ih as referralProgramRecordSchema,Lh as referralProgramWriteSchema,Ri as remoteFeatureResultSchema,El as renameFunnelScreenVariable,Dg as replaceFirstPageRoot,cn as resolveCouponDisplay,Yk as resolveFunnelBundle,gl as resolveFunnelCapabilityInputs,Ek as resolveFunnelTaskInputs,uk as resolveFunnelValueBinding,vk as resolveFunnelValueBindings,Zb as resolveProductVariant,Mg as resolveScreenLocale,Fc as resolveSdkProtocol,fj as responseMetaSchema,wb as revokeBillingAuthorizationInputSchema,Vh as rewardActivityRedemptionSchema,Wh as rewardActivitySchema,Fh as rewardCodeInputSchema,Uh as rewardCodeSchema,Xh as rewardCodeWriteSchema,Sh as rewardCollectionSchema,Ch as rewardConfigurationSchema,Ah as rewardGrantExpirySchema,Bh as rewardGrantSchema,Eh as rewardInputSchema,Dh as rewardKeySchema,Jh as rewardOptionSchema,Ph as rewardProductCheckoutSchema,Hh as rewardRecordSchema,Mh as rewardRedemptionSchema,zh as rewardStatusSchema,yh as rewardTypeSchema,Kh as rewardWriteSchema,ra as runExperiment,En as sameMembershipBillingCycle,Zj as saveSurfaceTemplateSchema,Y as scopeSchema,wg as screenActionSchema,mk as screenAnswersSchema,lk as screenDataCursorSchema,Eg as screenDocumentSchema,Xf as screenImageSourceSchema,pk as screenInputBindingsSchema,vg as screenNodeSchema,nk as screenParametersSchema,Tg as screenPresentationSchema,xf as screenProductScopes,yf as screenProductSelections,pj as screenRenderPath,nj as screenRenderPathSchema,rj as screenRenderTags,oj as screenRenderUrlSchema,qk as screenRendererInputSchema,Rg as screenSelections,xg as screenStringsSchema,to as sdkConfigurationManifestSchema,zc as sdkProtocolRegistry,Gc as sdkProtocolResponseHeaders,zd as seatCommandSchema,yd as seatReadSchema,Ad as seatsStateSchema,ol as selectFunnelCondition,vf as selectedPaywallProduct,Gf as selectedSurfaceValue,Lg as servableLocales,Lb as setBillingCouponsInputSchema,fg as shadowSchema,dg as shapeSchema,_f as sizeSchema,Vf as spaceSchema,ng as spacerNodeSchema,Z as stableKeySchema,tg as stackInteractionSchema,ug as stackNodeSchema,Ja as stickyAssignmentDocumentSchema,Xd as stripeAppendContextSchema,Wd as stripeCouponTermsSchema,Yd as stripePurchaseExecutionSchema,je as stripeRefundExecutionSchema,ze as stripeSetupExecutionSchema,be as stripeSubscriptionUpdateExecutionSchema,ce as stripeSubscriptionUpdatePreviewSchema,de as stripeSubscriptionUpdateResultSchema,ue as stripeTrialExecutionSchema,hg as styleSchema,Ud as subscriptionAttachCommandSchema,Zd as subscriptionAttachQuoteSchema,oe as subscriptionBatchCommandSchema,qe as subscriptionBatchGroupSchema,pe as subscriptionBatchReadSchema,re as subscriptionBatchSchema,$d as subscriptionCarryOptionsSchema,Ne as subscriptionConflictPageSchema,Ie as subscriptionConflictQuerySchema,Ke as subscriptionConflictRetryResultSchema,Je as subscriptionConflictRetrySchema,He as subscriptionConflictSchema,Kb as subscriptionCouponExecutionSchema,cj as subscriptionInvoiceModeSchema,Fe as subscriptionListItemSchema,Le as subscriptionListPageSchema,Vd as subscriptionOperationInputSchema,_d as subscriptionOperationSchema,ie as subscriptionRefundCommandSchema,ke as subscriptionRefundPreviewSchema,le as subscriptionRefundResultSchema,se as subscriptionTrialCommandSchema,we as subscriptionTrialPolicySchema,te as subscriptionTrialReadSchema,ve as subscriptionTrialResultSchema,ae as subscriptionUpdateCommandSchema,ge as subscriptionUpdatePreviewSchema,he as subscriptionUpdateResultSchema,Be as subscriptionVerificationInputSchema,Ce as subscriptionVerificationSchema,Qf as substituteHtmlVariables,Ff as substituteSurfaceVariables,Cf as surfaceDataSchema,yg as surfaceSchema,Yj as surfaceTemplateSchema,Bf as surfaceValueSchema,Df as surfaceVariableNames,Kg as templateChecks,yn as templateScreen,ig as textNodeSchema,gg as textStyleSchema,Yf as themeSchema,ma as toAttributeString,Ti as trackEventsRequestSchema,Ui as trackEventsResultSchema,pl as transitionFunnelGraph,Gg as translatableFields,P as trialPolicySchema,Q as trialRecordSchema,Ef as unknownSurfaceVariables,md as usageAlertNotificationDataSchema,nd as usageAllowanceNotificationDataSchema,uh as usageAnalyticsPageSchema,th as usageAnalyticsQuerySchema,xh as usageBatchPageSchema,wh as usageBatchReadSchema,vh as usageBatchSubmitSchema,hh as usageEntityCommandSchema,ih as usageEntitySchema,ld as usageLimitNotificationDataSchema,nl as validateFunnelGraph,gk as validateFunnelProjections,Dk as validateFunnelTaskData,Yl as validateScreenAnswers,Dc as validateSdkProtocolRegistry,ia as validitySchema,ej as verifiedPrincipalSchema,io as visualChangeSchema,lo as visualExperimentPayloadSchema,ko as visualExperimentSchema,ho as visualMutationSchema,no as visualSelectedElementSchema,jo as visualVariationSchema,Cg as walkDocument,Fg as walkScreen,Dd as workspaceSettingsSchema};
package/dist/visual.d.ts CHANGED
@@ -3,7 +3,6 @@ import 'zod';
3
3
 
4
4
  type VisualExperimentsOptions = {
5
5
  environmentId: string;
6
- /** Indiana API origin; defaults to https://api.tinker.cash. */
7
6
  baseUrl?: string;
8
7
  attributes?: Record<string, JsonValue>;
9
8
  disableJsInjection?: boolean;
@@ -14,6 +13,8 @@ type VisualExperimentsOptions = {
14
13
  antiFlickerTimeout?: number;
15
14
  fetch?: typeof globalThis.fetch;
16
15
  log?: (message: string, details: Record<string, unknown>) => void;
16
+ /** Exact IAM file digest emitted by the local build. Only this version's IAM experiments are eligible. */
17
+ appManifestRelease?: string;
17
18
  };
18
19
  declare function createVisualExperiments(options: VisualExperimentsOptions): {
19
20
  start(): Promise<void>;
@@ -31,6 +32,14 @@ declare function createVisualExperiments(options: VisualExperimentsOptions): {
31
32
  parentSelector?: string | undefined;
32
33
  insertBeforeSelector?: string | undefined;
33
34
  }[];
35
+ renderGuard?: {
36
+ schemaVersion: 1;
37
+ renderKey: string;
38
+ routeTemplate: string;
39
+ selectors: string[];
40
+ present: number[];
41
+ absent: number[];
42
+ } | undefined;
34
43
  }>>;
35
44
  readonly generation: string | null;
36
45
  destroy(): void;
package/dist/visual.js CHANGED
@@ -1 +1,2 @@
1
- import{b as _,c as q}from"./chunk-BIFEEVQO.js";import{a as $,b as j,c as P,d as G,e as K,f as N,g as H,i as Q}from"./chunk-N6UIDDAX.js";import"./chunk-S5TVMQRC.js";import"./chunk-OHDY27EI.js";import{f as L,i as O,k as d}from"./chunk-S2MSIA57.js";function re(e){let h=P(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let x=e.fetch??globalThis.fetch.bind(globalThis),E=`${h}/api/v1/visual-experiments/${e.environmentId}`,V=$(e.deviceIdCookie??"indiana_did"),b=j(),c=null,o=!1,I=!1,g="",w={...e.attributes??{}},k,p,v=0,s=new Map,S=new Map,T=new Set,J=K({endpoint:`${E}/events`,fetch:x,log:e.log,label:"Visual exposure"}),y=J.flush,R,u;function m(){clearTimeout(R),u?.remove(),u=void 0}function C(t,i){let l=d(t,i);T.has(l)||e.trackExposures===!1||c?.trackExposures===!1||o||(T.add(l),J.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:V,...b?{sessionId:b}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:t.key,variationKey:i.key}))}function f(){if(!c||o)return;let t=new Set,i={onExperimentViewed:(n,a)=>{t.add(d(n,a))},url:location.href,attributes:{...Q(V,location),...w},savedGroups:L(c.savedGroups),log:e.log},l=new Set;for(let n of c.experiments){let a=n;try{let r=O(a,i);if(S.set(n.changeId,r),!r.inExperiment)continue;l.add(n.changeId);let A=JSON.stringify([r.key,r.value]),D=s.get(n.changeId);if(D?.signature===A){D.applied()&&t.has(d(a,r))&&C(a,r);continue}s.get(n.changeId)?.revert(),s.delete(n.changeId);let F=q(r.value,{allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{t.has(d(a,r))&&C(a,r)},onError:B=>e.log?.("Visual experiment stopped",{experiment:n.key,error:String(B)})});s.set(n.changeId,{signature:A,revert:F.revert,applied:()=>F.applied})}catch(r){e.log?.("Skipping visual experiment",{experiment:n.key,error:String(r)})}}for(let[n,a]of s)l.has(n)||(a.revert(),s.delete(n));m()}async function M(){let t=++v,i=await x(E,{cache:"no-cache",credentials:"omit"});if(!i.ok)throw new Error(`Visual experiments unavailable (${i.status})`);let l=_(await i.json());if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");!o&&t===v&&(c=l)}let z=()=>{g!==location.href&&(g=location.href,f())},U=()=>{y()};return{async start(){if(I||o)return;I=!0;let t=N(h,e.environmentId);if(t){H();let i=await import("./visual-editor-agent-WW65CMKW.js");o||(p=i.startVisualEditorAgent(t,{allowJs:e.disableJsInjection===!1,nonce:e.nonce}));return}e.antiFlicker&&(u=document.createElement("style"),e.nonce&&(u.nonce=e.nonce),u.textContent="body { visibility: hidden !important }",document.head.append(u),R=setTimeout(m,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(await M(),o)return;k=G(z),addEventListener("pagehide",U),g=location.href,f()}finally{m()}},async refresh(){o||p||(await M(),f())},setAttributes(t){w={...t},p||f()},flush:y,getResults(){return new Map(S)},get generation(){return c?.generation??null},destroy(){o=!0,v++,k?.(),p?.(),removeEventListener("pagehide",U),m();for(let t of s.values())t.revert();s.clear(),y()}}}export{re as createVisualExperiments};
1
+ import{a as ce}from"./chunk-CB63JLGT.js";import{c as de}from"./chunk-VVSQKVE7.js";import{a as me,b as he,c as ge,d as ye,f as ve}from"./chunk-D7YHFS6B.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import{f as fe,i as pe,k as B}from"./chunk-S2MSIA57.js";async function be(e,t){let r=e?.body;if(!r)return;let n=r.getReader(),o=0,a=!1,s,i=new Promise((g,d)=>{s=setTimeout(()=>d(Error("Exposure response timeout")),2e3)}),u=()=>{},c=new Promise((g,d)=>{u=()=>d(t?.reason),t?.addEventListener("abort",u,{once:!0}),t?.aborted&&u()});try{for(;;){let g=await Promise.race([n.read(),i,c]);if(g.done){a=!0;return}if(o+=g.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(s),t?.removeEventListener("abort",u),a||n.cancel().catch(()=>{}),n.releaseLock()}}var we=2*1024*1024,At=256*1024;async function Ee(e,t,r,n){let o=()=>{},a=new Promise((s,i)=>{o=()=>i(n.reason),n.addEventListener("abort",o,{once:!0}),n.aborted&&o()});try{let s=e(t,{...r,signal:n});return s.then(i=>{n.aborted&&i.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([s,a])}finally{n.removeEventListener("abort",o)}}async function Ve(e,t,r,n=!1){if(new TextEncoder().encode(r).byteLength>65536)throw Error("Exposure request budget");let o=new AbortController,a=setTimeout(()=>o.abort(Error("Exposure request timeout")),5e3);try{let s=await Ee(e,t,{method:"POST",headers:{"Content-Type":"text/plain"},body:r,credentials:"omit",keepalive:n,redirect:"error"},o.signal);await be(s,o.signal)}finally{clearTimeout(a)}}function Ae(e){let t,r=!1;return{async read(n,o){if(r)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let a=new AbortController;t=a;let{signal:s}=a,i=setTimeout(()=>a.abort(Error("Experiment request timeout")),5e3);try{let u=await Ee(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},s),c=await ce(u,o,s,{requireJson:!1});return s.throwIfAborted(),c}finally{clearTimeout(i),t===a&&(t=void 0)}},destroy(){r=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}function J(e,t=()=>{}){let r=new WeakMap,n=0,o=a=>{let s=r.get(a);if(s!==void 0)return s;let i=[],u=a,c=!0;for(;u;){let g=r.get(u);if(g!==void 0){c=g;break}if(++n>8192||i.length>=256)throw Error("IAM render ancestry budget exceeded");if(i.push(u),t(),u.hasAttribute("hidden")||/(?:^|;)\s*display\s*:\s*none\s*(?:!\s*important\s*)?(?:;|$)/i.test(u.getAttribute("style")??"")){c=!1;break}u=u.parentElement}for(let g of i)r.set(g,c);return c};return a=>{let s=0,i=e.querySelectorAll(a);for(let u=0;u<i.length;u++){let c=i[u];if(!c)throw Error("IAM render selection changed");o(c)&&s++,t()}return s}}var je=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function j(e){if(!je(e)||Object.keys(e).some(a=>!["schemaVersion","renderKey","routeTemplate","selectors","present","absent"].includes(a))||e.schemaVersion!==1||typeof e.renderKey!="string"||!e.renderKey||e.renderKey.length>256||typeof e.routeTemplate!="string"||!e.routeTemplate.startsWith("/")||e.routeTemplate.length>2048||!Array.isArray(e.selectors)||e.selectors.length>512||e.selectors.some(a=>typeof a!="string"||a.length>512||!/^[a-z][a-z0-9-]*\[data-indiana-id="(?:[^"\\\x00-\x1f]|\\["\\])*"\]$/.test(a))||!Array.isArray(e.present)||!Array.isArray(e.absent))throw new Error("Invalid IAM render guard");if(e.present.length===0)throw Error("IAM render needs positive source evidence");let t=e.selectors,r=e.present,n=e.absent,o=[...r,...n];if(new Set(t).size!==t.length||o.length!==t.length||new Set(o).size!==o.length||o.some(a=>typeof a!="number"||!Number.isInteger(a)||a<0||a>=t.length))throw new Error("Invalid IAM render signature");return{schemaVersion:1,renderKey:e.renderKey,routeTemplate:e.routeTemplate,selectors:e.selectors,present:e.present,absent:e.absent}}function Ue(e,t){let r=e.split("/").filter(Boolean),n="";for(let o of r)/^\[\[\.\.\.[^\[\]]+\]\]$/.test(o)?n+="(?:/[^/]+)*":/^\[\.\.\.[^\[\]]+\]$/.test(o)?n+="(?:/[^/]+)+":/^\[[^\[\]]+\]$/.test(o)?n+="/[^/]+":n+="/"+o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+(n?n+"/?":"/")+"$").test(t)&&!/[\[\]]/.test(t)}function Me(e,t,r,n,o=J(t,n)){if(!Ue(e.routeTemplate,r))return!1;let a=new Set(e.present),s=!0;for(let i=0;i<e.selectors.length;i++){let u=o(e.selectors[i]);if(a.has(i)&&u>1)throw new Error("IAM render anchor is ambiguous");(a.has(i)?u!==1:u!==0)&&(s=!1),n()}return s}var _=new WeakMap,Z=new WeakSet;function Q(e){Z.add(e)}function He(e){let t=new Set,r=new Set,n,o=0,a=!1,s=()=>{t.size||o||(n?.disconnect(),e.removeEventListener("visibilitychange",u),_.delete(e))};function i(c){if(e.hidden)return;let g=performance.now(),d=new Map,m=new Map,b=()=>{if(performance.now()-g>8)throw Error("IAM page check exceeded its work budget")},M=l=>{b();let f=d.get(l);return f||(f=e.querySelectorAll(l),d.set(l,f)),b(),f},A=J({querySelectorAll:M},b),y={query:M,checkpoint:b,matches(l,f){let p=m.get(f);if(!p){try{p={match:Me(l,e,location.pathname,b,A)}}catch(h){p={error:h}}m.set(f,p)}if("error"in p)throw p.error;return p.match}},x=[],k=[],L=[];for(let l of c)if(t.has(l))try{x.push({job:l,commit:l.prepare(y)})}catch(f){k.push({job:l,error:f})}try{b()}catch(l){for(let f of[...t])f.fail(l);return}for(let{job:l,error:f}of k)t.has(l)&&l.fail(f);for(let{job:l,commit:f}of x)if(t.has(l))try{b(),f(p=>L.push(p))}catch(p){l.fail(p)}for(let l of L)l()}function u(){a||!t.size||e.hidden||(a=!0,queueMicrotask(()=>{a=!1,i([...t])}))}return{begin(){o++},end(){--o===0&&(r.clear(),i([...t])),s()},add(c){return n||(n=new MutationObserver(g=>{let d=m=>Z.has(m)||!!(m.parentNode&&Z.has(m.parentNode));g.some(m=>!d(m.target)&&!(m.type==="childList"&&[...m.addedNodes,...m.removedNodes].length>0&&[...m.addedNodes,...m.removedNodes].every(d)))&&u()}),n.observe(e.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["style","hidden","data-indiana-id","data-indiana-release","data-testid","id","name"]}),e.addEventListener("visibilitychange",u)),t.add(c),o?r.add(c):i([c]),()=>{t.delete(c),r.delete(c),s()}}}}function Se(){let e=_.get(document);return e||(e=He(document),_.set(document,e)),e}function xe(e){return Se().add(e)}function ke(e){let t=Se();t.begin();try{e()}finally{t.end()}}var ze=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,te={revert:function(){}},W=new Map,re=new Set;function We(e){return e==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[e]}}function F(e){var t=W.get(e);return t||(t={element:e,attributes:{}},W.set(e,t)),t}function K(e,t,r,n,o){var a=r(e),s={isDirty:!1,originalValue:a,virtualValue:a,mutations:[],el:e,_positionTimeout:null,observer:new MutationObserver(function(){if(!dt&&!(t==="position"&&s._positionTimeout)){t==="position"&&(s._positionTimeout=setTimeout(function(){s._positionTimeout=null},1e3));var i=r(e);t==="position"&&i.parentNode===s.virtualValue.parentNode&&i.insertBeforeNode===s.virtualValue.insertBeforeNode||i!==s.virtualValue&&(s.originalValue=i,o(s))}}),mutationRunner:o,setValue:n,getCurrentValue:r};return t==="position"&&e.parentNode?s.observer.observe(e.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):s.observer.observe(e,We(t)),s}function $(e,t){var r=t.getCurrentValue(t.el);t.virtualValue=e,e&&typeof e!="string"?(!r||e.parentNode!==r.parentNode||e.insertBeforeNode!==r.insertBeforeNode)&&(t.isDirty=!0,Re()):e!==r&&(t.isDirty=!0,Re())}function Fe(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),$(st(t),e)}function Ke(e){var t=new Set(e.originalValue.split(/\s+/).filter(Boolean));e.mutations.forEach(function(r){return r.mutate(t)}),$(Array.from(t).filter(Boolean).join(" "),e)}function $e(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),$(t,e)}function Ye(e){var t=e.parentSelector,r=e.insertBeforeSelector,n=document.querySelector(t);if(!n)return null;var o=r?document.querySelector(r):null;return r&&!o?null:{parentNode:n,insertBeforeNode:o}}function _e(e){var t=e.originalValue;e.mutations.forEach(function(r){var n=r.mutate(),o=Ye(n);t=o||t}),$(t,e)}var Ze=function(t){return t.innerHTML},Qe=function(t,r){return t.innerHTML=r};function Te(e){var t=F(e);return t.html||(t.html=K(e,"html",Ze,Qe,Fe)),t.html}var Xe=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},et=function(t,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(t,r.insertBeforeNode)};function Le(e){var t=F(e);return t.position||(t.position=K(e,"position",Xe,et,_e)),t.position}var tt=function(t,r){return r?t.className=r:t.removeAttribute("class")},rt=function(t){return t.className};function Ne(e){var t=F(e);return t.classes||(t.classes=K(e,"class",rt,tt,Ke)),t.classes}var nt=function(t){return function(r){var n;return(n=r.getAttribute(t))!=null?n:null}},ot=function(t){return function(r,n){return n!==null?r.setAttribute(t,n):r.removeAttribute(t)}};function Pe(e,t){var r=F(e);return r.attributes[t]||(r.attributes[t]=K(e,t,nt(t),ot(t),$e)),r.attributes[t]}function it(e,t){var r=W.get(e);if(r)if(t==="html"){var n,o;(n=r.html)==null||(o=n.observer)==null||o.disconnect(),delete r.html}else if(t==="class"){var a,s;(a=r.classes)==null||(s=a.observer)==null||s.disconnect(),delete r.classes}else if(t==="position"){var i,u;(i=r.position)==null||(u=i.observer)==null||u.disconnect(),delete r.position}else{var c,g,d;(c=r.attributes)==null||(g=c[t])==null||(d=g.observer)==null||d.disconnect(),delete r.attributes[t]}}var U;function st(e){return U||(U=document.createElement("div")),U.innerHTML=e,U.innerHTML}function H(e,t,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||it(e,t),r.setValue(e,n)}}function at(e,t){e.html&&H(t,"html",e.html),e.classes&&H(t,"class",e.classes),e.position&&H(t,"position",e.position),Object.keys(e.attributes).forEach(function(r){H(t,r,e.attributes[r])})}function Re(){W.forEach(at)}function ut(e,t){var r=null;e.kind==="html"?r=Te(t):e.kind==="class"?r=Ne(t):e.kind==="attribute"?r=Pe(t,e.attribute):e.kind==="position"&&(r=Le(t)),r&&(r.mutations.push(e),r.mutationRunner(r))}function lt(e,t){var r=null;if(e.kind==="html"?r=Te(t):e.kind==="class"?r=Ne(t):e.kind==="attribute"?r=Pe(t,e.attribute):e.kind==="position"&&(r=Le(t)),!!r){var n=r.mutations.indexOf(e);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function Oe(e){if(!(e.kind==="position"&&e.elements.size===1)){var t=new Set(e.elements),r=document.querySelectorAll(e.selector);r.forEach(function(n){t.has(n)||(e.elements.add(n),ut(e,n))})}}function ct(e){e.elements.forEach(function(t){return lt(e,t)}),e.elements.clear(),re.delete(e)}function Ie(){re.forEach(Oe)}var dt=!1;var X;function ft(){typeof document>"u"||(X||(X=new MutationObserver(function(){Ie()})),Ie(),X.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}ft();function Y(e){return typeof document>"u"?te:(re.add(e),Oe(e),{revert:function(){ct(e)}})}function ee(e,t){return Y({kind:"html",elements:new Set,mutate:t,selector:e})}function qe(e,t){return Y({kind:"position",elements:new Set,mutate:t,selector:e})}function D(e,t){return Y({kind:"class",elements:new Set,mutate:t,selector:e})}function z(e,t,r){return ze.test(t)?t==="class"||t==="className"?D(e,function(n){var o=r(Array.from(n).join(" "));n.clear(),o&&o.split(/\s+/g).filter(Boolean).forEach(function(a){return n.add(a)})}):Y({kind:"attribute",attribute:t,elements:new Set,mutate:r,selector:e}):te}function pt(e){var t=e.selector,r=e.action,n=e.value,o=e.attribute,a=e.parentSelector,s=e.insertBeforeSelector;if(o==="html"){if(r==="append")return ee(t,function(i){return i+(n??"")});if(r==="set")return ee(t,function(){return n??""})}else if(o==="class"){if(r==="append")return D(t,function(i){n&&i.add(n)});if(r==="remove")return D(t,function(i){n&&i.delete(n)});if(r==="set")return D(t,function(i){i.clear(),n&&i.add(n)})}else if(o==="position"){if(r==="set"&&a)return qe(t,function(){return{insertBeforeSelector:s,parentSelector:a}})}else{if(r==="append")return z(t,o,function(i){return i!==null?i+(n??""):n??""});if(r==="set")return z(t,o,function(){return n??""});if(r==="remove")return z(t,o,function(){return null})}return te}var mt={html:ee,classes:D,attribute:z,position:qe,declarative:pt},ne=mt;import ht from"dompurify";var oe,Be;function gt(e){return(!oe||Be!==window)&&(oe=ht(window),Be=window),oe.sanitize(e,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function De(e){let t={...e};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(t.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(t.attribute))throw new Error("Unsupported visual attribute");document.querySelector(t.selector);for(let r of document.querySelectorAll(t.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&t.attribute==="html")throw new Error("Protected visual target");if(t.attribute==="html"&&(t.value=gt(t.value??"")),["href","src"].includes(t.attribute)&&t.action!=="remove"){let r=new URL(t.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||t.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return t.parentSelector&&document.querySelector(t.parentSelector),t.insertBeforeSelector&&document.querySelector(t.insertBeforeSelector),t}function Ce(e,t={}){if(e.renderGuard&&!t.requireUniqueTargets)throw new Error("IAM render guard requires the source release fence");if(t.requireUniqueTargets)return yt(e,t);let r=e.domMutations.map(De),n=[],o=!1,a=!1,s,i=()=>{if(!o){o=!0,s?.disconnect();for(let c of n.reverse())c()}},u=()=>{o||a||(!r.length||e.css||t.allowJs&&e.js||r.some(c=>document.querySelector(c.selector)))&&(a=!0,t.onApplied?.())};try{if(e.css){let d=document.createElement("style");t.nonce&&(d.nonce=t.nonce),d.textContent=e.css,document.head.append(d),n.push(()=>d.remove())}for(let d of r){let m=ne.declarative(d);n.push(()=>m.revert())}if(t.allowJs&&e.js){let d=document.createElement("script");t.nonce&&(d.nonce=t.nonce),d.textContent=e.js,document.head.append(d),n.push(()=>d.remove())}let c=performance.now(),g=new WeakMap;s=new MutationObserver(d=>{if(!o){performance.now()-c>1e3&&(c=performance.now(),g=new WeakMap);for(let m of d){let b=(g.get(m.target)??0)+1;if(g.set(m.target,b),b>40){i(),t.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}u()}}),s.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),u()}catch(c){throw i(),c}return{revert:i,get applied(){return a}}}function yt(e,t){let r=t?.boundVariations??[e],n=new Set,o=new Set,a=[],s=new Map,i=r.flatMap(l=>l.renderGuard?[j(l.renderGuard)]:[]),u=i[0];if(i.some(l=>JSON.stringify(l)!==JSON.stringify(u)))throw new Error("IAM variations use different render states");if(e.js||r.some(l=>l.js))throw Error("IAM scripts cannot execute");if(r.length>20||r.reduce((l,f)=>l+f.css.length,0)>262144)throw Error("IAM target budget");let c=(l,f)=>{for(let h of l.domMutations){if(h.action!=="set"||h.attribute!=="html")throw Error("Unsupported IAM mutation");n.add(h.selector),o.add(h.selector)}if(!l.css)return;let p=document.createElement("style");Q(p),p.media="not all",t?.nonce&&(p.nonce=t.nonce),p.textContent=l.css;try{if(document.head.append(p),!p.sheet)throw Error("IAM CSS is blocked");for(let h of p.sheet.cssRules){if(!("selectorText"in h)||typeof h.selectorText!="string")throw Error("Unsupported IAM style rule");n.add(h.selectorText),f&&a.push({selector:h.selectorText,css:h.cssText})}}finally{p.remove()}};for(let l of r)c(l,!1);if(c(e,!0),n.size>200)throw Error("IAM target budget");let g=e.domMutations.map(De),d=!1,m=!1,b=!1,M={},A=u?JSON.stringify(u):"",y,x="",k=()=>{if(!d){d=!0,M.unsubscribe?.();for(let l of s.values())l.revert();s.clear(),y?.remove(),y=void 0,m=!1}},L=()=>{for(let l of s.values())l.revert();s.clear(),y?.remove(),y=void 0,x="",m=!1};return M.unsubscribe=xe({fail(l){k(),t?.onError?.(l)},prepare(l){if(u&&!l.matches(u,A))return()=>{d||L()};let f=new Map;for(let p of n){let h=l.query(p);if(h.length>1)throw Error("IAM target is ambiguous in this rendered state");if(h.length){if(o.has(p)&&h[0].children.length)throw Error("IAM text target is no longer a leaf");f.set(p,h[0])}l.checkpoint()}return p=>{if(d)return;for(let[E,R]of s)f.get(E)!==R.element&&(R.revert(),s.delete(E));for(let E of new Set(g.map(R=>R.selector))){let R=f.get(E);if(!R||s.has(E))continue;let P=g.filter(N=>N.selector===E).map(N=>ne.declarative(N));s.set(E,{element:R,revert:()=>P.forEach(N=>N.revert())})}let h=a.filter(E=>f.has(E.selector)).map(E=>E.css).join(`
2
+ `);h!==x&&(x=h,h?(y||(y=document.createElement("style"),Q(y),t?.nonce&&(y.nonce=t.nonce),document.head.append(y)),y.textContent=h):(y?.remove(),y=void 0)),m=n.size===0||f.size>0,m&&!b&&(b=!0,p(()=>{d||t?.onApplied?.()}))}}}),d&&M.unsubscribe(),{revert:k,get applied(){return m}}}var C=e=>!!e&&typeof e=="object"&&!Array.isArray(e),q=(e,t)=>typeof e=="string"&&e.length<=t,vt=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function bt(e){if(!C(e)||!q(e.css??"",1e5)||!q(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let t=e.domMutations??[];for(let r of t)if(!C(r)||!q(r.selector,2048)||!r.selector||!vt(r.attribute)||!["set","append","remove"].includes(String(r.action))||r.value!==void 0&&!q(r.value,5e4)||r.parentSelector!==void 0&&!q(r.parentSelector,2048)||r.insertBeforeSelector!==void 0&&!q(r.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:t,...e.renderGuard===void 0?{}:{renderGuard:j(e.renderGuard)}}}function Ge(e){if(!C(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!C(e.savedGroups))throw new Error("Invalid visual experiment payload");let t=e.experiments.map(r=>{if(!C(r)||!["key","changeId"].every(n=>typeof r[n]=="string"&&r[n])||!/^[a-f0-9]{64}$/.test(String(r.changeId))||["namespace","status","groups","url"].some(n=>Object.hasOwn(r,n))||r.hashVersion!==void 0&&r.hashVersion!==2||!Array.isArray(r.variations)||r.variations.length<2||r.variations.length>20||r.urlPatterns!==void 0&&!Array.isArray(r.urlPatterns))throw new Error("Invalid visual experiment");return{...r,variations:r.variations.map(bt)}});return{...e,experiments:t}}function Kt(e){let t=ge(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=Ae(r),o=`${t}/api/v1/visual-experiments/${e.environmentId}`,a=me(e.deviceIdCookie??"indiana_did"),s=he(),i=null,u=!1,c=!1,g="",d={...e.attributes??{}},m,b,M=0,A=new Map,y=new Map,x=new Set,k=[],L,l,f;function p(){clearTimeout(l),f?.remove(),f=void 0}function h(w=!1){clearTimeout(L),L=void 0;let V=k.splice(0,20);return V.length?Ve(r,`${o}/events`,JSON.stringify({events:V}),w).catch(I=>e.log?.("Visual exposure not sent",{error:I})):Promise.resolve()}function E(w,V){let I=B(w,V);x.has(I)||e.trackExposures===!1||i?.trackExposures===!1||u||(x.add(I),k.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:a,...s?{sessionId:s}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:w.key,variationKey:V.key}),k.length>=20?h():L??=setTimeout(()=>{h()},1e3))}function R(w){if(!i||u)return;let V=new Set,I={onExperimentViewed:(v,T)=>{V.add(B(v,T))},url:location.href,attributes:{...ve(a,location),...d,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:fe(i.savedGroups),log:e.log},G=new Set;for(let v of i.experiments){let T=v;try{let S=pe(T,I);if(y.set(v.changeId,S),!S.inExperiment)continue;G.add(v.changeId);let ae=JSON.stringify([S.key,S.value]),ue=A.get(v.changeId);if(ue?.signature===ae){V.has(B(T,S))&&w.push(()=>{ue.applied()&&E(T,S)});continue}A.get(v.changeId)?.revert(),A.delete(v.changeId);let le=Ce(S.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(v.condition?.$and)&&v.condition.$and.some(O=>O!==null&&typeof O=="object"&&!Array.isArray(O)&&O.indianaAppManifestRelease===e.appManifestRelease),boundVariations:v.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{V.has(B(T,S))&&E(T,S)},onError:O=>e.log?.("Visual experiment stopped",{experiment:v.key,error:String(O)})});A.set(v.changeId,{signature:ae,revert:le.revert,applied:()=>le.applied})}catch(S){e.log?.("Skipping visual experiment",{experiment:v.key,error:String(S)})}}for(let[v,T]of A)G.has(v)||(T.revert(),A.delete(v));p()}let P=()=>{let w=[];ke(()=>R(w));for(let V of w)V()};async function N(){let w=++M,V;try{V=await n.read(o,we)}catch(G){if(u||w!==M)return!1;throw G}let I=Ge(V);if(I.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return u||w!==M?!1:(i=I,!0)}let Je=()=>{g!==location.href&&(g=location.href,P())},ie=()=>{h(!0)},se=()=>{m||u||(m=ye(Je),addEventListener("pagehide",ie),g=location.href)};return{async start(){if(!(c||u)){c=!0,e.appManifestRelease&&(b=de(e.appManifestRelease)),e.antiFlicker&&(f=document.createElement("style"),e.nonce&&(f.nonce=e.nonce),f.textContent="body { visibility: hidden !important }",document.head.append(f),l=setTimeout(p,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await N()||u)return;se(),P()}finally{p()}}},async refresh(){u||await N()&&(c&&se(),P())},setAttributes(w){d={...w},P()},flush:()=>h(),getResults(){return new Map(y)},get generation(){return i?.generation??null},destroy(){u=!0,M++,n.destroy(),m?.(),b?.destroy(),removeEventListener("pagehide",ie),p();for(let w of A.values())w.revert();A.clear(),h(!0),i=null,y.clear(),x.clear(),d={}}}}export{Kt as createVisualExperiments};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkerlandai/indiana-sdk",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
4
4
  "description": "Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -52,6 +52,10 @@
52
52
  "./visual": {
53
53
  "types": "./dist/visual.d.ts",
54
54
  "import": "./dist/visual.js"
55
+ },
56
+ "./iam": {
57
+ "types": "./dist/iam.d.ts",
58
+ "import": "./dist/iam.js"
55
59
  }
56
60
  },
57
61
  "scripts": {
@@ -74,7 +78,9 @@
74
78
  "@types/css-tree": "^3.2.0",
75
79
  "ai": "7.0.136",
76
80
  "tsup": "^8.5.1",
77
- "typescript": "^5.9.3"
81
+ "typescript": "^5.9.3",
82
+ "rrweb-snapshot": "2.1.7",
83
+ "@rrweb/types": "2.1.7"
78
84
  },
79
85
  "peerDependencies": {
80
86
  "@openrouter/sdk": "^1.4.25"
@@ -1 +0,0 @@
1
- var p=e=>!!e&&typeof e=="object"&&!Array.isArray(e),f=(e,t)=>typeof e=="string"&&e.length<=t,x=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function z(e){if(!p(e)||!f(e.css??"",1e5)||!f(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let t=e.domMutations??[];for(let r of t)if(!p(r)||!f(r.selector,2048)||!r.selector||!x(r.attribute)||!["set","append","remove"].includes(String(r.action))||r.value!==void 0&&!f(r.value,5e4)||r.parentSelector!==void 0&&!f(r.parentSelector,2048)||r.insertBeforeSelector!==void 0&&!f(r.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:t}}function he(e){if(!p(e)||typeof e.environmentId!="string"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!p(e.savedGroups))throw new Error("Invalid visual experiment payload");let t=e.experiments.map(r=>{if(!p(r)||!["key","changeId"].every(n=>typeof r[n]=="string"&&r[n])||!/^[a-f0-9]{64}$/.test(String(r.changeId))||["namespace","status","groups","url"].some(n=>Object.hasOwn(r,n))||r.hashVersion!==void 0&&r.hashVersion!==2||!Array.isArray(r.variations)||r.variations.length<2||r.variations.length>20||r.urlPatterns!==void 0&&!Array.isArray(r.urlPatterns))throw new Error("Invalid visual experiment");return{...r,variations:r.variations.map(z)}});return{...e,experiments:t}}var G=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,N={revert:function(){}},y=new Map,B=new Set;function F(e){return e==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[e]}}function w(e){var t=y.get(e);return t||(t={element:e,attributes:{}},y.set(e,t)),t}function V(e,t,r,n,i){var u=r(e),s={isDirty:!1,originalValue:u,virtualValue:u,mutations:[],el:e,_positionTimeout:null,observer:new MutationObserver(function(){if(!le&&!(t==="position"&&s._positionTimeout)){t==="position"&&(s._positionTimeout=setTimeout(function(){s._positionTimeout=null},1e3));var o=r(e);t==="position"&&o.parentNode===s.virtualValue.parentNode&&o.insertBeforeNode===s.virtualValue.insertBeforeNode||o!==s.virtualValue&&(s.originalValue=o,i(s))}}),mutationRunner:i,setValue:n,getCurrentValue:r};return t==="position"&&e.parentNode?s.observer.observe(e.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):s.observer.observe(e,F(t)),s}function E(e,t){var r=t.getCurrentValue(t.el);t.virtualValue=e,e&&typeof e!="string"?(!r||e.parentNode!==r.parentNode||e.insertBeforeNode!==r.insertBeforeNode)&&(t.isDirty=!0,O()):e!==r&&(t.isDirty=!0,O())}function U(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),E(ie(t),e)}function J(e){var t=new Set(e.originalValue.split(/\s+/).filter(Boolean));e.mutations.forEach(function(r){return r.mutate(t)}),E(Array.from(t).filter(Boolean).join(" "),e)}function W(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),E(t,e)}function Z(e){var t=e.parentSelector,r=e.insertBeforeSelector,n=document.querySelector(t);if(!n)return null;var i=r?document.querySelector(r):null;return r&&!i?null:{parentNode:n,insertBeforeNode:i}}function Y(e){var t=e.originalValue;e.mutations.forEach(function(r){var n=r.mutate(),i=Z(n);t=i||t}),E(t,e)}var K=function(t){return t.innerHTML},Q=function(t,r){return t.innerHTML=r};function P(e){var t=w(e);return t.html||(t.html=V(e,"html",K,Q,U)),t.html}var X=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},_=function(t,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(t,r.insertBeforeNode)};function L(e){var t=w(e);return t.position||(t.position=V(e,"position",X,_,Y)),t.position}var $=function(t,r){return r?t.className=r:t.removeAttribute("class")},ee=function(t){return t.className};function D(e){var t=w(e);return t.classes||(t.classes=V(e,"class",ee,$,J)),t.classes}var te=function(t){return function(r){var n;return(n=r.getAttribute(t))!=null?n:null}},re=function(t){return function(r,n){return n!==null?r.setAttribute(t,n):r.removeAttribute(t)}};function H(e,t){var r=w(e);return r.attributes[t]||(r.attributes[t]=V(e,t,te(t),re(t),W)),r.attributes[t]}function ne(e,t){var r=y.get(e);if(r)if(t==="html"){var n,i;(n=r.html)==null||(i=n.observer)==null||i.disconnect(),delete r.html}else if(t==="class"){var u,s;(u=r.classes)==null||(s=u.observer)==null||s.disconnect(),delete r.classes}else if(t==="position"){var o,d;(o=r.position)==null||(d=o.observer)==null||d.disconnect(),delete r.position}else{var l,c,a;(l=r.attributes)==null||(c=l[t])==null||(a=c.observer)==null||a.disconnect(),delete r.attributes[t]}}var h;function ie(e){return h||(h=document.createElement("div")),h.innerHTML=e,h.innerHTML}function b(e,t,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||ne(e,t),r.setValue(e,n)}}function oe(e,t){e.html&&b(t,"html",e.html),e.classes&&b(t,"class",e.classes),e.position&&b(t,"position",e.position),Object.keys(e.attributes).forEach(function(r){b(t,r,e.attributes[r])})}function O(){y.forEach(oe)}function se(e,t){var r=null;e.kind==="html"?r=P(t):e.kind==="class"?r=D(t):e.kind==="attribute"?r=H(t,e.attribute):e.kind==="position"&&(r=L(t)),r&&(r.mutations.push(e),r.mutationRunner(r))}function ae(e,t){var r=null;if(e.kind==="html"?r=P(t):e.kind==="class"?r=D(t):e.kind==="attribute"?r=H(t,e.attribute):e.kind==="position"&&(r=L(t)),!!r){var n=r.mutations.indexOf(e);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function I(e){if(!(e.kind==="position"&&e.elements.size===1)){var t=new Set(e.elements),r=document.querySelectorAll(e.selector);r.forEach(function(n){t.has(n)||(e.elements.add(n),se(e,n))})}}function ue(e){e.elements.forEach(function(t){return ae(e,t)}),e.elements.clear(),B.delete(e)}function T(){B.forEach(I)}var le=!1;var S;function ce(){typeof document>"u"||(S||(S=new MutationObserver(function(){T()})),T(),S.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}ce();function M(e){return typeof document>"u"?N:(B.add(e),I(e),{revert:function(){ue(e)}})}function A(e,t){return M({kind:"html",elements:new Set,mutate:t,selector:e})}function C(e,t){return M({kind:"position",elements:new Set,mutate:t,selector:e})}function m(e,t){return M({kind:"class",elements:new Set,mutate:t,selector:e})}function g(e,t,r){return G.test(t)?t==="class"||t==="className"?m(e,function(n){var i=r(Array.from(n).join(" "));n.clear(),i&&i.split(/\s+/g).filter(Boolean).forEach(function(u){return n.add(u)})}):M({kind:"attribute",attribute:t,elements:new Set,mutate:r,selector:e}):N}function fe(e){var t=e.selector,r=e.action,n=e.value,i=e.attribute,u=e.parentSelector,s=e.insertBeforeSelector;if(i==="html"){if(r==="append")return A(t,function(o){return o+(n??"")});if(r==="set")return A(t,function(){return n??""})}else if(i==="class"){if(r==="append")return m(t,function(o){n&&o.add(n)});if(r==="remove")return m(t,function(o){n&&o.delete(n)});if(r==="set")return m(t,function(o){o.clear(),n&&o.add(n)})}else if(i==="position"){if(r==="set"&&u)return C(t,function(){return{insertBeforeSelector:s,parentSelector:u}})}else{if(r==="append")return g(t,i,function(o){return o!==null?o+(n??""):n??""});if(r==="set")return g(t,i,function(){return n??""});if(r==="remove")return g(t,i,function(){return null})}return N}var de={html:A,classes:m,attribute:g,position:C,declarative:fe},j=de;import pe from"dompurify";var R,q;function me(e){return(!R||q!==window)&&(R=pe(window),q=window),R.sanitize(e,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function ve(e){let t={...e};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(t.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(t.attribute))throw new Error("Unsupported visual attribute");document.querySelector(t.selector);for(let r of document.querySelectorAll(t.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&t.attribute==="html")throw new Error("Protected visual target");if(t.attribute==="html"&&(t.value=me(t.value??"")),["href","src"].includes(t.attribute)&&t.action!=="remove"){let r=new URL(t.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||t.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return t.parentSelector&&document.querySelector(t.parentSelector),t.insertBeforeSelector&&document.querySelector(t.insertBeforeSelector),t}function Ve(e,t={}){let r=e.domMutations.map(ve),n=[],i=!1,u=!1,s,o=()=>{if(!i){i=!0,s?.disconnect();for(let l of n.reverse())l()}},d=()=>{i||u||(!r.length||e.css||t.allowJs&&e.js||r.some(l=>document.querySelector(l.selector)))&&(u=!0,t.onApplied?.())};try{if(e.css){let a=document.createElement("style");t.nonce&&(a.nonce=t.nonce),a.textContent=e.css,document.head.append(a),n.push(()=>a.remove())}for(let a of r){let v=j.declarative(a);n.push(()=>v.revert())}if(t.allowJs&&e.js){let a=document.createElement("script");t.nonce&&(a.nonce=t.nonce),a.textContent=e.js,document.head.append(a),n.push(()=>a.remove())}let l=performance.now(),c=new WeakMap;s=new MutationObserver(a=>{if(!i){performance.now()-l>1e3&&(l=performance.now(),c=new WeakMap);for(let v of a){let k=(c.get(v.target)??0)+1;if(c.set(v.target,k),k>40){o(),t.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}d()}}),s.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),d()}catch(l){throw o(),l}return{revert:o,get applied(){return u}}}export{z as a,he as b,Ve as c};
@@ -1 +0,0 @@
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-VMLGV5OS.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.2",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 +0,0 @@
1
- import{a as ge}from"./chunk-ET4NANGB.js";import{a as l}from"./chunk-5TEZEOHX.js";import{a as Ne}from"./chunk-S5TVMQRC.js";import{Bf as Ge,Bi as Ae,Bk as H,Ci as $e,Ck as We,Gd as Me,Gk as xe,Hk as k,Ig as Be,Ii as Qe,Ik as Xe,Jk as en,Kg as Je,Kk as nn,Lg as ze,Li as be,Lk as tn,Mi as Ye,Mk as rn,Ng as He,Ok as De,Qh as _e,Rh as Te,Tg as Ke,Tk as on,Vf as ce,ag as je,ek as Ze,ri as te,xf as Ue,yf as qe}from"./chunk-VMLGV5OS.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 +0,0 @@
1
- import{l as n,n as i}from"./chunk-S2MSIA57.js";import{z as o}from"zod";var g=o.enum(["sandbox","live"]),p=o.object({projectId:o.string().min(1),environment:g}).strict();import{z as t}from"zod";var s=t.tuple([t.number().min(0).max(1),t.number().min(0).max(1)]).refine(([a,u])=>a<=u),x=t.strictObject({attribute:t.string().optional(),seed:t.string(),hashVersion:t.literal(2),ranges:t.array(s).max(100)}),b=t.strictObject({id:t.string().min(1).max(255),condition:i,gate:t.boolean().optional()}),d=t.strictObject({key:t.string().optional(),name:t.string().optional(),passthrough:t.boolean().optional()}),c={condition:i.optional(),parentConditions:t.array(b).max(100).optional(),weights:t.array(t.number().min(0).max(1)).max(20).optional(),coverage:t.number().min(0).max(1).optional(),hashAttribute:t.string().optional(),fallbackAttribute:t.string().optional(),hashVersion:t.literal(2).optional(),disableStickyBucketing:t.boolean().optional(),bucketVersion:t.number().int().nonnegative().optional(),minBucketVersion:t.number().int().nonnegative().optional(),filters:t.array(x).max(100).optional(),ranges:t.array(s).max(20).optional(),meta:t.array(d).max(20).optional(),seed:t.string().optional(),name:t.string().optional(),phase:t.string().optional()},r=t.strictObject({...c,key:t.string().min(1).max(255),variations:t.tuple([n,n]).rest(n).refine(a=>a.length<=20),urlPatterns:t.array(t.strictObject({include:t.boolean(),type:t.enum(["regex","simple"]),pattern:t.string()})).max(100).optional(),force:t.number().int().nonnegative().optional(),active:t.boolean().optional(),persistQueryString:t.boolean().optional()}),h=t.strictObject({value:n,variationId:t.number().int(),key:t.string(),name:t.string().optional(),bucket:t.number().optional(),passthrough:t.boolean().optional(),inExperiment:t.boolean(),hashUsed:t.boolean().optional(),hashAttribute:t.string(),hashValue:t.string(),featureId:t.string().nullable(),stickyBucketUsed:t.boolean().optional()}),f=t.strictObject({...c,id:t.string().max(255).optional(),force:n.optional(),variations:t.array(n).min(2).max(20).optional(),key:t.string().optional(),range:s.optional(),tracks:t.array(t.strictObject({experiment:r,result:h})).max(100).optional()}),y=t.strictObject({defaultValue:n.optional(),rules:t.array(f).max(500).optional()}),l=t.record(t.string(),t.union([t.strictObject({type:t.literal("hashed"),attributeKey:t.string(),values:t.array(t.string().regex(/^[a-f0-9]{64}$/))}),t.strictObject({type:t.literal("list"),attributeKey:t.string(),values:t.array(t.union([t.string(),t.number()]))}),t.strictObject({type:t.literal("condition"),condition:i})])),R=t.strictObject({scope:p,generation:t.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}).nullable(),features:t.record(t.string(),y),savedGroups:l,experiments:t.record(t.uuid(),r)});import{z as e}from"zod";var v=e.strictObject({selector:e.string().min(1).max(2048),action:e.enum(["set","append","remove"]),attribute:e.string().min(1).max(128).refine(a=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(a)||/^(aria|data)-[a-z0-9_-]+$/.test(a)),value:e.string().max(5e4).optional(),parentSelector:e.string().max(2048).optional(),insertBeforeSelector:e.string().max(2048).optional()}),S=e.strictObject({variation:e.string().min(1).max(128),description:e.string().max(2e3).default(""),css:e.string().max(1e5).default(""),js:e.string().max(1e5).default(""),domMutations:e.array(v).max(200).default([])}),m=S.omit({variation:!0,description:!0}),j=r.omit({variations:!0,active:!0}).extend({changeId:e.string().regex(/^[a-f0-9]{64}$/),variations:e.tuple([m,m]).rest(m).refine(a=>a.length<=20)}),_=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:e.string().regex(/^[a-f0-9]{64}$/),experiments:e.array(j).max(100),savedGroups:l}),C="__indiana_visual_editor",M=e.object({selector:e.string().max(2048),tag:e.string().max(64),text:e.string().max(1e3),href:e.string().max(2048),src:e.string().max(2048),matches:e.number().int().nonnegative()});export{g as a,p as b,r as c,h as d,f as e,y as f,l as g,R as h,v as i,S as j,m as k,j as l,_ as m,C as n,M as o};