@tinkerlandai/longplay-sdk 0.10.19-rc.3 → 0.10.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{b as mn,c as pn,d as gn,e as yn,f as wn}from"./chunk-FISFN5IY.js";import{a as te,b as Y}from"./chunk-DTJKESGC.js";import{a as m}from"./chunk-KHIQQNTR.js";import{a as dn,b as fn,c as Ce}from"./chunk-FSUP7HMS.js";import{$ as Re,$a as an,Ca as ne,Da as nn,Ga as tn,Ha as rn,Ma as Te,Na as on,Z as je,aa as Je,ab as sn,ba as He,ca as ze,db as un,eb as ln,hb as cn,kb as le,la as Q,ma as Qe,na as j,o as Ue,oa as Ye,pa as Oe,q as ue,qa as M,sa as $e,ta as We,ua as Ze,va as Xe,wa as en}from"./chunk-DBBUN53B.js";import{C as ke,J as Ge,M as Be,Na as Ke,P as ve,a as qe}from"./chunk-4SWGHICJ.js";function zn(e){let n=null,t=null,a=0,d=0,w=new Set,f=null,o=null,g=new Set,i=()=>{for(let s of g)try{s()}catch{}},l={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(s,r)=>{!w.has(s)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(s,structuredClone(r),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(s,r)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(s),structuredClone(r),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?s=>e.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},u=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function c(s,r=new Set){return w.has(s)?!f||!f.features[s]||["unknownFeature","cyclicPrerequisite"].includes(f.features[s].source):r.has(s)?!1:(r.add(s),(n?.features[s]?.rules??[]).some(p=>[...p.parentConditions??[],...(p.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>c(v.id,r))))}let h=s=>{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 f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,l.features=n.features),w.has(s)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?u():structuredClone(f.features[s]??u()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!f||c(s)?u():structuredClone(Be(s,l))};async function A(){if(!n||!w.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(w.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=d;if(o?.revision===s)return o.loading;let r=a,p=n,v=[...w],C=(async()=>{let S=ze.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(r!==a||s!==d||p!==n)){if(e.assertUsable?.(p.generation),S.generation!==p.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(R=>!Object.hasOwn(S.features,R))||Object.keys(S.features).some(R=>!w.has(R)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!S.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=ve.parse({...l.attributes,...S.merchandiseContext})}f=structuredClone(S),l.features={...p.features,...Object.fromEntries(Object.entries(f.features).map(([R,O])=>[R,{defaultValue:O.value}]))},i()}})();o={revision:s,loading:C};try{await C}finally{o?.loading===C&&(o=null)}}function N(){A().catch(s=>{try{e.onError?.(s)}catch{}})}async function x(){if(t)return t;let s=a,r=(async()=>{let p=await e.load(),v="remoteFeatures"in p?Je.parse(p):null,C=v??Re.parse(p);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(s!==a)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===C.generation){let{evaluatedAt:R,expiresAt:O,...D}=n,{evaluatedAt:L,expiresAt:k,...G}=C;if(M(D)!==M(G))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=C.evaluatedAt,n.expiresAt=C.expiresAt,i(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&N(),structuredClone(n)}let S=new Set(v?.remoteFeatures??[]);if([...S].some(R=>Object.hasOwn(C.features,R)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in C&&!n.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),n=structuredClone(C),w=S,f=null,o=null,d++,l.features=n.features,l.savedGroups=Ge(n.savedGroups),l.trackedFeatureUsage={},i(),N(),structuredClone(n)})();t=r;try{return await r}finally{t===r&&(t=null)}}return{init:x,refresh:x,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(s){return g.add(s),()=>{g.delete(s)}},setAttributes(s){let r=ve.parse(s);(l.attributes?.merchandise||l.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=r,d++,f=null,o=null,l.features=n?.features??{},l.trackedFeatureUsage={},i(),N()},evalFeature:h,isOn(s){return h(s).on},isOff(s){return h(s).off},getFeatureValue(s,r){let p=h(s).value;return structuredClone(p===null?r:p)},reset(){a++,d++,t=null,o=null,n=null,f=null,w.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),i()}}}function In(e){let n,t,a=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),d=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw a();let o=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),g=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return"indiana.funnel.commands.v1."+Array.from(g,i=>i.toString(16).padStart(2,"0")).join("")});d.catch(()=>{});async function w(o){try{let g=await d;return await t.request(g,{mode:"exclusive"},()=>o(g))}catch(g){throw g instanceof m?g:a()}}function f(o){let g=n.getItem(o);if(g===null)return{revision:0,entry:null};if(g.length>1048576)throw a();let i=JSON.parse(g);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw a();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>w(f),write:(o,g)=>w(i=>{if(f(i).revision!==o)return null;if(!Number.isSafeInteger(o+1))throw a();return n.setItem(i,JSON.stringify({revision:o+1,entry:g})),o+1})}}function be(e,n){let t=tn.safeParse(n);if(!t.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let a=t.data;if(e.scope&&(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return a}async function Pe(e,n){let t=Xe.parse(n),{artifact:a,environmentId:d}=t.content,w=new te(e.baseUrl??le).origin,f=new te(a.url,w);if(f.origin!==w||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${d}/artifacts/${a.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,g,i=new Promise((u,c)=>{g=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");o.abort(h),c(h)},j.initializationMs)}),l=(async()=>{let u=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(u.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>a.byteLength)throw u.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let c=await dn(u,a.byteLength,{signal:o.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(c,a))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return en(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c)))})();try{return await Promise.race([l,i])}finally{clearTimeout(g)}}var _e=(e,n)=>new m(e,n);function ut(e){return ln(e,_e)}var _n=3,Dn=2e3;function Ln(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function xn(e){for(let n=1;;n++)try{return await e.refresh()}catch(t){if(n===_n||!Ln(t))throw t;await new Promise(a=>setTimeout(a,n*Dn))}}async function De(e,n,{predict:t=!0}={}){let a=n.instruction;if(a?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==a.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let d=null,w;if(t)try{let f=await e.funnel(n.source.id,n.source.versionId);w=f.manifest.generation,d=Vn(e,n,f)}catch{d=null}return w??=e.snapshot?.generation??(await xn(e)).generation,{advance:{policyRevision:a.policyRevision,generation:w},prediction:d}}function Vn(e,n,t){let a=n.instruction;if(a?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==a.policyRevision)return null;let{analyticsConfig:d,remoteFeatures:w,...f}=t.growth,o=an({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:a.policyRevision,document:t.document,payload:Re.parse(f)}),g=Mn(o,t.document,{...n,...a}),i=g.steps.at(-1),l=g.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:n.visit+g.steps.length-1}:null);return l?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:l.nodeId,visit:l.visit,terminal:!g.boundary}:null}function Mn(e,n,t){return cn(e,n,t,_e)}import{z as J}from"zod";var hn=Q.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 m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),vn=J.strictObject({schemaVersion:J.literal(1),scope:qe,runId:J.uuid(),funnelId:J.uuid(),versionId:J.uuid(),processBindingIds:J.record(J.uuid(),J.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:J.strictObject({receiptId:J.uuid(),operationId:J.uuid(),generation:J.number().int().nonnegative()}).optional(),closed:J.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"),U=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function Rn(e){let n=0,t=null,a=i=>JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]),d=Promise.resolve();async function w(){let i=await e.read();if(!Number.isSafeInteger(i.revision)||i.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:i.revision,entry:i.entry===null?null:vn.parse(i.entry)}}function f(i){let l=d.then(i);return d=l.catch(()=>{}),l}async function o(i){for(let l=0;l<4;l++){let u=await w();if(u.entry&&t!==null&&a(u.entry)!==t)throw U();let c=i(u.entry,u.revision);if(Se(u.entry,c)){n=u.revision;return}let h=await e.write(u.revision,c);if(h!==null){if(!Number.isSafeInteger(h)||h<=u.revision)throw U();n=h;return}}throw U()}function g(i,l){if(!i||!l)return i;if(i.processBindingIds&&Object.hasOwn(i.processBindingIds,l)){let u={...i.processBindingIds};delete u[l],i={...i,processBindingIds:u}}return i.command?.requestId===l?i.closeCommand?{...i,command:i.closeCommand,closeCommand:void 0}:i.purchase?{...i,command:void 0}:null:i.closeCommand?.requestId===l?{...i,closeCommand:void 0}:i}return{bind(i){let l=JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]);if(t!==null&&t!==l)throw U();t=l},async load(){let i=await w();return n=i.revision,t=i.entry?a(i.entry):null,i.entry},retain(i){let l=vn.parse(i),u=l.command;return!u||t!==null&&a(l)!==t?Promise.reject(U()):(t??=a(l),f(()=>o((c,h)=>{if(c&&!Se(a(c),a(l)))throw U();if(c&&l.processBindingIds){for(let[A,N]of Object.entries(l.processBindingIds))if(c.processBindingIds&&Object.hasOwn(c.processBindingIds,A)&&c.processBindingIds[A]!==N)throw U();c={...c,processBindingIds:{...c.processBindingIds,...l.processBindingIds}}}if(!c){if(h!==n&&u.operation!=="close")throw U();return l}if(!c.command)return{...c,command:u,...u.operation==="close"?{closed:!0}:{}};if(u.operation==="close"&&c.command.operation!=="close"){if(c.command.requestId===u.requestId||c.closeCommand&&!Se(c.closeCommand,u))throw U();return{...c,closeCommand:u,closed:!0}}if(!Se(c.command,u))throw U();return c})))},observePurchase(i,l,u,c){return f(()=>o((h,A)=>{if(!h&&A!==n||h&&a(h)!==a({...i,schemaVersion:1}))throw U();if(h?.purchase&&h.purchase.generation>l.generation)return g(h,c);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw U();return u?!h?.purchase||h.purchase.operationId!==l.operationId?g(h,c):g(h.command?{...h,purchase:void 0}:null,c):g({schemaVersion:1,...i,...h,purchase:l},c)}))},settle(i){return f(()=>o(l=>g(l,i)))}}}function It(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(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,w)=>ce(d,n[w]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),a=Object.entries(n);return t.length===a.length&&t.every(([d,w])=>Object.hasOwn(n,d)&&ce(w,Reflect.get(n,d)))}function Cn(e,n){let t=n&&{...n},a=null,d=0,w=new AbortController;function f(){d++,w.abort(new m("IDENTITY_CHANGED","Run identity changed")),w=new AbortController}let o=!1,g,i=0,l=new Set;return{get scope(){return t},bindScope(u){if(t&&(t.projectId!==u.projectId||t.environment!==u.environment))throw new m("SCOPE_MISMATCH","Run scope changed");t??={...u}},get view(){return a},get generation(){return d},get signal(){return w.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return i},nextRead(){return++i},assertCurrent(u,c="Run identity changed during the request"){if(u!==d||o)throw new m("IDENTITY_CHANGED",c)},assertRun(u){if(a&&(u.id!==a.id||u.source.type!==a.source.type||u.source.id!==a.source.id||u.source.versionId!==a.source.versionId||u.locale!==a.locale||!ce(u.parameters,a.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&u.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(u,c,h,A,N){if(!(u.operation==="review"&&a&&a!==h&&c.run.revision<=a.revision)&&!(a&&c.run.revision===a.revision&&A!==void 0&&A<i)&&(u.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&a&&c.run.nodeId===a.nodeId&&c.run.visit===a.visit&&c.run.revision===a.revision&&(c.run.screen=a.screen,(a.paywall?.quote?.operationId===c.review?.activeOperationId||!a.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=a.paywall)),!(a?.paywall&&c.run.paywall&&a.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(a.paywall.selectionGeneration??0)))){if(!a||c.run.revision>=a.revision)a=c.run;else if(!N)return;if(a)for(let x of l)try{x(structuredClone(a))}catch{}}},identify(u){if(o)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(u))throw new m("INVALID_TOKEN","Customer credential required");f(),g=u},subscribe(u){return l.add(u),()=>l.delete(u)},reset(){o||(o=!0,f(),g=void 0,a=null,l.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function St(e,n,t="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",t)}function Et(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...t}=e;return t}var qn=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function bn({journal:e,state:n,call:t,processIdentity:a}){let d=null,w=null,f=!1,o={command:null,close:null},g=new Set,i,l=null,u=e?e.load().then(s=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=s,!s)return;if(a){if([s.command,s.closeCommand].some(p=>p&&!Object.hasOwn(s.processBindingIds??{},p.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");a.restore(s.processBindingIds??{})}if(n.scope&&(s.scope.projectId!==n.scope.projectId||s.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,f=s.closed===!0,!s.command)return;let r=s.command;d=r.operation==="close"?null:r,w=r.operation==="close"?r:s.closeCommand?.operation==="close"?s.closeCommand:null,w&&(f=!0);for(let p of[d,w])p&&g.add(p.requestId)}):Promise.resolve();u.catch(()=>{});async function c(s){e&&await u;let r=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(s),...a?{processBindingIds:{[s.requestId]:a.binding(s.requestId)}}:{}})}if(r!==n.generation||d!==s&&w!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let p=g.has(s.requestId);g.add(s.requestId);try{return await t(s)}catch(v){throw r===n.generation&&(d===s||w===s)&&!p&&!qn(v)&&(e&&await e.settle(s.requestId),r===n.generation&&x(s)),v}}function h(s){let r=Q.parse(s);if(r.operation==="start"||r.operation==="get"||r.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&r.operation!=="close"){if(d?.requestId===r.requestId)return N(r.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(r.operation==="close"){if(d?.requestId===r.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,w&&JSON.stringify($(w))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original Close");return w??=r,o.close?o.close:A(w,"close")}if(d){if(JSON.stringify($(d))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(o.command)return o.command}else d=r;return A(d,"command")}function A(s,r){let p=c(s);o[r]=p;let v=()=>{o[r]===p&&(o[r]=null)};return p.then(v,v),p}function N(s){return t({operation:"get",settlementRequestId:s})}function x(s){return!s||d!==s&&w!==s?!1:(d===s&&(d=null),w===s&&(w=null),g.delete(s.requestId),!d&&!w&&(l=null),!0)}return{ready:u,get pending(){return d},get closing(){return w},get closeRequested(){return f},get inFlight(){return o.command},get closeFlight(){return o.close},get purchase(){return i},assertBinding(s){if(l&&(s.run.id!==l.runId||s.run.source.id!==l.funnelId||s.run.source.versionId!==l.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,r,p,v){let C=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,S=C&&r.settlement?.state==="settled"&&r.run.pendingRequest?.requestId!==C&&(s.operation==="get"||!f||s.operation==="close"||!["running","waiting"].includes(r.run.status))?C:void 0,R=d?.requestId===S?d:w?.requestId===S?w:void 0;e?.bind({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId});let O=r.run.paywall,D=O??r.purchase,L=D?.operation,k=r.settlement&&(!O||O.purchaseRequestId===r.settlement.requestId)&&(!i||i.operationId===r.settlement.operationId)?r.settlement:void 0,G=L?.operationId??D?.quote?.operationId??k?.operationId,H=D?.receiptId??k?.receiptId,de=O?.selectionGeneration??i?.generation??0;if(e&&G&&H&&s.operation!=="review"&&(!n.view||r.run.revision>=n.view.revision)&&(v===void 0||v>=n.readSequence)&&(!i||de>=i.generation)){let Z={receiptId:H,operationId:G,generation:de},fe=L?.status==="complete"||D?.canReselect===!0;await e.observePurchase({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId},Z,fe,S),n.assertCurrent(p),(!i||Z.generation>=i.generation)&&(v===void 0||v>=n.readSequence)&&(fe?i?.operationId===Z.operationId&&(i=void 0):i=Z)}else e&&S&&await e.settle(S);return n.assertCurrent(p),S?x(R):!1},stop(){f=!0},submit:h,settle:N,reset(){f=!0,d=null,w=null,i=void 0,l=null,o.close=null,g.clear(),o.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=Cn(e.funnelId,e.scope??e.configuration?.scope),a=e.session?.subscribeIdentity(i),d=null,w=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?In(e):void 0),f=w&&Rn(w),o=bn({journal:f,state:t,call:l,processIdentity:e.process});async function g(r){if(e.process)return e.process.request(r);let p=t.generation;t.assertCurrent(p);let v=performance.now()+(e.timeoutMs??35e3),C=t.customerToken??("customerToken"in r?r.customerToken:void 0);if(e.session){let O=t.signal,D,L=()=>{},k=new Promise((G,H)=>{L=()=>H(O.reason),O.addEventListener("abort",L,{once:!0}),D=setTimeout(()=>H(new m("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(p),e.session.access())),k])}finally{clearTimeout(D),O.removeEventListener("abort",L)}}t.assertCurrent(p);let S={...r,...C?{customerToken:C}:{}},R=r.operation==="page_experiments"?Te.parse(S):Q.parse(S);return n.requestWithCredential("funnels",R,e.runToken,{headers:e.serverKey&&!C?{[rn]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function i(){a?.(),t.reset(),o.reset(),d=null,n.dispose()}async function l(r,p){let v=t.generation,C=()=>t.assertCurrent(v);f&&await o.ready,C();let S=t.view,R=be(e,await g(r));if(r.operation==="review"&&!R.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(C(),R.runToken&&R.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let O=r.operation==="get"?r.settlementRequestId:"requestId"in r&&r.operation!=="start"?r.requestId:void 0;if(O&&R.settlement?.requestId!==O)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(R),t.assertRun(R.run),t.bindScope(R.scope);let D=await o.observe(r,R,v,p);return!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r.operation==="get"&&r.settlementRequestId||(C(),["running","waiting"].includes(R.run.status)||o.stop(),t.publish(r,R,S,p,D)),R}let u=o.submit,c=null,h=new WeakMap;function A(r){let p=h.get(r);if(p)return p;let v=x(r);return h.set(r,v),v}let N=!1;async function x(r){let p=await r;if(p.run.instruction?.type!=="evaluate_segment")return p;if(c)return c;N=!0;let v=t.generation,C=(async()=>{for(let S=0;S<32&&p.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return p;let R=p.run;if(p.run.instruction?.type==="evaluate_segment"){let{advance:D}=await De(e.configuration,R,{predict:!1});if(v!==t.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return p;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return l({operation:"get"});let L=!0;De(e.configuration,R).then(({prediction:k})=>{L&&v===t.generation&&!o.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(d=k)}).catch(()=>{});try{p=await u({operation:"commit_segment",requestId:nn(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...D})}finally{L=!1,d=null}}}return p})();c=C;try{return await C}finally{c===C&&(c=null)}}let s={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let r=o.closing??o.pending;return r?structuredClone($(r)):null},get pendingCommands(){return[o.pending,o.closing].filter(r=>r!==null).map(r=>structuredClone($(r)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return f!==void 0},get prediction(){let r=t.view;return d&&r&&!r.stopped&&["running","waiting"].includes(r.status)&&r.id===d.runId&&r.nodeId===d.from.nodeId&&r.visit===d.from.visit&&r.revision===d.from.revision&&!o.closeRequested?structuredClone(d):null},settle:o.settle,get webViewUrl(){return"bundled"},resolvePaywall(r){return Pe(e,r)},async pageExperiments(r,p=[]){let v=t.generation;t.assertCurrent(v);let C=t.view?.id;if(!C)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=on.parse(await g(Te.parse({operation:"page_experiments",release:r,usedReceiptIds:p})));if(t.assertCurrent(v),S.runId!==C||S.scope.projectId!==t.scope?.projectId||S.scope.environment!==t.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(r){return l({operation:"review",...r?{receiptId:r}:{}},t.nextRead())},async get(r,p){f&&await o.ready,p??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let v=t.nextRead();return A(l({operation:"get",...r?{data:r}:{},...p?{purchase:p}:{}},v))},resume(r=t.view?.pendingRequest?.requestId){return r?o.closeRequested?s.settle(r):o.pending?.requestId===r?A(u(o.pending)):A(u({operation:"resume",requestId:r})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(r){return A(u(r))},retry(){return o.closeFlight?o.closeFlight:o.closing?u(o.closing):o.closeRequested&&o.pending?s.settle(o.pending.requestId):o.inFlight?A(o.inFlight):o.pending?A(u(o.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(r){t.identify(r),d=null,n.reset()},subscribe:t.subscribe,reset:i};return s}function Un(e,n,t,a){if(!ke(e,n)||t!==void 0&&n.observation&&n.observation.subject.customerId!==t||a!==void 0&&n.observation!==void 0&&(n.observation.subject.scope.projectId!==a.projectId||n.observation.subject.scope.environment!==a.environment))throw new m("INVALID_RESPONSE","The access requirement or Customer changed");return n}function Sn(e,n,t){if(e.requirement){if(!n)throw new m("INVALID_RESPONSE","The requested access check is missing");Un(e.requirement,n,e.customerId,t)}}import{ZodError as kn}from"zod";function En(e,n,t,a){try{return e.parse(n)}catch(d){throw a&&d instanceof kn?new m(t,a):d}}async function Ee(e,n,t,a={},d){let w=typeof a=="function"?{}:a,f=En(n.request,t,"INVALID_REQUEST",w.request);try{let o=await e(n.path,f,n.method,d),g=typeof a=="function"?a:a.parseResponse;return g?g(n.response,o):En(n.response,o,"INVALID_RESPONSE",w.response)}catch(o){throw o instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(o.commandRequestId??=f.requestId),o}}async function rr(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let t=ne.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}:{}}),a=Y(e);e.session||a.identify(n.customerToken);let d=null,w=!1,f=null,o=null,g=null,i=null,l=null,u=null,c=null,h=0;function A(){if(w)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function N(){A();let p=ne.resolvePaywall,v=await Ee(a.request,p,{...t,selector:d?{type:"version",versionId:d.id}:t.selector});Sn(t,v.paywall.check,v.scope);let C=await Pe(e,v.paywall);if(A(),n.paywallVersionId?C.id!==n.paywallVersionId:C.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(d&&(!mn(C,d)||C.paywallId!==d.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return d=C,structuredClone(d)}async function x(p){if(A(),i&&p!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let v=f;if(p!=="read"){if(c){if(u===p)return c;throw new m("COMMAND_PENDING","Wait for the original purchase command")}if(u&&u!==p)throw new m("COMMAND_PENDING","Read the original purchase before changing an uncertain command");u=p,h++}let C=u,S=h,R=p==="read"&&c===null,O=p==="read"?ne.readSubscriptionOperation:ne.attach,D=(async()=>{let L=await Ee(a.request,O,{operationId:v.operationId,...p==="read"?{}:{intent:p},...p==="confirm"&&v.merchantTerms?{merchantConfirmation:Ue(v.merchantTerms)}:{}});return pn(L.operation,{operationId:v.operationId,currency:t.commerce.currency},"The purchase operation changed"),A(),f?.operationId!==v.operationId?structuredClone(L.operation):(o=yn(o,L.operation),(p!=="read"||R&&c===null)&&h===S&&u===C&&(u=null),structuredClone(o))})();if(p!=="read"){c=D;let L=()=>{c===D&&(c=null)};D.then(L,L)}return D}let s={get view(){return d?structuredClone(d):null},get quote(){return f?structuredClone(f):null},get operation(){return o?structuredClone(o):null},get webViewUrl(){return"bundled"},get recovery(){return wn({quote:f,operation:o,requestId:l,pending:i!==null||u!==null,destroyed:w})},get pendingCancellation(){return!w&&u==="cancel"},refresh:N,async preview(p){if(A(),!d)throw new m("INVALID_REQUEST","Load the Paywall first");let v=d.document.buttons[p.actionId];if(v?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let C=je(v.product,p.selection,d.capabilities);if(!C)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let S=Ke(d.document.screen,C,p.selection,d.capabilities),R=ne.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:C,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:t.commerce.provider,currency:t.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),O=JSON.stringify(R);if(g&&g!==O&&(i||u||!o||o.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(g===O){if(i)return i;if(f)return structuredClone(f)}g!==O&&(f=null,o=null),g=O,l=R.requestId;let D=(async()=>{let L=ne.previewAttach,k=await Ee(a.request,L,R);return A(),gn(k.quote,{productVersionId:C,featureQuantities:S,currency:t.commerce.currency,provider:t.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=k.quote,o=null,structuredClone(f)})();i=D;try{return await D}finally{i===D&&(i=null)}},confirm:()=>x("confirm"),cancel:()=>x("cancel"),read:()=>x("read"),destroy(){w||(w=!0,r?.(),a.dispose(),d=null,f=null,o=null,g=null,l=null)}},r=e.session?.subscribeIdentity(s.destroy);try{return await N(),s}catch(p){throw s.destroy(),p}}import{z as Jn}from"zod";import{z as ge}from"zod";var Gn=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,Bn=100;function jn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function An(e,n){let t=n===void 0?jn():n,a=new Map,d=0,w=!1,f=!1,o,g;async function i(u){if(!t)return null;let c;try{let h=await Promise.race([Promise.resolve().then(()=>t.getItem(u)),new Promise(A=>{c=setTimeout(()=>A(null),Bn)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(c)}}function l(){if(g)return g;let u=(async()=>{try{let c=await i(`${e}:artifacts`);if(c)return Gn.parse(JSON.parse(c))}catch{}return{}})();return g=u,u.finally(()=>{g===u&&(g=void 0)}),u}return{async readManifest(){return i(e)},writeManifest(u){!t||u.length>oe||new TextEncoder().encode(u).byteLength>oe||(o=u,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;o!==void 0;){let c=o;try{await t.setItem(e,c)}catch{}o===c&&(o=void 0)}}finally{f=!1}})))},async readArtifact(u){let c=(await l())[u],h=Date.now();return c&&h>=c.at&&h-c.at<=j.retentionMs?c.text:void 0},writeArtifact(u,c){if(!t||c.length>oe)return;let h=a.get(u);if(h?.text===c||!h&&a.size>=128)return;let A=new TextEncoder().encode(c).byteLength;d-(h?.byteLength??0)+A>oe||(a.set(u,{text:c,byteLength:A}),d+=A-(h?.byteLength??0),!w&&(w=!0,Promise.resolve().then(async()=>{try{for(;a.size;){let N=new Map(a);try{let x={...await l()},s=Date.now();for(let[C,S]of N)x[C]={at:s,text:S.text};let r={},p=2,v=0;for(let[C,S]of Object.entries(x).sort(([,R],[,O])=>O.at-R.at)){if(S.at>s||s-S.at>j.retentionMs)continue;let R=new TextEncoder().encode(JSON.stringify({[C]:S})).byteLength;p+R>oe||v>=128||(r[C]=S,p+=R,v++)}await t.setItem(`${e}:artifacts`,JSON.stringify(r))}catch{}finally{for(let[x,s]of N)a.get(x)===s&&(a.delete(x),d-=s.byteLength)}}}finally{w=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Fn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function gr(e){let n=Ye.parse(e.scope),t=new te(e.origin??le);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let a=new Set([t.origin,...(e.assetOrigins??[]).map(I=>{let y=new te(I);if(y.protocol!=="https:"||y.username||y.password||y.search||y.hash||y.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return y.origin})]),d=e.fetch??globalThis.fetch.bind(globalThis),w=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${t.origin}:${M(n)}`,o=An(f,e.storage),g,i=0,l=0,u=!1,c=!1,h=0,A=0,N,x,s,r,p=0,v=new Set,C=new Set,S=new Map,R=new Map,O=0,D=!1;function L(){for(let I of v)try{I()}catch{}}function k(I){try{e.onError?.(I)}catch{}}let G=()=>!c&&!u&&!!g&&W()<i&&Date.now()<l;function H(){if(!G())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(I,y,b){if(!S.has(I)){for(;S.size&&(S.size>=128||O+b>j.maxCacheBytes);){let P=S.entries().next().value;O-=P[1].byteLength,S.delete(P[0])}S.set(I,{text:y,byteLength:b}),O+=b}}function Z(I,y,b){return fn(I,y,{signal:b,error:P=>E("INVALID_RESPONSE",P==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(I){let y=new te(I,t);if(!a.has(y.origin)||y.username||y.password||y.hash||y.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return y.href}async function Ae(I,y,b=!1){let P=await d(fe(I),{method:"GET",credentials:"omit",redirect:"error",cache:b?"default":"no-cache",signal:y,headers:{}});if(P.status===429){let T=P.headers.get("retry-after")??"";p=/^\d+$/.test(T)?Number(T)*1e3:Math.max(0,Date.parse(T)-Date.now())||15e3}if(!P.ok&&P.status!==304)throw E(`CONFIGURATION_HTTP_${P.status}`,"Configuration synchronization failed");return P}function On(I,y,b){let P=Date.parse(I.headers.get("x-indiana-config-validated-at")??""),T=Date.parse(I.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(I.headers.get("date")??""),F=I.headers.get("age"),B=F!==null&&/^\d+(\.\d+)?$/.test(F)?Number(F)*1e3:NaN;if(![P,T,_,B].every(Number.isFinite)||T<=P||T-P>j.maxControlAgeMs||P>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let V=Math.min(T-P,b.maxControlAgeSeconds*1e3,j.maxControlAgeMs)-Math.max(B,_-P,0)-(W()-y);if(V<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+V}function Fe(){if(clearTimeout(s),clearTimeout(r),c||!v.size)return;G()&&(r=setTimeout(()=>{G()?Fe():L()},Math.max(1,i-W())),Fn(r));let I=A?Math.min(15e3,1e3*2**Math.min(A-1,4)):Math.min(15e3,(g?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{ie().catch(k)},Math.max(p,I*(.8+Math.random()*.2))),Fn(s)}async function ie(){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(N)return N;let I=h,y=new AbortController;x=y;let b=(async()=>{if(!D){D=!0;try{let he=await o.readManifest();if(he&&!g){let K=Oe.parse(JSON.parse(he));M(K.scope)===M(n)&&(g=K)}}catch{}}y.signal.throwIfAborted();let F=g,B=W(),q=await Ae(w,y.signal);q.status===304&&(!F||!q.headers.has("x-indiana-config-validated-at")||!q.headers.has("x-indiana-config-valid-until")||!q.headers.has("age"))&&(q=await Ae(w,y.signal));let V=q.status===304?F:Oe.parse(JSON.parse(await Z(q,j.maxManifestBytes,y.signal))),{generation:ae,...se}=V,z=q.headers.get("etag");if(M(V.scope)!==M(n)||$e(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(F&&(V.revision<F.revision||V.revision===F.revision&&V.generation!==F.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(F?.funnels??{})){let ee=V.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=On(q,B,V.policy);if(y.signal.throwIfAborted(),I!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return g=V,i=X,l=Date.now()+Math.max(0,X-W()),u=!1,A=0,p=0,o.writeManifest(M(V)),L(),structuredClone(V)})(),P=setTimeout(()=>y.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),j.initializationMs),T=new Promise((F,B)=>y.signal.addEventListener("abort",()=>B(y.signal.reason),{once:!0})),_=Promise.race([b,T]).catch(F=>{throw A++,(F instanceof Jn.ZodError||F instanceof SyntaxError||F instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(F.code))&&(i=0,u=!0,L()),F}).finally(()=>{clearTimeout(P),N===_&&(N=void 0),Fe()});return N=_,_}async function ye(I){let y=I.sha256,b=se=>Ce(se,I);fe(I.url);let P=S.get(y);if(P){if(P.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return S.delete(y),S.set(y,P),P.text}let T=R.get(y);if(T){if(T.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.promise}let _=new AbortController;C.add(_);let F=h,B=(async()=>{try{let X=await o.readArtifact(y);if(X&&b(X)){if(_.signal.throwIfAborted(),c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,X,I.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Ae(I.url,_.signal,!0),z=await Z(se,I.byteLength,_.signal);if(!b(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,z,I.byteLength),o.writeArtifact(y,z),z})(),q=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),j.initializationMs),V=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([B,V]).finally(()=>{clearTimeout(q),C.delete(_),R.delete(y)});return R.set(y,{promise:ae,byteLength:I.byteLength}),ae}async function we(){return G()||await ie(),H(),g}async function me(I){let y,b=new Promise((P,T)=>{y=setTimeout(()=>T(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),j.initializationMs)});try{return await Promise.race([I(),b])}finally{clearTimeout(y)}}function pe(I,y){if(H(),g?.generation!==I.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(y&&g.funnels[y]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Le(I){let y=I.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let P=He.parse(JSON.parse(await ye(b)));if(M(P.scope)!==M({projectId:n.projectId,environment:n.environment})||P.generation!==b.generation||P.remoteFeatures.some(T=>Object.hasOwn(P.features,T)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(I),{...P,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,i-W())).toISOString()}}async function xe(I,y){let b=await we(),P=b.funnels[I];y&&(!P||P.evaluationMode==="local"&&!P.versions[y])&&(N&&await N,b=await ie()),pe(b,I);let T=b.funnels[I];if(T.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=y??T.currentVersionId,F=T.versions[_];if(!F)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(b.artifacts[F.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[B,q]=await Promise.all([ye(b.artifacts[F.artifact]).then(V=>Ze(JSON.parse(V))),T.evaluationMode==="local"?Le(b):void 0]);if(q&&M(We(B,q))!==M(F.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(b,I),{document:B,growth:q,versionId:_,control:structuredClone(T),manifest:structuredClone(b)}}async function Ve(I,y){try{return await xe(I,y)}catch(b){if(!(b instanceof m)||!(b.code==="CONFIGURATION_CHANGED"||b.code==="CONFIGURATION_HTTP_404"&&G()))throw b;let P=g?.generation;if(N&&await N,await ie(),b.code!=="CONFIGURATION_CHANGED"&&g?.generation===P)throw b;return xe(I,y)}}function Ne(){u=!0,L(),ie().catch(k)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function Tn(I){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(I),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Fe()),()=>{v.delete(I),v.size||(clearTimeout(s),clearTimeout(r),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:Tn,assertFresh:H,assertFeatures(I){H();let y=g.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(I!==void 0&&g.artifacts[y].generation!==I)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return g?structuredClone(g):null},get remainingMs(){return G()?Math.max(0,i-W()):0},async features(){return me(async()=>Le(await we()))},pageExperiments:()=>me(async()=>{let I=await we(),y=I.gb.pageExperiments;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let P=un.parse(JSON.parse(await ye(b)));if(P.environmentId!==n.environmentId||P.generation!==b.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(I),P}),funnel:(I,y)=>me(()=>Ve(I,y)),paywall:(I,y)=>me(async()=>{let b=await we(),P=b.paywalls?.[I];if(!P||!y&&P.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let T=y??P.currentVersionId,_=P.versions[T],F=_&&b.artifacts[_.artifact];if(!F||F.kind!=="paywall"||F.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let B=Qe.parse(JSON.parse(await ye(F)));return pe(b),{document:B,versionId:T,version:_.version,control:structuredClone(P),manifest:structuredClone(b)}}),async localFunnel(I,y){let b=await me(()=>Ve(I,y));if(!b.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:P,remoteFeatures:T,..._}=b.growth;return sn({scope:{projectId:n.projectId,environment:n.environment},funnelId:I,versionId:b.versionId,evaluationMode:"local",evaluationRevision:b.control.evaluationRevision,document:b.document,payload:_})},assertFunnel(I,y,b){H();let P=g.funnels[I];if(!P||P.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(P.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(y!==void 0&&P.controlRevision!==y)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(b!==void 0&&!P.versions[b])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!c){c=!0,h++,i=0,x?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(r),Me(),L(),v.clear();for(let I of C)I.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));S.clear(),O=0}}}}function Nn(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(t){let a=Q.safeParse({...t,operation:"start"});if(!a.success||a.data.operation!=="start"||(n?a.data.customer!==void 0:a.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let d=a.data,w=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||w.identify(e.apiKey);let f=be(e,await w.request("funnels",d));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==d.funnelId||f.run.locale!==(d.locale??"en")||!ce(f.run.parameters,d.parameters??{})||(d.customer?!f.customerId||d.customer.type==="id"&&f.customerId!==d.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{w.dispose()}}}}async function Fr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&M(t)!==M(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let d=re.test(e.credential);if(d?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let w=Nn({...e,scope:t,apiKey:e.credential}),f=o=>{let g=Pn({...e,scope:t,runToken:o,...d?{serverKey:e.credential}:{}});return d||g.identify(e.credential),g};return{async start(o){let g=await w.start({...o,funnelId:e.funnelId,...d?{customer:{type:"id",value:e.customerId}}:{}}),i=f(g.runToken),l=await i.get();return{...g,...l,controller:i}},async restore(o){let g=f(o),i=await g.get();if(i.run.source.id!==e.funnelId)throw g.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...i,runToken:o,controller:g}}}}export{Ee as a,Un as b,Sn as c,zn as d,be as e,_e as f,ut as g,Mn as h,In as i,It as j,ce as k,St as l,Et as m,Pn as n,rr as o,gr as p,Nn as q,Fr as r};
1
+ import{b as mn,c as pn,d as gn,e as yn,f as wn}from"./chunk-FISFN5IY.js";import{a as te,b as Y}from"./chunk-YNMSSQQY.js";import{a as m}from"./chunk-KHIQQNTR.js";import{a as dn,b as fn,c as Ce}from"./chunk-CCRBXW4M.js";import{$ as Re,$a as an,Ca as ne,Da as nn,Ga as tn,Ha as rn,Ma as Te,Na as on,Z as je,aa as Je,ab as sn,ba as He,ca as ze,db as un,eb as ln,hb as cn,kb as le,la as Q,ma as Qe,na as j,o as Ue,oa as Ye,pa as Oe,q as ue,qa as M,sa as $e,ta as We,ua as Ze,va as Xe,wa as en}from"./chunk-GSFNAB3W.js";import{C as ke,J as Ge,M as Be,Na as Ke,P as ve,a as qe}from"./chunk-4SWGHICJ.js";function zn(e){let n=null,t=null,a=0,d=0,w=new Set,f=null,o=null,g=new Set,i=()=>{for(let s of g)try{s()}catch{}},l={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(s,r)=>{!w.has(s)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(s,structuredClone(r),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(s,r)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(s),structuredClone(r),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?s=>e.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},u=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function c(s,r=new Set){return w.has(s)?!f||!f.features[s]||["unknownFeature","cyclicPrerequisite"].includes(f.features[s].source):r.has(s)?!1:(r.add(s),(n?.features[s]?.rules??[]).some(p=>[...p.parentConditions??[],...(p.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>c(v.id,r))))}let h=s=>{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 f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,l.features=n.features),w.has(s)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?u():structuredClone(f.features[s]??u()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!f||c(s)?u():structuredClone(Be(s,l))};async function A(){if(!n||!w.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(w.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=d;if(o?.revision===s)return o.loading;let r=a,p=n,v=[...w],C=(async()=>{let S=ze.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(r!==a||s!==d||p!==n)){if(e.assertUsable?.(p.generation),S.generation!==p.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(R=>!Object.hasOwn(S.features,R))||Object.keys(S.features).some(R=>!w.has(R)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!S.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=ve.parse({...l.attributes,...S.merchandiseContext})}f=structuredClone(S),l.features={...p.features,...Object.fromEntries(Object.entries(f.features).map(([R,O])=>[R,{defaultValue:O.value}]))},i()}})();o={revision:s,loading:C};try{await C}finally{o?.loading===C&&(o=null)}}function N(){A().catch(s=>{try{e.onError?.(s)}catch{}})}async function x(){if(t)return t;let s=a,r=(async()=>{let p=await e.load(),v="remoteFeatures"in p?Je.parse(p):null,C=v??Re.parse(p);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(s!==a)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===C.generation){let{evaluatedAt:R,expiresAt:O,...D}=n,{evaluatedAt:L,expiresAt:k,...G}=C;if(M(D)!==M(G))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=C.evaluatedAt,n.expiresAt=C.expiresAt,i(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&N(),structuredClone(n)}let S=new Set(v?.remoteFeatures??[]);if([...S].some(R=>Object.hasOwn(C.features,R)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in C&&!n.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),n=structuredClone(C),w=S,f=null,o=null,d++,l.features=n.features,l.savedGroups=Ge(n.savedGroups),l.trackedFeatureUsage={},i(),N(),structuredClone(n)})();t=r;try{return await r}finally{t===r&&(t=null)}}return{init:x,refresh:x,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(s){return g.add(s),()=>{g.delete(s)}},setAttributes(s){let r=ve.parse(s);(l.attributes?.merchandise||l.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=r,d++,f=null,o=null,l.features=n?.features??{},l.trackedFeatureUsage={},i(),N()},evalFeature:h,isOn(s){return h(s).on},isOff(s){return h(s).off},getFeatureValue(s,r){let p=h(s).value;return structuredClone(p===null?r:p)},reset(){a++,d++,t=null,o=null,n=null,f=null,w.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),i()}}}function In(e){let n,t,a=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),d=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw a();let o=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),g=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return"indiana.funnel.commands.v1."+Array.from(g,i=>i.toString(16).padStart(2,"0")).join("")});d.catch(()=>{});async function w(o){try{let g=await d;return await t.request(g,{mode:"exclusive"},()=>o(g))}catch(g){throw g instanceof m?g:a()}}function f(o){let g=n.getItem(o);if(g===null)return{revision:0,entry:null};if(g.length>1048576)throw a();let i=JSON.parse(g);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw a();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>w(f),write:(o,g)=>w(i=>{if(f(i).revision!==o)return null;if(!Number.isSafeInteger(o+1))throw a();return n.setItem(i,JSON.stringify({revision:o+1,entry:g})),o+1})}}function be(e,n){let t=tn.safeParse(n);if(!t.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let a=t.data;if(e.scope&&(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return a}async function Pe(e,n){let t=Xe.parse(n),{artifact:a,environmentId:d}=t.content,w=new te(e.baseUrl??le).origin,f=new te(a.url,w);if(f.origin!==w||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${d}/artifacts/${a.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,g,i=new Promise((u,c)=>{g=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");o.abort(h),c(h)},j.initializationMs)}),l=(async()=>{let u=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(u.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>a.byteLength)throw u.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let c=await dn(u,a.byteLength,{signal:o.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(c,a))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return en(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c)))})();try{return await Promise.race([l,i])}finally{clearTimeout(g)}}var _e=(e,n)=>new m(e,n);function ut(e){return ln(e,_e)}var _n=3,Dn=2e3;function Ln(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function xn(e){for(let n=1;;n++)try{return await e.refresh()}catch(t){if(n===_n||!Ln(t))throw t;await new Promise(a=>setTimeout(a,n*Dn))}}async function De(e,n,{predict:t=!0}={}){let a=n.instruction;if(a?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==a.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let d=null,w;if(t)try{let f=await e.funnel(n.source.id,n.source.versionId);w=f.manifest.generation,d=Vn(e,n,f)}catch{d=null}return w??=e.snapshot?.generation??(await xn(e)).generation,{advance:{policyRevision:a.policyRevision,generation:w},prediction:d}}function Vn(e,n,t){let a=n.instruction;if(a?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==a.policyRevision)return null;let{analyticsConfig:d,remoteFeatures:w,...f}=t.growth,o=an({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:a.policyRevision,document:t.document,payload:Re.parse(f)}),g=Mn(o,t.document,{...n,...a}),i=g.steps.at(-1),l=g.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:n.visit+g.steps.length-1}:null);return l?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:l.nodeId,visit:l.visit,terminal:!g.boundary}:null}function Mn(e,n,t){return cn(e,n,t,_e)}import{z as J}from"zod";var hn=Q.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 m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),vn=J.strictObject({schemaVersion:J.literal(1),scope:qe,runId:J.uuid(),funnelId:J.uuid(),versionId:J.uuid(),processBindingIds:J.record(J.uuid(),J.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:J.strictObject({receiptId:J.uuid(),operationId:J.uuid(),generation:J.number().int().nonnegative()}).optional(),closed:J.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"),U=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function Rn(e){let n=0,t=null,a=i=>JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]),d=Promise.resolve();async function w(){let i=await e.read();if(!Number.isSafeInteger(i.revision)||i.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:i.revision,entry:i.entry===null?null:vn.parse(i.entry)}}function f(i){let l=d.then(i);return d=l.catch(()=>{}),l}async function o(i){for(let l=0;l<4;l++){let u=await w();if(u.entry&&t!==null&&a(u.entry)!==t)throw U();let c=i(u.entry,u.revision);if(Se(u.entry,c)){n=u.revision;return}let h=await e.write(u.revision,c);if(h!==null){if(!Number.isSafeInteger(h)||h<=u.revision)throw U();n=h;return}}throw U()}function g(i,l){if(!i||!l)return i;if(i.processBindingIds&&Object.hasOwn(i.processBindingIds,l)){let u={...i.processBindingIds};delete u[l],i={...i,processBindingIds:u}}return i.command?.requestId===l?i.closeCommand?{...i,command:i.closeCommand,closeCommand:void 0}:i.purchase?{...i,command:void 0}:null:i.closeCommand?.requestId===l?{...i,closeCommand:void 0}:i}return{bind(i){let l=JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]);if(t!==null&&t!==l)throw U();t=l},async load(){let i=await w();return n=i.revision,t=i.entry?a(i.entry):null,i.entry},retain(i){let l=vn.parse(i),u=l.command;return!u||t!==null&&a(l)!==t?Promise.reject(U()):(t??=a(l),f(()=>o((c,h)=>{if(c&&!Se(a(c),a(l)))throw U();if(c&&l.processBindingIds){for(let[A,N]of Object.entries(l.processBindingIds))if(c.processBindingIds&&Object.hasOwn(c.processBindingIds,A)&&c.processBindingIds[A]!==N)throw U();c={...c,processBindingIds:{...c.processBindingIds,...l.processBindingIds}}}if(!c){if(h!==n&&u.operation!=="close")throw U();return l}if(!c.command)return{...c,command:u,...u.operation==="close"?{closed:!0}:{}};if(u.operation==="close"&&c.command.operation!=="close"){if(c.command.requestId===u.requestId||c.closeCommand&&!Se(c.closeCommand,u))throw U();return{...c,closeCommand:u,closed:!0}}if(!Se(c.command,u))throw U();return c})))},observePurchase(i,l,u,c){return f(()=>o((h,A)=>{if(!h&&A!==n||h&&a(h)!==a({...i,schemaVersion:1}))throw U();if(h?.purchase&&h.purchase.generation>l.generation)return g(h,c);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw U();return u?!h?.purchase||h.purchase.operationId!==l.operationId?g(h,c):g(h.command?{...h,purchase:void 0}:null,c):g({schemaVersion:1,...i,...h,purchase:l},c)}))},settle(i){return f(()=>o(l=>g(l,i)))}}}function It(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(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,w)=>ce(d,n[w]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),a=Object.entries(n);return t.length===a.length&&t.every(([d,w])=>Object.hasOwn(n,d)&&ce(w,Reflect.get(n,d)))}function Cn(e,n){let t=n&&{...n},a=null,d=0,w=new AbortController;function f(){d++,w.abort(new m("IDENTITY_CHANGED","Run identity changed")),w=new AbortController}let o=!1,g,i=0,l=new Set;return{get scope(){return t},bindScope(u){if(t&&(t.projectId!==u.projectId||t.environment!==u.environment))throw new m("SCOPE_MISMATCH","Run scope changed");t??={...u}},get view(){return a},get generation(){return d},get signal(){return w.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return i},nextRead(){return++i},assertCurrent(u,c="Run identity changed during the request"){if(u!==d||o)throw new m("IDENTITY_CHANGED",c)},assertRun(u){if(a&&(u.id!==a.id||u.source.type!==a.source.type||u.source.id!==a.source.id||u.source.versionId!==a.source.versionId||u.locale!==a.locale||!ce(u.parameters,a.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&u.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(u,c,h,A,N){if(!(u.operation==="review"&&a&&a!==h&&c.run.revision<=a.revision)&&!(a&&c.run.revision===a.revision&&A!==void 0&&A<i)&&(u.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&a&&c.run.nodeId===a.nodeId&&c.run.visit===a.visit&&c.run.revision===a.revision&&(c.run.screen=a.screen,(a.paywall?.quote?.operationId===c.review?.activeOperationId||!a.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=a.paywall)),!(a?.paywall&&c.run.paywall&&a.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(a.paywall.selectionGeneration??0)))){if(!a||c.run.revision>=a.revision)a=c.run;else if(!N)return;if(a)for(let x of l)try{x(structuredClone(a))}catch{}}},identify(u){if(o)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(u))throw new m("INVALID_TOKEN","Customer credential required");f(),g=u},subscribe(u){return l.add(u),()=>l.delete(u)},reset(){o||(o=!0,f(),g=void 0,a=null,l.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function St(e,n,t="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",t)}function Et(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...t}=e;return t}var qn=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function bn({journal:e,state:n,call:t,processIdentity:a}){let d=null,w=null,f=!1,o={command:null,close:null},g=new Set,i,l=null,u=e?e.load().then(s=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=s,!s)return;if(a){if([s.command,s.closeCommand].some(p=>p&&!Object.hasOwn(s.processBindingIds??{},p.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");a.restore(s.processBindingIds??{})}if(n.scope&&(s.scope.projectId!==n.scope.projectId||s.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,f=s.closed===!0,!s.command)return;let r=s.command;d=r.operation==="close"?null:r,w=r.operation==="close"?r:s.closeCommand?.operation==="close"?s.closeCommand:null,w&&(f=!0);for(let p of[d,w])p&&g.add(p.requestId)}):Promise.resolve();u.catch(()=>{});async function c(s){e&&await u;let r=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(s),...a?{processBindingIds:{[s.requestId]:a.binding(s.requestId)}}:{}})}if(r!==n.generation||d!==s&&w!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let p=g.has(s.requestId);g.add(s.requestId);try{return await t(s)}catch(v){throw r===n.generation&&(d===s||w===s)&&!p&&!qn(v)&&(e&&await e.settle(s.requestId),r===n.generation&&x(s)),v}}function h(s){let r=Q.parse(s);if(r.operation==="start"||r.operation==="get"||r.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&r.operation!=="close"){if(d?.requestId===r.requestId)return N(r.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(r.operation==="close"){if(d?.requestId===r.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,w&&JSON.stringify($(w))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original Close");return w??=r,o.close?o.close:A(w,"close")}if(d){if(JSON.stringify($(d))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(o.command)return o.command}else d=r;return A(d,"command")}function A(s,r){let p=c(s);o[r]=p;let v=()=>{o[r]===p&&(o[r]=null)};return p.then(v,v),p}function N(s){return t({operation:"get",settlementRequestId:s})}function x(s){return!s||d!==s&&w!==s?!1:(d===s&&(d=null),w===s&&(w=null),g.delete(s.requestId),!d&&!w&&(l=null),!0)}return{ready:u,get pending(){return d},get closing(){return w},get closeRequested(){return f},get inFlight(){return o.command},get closeFlight(){return o.close},get purchase(){return i},assertBinding(s){if(l&&(s.run.id!==l.runId||s.run.source.id!==l.funnelId||s.run.source.versionId!==l.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,r,p,v){let C=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,S=C&&r.settlement?.state==="settled"&&r.run.pendingRequest?.requestId!==C&&(s.operation==="get"||!f||s.operation==="close"||!["running","waiting"].includes(r.run.status))?C:void 0,R=d?.requestId===S?d:w?.requestId===S?w:void 0;e?.bind({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId});let O=r.run.paywall,D=O??r.purchase,L=D?.operation,k=r.settlement&&(!O||O.purchaseRequestId===r.settlement.requestId)&&(!i||i.operationId===r.settlement.operationId)?r.settlement:void 0,G=L?.operationId??D?.quote?.operationId??k?.operationId,H=D?.receiptId??k?.receiptId,de=O?.selectionGeneration??i?.generation??0;if(e&&G&&H&&s.operation!=="review"&&(!n.view||r.run.revision>=n.view.revision)&&(v===void 0||v>=n.readSequence)&&(!i||de>=i.generation)){let Z={receiptId:H,operationId:G,generation:de},fe=L?.status==="complete"||D?.canReselect===!0;await e.observePurchase({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId},Z,fe,S),n.assertCurrent(p),(!i||Z.generation>=i.generation)&&(v===void 0||v>=n.readSequence)&&(fe?i?.operationId===Z.operationId&&(i=void 0):i=Z)}else e&&S&&await e.settle(S);return n.assertCurrent(p),S?x(R):!1},stop(){f=!0},submit:h,settle:N,reset(){f=!0,d=null,w=null,i=void 0,l=null,o.close=null,g.clear(),o.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=Cn(e.funnelId,e.scope??e.configuration?.scope),a=e.session?.subscribeIdentity(i),d=null,w=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?In(e):void 0),f=w&&Rn(w),o=bn({journal:f,state:t,call:l,processIdentity:e.process});async function g(r){if(e.process)return e.process.request(r);let p=t.generation;t.assertCurrent(p);let v=performance.now()+(e.timeoutMs??35e3),C=t.customerToken??("customerToken"in r?r.customerToken:void 0);if(e.session){let O=t.signal,D,L=()=>{},k=new Promise((G,H)=>{L=()=>H(O.reason),O.addEventListener("abort",L,{once:!0}),D=setTimeout(()=>H(new m("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(p),e.session.access())),k])}finally{clearTimeout(D),O.removeEventListener("abort",L)}}t.assertCurrent(p);let S={...r,...C?{customerToken:C}:{}},R=r.operation==="page_experiments"?Te.parse(S):Q.parse(S);return n.requestWithCredential("funnels",R,e.runToken,{headers:e.serverKey&&!C?{[rn]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function i(){a?.(),t.reset(),o.reset(),d=null,n.dispose()}async function l(r,p){let v=t.generation,C=()=>t.assertCurrent(v);f&&await o.ready,C();let S=t.view,R=be(e,await g(r));if(r.operation==="review"&&!R.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(C(),R.runToken&&R.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let O=r.operation==="get"?r.settlementRequestId:"requestId"in r&&r.operation!=="start"?r.requestId:void 0;if(O&&R.settlement?.requestId!==O)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(R),t.assertRun(R.run),t.bindScope(R.scope);let D=await o.observe(r,R,v,p);return!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r.operation==="get"&&r.settlementRequestId||(C(),["running","waiting"].includes(R.run.status)||o.stop(),t.publish(r,R,S,p,D)),R}let u=o.submit,c=null,h=new WeakMap;function A(r){let p=h.get(r);if(p)return p;let v=x(r);return h.set(r,v),v}let N=!1;async function x(r){let p=await r;if(p.run.instruction?.type!=="evaluate_segment")return p;if(c)return c;N=!0;let v=t.generation,C=(async()=>{for(let S=0;S<32&&p.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return p;let R=p.run;if(p.run.instruction?.type==="evaluate_segment"){let{advance:D}=await De(e.configuration,R,{predict:!1});if(v!==t.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return p;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return l({operation:"get"});let L=!0;De(e.configuration,R).then(({prediction:k})=>{L&&v===t.generation&&!o.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(d=k)}).catch(()=>{});try{p=await u({operation:"commit_segment",requestId:nn(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...D})}finally{L=!1,d=null}}}return p})();c=C;try{return await C}finally{c===C&&(c=null)}}let s={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let r=o.closing??o.pending;return r?structuredClone($(r)):null},get pendingCommands(){return[o.pending,o.closing].filter(r=>r!==null).map(r=>structuredClone($(r)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return f!==void 0},get prediction(){let r=t.view;return d&&r&&!r.stopped&&["running","waiting"].includes(r.status)&&r.id===d.runId&&r.nodeId===d.from.nodeId&&r.visit===d.from.visit&&r.revision===d.from.revision&&!o.closeRequested?structuredClone(d):null},settle:o.settle,get webViewUrl(){return"bundled"},resolvePaywall(r){return Pe(e,r)},async pageExperiments(r,p=[]){let v=t.generation;t.assertCurrent(v);let C=t.view?.id;if(!C)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=on.parse(await g(Te.parse({operation:"page_experiments",release:r,usedReceiptIds:p})));if(t.assertCurrent(v),S.runId!==C||S.scope.projectId!==t.scope?.projectId||S.scope.environment!==t.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(r){return l({operation:"review",...r?{receiptId:r}:{}},t.nextRead())},async get(r,p){f&&await o.ready,p??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let v=t.nextRead();return A(l({operation:"get",...r?{data:r}:{},...p?{purchase:p}:{}},v))},resume(r=t.view?.pendingRequest?.requestId){return r?o.closeRequested?s.settle(r):o.pending?.requestId===r?A(u(o.pending)):A(u({operation:"resume",requestId:r})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(r){return A(u(r))},retry(){return o.closeFlight?o.closeFlight:o.closing?u(o.closing):o.closeRequested&&o.pending?s.settle(o.pending.requestId):o.inFlight?A(o.inFlight):o.pending?A(u(o.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(r){t.identify(r),d=null,n.reset()},subscribe:t.subscribe,reset:i};return s}function Un(e,n,t,a){if(!ke(e,n)||t!==void 0&&n.observation&&n.observation.subject.customerId!==t||a!==void 0&&n.observation!==void 0&&(n.observation.subject.scope.projectId!==a.projectId||n.observation.subject.scope.environment!==a.environment))throw new m("INVALID_RESPONSE","The access requirement or Customer changed");return n}function Sn(e,n,t){if(e.requirement){if(!n)throw new m("INVALID_RESPONSE","The requested access check is missing");Un(e.requirement,n,e.customerId,t)}}import{ZodError as kn}from"zod";function En(e,n,t,a){try{return e.parse(n)}catch(d){throw a&&d instanceof kn?new m(t,a):d}}async function Ee(e,n,t,a={},d){let w=typeof a=="function"?{}:a,f=En(n.request,t,"INVALID_REQUEST",w.request);try{let o=await e(n.path,f,n.method,d),g=typeof a=="function"?a:a.parseResponse;return g?g(n.response,o):En(n.response,o,"INVALID_RESPONSE",w.response)}catch(o){throw o instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(o.commandRequestId??=f.requestId),o}}async function rr(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let t=ne.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}:{}}),a=Y(e);e.session||a.identify(n.customerToken);let d=null,w=!1,f=null,o=null,g=null,i=null,l=null,u=null,c=null,h=0;function A(){if(w)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function N(){A();let p=ne.resolvePaywall,v=await Ee(a.request,p,{...t,selector:d?{type:"version",versionId:d.id}:t.selector});Sn(t,v.paywall.check,v.scope);let C=await Pe(e,v.paywall);if(A(),n.paywallVersionId?C.id!==n.paywallVersionId:C.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(d&&(!mn(C,d)||C.paywallId!==d.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return d=C,structuredClone(d)}async function x(p){if(A(),i&&p!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let v=f;if(p!=="read"){if(c){if(u===p)return c;throw new m("COMMAND_PENDING","Wait for the original purchase command")}if(u&&u!==p)throw new m("COMMAND_PENDING","Read the original purchase before changing an uncertain command");u=p,h++}let C=u,S=h,R=p==="read"&&c===null,O=p==="read"?ne.readSubscriptionOperation:ne.attach,D=(async()=>{let L=await Ee(a.request,O,{operationId:v.operationId,...p==="read"?{}:{intent:p},...p==="confirm"&&v.merchantTerms?{merchantConfirmation:Ue(v.merchantTerms)}:{}});return pn(L.operation,{operationId:v.operationId,currency:t.commerce.currency},"The purchase operation changed"),A(),f?.operationId!==v.operationId?structuredClone(L.operation):(o=yn(o,L.operation),(p!=="read"||R&&c===null)&&h===S&&u===C&&(u=null),structuredClone(o))})();if(p!=="read"){c=D;let L=()=>{c===D&&(c=null)};D.then(L,L)}return D}let s={get view(){return d?structuredClone(d):null},get quote(){return f?structuredClone(f):null},get operation(){return o?structuredClone(o):null},get webViewUrl(){return"bundled"},get recovery(){return wn({quote:f,operation:o,requestId:l,pending:i!==null||u!==null,destroyed:w})},get pendingCancellation(){return!w&&u==="cancel"},refresh:N,async preview(p){if(A(),!d)throw new m("INVALID_REQUEST","Load the Paywall first");let v=d.document.buttons[p.actionId];if(v?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let C=je(v.product,p.selection,d.capabilities);if(!C)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let S=Ke(d.document.screen,C,p.selection,d.capabilities),R=ne.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:C,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:t.commerce.provider,currency:t.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),O=JSON.stringify(R);if(g&&g!==O&&(i||u||!o||o.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(g===O){if(i)return i;if(f)return structuredClone(f)}g!==O&&(f=null,o=null),g=O,l=R.requestId;let D=(async()=>{let L=ne.previewAttach,k=await Ee(a.request,L,R);return A(),gn(k.quote,{productVersionId:C,featureQuantities:S,currency:t.commerce.currency,provider:t.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=k.quote,o=null,structuredClone(f)})();i=D;try{return await D}finally{i===D&&(i=null)}},confirm:()=>x("confirm"),cancel:()=>x("cancel"),read:()=>x("read"),destroy(){w||(w=!0,r?.(),a.dispose(),d=null,f=null,o=null,g=null,l=null)}},r=e.session?.subscribeIdentity(s.destroy);try{return await N(),s}catch(p){throw s.destroy(),p}}import{z as Jn}from"zod";import{z as ge}from"zod";var Gn=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,Bn=100;function jn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function An(e,n){let t=n===void 0?jn():n,a=new Map,d=0,w=!1,f=!1,o,g;async function i(u){if(!t)return null;let c;try{let h=await Promise.race([Promise.resolve().then(()=>t.getItem(u)),new Promise(A=>{c=setTimeout(()=>A(null),Bn)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(c)}}function l(){if(g)return g;let u=(async()=>{try{let c=await i(`${e}:artifacts`);if(c)return Gn.parse(JSON.parse(c))}catch{}return{}})();return g=u,u.finally(()=>{g===u&&(g=void 0)}),u}return{async readManifest(){return i(e)},writeManifest(u){!t||u.length>oe||new TextEncoder().encode(u).byteLength>oe||(o=u,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;o!==void 0;){let c=o;try{await t.setItem(e,c)}catch{}o===c&&(o=void 0)}}finally{f=!1}})))},async readArtifact(u){let c=(await l())[u],h=Date.now();return c&&h>=c.at&&h-c.at<=j.retentionMs?c.text:void 0},writeArtifact(u,c){if(!t||c.length>oe)return;let h=a.get(u);if(h?.text===c||!h&&a.size>=128)return;let A=new TextEncoder().encode(c).byteLength;d-(h?.byteLength??0)+A>oe||(a.set(u,{text:c,byteLength:A}),d+=A-(h?.byteLength??0),!w&&(w=!0,Promise.resolve().then(async()=>{try{for(;a.size;){let N=new Map(a);try{let x={...await l()},s=Date.now();for(let[C,S]of N)x[C]={at:s,text:S.text};let r={},p=2,v=0;for(let[C,S]of Object.entries(x).sort(([,R],[,O])=>O.at-R.at)){if(S.at>s||s-S.at>j.retentionMs)continue;let R=new TextEncoder().encode(JSON.stringify({[C]:S})).byteLength;p+R>oe||v>=128||(r[C]=S,p+=R,v++)}await t.setItem(`${e}:artifacts`,JSON.stringify(r))}catch{}finally{for(let[x,s]of N)a.get(x)===s&&(a.delete(x),d-=s.byteLength)}}}finally{w=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Fn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function gr(e){let n=Ye.parse(e.scope),t=new te(e.origin??le);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let a=new Set([t.origin,...(e.assetOrigins??[]).map(I=>{let y=new te(I);if(y.protocol!=="https:"||y.username||y.password||y.search||y.hash||y.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return y.origin})]),d=e.fetch??globalThis.fetch.bind(globalThis),w=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${t.origin}:${M(n)}`,o=An(f,e.storage),g,i=0,l=0,u=!1,c=!1,h=0,A=0,N,x,s,r,p=0,v=new Set,C=new Set,S=new Map,R=new Map,O=0,D=!1;function L(){for(let I of v)try{I()}catch{}}function k(I){try{e.onError?.(I)}catch{}}let G=()=>!c&&!u&&!!g&&W()<i&&Date.now()<l;function H(){if(!G())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(I,y,b){if(!S.has(I)){for(;S.size&&(S.size>=128||O+b>j.maxCacheBytes);){let P=S.entries().next().value;O-=P[1].byteLength,S.delete(P[0])}S.set(I,{text:y,byteLength:b}),O+=b}}function Z(I,y,b){return fn(I,y,{signal:b,error:P=>E("INVALID_RESPONSE",P==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(I){let y=new te(I,t);if(!a.has(y.origin)||y.username||y.password||y.hash||y.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return y.href}async function Ae(I,y,b=!1){let P=await d(fe(I),{method:"GET",credentials:"omit",redirect:"error",cache:b?"default":"no-cache",signal:y,headers:{}});if(P.status===429){let T=P.headers.get("retry-after")??"";p=/^\d+$/.test(T)?Number(T)*1e3:Math.max(0,Date.parse(T)-Date.now())||15e3}if(!P.ok&&P.status!==304)throw E(`CONFIGURATION_HTTP_${P.status}`,"Configuration synchronization failed");return P}function On(I,y,b){let P=Date.parse(I.headers.get("x-indiana-config-validated-at")??""),T=Date.parse(I.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(I.headers.get("date")??""),F=I.headers.get("age"),B=F!==null&&/^\d+(\.\d+)?$/.test(F)?Number(F)*1e3:NaN;if(![P,T,_,B].every(Number.isFinite)||T<=P||T-P>j.maxControlAgeMs||P>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let V=Math.min(T-P,b.maxControlAgeSeconds*1e3,j.maxControlAgeMs)-Math.max(B,_-P,0)-(W()-y);if(V<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+V}function Fe(){if(clearTimeout(s),clearTimeout(r),c||!v.size)return;G()&&(r=setTimeout(()=>{G()?Fe():L()},Math.max(1,i-W())),Fn(r));let I=A?Math.min(15e3,1e3*2**Math.min(A-1,4)):Math.min(15e3,(g?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{ie().catch(k)},Math.max(p,I*(.8+Math.random()*.2))),Fn(s)}async function ie(){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(N)return N;let I=h,y=new AbortController;x=y;let b=(async()=>{if(!D){D=!0;try{let he=await o.readManifest();if(he&&!g){let K=Oe.parse(JSON.parse(he));M(K.scope)===M(n)&&(g=K)}}catch{}}y.signal.throwIfAborted();let F=g,B=W(),q=await Ae(w,y.signal);q.status===304&&(!F||!q.headers.has("x-indiana-config-validated-at")||!q.headers.has("x-indiana-config-valid-until")||!q.headers.has("age"))&&(q=await Ae(w,y.signal));let V=q.status===304?F:Oe.parse(JSON.parse(await Z(q,j.maxManifestBytes,y.signal))),{generation:ae,...se}=V,z=q.headers.get("etag");if(M(V.scope)!==M(n)||$e(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(F&&(V.revision<F.revision||V.revision===F.revision&&V.generation!==F.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(F?.funnels??{})){let ee=V.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=On(q,B,V.policy);if(y.signal.throwIfAborted(),I!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return g=V,i=X,l=Date.now()+Math.max(0,X-W()),u=!1,A=0,p=0,o.writeManifest(M(V)),L(),structuredClone(V)})(),P=setTimeout(()=>y.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),j.initializationMs),T=new Promise((F,B)=>y.signal.addEventListener("abort",()=>B(y.signal.reason),{once:!0})),_=Promise.race([b,T]).catch(F=>{throw A++,(F instanceof Jn.ZodError||F instanceof SyntaxError||F instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(F.code))&&(i=0,u=!0,L()),F}).finally(()=>{clearTimeout(P),N===_&&(N=void 0),Fe()});return N=_,_}async function ye(I){let y=I.sha256,b=se=>Ce(se,I);fe(I.url);let P=S.get(y);if(P){if(P.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return S.delete(y),S.set(y,P),P.text}let T=R.get(y);if(T){if(T.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.promise}let _=new AbortController;C.add(_);let F=h,B=(async()=>{try{let X=await o.readArtifact(y);if(X&&b(X)){if(_.signal.throwIfAborted(),c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,X,I.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Ae(I.url,_.signal,!0),z=await Z(se,I.byteLength,_.signal);if(!b(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,z,I.byteLength),o.writeArtifact(y,z),z})(),q=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),j.initializationMs),V=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([B,V]).finally(()=>{clearTimeout(q),C.delete(_),R.delete(y)});return R.set(y,{promise:ae,byteLength:I.byteLength}),ae}async function we(){return G()||await ie(),H(),g}async function me(I){let y,b=new Promise((P,T)=>{y=setTimeout(()=>T(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),j.initializationMs)});try{return await Promise.race([I(),b])}finally{clearTimeout(y)}}function pe(I,y){if(H(),g?.generation!==I.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(y&&g.funnels[y]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Le(I){let y=I.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let P=He.parse(JSON.parse(await ye(b)));if(M(P.scope)!==M({projectId:n.projectId,environment:n.environment})||P.generation!==b.generation||P.remoteFeatures.some(T=>Object.hasOwn(P.features,T)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(I),{...P,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,i-W())).toISOString()}}async function xe(I,y){let b=await we(),P=b.funnels[I];y&&(!P||P.evaluationMode==="local"&&!P.versions[y])&&(N&&await N,b=await ie()),pe(b,I);let T=b.funnels[I];if(T.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=y??T.currentVersionId,F=T.versions[_];if(!F)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(b.artifacts[F.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[B,q]=await Promise.all([ye(b.artifacts[F.artifact]).then(V=>Ze(JSON.parse(V))),T.evaluationMode==="local"?Le(b):void 0]);if(q&&M(We(B,q))!==M(F.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(b,I),{document:B,growth:q,versionId:_,control:structuredClone(T),manifest:structuredClone(b)}}async function Ve(I,y){try{return await xe(I,y)}catch(b){if(!(b instanceof m)||!(b.code==="CONFIGURATION_CHANGED"||b.code==="CONFIGURATION_HTTP_404"&&G()))throw b;let P=g?.generation;if(N&&await N,await ie(),b.code!=="CONFIGURATION_CHANGED"&&g?.generation===P)throw b;return xe(I,y)}}function Ne(){u=!0,L(),ie().catch(k)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function Tn(I){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(I),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Fe()),()=>{v.delete(I),v.size||(clearTimeout(s),clearTimeout(r),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:Tn,assertFresh:H,assertFeatures(I){H();let y=g.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(I!==void 0&&g.artifacts[y].generation!==I)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return g?structuredClone(g):null},get remainingMs(){return G()?Math.max(0,i-W()):0},async features(){return me(async()=>Le(await we()))},pageExperiments:()=>me(async()=>{let I=await we(),y=I.gb.pageExperiments;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let P=un.parse(JSON.parse(await ye(b)));if(P.environmentId!==n.environmentId||P.generation!==b.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(I),P}),funnel:(I,y)=>me(()=>Ve(I,y)),paywall:(I,y)=>me(async()=>{let b=await we(),P=b.paywalls?.[I];if(!P||!y&&P.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let T=y??P.currentVersionId,_=P.versions[T],F=_&&b.artifacts[_.artifact];if(!F||F.kind!=="paywall"||F.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let B=Qe.parse(JSON.parse(await ye(F)));return pe(b),{document:B,versionId:T,version:_.version,control:structuredClone(P),manifest:structuredClone(b)}}),async localFunnel(I,y){let b=await me(()=>Ve(I,y));if(!b.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:P,remoteFeatures:T,..._}=b.growth;return sn({scope:{projectId:n.projectId,environment:n.environment},funnelId:I,versionId:b.versionId,evaluationMode:"local",evaluationRevision:b.control.evaluationRevision,document:b.document,payload:_})},assertFunnel(I,y,b){H();let P=g.funnels[I];if(!P||P.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(P.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(y!==void 0&&P.controlRevision!==y)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(b!==void 0&&!P.versions[b])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!c){c=!0,h++,i=0,x?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(r),Me(),L(),v.clear();for(let I of C)I.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));S.clear(),O=0}}}}function Nn(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(t){let a=Q.safeParse({...t,operation:"start"});if(!a.success||a.data.operation!=="start"||(n?a.data.customer!==void 0:a.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let d=a.data,w=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||w.identify(e.apiKey);let f=be(e,await w.request("funnels",d));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==d.funnelId||f.run.locale!==(d.locale??"en")||!ce(f.run.parameters,d.parameters??{})||(d.customer?!f.customerId||d.customer.type==="id"&&f.customerId!==d.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{w.dispose()}}}}async function Fr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&M(t)!==M(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let d=re.test(e.credential);if(d?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let w=Nn({...e,scope:t,apiKey:e.credential}),f=o=>{let g=Pn({...e,scope:t,runToken:o,...d?{serverKey:e.credential}:{}});return d||g.identify(e.credential),g};return{async start(o){let g=await w.start({...o,funnelId:e.funnelId,...d?{customer:{type:"id",value:e.customerId}}:{}}),i=f(g.runToken),l=await i.get();return{...g,...l,controller:i}},async restore(o){let g=f(o),i=await g.get();if(i.run.source.id!==e.funnelId)throw g.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...i,runToken:o,controller:g}}}}export{Ee as a,Un as b,Sn as c,zn as d,be as e,_e as f,ut as g,Mn as h,In as i,It as j,ce as k,St as l,Et as m,Pn as n,rr as o,gr as p,Nn as q,Fr as r};
@@ -1 +1 @@
1
- import{a as d,b as te,c as U,d as ne,n as j,q as re}from"./chunk-CJMHP3S7.js";import{b as ee}from"./chunk-DTJKESGC.js";import{a as o}from"./chunk-KHIQQNTR.js";import{a as J}from"./chunk-DSPLGTQI.js";import{Ca as c,Ea as G,Pa as Z,_ as $,a as K,b as Q,c as W,d as M,e as H,f as X,q as B}from"./chunk-DBBUN53B.js";import{a as Y}from"./chunk-4SWGHICJ.js";var L=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new o("INVALID_STATE","Installation sequence exhausted");return t+1},we=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new o("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ie(t,e,n){let r=null,s=0,a=0,l=0,I=Promise.resolve(),v=!1;if(t&&(!n||Y.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new o("SCOPE_MISMATCH","Push installation belongs to another scope");let y=()=>{if(v)throw new o("CLOSED","SDK client was destroyed");if(!t)throw new o("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==s)throw new o("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(i){let u=y();if(!u.sha256&&!globalThis.crypto?.subtle)throw new o("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let p=u.sha256?await u.sha256(Uint8Array.from(i,h=>h.charCodeAt(0))):await we(i);if(!/^[a-f0-9]{64}$/.test(p))throw new o("INVALID_STATE","Push credential digest is invalid");return p}function f(i){let u=H.parse(i);if(u.installationId.toLowerCase()!==y().installationId.toLowerCase())throw new o("INVALID_RESPONSE","Push response belongs to another installation");return u}async function C(i,u){let p=y(),h={installationId:p.installationId,publicKey:p.publicKey,issuedAt:new Date().toISOString(),...u},P=await p.sign(X(i,p.scope,h));return{...h,signature:P}}let m=(i,u,p)=>e.requestWithCredential?e.requestWithCredential(i,u,p):e.request(i,u);async function w(){let i=y(),u=s,p=r?await(e.session?.access()??r):null,h=_(i,A=>A),P;if(h.detachSeq!==null){let A=h.detachSeq,V=K.parse(await C("detach",{sequence:A,platform:i.platform}));try{let N=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new o("INVALID_RESPONSE","Push detach acknowledgement is invalid");let F=f(N.installation);if(F.bound||F.identitySeq!==A)throw new o("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof o&&N.status===404)P=N;else if(!(N instanceof o)||N.status!==412)throw N}P||_(i,N=>({...N,detachSeq:N.detachSeq===A?null:N.detachSeq}))}if(O(u),!p){if(P)throw P;return null}let R=c.bindPushInstallation,k=R.request.parse(await C("bind",{sequence:l,platform:i.platform,credentialDigest:await D(p)}));O(u);let q=R.response.parse(await m(R.path,k,p));O(u);let T=f(q.installation);if(!T.bound||T.identitySeq!==l)throw new o("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return P&&h.detachSeq!==null&&l>h.detachSeq&&_(i,A=>({...A,detachSeq:A.detachSeq===h.detachSeq?null:A.detachSeq})),T}async function E(){y();let i=s,u=r?await(e.session?.access()??r):null;if(!u)throw new o("NOT_IDENTIFIED","Identify before reading this installation");let p=c.readPushInstallation,h=p.request.parse(await C("read",{credentialDigest:await D(u)}));O(i);let P=p.response.parse(await m(p.path,h,u));return O(i),f(P.installation)}function g(i=w){let u=I.catch(()=>{}).then(i);return I=u,u.catch(p=>{try{t?.onError?.(p instanceof Error?p:new Error("Push synchronization failed"))}catch{}}),u}async function S(i,u,p){let h=y(),P=u.identity,R=u.observation,k=r?await(e.session?.access()??r):null;if(O(P),R!==a)throw new o("INVALID_STATE","Push observation changed during recovery");if(!k)throw new o("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new o("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await g(async()=>{if(O(P),await w(),O(P),R!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let q=_(h,F=>p?F:{...F,addressSeq:L(F.addressSeq)}),A=await C(p?"recovery_confirm":"recovery_request",{...i,sequence:q.addressSeq,credentialDigest:await D(k),...p?{challenge:p}:{}}),V=p?W.parse(A):Q.parse(A);if(O(P),R!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let N=await m(`push/installations/recovery/${p?"confirm":"request"}`,V,k);if(O(P),R!==a||_(h,F=>F).addressSeq!==q.addressSeq)throw new o("INVALID_STATE","Push observation changed during recovery");if(p){let F=c.updatePushAddress.response.parse(N),x=f(F.installation);if(!x.bound||x.identitySeq!==l||x.addressSeq!==q.addressSeq||x.connectionId!==i.connectionId||x.addressStatus!=="active")throw new o("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return x}if(!N||typeof N!="object"||!("recovery"in N))throw new o("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return M.parse(N.recovery)})}return{recoveryObserver(){y();let i={identity:s,observation:++a};return{async request(u){return M.parse(await S(u,i))},async confirm(u,p){return H.parse(await S(p,i,u))}}},identify(i){if(!t)return;l=_(t,p=>({...p,identitySeq:L(p.identitySeq)})).identitySeq,r=i,s++,a++},reset(){if(t)try{_(t,i=>{let u=L(i.identitySeq);return{...i,identitySeq:u,detachSeq:u}})}finally{r=null,s++,a++}},start(){t&&!v&&g()},destroy(){v=!0,r=null,s++,a++},async sync(){return await g()},read:E,async recover(){let i=y(),u=s,p=l;return a++,await g(async()=>{O(u);let h=await E();return O(u),l=_(i,R=>{if(R.identitySeq!==p)throw new o("IDENTITY_CHANGED","A newer installation intent exists");return{...R,identitySeq:L(Math.max(R.identitySeq,h.identitySeq)),addressSeq:Math.max(R.addressSeq,h.addressSeq)}}).identitySeq,await w()})},tokenObserver(){y();let i=++a,u=s;return async p=>{if(i!==a||u!==s)return null;let h=y(),P=r?await(e.session?.access()??r):null;if(!P)throw new o("NOT_IDENTIFIED","Identify before registering a Push token");if(await g(),O(u),i!==a)return null;let R=_(h,A=>({...A,addressSeq:L(A.addressSeq)})),k=c.updatePushAddress,q=k.request.parse(await C("address",{...p,sequence:R.addressSeq,credentialDigest:await D(P)}));if(O(u),i!==a)return null;let T=await m(k.path,q,P);return O(u),i!==a||_(h,A=>A).addressSeq!==R.addressSeq?null:f(k.response.parse(T).installation)}}}}function se(t,e){let n={async preference(r){let s=c.readMessagingPreference;return(await d(t,s,{channel:r})).preference},async setPreference(r){let s=c.setMessagingPreference;return(await d(t,s,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}function oe(t,e,n={}){let r=!1;function s(){if(r)throw new o("CLOSED","SDK client was destroyed")}let a=new Set,l=v=>{for(let y of a)try{y(v)}catch{}},I=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:s,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(v){return s(),a.add(v),()=>{a.delete(v)}},identify(v){s();let y=typeof v=="string"?v:v.accessToken;if(!B.test(y))throw new o("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(y),t.identify(v)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,I(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function b(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new o("INVALID_REQUEST","Customer requests use the verified session identity")}var ve={...c.readHoldings,request:c.readHoldings.request.omit({customerId:!0})};function ae(t){return{async checkEntitlement(e){b(e);let n=c.checkEntitlement,r=n.request.parse(e),s=await d(t,n,r);return te(r.requirement,s.check,void 0,s.scope),s},async readHoldings(e={}){return d(t,ve,e)}}}function ce(t){return{async readLedger(e){let n=c.readLedger;return d(t,n,{query:e})},async readCreditStatement(e){b(e);let n=c.readCreditStatement;return d(t,n,e)},async quoteBalance(e){b(e);let n=c.quoteBalance;return d(t,n,{command:e})}}}function ue(t){return{async setupPayment(e){b(e);let n=c.setupPayment;return d(t,n,e)},async readPaymentSetup(e){b(e);let n=c.readPaymentSetup;return d(t,n,e)},async readBillingInvoice(e){b(e);let n=c.readBillingInvoice;return d(t,n,e)},async readBillingControls(e={}){b(e);let n=c.readBillingControls;return d(t,n,e)},async prepareBillingAuthorization(e){b(e);let n=c.prepareBillingAuthorization;return d(t,n,e)},async confirmBillingAuthorization(e){b(e);let n=c.confirmBillingAuthorization;return d(t,n,e)},async setBillingCoupons(e){b(e);let n=c.setBillingCoupons;return d(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){b(e);let n=c.revokeBillingAuthorization;return d(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){b(e);let n=c.listBillingInvoices;return d(t,n,e)},async confirmBillingAdjustment(e){b(e);let n=c.confirmBillingAdjustment;return d(t,n,e)}}}function de(t){return{async previewUpdate(e){b(e);let n=c.previewUpdate;return d(t,n,e)},async update(e){b(e);let n=c.update;return d(t,n,e)},async readSubscriptionUpdate(e){b(e);let n=c.readSubscriptionUpdate;return d(t,n,e)},async restoreNativePurchase(e){b(e);let n=c.restoreNativePurchase;return d(t,n,e)},async previewAttach(e){b(e);let n=c.previewAttach;return d(t,n,e)},async attach(e){b(e);let n=c.attach;return d(t,n,e)},async readSubscriptionOperation(e){b(e);let n=c.readSubscriptionOperation;return d(t,n,e)}}}function pe(t){return{async redeemReward(e){return b(e),(await d(t,c.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return b(e),(await d(t,c.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return b(e),(await d(t,c.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await d(t,c.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await d(t,c.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await d(t,c.listOffers,{},{response:"Invalid offers response"})).offers}}}function le(t){return{...ae(t),...ce(t),...ue(t),...de(t),...pe(t)}}function me(t){return{async resolveContent(e){b(e);let n=c.resolveContent;return d(t,n,e)},async resolvePaywall(e){b(e);let n=c.resolvePaywall,r=n.request.parse(e),s=await d(t,n,r);return U(r,s.paywall.check,s.scope),s},async resolveOffering(e){b(e);let n=c.resolveOffering,r=n.request.parse(e),s=await d(t,n,r);return U(r,s.check,s.scope),s}}}var z=t=>new TextEncoder().encode(JSON.stringify(t)).length,fe=16384;function ye(t,e){let n=0,r,s=m=>{r={config:structuredClone(m),until:Date.now()+3e4}},a=[],l=null,I;function v(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}function y(){I||!a.length||(I=setTimeout(()=>{I=void 0,D().catch(()=>{}).finally(y)},5e3),typeof I=="object"&&"unref"in I&&I.unref())}function O(m,w={},E={}){if(v(),r&&Date.now()<r.until&&!$(r.config,m))return;C();let g=c.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:m,properties:w,...E}]}).events[0];if(z({events:[g]})>fe)throw new o("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new o("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(g)),y()}async function D(m=!1){if(v(),l)return l;let w=n,E=(async()=>{let g={inserted:0,duplicates:0,rejected:0,skipped:0},S=a.length;for(;S&&w===n;){let i=[],u=z({events:[]});for(let P of a.slice(0,Math.min(S,100))){let R=z(P)+(i.length?1:0);if(i.length&&u+R>fe)break;i.push(P),u+=R}let p=c.trackEvents,h=await d(t,p,{events:i},void 0,{keepalive:m});if(w!==n)throw new o("IDENTITY_CHANGED","Event identity changed during delivery");if(h.inserted+h.duplicates+h.rejected+h.skipped!==i.length)throw new o("INVALID_RESPONSE","Incomplete event acknowledgement");s(h.analyticsConfig),a.splice(0,i.length),S-=i.length,g.inserted+=h.inserted,g.duplicates+=h.duplicates,g.rejected+=h.rejected,g.skipped+=h.skipped}return g})();l=E;try{return await E}finally{l===E&&(l=null)}}let f;function C(){if(f||typeof document>"u")return;let m=()=>{document.visibilityState==="hidden"&&e()&&a.length&&D(!0).catch(()=>{})};document.addEventListener("visibilitychange",m),f=()=>document.removeEventListener("visibilitychange",m)}return{rememberConfiguration:s,track:O,flush:D,reset(){n++,r=void 0,clearTimeout(I),I=void 0,a=[],l=null},detachVisibility(){f?.(),f=void 0}}}function Ie(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function Ae(t){let e=Ie(t),{merchandiseId:n,merchandise:r,...s}=t;return{...s,...e?{merchandise:e}:{}}}function he(t,e,n,r,s){if(s&&r&&(s.scope.projectId!==r.projectId||s.scope.environment!==r.environment))throw new o("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,l=new Set;function I(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}async function v(y={}){s||I();let O=a,D=!1,f=async()=>{if(D||O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let q=c.getFeatures,T=s?{scope:{projectId:s.scope.projectId,environment:s.scope.environment},payload:await s.features()}:await d(t,q,{});if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");if(r&&(T.scope.projectId!==r.projectId||T.scope.environment!==r.environment))throw new o("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(T.payload.analyticsConfig),T},C=await f(),m=!0,w,E=q=>{try{y.onError?.(q)}catch{}},g=(q,T,A)=>{try{let V=Ie(A);n.track(q,T,V?{merchandise:V}:{})}catch(V){E(V)}},S=ne({assertUsable:s?.assertFeatures,scope:C.scope,attributes:y.attributes,onError:y.onError,load:async()=>m?(m=!1,C.payload):(await f()).payload,evaluateRemote:async q=>{if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let T=c.evaluateFeatures,A=await d(t,T,{...q,attributes:Ae(q.attributes)});if(A.scope.projectId!==C.scope.projectId||A.scope.environment!==C.scope.environment)throw new o("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:A.generation,evaluatedAt:A.evaluatedAt,expiresAt:A.expiresAt,features:A.features,...A.merchandiseContext?{merchandiseContext:A.merchandiseContext}:{}}},onExperimentViewed:(q,T,A)=>g("Experiment Viewed",{experimentId:q.key,variationId:T.key},A),onFeatureUsage:(q,T,A)=>g("Feature Evaluated",{feature:q,value:T.value,source:T.source,ruleId:T.ruleId,...T.experimentResult?{variationId:T.experimentResult.key}:{}},A)}),i=S.refresh;function u(){clearTimeout(w),!s&&(D||O!==a||!S.expiresAt||(w=setTimeout(()=>{p().catch(E)},Math.min(2147483647,Math.max(1e3,Date.parse(S.expiresAt)-Date.now()))),typeof w=="object"&&"unref"in w&&w.unref()))}async function p(){try{return await i()}finally{u()}}let h=()=>{D||p().catch(E)},P=S.subscribe(u),R=s?.subscribe(()=>{!D&&s.fresh&&p().catch(E)});function k(){D||(D=!0,clearTimeout(w),typeof window<"u"&&window.removeEventListener("focus",h),P(),R?.(),S.reset(),l.delete(k))}l.add(k);try{await S.init(),(y.attributes?.merchandise||y.attributes?.merchandiseId)&&await S.refreshRemote()}catch(q){throw k(),q}return u(),!s&&typeof window<"u"&&window.addEventListener("focus",h),Object.assign(S,{refresh:p,destroy:k})}return{features:v,reset(y){a++,y();for(let O of l)O()}}}import{z as be}from"zod";function ge(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=be.object({funnelId:G.shape.id,funnelVersionId:G.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new o("INVALID_REQUEST","A valid Funnel source is required");let s=Object.freeze(r.data);function a(l){if("customerId"in l)throw new o("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==s.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==s.funnelVersionId)throw new o("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...s}}return{async claimCoupon(l,I=crypto.randomUUID()){let v=c.grantOffer,y=await d(t,v,a({couponId:l,requestId:I}));return{offer:y.offer,reason:y.reason}},async resolveOffering(l){let I=c.resolveOffering,v=I.request.parse(a(l)),y=await d(t,I,v);return U(v,y.check,y.scope),y},async resolvePaywall(l){let I=c.resolvePaywall,v=I.request.parse(a(l)),y=await d(t,I,v);return U(v,y.paywall.check,y.scope),y},async previewAttach(l){let I=c.previewAttach;return d(t,I,a(l))}}}function xt(t){return Oe(t)}function Oe(t){let e=ee(t),n=e.request,r;try{r=ie(t.push,e,t.scope??t.configuration?.scope)}catch(I){throw e.dispose(),I}let s=oe(e,()=>{l.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ye(n,s.isIdentified),l=he(n,s.isIdentified,a,t.scope,t.configuration);return{session:e.session,...se(n,r),...le(n),...me(n),forFunnel(I){return s.assertActive(),ge(n,I)},async features(I={}){return s.assertActive(),l.features(I)},track(I,v,y={}){return a.track(I,v,y)},flush(){return a.flush()},...s.methods}}function Ht(t){if(!B.test(t.customerToken))throw new o("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new o("INVALID_REQUEST","An explicit App and environment scope is required");let e=re({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),s=j({...t,runToken:r.runToken});s.identify(t.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await s.get():r;return{...r,...a,controller:s}}}}function Qt(t){if(!t.scope)throw new o("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new o("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,s=new Set,a=new Map,l=new Map;async function I(f){let C,m=new Promise((w,E)=>{C=setTimeout(()=>E(new o("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(f),m])}finally{clearTimeout(C)}}function v(f){throw f instanceof o&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear()),f}function y(f,C){if(C!==r)throw new o("IDENTITY_CHANGED","Process was detached during a request");let m=Z.parse(f);if(m.scope.projectId!==t.scope.projectId||m.scope.environment!==t.scope.environment)throw new o("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==m.run.id||e.run.source.versionId!==m.run.source.versionId||e.run.source.id!==m.run.source.id||e.run.runExpiresAt!==m.run.runExpiresAt||e.run.identity.startedAs!==m.run.identity.startedAs||e.run.identity.participantId!==m.run.identity.participantId||e.run.identity.binding&&m.run.identity.binding&&e.run.identity.binding.id!==m.run.identity.binding.id))throw new o("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||m.run.revision>=e.run.revision){if(e?.run.identity.binding&&!m.run.identity.binding)throw new o("INVALID_RESPONSE","The process lost its Customer binding");e=m;for(let h of s)J(h,m.run);m.run.instruction?.type==="authentication_required"&&J(t.onAuthenticationRequired,m.run)}m.settlement?.accepted!==void 0&&l.set(m.settlement.requestId,m.settlement.accepted);let{identity:w,instruction:E,...g}=m.run,{contract:S,settlement:i,...u}=m,p=i&&(({accepted:h,...P})=>P)(i);return{...u,run:{...g,authenticated:w.binding!==null,instruction:E?.type==="authentication_required"?null:E},...p?{settlement:p}:{}}}let O=f=>(a.has(f)||a.set(f,e?.run.identity.binding?.id??null),a.get(f));async function D(f){let C=r,m=e?.run.identity.binding?.id??null,w=g=>{if(m!==(e?.run.identity.binding?.id??null))throw g;return v(g)};if(f.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new o("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return I(()=>t.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(w)}let E;if(f.operation==="get"){let{operation:g,customerToken:S,...i}=f;E=await I(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(w)}else if(f.operation==="review")E=await I(()=>t.adapter.review(f.receiptId)).catch(w);else{if(f.operation==="start")throw new o("INVALID_REQUEST","Use process.open for entry");{let{customerToken:g,...S}=f;E=await I(()=>t.adapter.command(S,O(S.requestId))).catch(w)}}return y(E,C)}return{get view(){return e?.run??null},get controller(){return n},async open(f){let C=r,m=await I(()=>t.adapter.open(f)).catch(v);if(y(m,C),!n){n=j({...t,runToken:m.runToken,process:{request:D,binding:O,restore(g){for(let[S,i]of Object.entries(g))a.set(S,i)}}});let w=n,E=w.submit;w.submit=async g=>{try{return await E(g)}catch(S){if(!(S instanceof o)||S.reason!=="IDENTITY_CONTEXT_CHANGED"||g.operation!=="submit"||g.input.type!=="screen"||a.get(g.requestId)!==null)throw S;await w.settle?.(g.requestId),await w.get();let i=w.view;if(l.get(g.requestId)!==!1||!i||i.id!==e?.run.id||i.nodeId!==g.nodeId||i.visit!==g.visit||!e?.run.identity.binding)throw S;return E({...g,requestId:crypto.randomUUID(),revision:i.revision})}}}await n.get();for(let w of n.pendingCommands??[])a.has(w.requestId)&&a.get(w.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(w.requestId);return{run:e.run,controller:n}},async syncIdentity(){let f=r;y(await I(()=>t.adapter.syncIdentity()).catch(v),f),await n?.get();for(let C of n?.pendingCommands??[])a.has(C.requestId)&&a.get(C.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(C.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),await I(()=>t.adapter.detach())},forProcess(f){if(!e?.run.identity.binding)throw new o("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:f}},subscribe(f){return s.add(f),()=>{s.delete(f)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),s.clear()}}}export{xt as a,Oe as b,Ht as c,Qt as d};
1
+ import{a as d,b as te,c as U,d as ne,n as j,q as re}from"./chunk-2JBNOE2D.js";import{b as ee}from"./chunk-YNMSSQQY.js";import{a as o}from"./chunk-KHIQQNTR.js";import{a as J}from"./chunk-DSPLGTQI.js";import{Ca as c,Ea as G,Pa as Z,_ as $,a as K,b as Q,c as W,d as M,e as H,f as X,q as B}from"./chunk-GSFNAB3W.js";import{a as Y}from"./chunk-4SWGHICJ.js";var L=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new o("INVALID_STATE","Installation sequence exhausted");return t+1},we=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new o("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ie(t,e,n){let r=null,s=0,a=0,l=0,I=Promise.resolve(),v=!1;if(t&&(!n||Y.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new o("SCOPE_MISMATCH","Push installation belongs to another scope");let y=()=>{if(v)throw new o("CLOSED","SDK client was destroyed");if(!t)throw new o("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==s)throw new o("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(i){let u=y();if(!u.sha256&&!globalThis.crypto?.subtle)throw new o("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let p=u.sha256?await u.sha256(Uint8Array.from(i,h=>h.charCodeAt(0))):await we(i);if(!/^[a-f0-9]{64}$/.test(p))throw new o("INVALID_STATE","Push credential digest is invalid");return p}function f(i){let u=H.parse(i);if(u.installationId.toLowerCase()!==y().installationId.toLowerCase())throw new o("INVALID_RESPONSE","Push response belongs to another installation");return u}async function C(i,u){let p=y(),h={installationId:p.installationId,publicKey:p.publicKey,issuedAt:new Date().toISOString(),...u},P=await p.sign(X(i,p.scope,h));return{...h,signature:P}}let m=(i,u,p)=>e.requestWithCredential?e.requestWithCredential(i,u,p):e.request(i,u);async function w(){let i=y(),u=s,p=r?await(e.session?.access()??r):null,h=_(i,A=>A),P;if(h.detachSeq!==null){let A=h.detachSeq,V=K.parse(await C("detach",{sequence:A,platform:i.platform}));try{let N=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new o("INVALID_RESPONSE","Push detach acknowledgement is invalid");let F=f(N.installation);if(F.bound||F.identitySeq!==A)throw new o("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof o&&N.status===404)P=N;else if(!(N instanceof o)||N.status!==412)throw N}P||_(i,N=>({...N,detachSeq:N.detachSeq===A?null:N.detachSeq}))}if(O(u),!p){if(P)throw P;return null}let R=c.bindPushInstallation,k=R.request.parse(await C("bind",{sequence:l,platform:i.platform,credentialDigest:await D(p)}));O(u);let q=R.response.parse(await m(R.path,k,p));O(u);let T=f(q.installation);if(!T.bound||T.identitySeq!==l)throw new o("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return P&&h.detachSeq!==null&&l>h.detachSeq&&_(i,A=>({...A,detachSeq:A.detachSeq===h.detachSeq?null:A.detachSeq})),T}async function E(){y();let i=s,u=r?await(e.session?.access()??r):null;if(!u)throw new o("NOT_IDENTIFIED","Identify before reading this installation");let p=c.readPushInstallation,h=p.request.parse(await C("read",{credentialDigest:await D(u)}));O(i);let P=p.response.parse(await m(p.path,h,u));return O(i),f(P.installation)}function g(i=w){let u=I.catch(()=>{}).then(i);return I=u,u.catch(p=>{try{t?.onError?.(p instanceof Error?p:new Error("Push synchronization failed"))}catch{}}),u}async function S(i,u,p){let h=y(),P=u.identity,R=u.observation,k=r?await(e.session?.access()??r):null;if(O(P),R!==a)throw new o("INVALID_STATE","Push observation changed during recovery");if(!k)throw new o("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new o("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await g(async()=>{if(O(P),await w(),O(P),R!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let q=_(h,F=>p?F:{...F,addressSeq:L(F.addressSeq)}),A=await C(p?"recovery_confirm":"recovery_request",{...i,sequence:q.addressSeq,credentialDigest:await D(k),...p?{challenge:p}:{}}),V=p?W.parse(A):Q.parse(A);if(O(P),R!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let N=await m(`push/installations/recovery/${p?"confirm":"request"}`,V,k);if(O(P),R!==a||_(h,F=>F).addressSeq!==q.addressSeq)throw new o("INVALID_STATE","Push observation changed during recovery");if(p){let F=c.updatePushAddress.response.parse(N),x=f(F.installation);if(!x.bound||x.identitySeq!==l||x.addressSeq!==q.addressSeq||x.connectionId!==i.connectionId||x.addressStatus!=="active")throw new o("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return x}if(!N||typeof N!="object"||!("recovery"in N))throw new o("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return M.parse(N.recovery)})}return{recoveryObserver(){y();let i={identity:s,observation:++a};return{async request(u){return M.parse(await S(u,i))},async confirm(u,p){return H.parse(await S(p,i,u))}}},identify(i){if(!t)return;l=_(t,p=>({...p,identitySeq:L(p.identitySeq)})).identitySeq,r=i,s++,a++},reset(){if(t)try{_(t,i=>{let u=L(i.identitySeq);return{...i,identitySeq:u,detachSeq:u}})}finally{r=null,s++,a++}},start(){t&&!v&&g()},destroy(){v=!0,r=null,s++,a++},async sync(){return await g()},read:E,async recover(){let i=y(),u=s,p=l;return a++,await g(async()=>{O(u);let h=await E();return O(u),l=_(i,R=>{if(R.identitySeq!==p)throw new o("IDENTITY_CHANGED","A newer installation intent exists");return{...R,identitySeq:L(Math.max(R.identitySeq,h.identitySeq)),addressSeq:Math.max(R.addressSeq,h.addressSeq)}}).identitySeq,await w()})},tokenObserver(){y();let i=++a,u=s;return async p=>{if(i!==a||u!==s)return null;let h=y(),P=r?await(e.session?.access()??r):null;if(!P)throw new o("NOT_IDENTIFIED","Identify before registering a Push token");if(await g(),O(u),i!==a)return null;let R=_(h,A=>({...A,addressSeq:L(A.addressSeq)})),k=c.updatePushAddress,q=k.request.parse(await C("address",{...p,sequence:R.addressSeq,credentialDigest:await D(P)}));if(O(u),i!==a)return null;let T=await m(k.path,q,P);return O(u),i!==a||_(h,A=>A).addressSeq!==R.addressSeq?null:f(k.response.parse(T).installation)}}}}function se(t,e){let n={async preference(r){let s=c.readMessagingPreference;return(await d(t,s,{channel:r})).preference},async setPreference(r){let s=c.setMessagingPreference;return(await d(t,s,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}function oe(t,e,n={}){let r=!1;function s(){if(r)throw new o("CLOSED","SDK client was destroyed")}let a=new Set,l=v=>{for(let y of a)try{y(v)}catch{}},I=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:s,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(v){return s(),a.add(v),()=>{a.delete(v)}},identify(v){s();let y=typeof v=="string"?v:v.accessToken;if(!B.test(y))throw new o("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(y),t.identify(v)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,I(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function b(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new o("INVALID_REQUEST","Customer requests use the verified session identity")}var ve={...c.readHoldings,request:c.readHoldings.request.omit({customerId:!0})};function ae(t){return{async checkEntitlement(e){b(e);let n=c.checkEntitlement,r=n.request.parse(e),s=await d(t,n,r);return te(r.requirement,s.check,void 0,s.scope),s},async readHoldings(e={}){return d(t,ve,e)}}}function ce(t){return{async readLedger(e){let n=c.readLedger;return d(t,n,{query:e})},async readCreditStatement(e){b(e);let n=c.readCreditStatement;return d(t,n,e)},async quoteBalance(e){b(e);let n=c.quoteBalance;return d(t,n,{command:e})}}}function ue(t){return{async setupPayment(e){b(e);let n=c.setupPayment;return d(t,n,e)},async readPaymentSetup(e){b(e);let n=c.readPaymentSetup;return d(t,n,e)},async readBillingInvoice(e){b(e);let n=c.readBillingInvoice;return d(t,n,e)},async readBillingControls(e={}){b(e);let n=c.readBillingControls;return d(t,n,e)},async prepareBillingAuthorization(e){b(e);let n=c.prepareBillingAuthorization;return d(t,n,e)},async confirmBillingAuthorization(e){b(e);let n=c.confirmBillingAuthorization;return d(t,n,e)},async setBillingCoupons(e){b(e);let n=c.setBillingCoupons;return d(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){b(e);let n=c.revokeBillingAuthorization;return d(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){b(e);let n=c.listBillingInvoices;return d(t,n,e)},async confirmBillingAdjustment(e){b(e);let n=c.confirmBillingAdjustment;return d(t,n,e)}}}function de(t){return{async previewUpdate(e){b(e);let n=c.previewUpdate;return d(t,n,e)},async update(e){b(e);let n=c.update;return d(t,n,e)},async readSubscriptionUpdate(e){b(e);let n=c.readSubscriptionUpdate;return d(t,n,e)},async restoreNativePurchase(e){b(e);let n=c.restoreNativePurchase;return d(t,n,e)},async previewAttach(e){b(e);let n=c.previewAttach;return d(t,n,e)},async attach(e){b(e);let n=c.attach;return d(t,n,e)},async readSubscriptionOperation(e){b(e);let n=c.readSubscriptionOperation;return d(t,n,e)}}}function pe(t){return{async redeemReward(e){return b(e),(await d(t,c.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return b(e),(await d(t,c.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return b(e),(await d(t,c.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await d(t,c.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await d(t,c.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await d(t,c.listOffers,{},{response:"Invalid offers response"})).offers}}}function le(t){return{...ae(t),...ce(t),...ue(t),...de(t),...pe(t)}}function me(t){return{async resolveContent(e){b(e);let n=c.resolveContent;return d(t,n,e)},async resolvePaywall(e){b(e);let n=c.resolvePaywall,r=n.request.parse(e),s=await d(t,n,r);return U(r,s.paywall.check,s.scope),s},async resolveOffering(e){b(e);let n=c.resolveOffering,r=n.request.parse(e),s=await d(t,n,r);return U(r,s.check,s.scope),s}}}var z=t=>new TextEncoder().encode(JSON.stringify(t)).length,fe=16384;function ye(t,e){let n=0,r,s=m=>{r={config:structuredClone(m),until:Date.now()+3e4}},a=[],l=null,I;function v(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}function y(){I||!a.length||(I=setTimeout(()=>{I=void 0,D().catch(()=>{}).finally(y)},5e3),typeof I=="object"&&"unref"in I&&I.unref())}function O(m,w={},E={}){if(v(),r&&Date.now()<r.until&&!$(r.config,m))return;C();let g=c.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:m,properties:w,...E}]}).events[0];if(z({events:[g]})>fe)throw new o("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new o("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(g)),y()}async function D(m=!1){if(v(),l)return l;let w=n,E=(async()=>{let g={inserted:0,duplicates:0,rejected:0,skipped:0},S=a.length;for(;S&&w===n;){let i=[],u=z({events:[]});for(let P of a.slice(0,Math.min(S,100))){let R=z(P)+(i.length?1:0);if(i.length&&u+R>fe)break;i.push(P),u+=R}let p=c.trackEvents,h=await d(t,p,{events:i},void 0,{keepalive:m});if(w!==n)throw new o("IDENTITY_CHANGED","Event identity changed during delivery");if(h.inserted+h.duplicates+h.rejected+h.skipped!==i.length)throw new o("INVALID_RESPONSE","Incomplete event acknowledgement");s(h.analyticsConfig),a.splice(0,i.length),S-=i.length,g.inserted+=h.inserted,g.duplicates+=h.duplicates,g.rejected+=h.rejected,g.skipped+=h.skipped}return g})();l=E;try{return await E}finally{l===E&&(l=null)}}let f;function C(){if(f||typeof document>"u")return;let m=()=>{document.visibilityState==="hidden"&&e()&&a.length&&D(!0).catch(()=>{})};document.addEventListener("visibilitychange",m),f=()=>document.removeEventListener("visibilitychange",m)}return{rememberConfiguration:s,track:O,flush:D,reset(){n++,r=void 0,clearTimeout(I),I=void 0,a=[],l=null},detachVisibility(){f?.(),f=void 0}}}function Ie(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function Ae(t){let e=Ie(t),{merchandiseId:n,merchandise:r,...s}=t;return{...s,...e?{merchandise:e}:{}}}function he(t,e,n,r,s){if(s&&r&&(s.scope.projectId!==r.projectId||s.scope.environment!==r.environment))throw new o("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,l=new Set;function I(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}async function v(y={}){s||I();let O=a,D=!1,f=async()=>{if(D||O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let q=c.getFeatures,T=s?{scope:{projectId:s.scope.projectId,environment:s.scope.environment},payload:await s.features()}:await d(t,q,{});if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");if(r&&(T.scope.projectId!==r.projectId||T.scope.environment!==r.environment))throw new o("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(T.payload.analyticsConfig),T},C=await f(),m=!0,w,E=q=>{try{y.onError?.(q)}catch{}},g=(q,T,A)=>{try{let V=Ie(A);n.track(q,T,V?{merchandise:V}:{})}catch(V){E(V)}},S=ne({assertUsable:s?.assertFeatures,scope:C.scope,attributes:y.attributes,onError:y.onError,load:async()=>m?(m=!1,C.payload):(await f()).payload,evaluateRemote:async q=>{if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let T=c.evaluateFeatures,A=await d(t,T,{...q,attributes:Ae(q.attributes)});if(A.scope.projectId!==C.scope.projectId||A.scope.environment!==C.scope.environment)throw new o("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:A.generation,evaluatedAt:A.evaluatedAt,expiresAt:A.expiresAt,features:A.features,...A.merchandiseContext?{merchandiseContext:A.merchandiseContext}:{}}},onExperimentViewed:(q,T,A)=>g("Experiment Viewed",{experimentId:q.key,variationId:T.key},A),onFeatureUsage:(q,T,A)=>g("Feature Evaluated",{feature:q,value:T.value,source:T.source,ruleId:T.ruleId,...T.experimentResult?{variationId:T.experimentResult.key}:{}},A)}),i=S.refresh;function u(){clearTimeout(w),!s&&(D||O!==a||!S.expiresAt||(w=setTimeout(()=>{p().catch(E)},Math.min(2147483647,Math.max(1e3,Date.parse(S.expiresAt)-Date.now()))),typeof w=="object"&&"unref"in w&&w.unref()))}async function p(){try{return await i()}finally{u()}}let h=()=>{D||p().catch(E)},P=S.subscribe(u),R=s?.subscribe(()=>{!D&&s.fresh&&p().catch(E)});function k(){D||(D=!0,clearTimeout(w),typeof window<"u"&&window.removeEventListener("focus",h),P(),R?.(),S.reset(),l.delete(k))}l.add(k);try{await S.init(),(y.attributes?.merchandise||y.attributes?.merchandiseId)&&await S.refreshRemote()}catch(q){throw k(),q}return u(),!s&&typeof window<"u"&&window.addEventListener("focus",h),Object.assign(S,{refresh:p,destroy:k})}return{features:v,reset(y){a++,y();for(let O of l)O()}}}import{z as be}from"zod";function ge(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=be.object({funnelId:G.shape.id,funnelVersionId:G.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new o("INVALID_REQUEST","A valid Funnel source is required");let s=Object.freeze(r.data);function a(l){if("customerId"in l)throw new o("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==s.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==s.funnelVersionId)throw new o("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...s}}return{async claimCoupon(l,I=crypto.randomUUID()){let v=c.grantOffer,y=await d(t,v,a({couponId:l,requestId:I}));return{offer:y.offer,reason:y.reason}},async resolveOffering(l){let I=c.resolveOffering,v=I.request.parse(a(l)),y=await d(t,I,v);return U(v,y.check,y.scope),y},async resolvePaywall(l){let I=c.resolvePaywall,v=I.request.parse(a(l)),y=await d(t,I,v);return U(v,y.paywall.check,y.scope),y},async previewAttach(l){let I=c.previewAttach;return d(t,I,a(l))}}}function xt(t){return Oe(t)}function Oe(t){let e=ee(t),n=e.request,r;try{r=ie(t.push,e,t.scope??t.configuration?.scope)}catch(I){throw e.dispose(),I}let s=oe(e,()=>{l.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ye(n,s.isIdentified),l=he(n,s.isIdentified,a,t.scope,t.configuration);return{session:e.session,...se(n,r),...le(n),...me(n),forFunnel(I){return s.assertActive(),ge(n,I)},async features(I={}){return s.assertActive(),l.features(I)},track(I,v,y={}){return a.track(I,v,y)},flush(){return a.flush()},...s.methods}}function Ht(t){if(!B.test(t.customerToken))throw new o("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new o("INVALID_REQUEST","An explicit App and environment scope is required");let e=re({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),s=j({...t,runToken:r.runToken});s.identify(t.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await s.get():r;return{...r,...a,controller:s}}}}function Qt(t){if(!t.scope)throw new o("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new o("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,s=new Set,a=new Map,l=new Map;async function I(f){let C,m=new Promise((w,E)=>{C=setTimeout(()=>E(new o("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(f),m])}finally{clearTimeout(C)}}function v(f){throw f instanceof o&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear()),f}function y(f,C){if(C!==r)throw new o("IDENTITY_CHANGED","Process was detached during a request");let m=Z.parse(f);if(m.scope.projectId!==t.scope.projectId||m.scope.environment!==t.scope.environment)throw new o("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==m.run.id||e.run.source.versionId!==m.run.source.versionId||e.run.source.id!==m.run.source.id||e.run.runExpiresAt!==m.run.runExpiresAt||e.run.identity.startedAs!==m.run.identity.startedAs||e.run.identity.participantId!==m.run.identity.participantId||e.run.identity.binding&&m.run.identity.binding&&e.run.identity.binding.id!==m.run.identity.binding.id))throw new o("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||m.run.revision>=e.run.revision){if(e?.run.identity.binding&&!m.run.identity.binding)throw new o("INVALID_RESPONSE","The process lost its Customer binding");e=m;for(let h of s)J(h,m.run);m.run.instruction?.type==="authentication_required"&&J(t.onAuthenticationRequired,m.run)}m.settlement?.accepted!==void 0&&l.set(m.settlement.requestId,m.settlement.accepted);let{identity:w,instruction:E,...g}=m.run,{contract:S,settlement:i,...u}=m,p=i&&(({accepted:h,...P})=>P)(i);return{...u,run:{...g,authenticated:w.binding!==null,instruction:E?.type==="authentication_required"?null:E},...p?{settlement:p}:{}}}let O=f=>(a.has(f)||a.set(f,e?.run.identity.binding?.id??null),a.get(f));async function D(f){let C=r,m=e?.run.identity.binding?.id??null,w=g=>{if(m!==(e?.run.identity.binding?.id??null))throw g;return v(g)};if(f.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new o("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return I(()=>t.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(w)}let E;if(f.operation==="get"){let{operation:g,customerToken:S,...i}=f;E=await I(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(w)}else if(f.operation==="review")E=await I(()=>t.adapter.review(f.receiptId)).catch(w);else{if(f.operation==="start")throw new o("INVALID_REQUEST","Use process.open for entry");{let{customerToken:g,...S}=f;E=await I(()=>t.adapter.command(S,O(S.requestId))).catch(w)}}return y(E,C)}return{get view(){return e?.run??null},get controller(){return n},async open(f){let C=r,m=await I(()=>t.adapter.open(f)).catch(v);if(y(m,C),!n){n=j({...t,runToken:m.runToken,process:{request:D,binding:O,restore(g){for(let[S,i]of Object.entries(g))a.set(S,i)}}});let w=n,E=w.submit;w.submit=async g=>{try{return await E(g)}catch(S){if(!(S instanceof o)||S.reason!=="IDENTITY_CONTEXT_CHANGED"||g.operation!=="submit"||g.input.type!=="screen"||a.get(g.requestId)!==null)throw S;await w.settle?.(g.requestId),await w.get();let i=w.view;if(l.get(g.requestId)!==!1||!i||i.id!==e?.run.id||i.nodeId!==g.nodeId||i.visit!==g.visit||!e?.run.identity.binding)throw S;return E({...g,requestId:crypto.randomUUID(),revision:i.revision})}}}await n.get();for(let w of n.pendingCommands??[])a.has(w.requestId)&&a.get(w.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(w.requestId);return{run:e.run,controller:n}},async syncIdentity(){let f=r;y(await I(()=>t.adapter.syncIdentity()).catch(v),f),await n?.get();for(let C of n?.pendingCommands??[])a.has(C.requestId)&&a.get(C.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(C.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),await I(()=>t.adapter.detach())},forProcess(f){if(!e?.run.identity.binding)throw new o("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:f}},subscribe(f){return s.add(f),()=>{s.delete(f)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),s.clear()}}}export{xt as a,Oe as b,Ht as c,Qt as d};
@@ -1,4 +1,4 @@
1
- import{a as $,b as N,c as J,d as q}from"./chunk-SR6CERFC.js";import{a as _}from"./chunk-DSPLGTQI.js";import{a as P}from"./chunk-FSUP7HMS.js";import{jb as D}from"./chunk-DBBUN53B.js";import{I as C,J as O,L as j}from"./chunk-4SWGHICJ.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
1
+ import{a as $,b as N,c as J,d as q}from"./chunk-LNSFRQ6G.js";import{a as _}from"./chunk-DSPLGTQI.js";import{a as P}from"./chunk-CCRBXW4M.js";import{jb as D}from"./chunk-GSFNAB3W.js";import{I as C,J as O,L as j}from"./chunk-4SWGHICJ.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
2
2
  Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
3
  plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
4
  */function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
@@ -1 +1 @@
1
- import{ra as g}from"./chunk-DBBUN53B.js";async function u(t,r,e){if(Number(t.headers.get("content-length"))>r)throw t.body?.cancel().catch(()=>{}),e.error("limit");let o=t.body?.getReader();if(!o)throw e.error("missing");let i=[],s=0,c=!1,a=()=>{},b=new Promise((n,f)=>{a=()=>f(e.signal?.reason),e.signal?.addEventListener("abort",a,{once:!0}),e.signal?.aborted&&a()});try{for(;;){let n=await Promise.race([o.read(),b]);if(n.done){c=!0;break}if(s+=n.value.length,s>r)throw e.error("limit");i.push(n.value)}}finally{e.signal?.removeEventListener("abort",a),c||o.cancel().catch(()=>{}),o.releaseLock()}e.signal?.throwIfAborted();let l=new Uint8Array(s),d=0;for(let n of i)l.set(n,d),d+=n.length;return l}async function m(t,r,e){return new TextDecoder("utf-8",{fatal:!0}).decode(await u(t,r,e))}function y(t,r){let e=typeof t=="string"?new TextEncoder().encode(t):t;return e.byteLength===r.byteLength&&g(e)===r.sha256}export{u as a,m as b,y as c};
1
+ import{ra as g}from"./chunk-GSFNAB3W.js";async function u(t,r,e){if(Number(t.headers.get("content-length"))>r)throw t.body?.cancel().catch(()=>{}),e.error("limit");let o=t.body?.getReader();if(!o)throw e.error("missing");let i=[],s=0,c=!1,a=()=>{},b=new Promise((n,f)=>{a=()=>f(e.signal?.reason),e.signal?.addEventListener("abort",a,{once:!0}),e.signal?.aborted&&a()});try{for(;;){let n=await Promise.race([o.read(),b]);if(n.done){c=!0;break}if(s+=n.value.length,s>r)throw e.error("limit");i.push(n.value)}}finally{e.signal?.removeEventListener("abort",a),c||o.cancel().catch(()=>{}),o.releaseLock()}e.signal?.throwIfAborted();let l=new Uint8Array(s),d=0;for(let n of i)l.set(n,d),d+=n.length;return l}async function m(t,r,e){return new TextDecoder("utf-8",{fatal:!0}).decode(await u(t,r,e))}function y(t,r){let e=typeof t=="string"?new TextEncoder().encode(t):t;return e.byteLength===r.byteLength&&g(e)===r.sha256}export{u as a,m as b,y as c};
@@ -0,0 +1 @@
1
+ import{f as t}from"./chunk-2JBNOE2D.js";import{fb as n}from"./chunk-GSFNAB3W.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};