@tinkerlandai/indiana-sdk 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +9 -4
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +3 -3
  4. package/dist/{ai-usage-B4W5m4Ie.d.ts → ai-usage-BsrSG955.d.ts} +334 -518
  5. package/dist/chunk-3SONNXFG.js +1 -0
  6. package/dist/chunk-467Z5ISI.js +11 -0
  7. package/dist/{chunk-2EJSV6BA.js → chunk-4AWSZWZD.js} +1 -1
  8. package/dist/{chunk-5TEZEOHX.js → chunk-6MO6Y24B.js} +1 -1
  9. package/dist/chunk-HD74AAFS.js +1 -0
  10. package/dist/chunk-J4RHVU3W.js +1 -0
  11. package/dist/chunk-KQCTDXVD.js +17 -0
  12. package/dist/chunk-NOFNOHUI.js +1 -0
  13. package/dist/chunk-QO4YQLZ4.js +1 -0
  14. package/dist/chunk-RRII2DMC.js +1 -0
  15. package/dist/chunk-WCFVNF5D.js +1 -0
  16. package/dist/chunk-YAFMBXIE.js +4 -0
  17. package/dist/{client-OYRHOMUQ.js → client-F6UPJMHR.js} +1 -1
  18. package/dist/{configuration-sync-C2mytNwU.d.ts → configuration-sync-Bvd956GL.d.ts} +333 -25
  19. package/dist/controls-XG46TKUU.js +2 -0
  20. package/dist/funnel-runtime-host-26QI2W3S.js +1 -0
  21. package/dist/{funnel-runtime-start-sZ8ZCNlq.d.ts → funnel-runtime-start-ChVYbLzV.d.ts} +6655 -2785
  22. package/dist/iam.js +1 -1
  23. package/dist/index.d.ts +3634 -1485
  24. package/dist/index.js +1 -1
  25. package/dist/native-shell.js +1 -1
  26. package/dist/openrouter.d.ts +2 -3
  27. package/dist/openrouter.js +1 -1
  28. package/dist/page.d.ts +13 -13
  29. package/dist/page.js +1 -1
  30. package/dist/paywall-WKOHBYW7.js +1 -0
  31. package/dist/popup.d.ts +9 -16
  32. package/dist/popup.js +12 -12
  33. package/dist/react-native.d.ts +14 -14
  34. package/dist/react-native.js +1 -1
  35. package/dist/server.d.ts +4 -4
  36. package/dist/server.js +1 -1
  37. package/dist/src-UHLPVD6E.js +1 -0
  38. package/dist/visual.js +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-63BWE27V.js +0 -1
  41. package/dist/chunk-CB63JLGT.js +0 -1
  42. package/dist/chunk-D7YHFS6B.js +0 -4
  43. package/dist/chunk-HTRQPMJO.js +0 -11
  44. package/dist/chunk-ISUXYPYL.js +0 -1
  45. package/dist/chunk-QG3WUJG5.js +0 -1
  46. package/dist/chunk-RMJJOSVZ.js +0 -1
  47. package/dist/chunk-S2MSIA57.js +0 -17
  48. package/dist/chunk-VVSQKVE7.js +0 -1
  49. package/dist/funnel-runtime-host-NWS3URFA.js +0 -1
  50. package/dist/paywall-4XZ6NDMY.js +0 -1
  51. package/dist/src-WV6GZYWA.js +0 -1
  52. package/dist/{customer-page-B4FGCVpt.d.ts → customer-page-B4LkIr5q.d.ts} +4 -4
  53. package/dist/{screen-16d-xADb.d.ts → screen-iFngkxaL.d.ts} +185 -185
package/dist/visual.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as ce}from"./chunk-CB63JLGT.js";import{c as de}from"./chunk-VVSQKVE7.js";import{a as me,b as he,c as ge,d as ye,f as ve}from"./chunk-D7YHFS6B.js";import"./chunk-S5TVMQRC.js";import"./chunk-ISUXYPYL.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import{f as fe,i as pe,k as B}from"./chunk-S2MSIA57.js";async function be(e,t){let r=e?.body;if(!r)return;let n=r.getReader(),o=0,a=!1,s,i=new Promise((g,d)=>{s=setTimeout(()=>d(Error("Exposure response timeout")),2e3)}),u=()=>{},c=new Promise((g,d)=>{u=()=>d(t?.reason),t?.addEventListener("abort",u,{once:!0}),t?.aborted&&u()});try{for(;;){let g=await Promise.race([n.read(),i,c]);if(g.done){a=!0;return}if(o+=g.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(s),t?.removeEventListener("abort",u),a||n.cancel().catch(()=>{}),n.releaseLock()}}var we=2*1024*1024,At=256*1024;async function Ee(e,t,r,n){let o=()=>{},a=new Promise((s,i)=>{o=()=>i(n.reason),n.addEventListener("abort",o,{once:!0}),n.aborted&&o()});try{let s=e(t,{...r,signal:n});return s.then(i=>{n.aborted&&i.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([s,a])}finally{n.removeEventListener("abort",o)}}async function Ve(e,t,r,n=!1){if(new TextEncoder().encode(r).byteLength>65536)throw Error("Exposure request budget");let o=new AbortController,a=setTimeout(()=>o.abort(Error("Exposure request timeout")),5e3);try{let s=await Ee(e,t,{method:"POST",headers:{"Content-Type":"text/plain"},body:r,credentials:"omit",keepalive:n,redirect:"error"},o.signal);await be(s,o.signal)}finally{clearTimeout(a)}}function Ae(e){let t,r=!1;return{async read(n,o){if(r)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let a=new AbortController;t=a;let{signal:s}=a,i=setTimeout(()=>a.abort(Error("Experiment request timeout")),5e3);try{let u=await Ee(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},s),c=await ce(u,o,s,{requireJson:!1});return s.throwIfAborted(),c}finally{clearTimeout(i),t===a&&(t=void 0)}},destroy(){r=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}function J(e,t=()=>{}){let r=new WeakMap,n=0,o=a=>{let s=r.get(a);if(s!==void 0)return s;let i=[],u=a,c=!0;for(;u;){let g=r.get(u);if(g!==void 0){c=g;break}if(++n>8192||i.length>=256)throw Error("IAM render ancestry budget exceeded");if(i.push(u),t(),u.hasAttribute("hidden")||/(?:^|;)\s*display\s*:\s*none\s*(?:!\s*important\s*)?(?:;|$)/i.test(u.getAttribute("style")??"")){c=!1;break}u=u.parentElement}for(let g of i)r.set(g,c);return c};return a=>{let s=0,i=e.querySelectorAll(a);for(let u=0;u<i.length;u++){let c=i[u];if(!c)throw Error("IAM render selection changed");o(c)&&s++,t()}return s}}var je=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function j(e){if(!je(e)||Object.keys(e).some(a=>!["schemaVersion","renderKey","routeTemplate","selectors","present","absent"].includes(a))||e.schemaVersion!==1||typeof e.renderKey!="string"||!e.renderKey||e.renderKey.length>256||typeof e.routeTemplate!="string"||!e.routeTemplate.startsWith("/")||e.routeTemplate.length>2048||!Array.isArray(e.selectors)||e.selectors.length>512||e.selectors.some(a=>typeof a!="string"||a.length>512||!/^[a-z][a-z0-9-]*\[data-indiana-id="(?:[^"\\\x00-\x1f]|\\["\\])*"\]$/.test(a))||!Array.isArray(e.present)||!Array.isArray(e.absent))throw new Error("Invalid IAM render guard");if(e.present.length===0)throw Error("IAM render needs positive source evidence");let t=e.selectors,r=e.present,n=e.absent,o=[...r,...n];if(new Set(t).size!==t.length||o.length!==t.length||new Set(o).size!==o.length||o.some(a=>typeof a!="number"||!Number.isInteger(a)||a<0||a>=t.length))throw new Error("Invalid IAM render signature");return{schemaVersion:1,renderKey:e.renderKey,routeTemplate:e.routeTemplate,selectors:e.selectors,present:e.present,absent:e.absent}}function Ue(e,t){let r=e.split("/").filter(Boolean),n="";for(let o of r)/^\[\[\.\.\.[^\[\]]+\]\]$/.test(o)?n+="(?:/[^/]+)*":/^\[\.\.\.[^\[\]]+\]$/.test(o)?n+="(?:/[^/]+)+":/^\[[^\[\]]+\]$/.test(o)?n+="/[^/]+":n+="/"+o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+(n?n+"/?":"/")+"$").test(t)&&!/[\[\]]/.test(t)}function Me(e,t,r,n,o=J(t,n)){if(!Ue(e.routeTemplate,r))return!1;let a=new Set(e.present),s=!0;for(let i=0;i<e.selectors.length;i++){let u=o(e.selectors[i]);if(a.has(i)&&u>1)throw new Error("IAM render anchor is ambiguous");(a.has(i)?u!==1:u!==0)&&(s=!1),n()}return s}var _=new WeakMap,Z=new WeakSet;function Q(e){Z.add(e)}function He(e){let t=new Set,r=new Set,n,o=0,a=!1,s=()=>{t.size||o||(n?.disconnect(),e.removeEventListener("visibilitychange",u),_.delete(e))};function i(c){if(e.hidden)return;let g=performance.now(),d=new Map,m=new Map,b=()=>{if(performance.now()-g>8)throw Error("IAM page check exceeded its work budget")},M=l=>{b();let f=d.get(l);return f||(f=e.querySelectorAll(l),d.set(l,f)),b(),f},A=J({querySelectorAll:M},b),y={query:M,checkpoint:b,matches(l,f){let p=m.get(f);if(!p){try{p={match:Me(l,e,location.pathname,b,A)}}catch(h){p={error:h}}m.set(f,p)}if("error"in p)throw p.error;return p.match}},x=[],k=[],L=[];for(let l of c)if(t.has(l))try{x.push({job:l,commit:l.prepare(y)})}catch(f){k.push({job:l,error:f})}try{b()}catch(l){for(let f of[...t])f.fail(l);return}for(let{job:l,error:f}of k)t.has(l)&&l.fail(f);for(let{job:l,commit:f}of x)if(t.has(l))try{b(),f(p=>L.push(p))}catch(p){l.fail(p)}for(let l of L)l()}function u(){a||!t.size||e.hidden||(a=!0,queueMicrotask(()=>{a=!1,i([...t])}))}return{begin(){o++},end(){--o===0&&(r.clear(),i([...t])),s()},add(c){return n||(n=new MutationObserver(g=>{let d=m=>Z.has(m)||!!(m.parentNode&&Z.has(m.parentNode));g.some(m=>!d(m.target)&&!(m.type==="childList"&&[...m.addedNodes,...m.removedNodes].length>0&&[...m.addedNodes,...m.removedNodes].every(d)))&&u()}),n.observe(e.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["style","hidden","data-indiana-id","data-indiana-release","data-testid","id","name"]}),e.addEventListener("visibilitychange",u)),t.add(c),o?r.add(c):i([c]),()=>{t.delete(c),r.delete(c),s()}}}}function Se(){let e=_.get(document);return e||(e=He(document),_.set(document,e)),e}function xe(e){return Se().add(e)}function ke(e){let t=Se();t.begin();try{e()}finally{t.end()}}var ze=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,te={revert:function(){}},W=new Map,re=new Set;function We(e){return e==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[e]}}function F(e){var t=W.get(e);return t||(t={element:e,attributes:{}},W.set(e,t)),t}function K(e,t,r,n,o){var a=r(e),s={isDirty:!1,originalValue:a,virtualValue:a,mutations:[],el:e,_positionTimeout:null,observer:new MutationObserver(function(){if(!dt&&!(t==="position"&&s._positionTimeout)){t==="position"&&(s._positionTimeout=setTimeout(function(){s._positionTimeout=null},1e3));var i=r(e);t==="position"&&i.parentNode===s.virtualValue.parentNode&&i.insertBeforeNode===s.virtualValue.insertBeforeNode||i!==s.virtualValue&&(s.originalValue=i,o(s))}}),mutationRunner:o,setValue:n,getCurrentValue:r};return t==="position"&&e.parentNode?s.observer.observe(e.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):s.observer.observe(e,We(t)),s}function $(e,t){var r=t.getCurrentValue(t.el);t.virtualValue=e,e&&typeof e!="string"?(!r||e.parentNode!==r.parentNode||e.insertBeforeNode!==r.insertBeforeNode)&&(t.isDirty=!0,Re()):e!==r&&(t.isDirty=!0,Re())}function Fe(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),$(st(t),e)}function Ke(e){var t=new Set(e.originalValue.split(/\s+/).filter(Boolean));e.mutations.forEach(function(r){return r.mutate(t)}),$(Array.from(t).filter(Boolean).join(" "),e)}function $e(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),$(t,e)}function Ye(e){var t=e.parentSelector,r=e.insertBeforeSelector,n=document.querySelector(t);if(!n)return null;var o=r?document.querySelector(r):null;return r&&!o?null:{parentNode:n,insertBeforeNode:o}}function _e(e){var t=e.originalValue;e.mutations.forEach(function(r){var n=r.mutate(),o=Ye(n);t=o||t}),$(t,e)}var Ze=function(t){return t.innerHTML},Qe=function(t,r){return t.innerHTML=r};function Te(e){var t=F(e);return t.html||(t.html=K(e,"html",Ze,Qe,Fe)),t.html}var Xe=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},et=function(t,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(t,r.insertBeforeNode)};function Le(e){var t=F(e);return t.position||(t.position=K(e,"position",Xe,et,_e)),t.position}var tt=function(t,r){return r?t.className=r:t.removeAttribute("class")},rt=function(t){return t.className};function Ne(e){var t=F(e);return t.classes||(t.classes=K(e,"class",rt,tt,Ke)),t.classes}var nt=function(t){return function(r){var n;return(n=r.getAttribute(t))!=null?n:null}},ot=function(t){return function(r,n){return n!==null?r.setAttribute(t,n):r.removeAttribute(t)}};function Pe(e,t){var r=F(e);return r.attributes[t]||(r.attributes[t]=K(e,t,nt(t),ot(t),$e)),r.attributes[t]}function it(e,t){var r=W.get(e);if(r)if(t==="html"){var n,o;(n=r.html)==null||(o=n.observer)==null||o.disconnect(),delete r.html}else if(t==="class"){var a,s;(a=r.classes)==null||(s=a.observer)==null||s.disconnect(),delete r.classes}else if(t==="position"){var i,u;(i=r.position)==null||(u=i.observer)==null||u.disconnect(),delete r.position}else{var c,g,d;(c=r.attributes)==null||(g=c[t])==null||(d=g.observer)==null||d.disconnect(),delete r.attributes[t]}}var U;function st(e){return U||(U=document.createElement("div")),U.innerHTML=e,U.innerHTML}function H(e,t,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||it(e,t),r.setValue(e,n)}}function at(e,t){e.html&&H(t,"html",e.html),e.classes&&H(t,"class",e.classes),e.position&&H(t,"position",e.position),Object.keys(e.attributes).forEach(function(r){H(t,r,e.attributes[r])})}function Re(){W.forEach(at)}function ut(e,t){var r=null;e.kind==="html"?r=Te(t):e.kind==="class"?r=Ne(t):e.kind==="attribute"?r=Pe(t,e.attribute):e.kind==="position"&&(r=Le(t)),r&&(r.mutations.push(e),r.mutationRunner(r))}function lt(e,t){var r=null;if(e.kind==="html"?r=Te(t):e.kind==="class"?r=Ne(t):e.kind==="attribute"?r=Pe(t,e.attribute):e.kind==="position"&&(r=Le(t)),!!r){var n=r.mutations.indexOf(e);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function Oe(e){if(!(e.kind==="position"&&e.elements.size===1)){var t=new Set(e.elements),r=document.querySelectorAll(e.selector);r.forEach(function(n){t.has(n)||(e.elements.add(n),ut(e,n))})}}function ct(e){e.elements.forEach(function(t){return lt(e,t)}),e.elements.clear(),re.delete(e)}function Ie(){re.forEach(Oe)}var dt=!1;var X;function ft(){typeof document>"u"||(X||(X=new MutationObserver(function(){Ie()})),Ie(),X.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}ft();function Y(e){return typeof document>"u"?te:(re.add(e),Oe(e),{revert:function(){ct(e)}})}function ee(e,t){return Y({kind:"html",elements:new Set,mutate:t,selector:e})}function qe(e,t){return Y({kind:"position",elements:new Set,mutate:t,selector:e})}function D(e,t){return Y({kind:"class",elements:new Set,mutate:t,selector:e})}function z(e,t,r){return ze.test(t)?t==="class"||t==="className"?D(e,function(n){var o=r(Array.from(n).join(" "));n.clear(),o&&o.split(/\s+/g).filter(Boolean).forEach(function(a){return n.add(a)})}):Y({kind:"attribute",attribute:t,elements:new Set,mutate:r,selector:e}):te}function pt(e){var t=e.selector,r=e.action,n=e.value,o=e.attribute,a=e.parentSelector,s=e.insertBeforeSelector;if(o==="html"){if(r==="append")return ee(t,function(i){return i+(n??"")});if(r==="set")return ee(t,function(){return n??""})}else if(o==="class"){if(r==="append")return D(t,function(i){n&&i.add(n)});if(r==="remove")return D(t,function(i){n&&i.delete(n)});if(r==="set")return D(t,function(i){i.clear(),n&&i.add(n)})}else if(o==="position"){if(r==="set"&&a)return qe(t,function(){return{insertBeforeSelector:s,parentSelector:a}})}else{if(r==="append")return z(t,o,function(i){return i!==null?i+(n??""):n??""});if(r==="set")return z(t,o,function(){return n??""});if(r==="remove")return z(t,o,function(){return null})}return te}var mt={html:ee,classes:D,attribute:z,position:qe,declarative:pt},ne=mt;import ht from"dompurify";var oe,Be;function gt(e){return(!oe||Be!==window)&&(oe=ht(window),Be=window),oe.sanitize(e,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function De(e){let t={...e};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(t.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(t.attribute))throw new Error("Unsupported visual attribute");document.querySelector(t.selector);for(let r of document.querySelectorAll(t.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&t.attribute==="html")throw new Error("Protected visual target");if(t.attribute==="html"&&(t.value=gt(t.value??"")),["href","src"].includes(t.attribute)&&t.action!=="remove"){let r=new URL(t.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||t.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return t.parentSelector&&document.querySelector(t.parentSelector),t.insertBeforeSelector&&document.querySelector(t.insertBeforeSelector),t}function Ce(e,t={}){if(e.renderGuard&&!t.requireUniqueTargets)throw new Error("IAM render guard requires the source release fence");if(t.requireUniqueTargets)return yt(e,t);let r=e.domMutations.map(De),n=[],o=!1,a=!1,s,i=()=>{if(!o){o=!0,s?.disconnect();for(let c of n.reverse())c()}},u=()=>{o||a||(!r.length||e.css||t.allowJs&&e.js||r.some(c=>document.querySelector(c.selector)))&&(a=!0,t.onApplied?.())};try{if(e.css){let d=document.createElement("style");t.nonce&&(d.nonce=t.nonce),d.textContent=e.css,document.head.append(d),n.push(()=>d.remove())}for(let d of r){let m=ne.declarative(d);n.push(()=>m.revert())}if(t.allowJs&&e.js){let d=document.createElement("script");t.nonce&&(d.nonce=t.nonce),d.textContent=e.js,document.head.append(d),n.push(()=>d.remove())}let c=performance.now(),g=new WeakMap;s=new MutationObserver(d=>{if(!o){performance.now()-c>1e3&&(c=performance.now(),g=new WeakMap);for(let m of d){let b=(g.get(m.target)??0)+1;if(g.set(m.target,b),b>40){i(),t.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}u()}}),s.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),u()}catch(c){throw i(),c}return{revert:i,get applied(){return a}}}function yt(e,t){let r=t?.boundVariations??[e],n=new Set,o=new Set,a=[],s=new Map,i=r.flatMap(l=>l.renderGuard?[j(l.renderGuard)]:[]),u=i[0];if(i.some(l=>JSON.stringify(l)!==JSON.stringify(u)))throw new Error("IAM variations use different render states");if(e.js||r.some(l=>l.js))throw Error("IAM scripts cannot execute");if(r.length>20||r.reduce((l,f)=>l+f.css.length,0)>262144)throw Error("IAM target budget");let c=(l,f)=>{for(let h of l.domMutations){if(h.action!=="set"||h.attribute!=="html")throw Error("Unsupported IAM mutation");n.add(h.selector),o.add(h.selector)}if(!l.css)return;let p=document.createElement("style");Q(p),p.media="not all",t?.nonce&&(p.nonce=t.nonce),p.textContent=l.css;try{if(document.head.append(p),!p.sheet)throw Error("IAM CSS is blocked");for(let h of p.sheet.cssRules){if(!("selectorText"in h)||typeof h.selectorText!="string")throw Error("Unsupported IAM style rule");n.add(h.selectorText),f&&a.push({selector:h.selectorText,css:h.cssText})}}finally{p.remove()}};for(let l of r)c(l,!1);if(c(e,!0),n.size>200)throw Error("IAM target budget");let g=e.domMutations.map(De),d=!1,m=!1,b=!1,M={},A=u?JSON.stringify(u):"",y,x="",k=()=>{if(!d){d=!0,M.unsubscribe?.();for(let l of s.values())l.revert();s.clear(),y?.remove(),y=void 0,m=!1}},L=()=>{for(let l of s.values())l.revert();s.clear(),y?.remove(),y=void 0,x="",m=!1};return M.unsubscribe=xe({fail(l){k(),t?.onError?.(l)},prepare(l){if(u&&!l.matches(u,A))return()=>{d||L()};let f=new Map;for(let p of n){let h=l.query(p);if(h.length>1)throw Error("IAM target is ambiguous in this rendered state");if(h.length){if(o.has(p)&&h[0].children.length)throw Error("IAM text target is no longer a leaf");f.set(p,h[0])}l.checkpoint()}return p=>{if(d)return;for(let[E,R]of s)f.get(E)!==R.element&&(R.revert(),s.delete(E));for(let E of new Set(g.map(R=>R.selector))){let R=f.get(E);if(!R||s.has(E))continue;let P=g.filter(N=>N.selector===E).map(N=>ne.declarative(N));s.set(E,{element:R,revert:()=>P.forEach(N=>N.revert())})}let h=a.filter(E=>f.has(E.selector)).map(E=>E.css).join(`
1
+ import{a as ce}from"./chunk-WCFVNF5D.js";import{c as de}from"./chunk-J4RHVU3W.js";import{a as me,b as he,c as ge,d as ye,f as ve}from"./chunk-YAFMBXIE.js";import"./chunk-3SONNXFG.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import"./chunk-S5TVMQRC.js";import"./chunk-RRII2DMC.js";import{h as fe,k as pe,m as B}from"./chunk-KQCTDXVD.js";async function be(e,t){let r=e?.body;if(!r)return;let n=r.getReader(),o=0,a=!1,s,i=new Promise((g,d)=>{s=setTimeout(()=>d(Error("Exposure response timeout")),2e3)}),u=()=>{},c=new Promise((g,d)=>{u=()=>d(t?.reason),t?.addEventListener("abort",u,{once:!0}),t?.aborted&&u()});try{for(;;){let g=await Promise.race([n.read(),i,c]);if(g.done){a=!0;return}if(o+=g.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(s),t?.removeEventListener("abort",u),a||n.cancel().catch(()=>{}),n.releaseLock()}}var we=2*1024*1024,At=256*1024;async function Ee(e,t,r,n){let o=()=>{},a=new Promise((s,i)=>{o=()=>i(n.reason),n.addEventListener("abort",o,{once:!0}),n.aborted&&o()});try{let s=e(t,{...r,signal:n});return s.then(i=>{n.aborted&&i.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([s,a])}finally{n.removeEventListener("abort",o)}}async function Ve(e,t,r,n=!1){if(new TextEncoder().encode(r).byteLength>65536)throw Error("Exposure request budget");let o=new AbortController,a=setTimeout(()=>o.abort(Error("Exposure request timeout")),5e3);try{let s=await Ee(e,t,{method:"POST",headers:{"Content-Type":"text/plain"},body:r,credentials:"omit",keepalive:n,redirect:"error"},o.signal);await be(s,o.signal)}finally{clearTimeout(a)}}function Ae(e){let t,r=!1;return{async read(n,o){if(r)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let a=new AbortController;t=a;let{signal:s}=a,i=setTimeout(()=>a.abort(Error("Experiment request timeout")),5e3);try{let u=await Ee(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},s),c=await ce(u,o,s);return s.throwIfAborted(),c}finally{clearTimeout(i),t===a&&(t=void 0)}},destroy(){r=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}function J(e,t=()=>{}){let r=new WeakMap,n=0,o=a=>{let s=r.get(a);if(s!==void 0)return s;let i=[],u=a,c=!0;for(;u;){let g=r.get(u);if(g!==void 0){c=g;break}if(++n>8192||i.length>=256)throw Error("IAM render ancestry budget exceeded");if(i.push(u),t(),u.hasAttribute("hidden")||/(?:^|;)\s*display\s*:\s*none\s*(?:!\s*important\s*)?(?:;|$)/i.test(u.getAttribute("style")??"")){c=!1;break}u=u.parentElement}for(let g of i)r.set(g,c);return c};return a=>{let s=0,i=e.querySelectorAll(a);for(let u=0;u<i.length;u++){let c=i[u];if(!c)throw Error("IAM render selection changed");o(c)&&s++,t()}return s}}var je=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function j(e){if(!je(e)||Object.keys(e).some(a=>!["schemaVersion","renderKey","routeTemplate","selectors","present","absent"].includes(a))||e.schemaVersion!==1||typeof e.renderKey!="string"||!e.renderKey||e.renderKey.length>256||typeof e.routeTemplate!="string"||!e.routeTemplate.startsWith("/")||e.routeTemplate.length>2048||!Array.isArray(e.selectors)||e.selectors.length>512||e.selectors.some(a=>typeof a!="string"||a.length>512||!/^[a-z][a-z0-9-]*\[data-indiana-id="(?:[^"\\\x00-\x1f]|\\["\\])*"\]$/.test(a))||!Array.isArray(e.present)||!Array.isArray(e.absent))throw new Error("Invalid IAM render guard");if(e.present.length===0)throw Error("IAM render needs positive source evidence");let t=e.selectors,r=e.present,n=e.absent,o=[...r,...n];if(new Set(t).size!==t.length||o.length!==t.length||new Set(o).size!==o.length||o.some(a=>typeof a!="number"||!Number.isInteger(a)||a<0||a>=t.length))throw new Error("Invalid IAM render signature");return{schemaVersion:1,renderKey:e.renderKey,routeTemplate:e.routeTemplate,selectors:e.selectors,present:e.present,absent:e.absent}}function Ue(e,t){let r=e.split("/").filter(Boolean),n="";for(let o of r)/^\[\[\.\.\.[^\[\]]+\]\]$/.test(o)?n+="(?:/[^/]+)*":/^\[\.\.\.[^\[\]]+\]$/.test(o)?n+="(?:/[^/]+)+":/^\[[^\[\]]+\]$/.test(o)?n+="/[^/]+":n+="/"+o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+(n?n+"/?":"/")+"$").test(t)&&!/[\[\]]/.test(t)}function Me(e,t,r,n,o=J(t,n)){if(!Ue(e.routeTemplate,r))return!1;let a=new Set(e.present),s=!0;for(let i=0;i<e.selectors.length;i++){let u=o(e.selectors[i]);if(a.has(i)&&u>1)throw new Error("IAM render anchor is ambiguous");(a.has(i)?u!==1:u!==0)&&(s=!1),n()}return s}var _=new WeakMap,Z=new WeakSet;function Q(e){Z.add(e)}function He(e){let t=new Set,r=new Set,n,o=0,a=!1,s=()=>{t.size||o||(n?.disconnect(),e.removeEventListener("visibilitychange",u),_.delete(e))};function i(c){if(e.hidden)return;let g=performance.now(),d=new Map,m=new Map,b=()=>{if(performance.now()-g>8)throw Error("IAM page check exceeded its work budget")},M=l=>{b();let f=d.get(l);return f||(f=e.querySelectorAll(l),d.set(l,f)),b(),f},A=J({querySelectorAll:M},b),y={query:M,checkpoint:b,matches(l,f){let p=m.get(f);if(!p){try{p={match:Me(l,e,location.pathname,b,A)}}catch(h){p={error:h}}m.set(f,p)}if("error"in p)throw p.error;return p.match}},x=[],k=[],L=[];for(let l of c)if(t.has(l))try{x.push({job:l,commit:l.prepare(y)})}catch(f){k.push({job:l,error:f})}try{b()}catch(l){for(let f of[...t])f.fail(l);return}for(let{job:l,error:f}of k)t.has(l)&&l.fail(f);for(let{job:l,commit:f}of x)if(t.has(l))try{b(),f(p=>L.push(p))}catch(p){l.fail(p)}for(let l of L)l()}function u(){a||!t.size||e.hidden||(a=!0,queueMicrotask(()=>{a=!1,i([...t])}))}return{begin(){o++},end(){--o===0&&(r.clear(),i([...t])),s()},add(c){return n||(n=new MutationObserver(g=>{let d=m=>Z.has(m)||!!(m.parentNode&&Z.has(m.parentNode));g.some(m=>!d(m.target)&&!(m.type==="childList"&&[...m.addedNodes,...m.removedNodes].length>0&&[...m.addedNodes,...m.removedNodes].every(d)))&&u()}),n.observe(e.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["style","hidden","data-indiana-id","data-indiana-release","data-testid","id","name"]}),e.addEventListener("visibilitychange",u)),t.add(c),o?r.add(c):i([c]),()=>{t.delete(c),r.delete(c),s()}}}}function Se(){let e=_.get(document);return e||(e=He(document),_.set(document,e)),e}function xe(e){return Se().add(e)}function ke(e){let t=Se();t.begin();try{e()}finally{t.end()}}var ze=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,te={revert:function(){}},W=new Map,re=new Set;function We(e){return e==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[e]}}function F(e){var t=W.get(e);return t||(t={element:e,attributes:{}},W.set(e,t)),t}function K(e,t,r,n,o){var a=r(e),s={isDirty:!1,originalValue:a,virtualValue:a,mutations:[],el:e,_positionTimeout:null,observer:new MutationObserver(function(){if(!dt&&!(t==="position"&&s._positionTimeout)){t==="position"&&(s._positionTimeout=setTimeout(function(){s._positionTimeout=null},1e3));var i=r(e);t==="position"&&i.parentNode===s.virtualValue.parentNode&&i.insertBeforeNode===s.virtualValue.insertBeforeNode||i!==s.virtualValue&&(s.originalValue=i,o(s))}}),mutationRunner:o,setValue:n,getCurrentValue:r};return t==="position"&&e.parentNode?s.observer.observe(e.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):s.observer.observe(e,We(t)),s}function $(e,t){var r=t.getCurrentValue(t.el);t.virtualValue=e,e&&typeof e!="string"?(!r||e.parentNode!==r.parentNode||e.insertBeforeNode!==r.insertBeforeNode)&&(t.isDirty=!0,Re()):e!==r&&(t.isDirty=!0,Re())}function Fe(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),$(st(t),e)}function Ke(e){var t=new Set(e.originalValue.split(/\s+/).filter(Boolean));e.mutations.forEach(function(r){return r.mutate(t)}),$(Array.from(t).filter(Boolean).join(" "),e)}function $e(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),$(t,e)}function Ye(e){var t=e.parentSelector,r=e.insertBeforeSelector,n=document.querySelector(t);if(!n)return null;var o=r?document.querySelector(r):null;return r&&!o?null:{parentNode:n,insertBeforeNode:o}}function _e(e){var t=e.originalValue;e.mutations.forEach(function(r){var n=r.mutate(),o=Ye(n);t=o||t}),$(t,e)}var Ze=function(t){return t.innerHTML},Qe=function(t,r){return t.innerHTML=r};function Te(e){var t=F(e);return t.html||(t.html=K(e,"html",Ze,Qe,Fe)),t.html}var Xe=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},et=function(t,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(t,r.insertBeforeNode)};function Le(e){var t=F(e);return t.position||(t.position=K(e,"position",Xe,et,_e)),t.position}var tt=function(t,r){return r?t.className=r:t.removeAttribute("class")},rt=function(t){return t.className};function Ne(e){var t=F(e);return t.classes||(t.classes=K(e,"class",rt,tt,Ke)),t.classes}var nt=function(t){return function(r){var n;return(n=r.getAttribute(t))!=null?n:null}},ot=function(t){return function(r,n){return n!==null?r.setAttribute(t,n):r.removeAttribute(t)}};function Pe(e,t){var r=F(e);return r.attributes[t]||(r.attributes[t]=K(e,t,nt(t),ot(t),$e)),r.attributes[t]}function it(e,t){var r=W.get(e);if(r)if(t==="html"){var n,o;(n=r.html)==null||(o=n.observer)==null||o.disconnect(),delete r.html}else if(t==="class"){var a,s;(a=r.classes)==null||(s=a.observer)==null||s.disconnect(),delete r.classes}else if(t==="position"){var i,u;(i=r.position)==null||(u=i.observer)==null||u.disconnect(),delete r.position}else{var c,g,d;(c=r.attributes)==null||(g=c[t])==null||(d=g.observer)==null||d.disconnect(),delete r.attributes[t]}}var U;function st(e){return U||(U=document.createElement("div")),U.innerHTML=e,U.innerHTML}function H(e,t,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||it(e,t),r.setValue(e,n)}}function at(e,t){e.html&&H(t,"html",e.html),e.classes&&H(t,"class",e.classes),e.position&&H(t,"position",e.position),Object.keys(e.attributes).forEach(function(r){H(t,r,e.attributes[r])})}function Re(){W.forEach(at)}function ut(e,t){var r=null;e.kind==="html"?r=Te(t):e.kind==="class"?r=Ne(t):e.kind==="attribute"?r=Pe(t,e.attribute):e.kind==="position"&&(r=Le(t)),r&&(r.mutations.push(e),r.mutationRunner(r))}function lt(e,t){var r=null;if(e.kind==="html"?r=Te(t):e.kind==="class"?r=Ne(t):e.kind==="attribute"?r=Pe(t,e.attribute):e.kind==="position"&&(r=Le(t)),!!r){var n=r.mutations.indexOf(e);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function Oe(e){if(!(e.kind==="position"&&e.elements.size===1)){var t=new Set(e.elements),r=document.querySelectorAll(e.selector);r.forEach(function(n){t.has(n)||(e.elements.add(n),ut(e,n))})}}function ct(e){e.elements.forEach(function(t){return lt(e,t)}),e.elements.clear(),re.delete(e)}function Ie(){re.forEach(Oe)}var dt=!1;var X;function ft(){typeof document>"u"||(X||(X=new MutationObserver(function(){Ie()})),Ie(),X.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}ft();function Y(e){return typeof document>"u"?te:(re.add(e),Oe(e),{revert:function(){ct(e)}})}function ee(e,t){return Y({kind:"html",elements:new Set,mutate:t,selector:e})}function qe(e,t){return Y({kind:"position",elements:new Set,mutate:t,selector:e})}function D(e,t){return Y({kind:"class",elements:new Set,mutate:t,selector:e})}function z(e,t,r){return ze.test(t)?t==="class"||t==="className"?D(e,function(n){var o=r(Array.from(n).join(" "));n.clear(),o&&o.split(/\s+/g).filter(Boolean).forEach(function(a){return n.add(a)})}):Y({kind:"attribute",attribute:t,elements:new Set,mutate:r,selector:e}):te}function pt(e){var t=e.selector,r=e.action,n=e.value,o=e.attribute,a=e.parentSelector,s=e.insertBeforeSelector;if(o==="html"){if(r==="append")return ee(t,function(i){return i+(n??"")});if(r==="set")return ee(t,function(){return n??""})}else if(o==="class"){if(r==="append")return D(t,function(i){n&&i.add(n)});if(r==="remove")return D(t,function(i){n&&i.delete(n)});if(r==="set")return D(t,function(i){i.clear(),n&&i.add(n)})}else if(o==="position"){if(r==="set"&&a)return qe(t,function(){return{insertBeforeSelector:s,parentSelector:a}})}else{if(r==="append")return z(t,o,function(i){return i!==null?i+(n??""):n??""});if(r==="set")return z(t,o,function(){return n??""});if(r==="remove")return z(t,o,function(){return null})}return te}var mt={html:ee,classes:D,attribute:z,position:qe,declarative:pt},ne=mt;import ht from"dompurify";var oe,Be;function gt(e){return(!oe||Be!==window)&&(oe=ht(window),Be=window),oe.sanitize(e,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function De(e){let t={...e};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(t.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(t.attribute))throw new Error("Unsupported visual attribute");document.querySelector(t.selector);for(let r of document.querySelectorAll(t.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&t.attribute==="html")throw new Error("Protected visual target");if(t.attribute==="html"&&(t.value=gt(t.value??"")),["href","src"].includes(t.attribute)&&t.action!=="remove"){let r=new URL(t.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||t.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return t.parentSelector&&document.querySelector(t.parentSelector),t.insertBeforeSelector&&document.querySelector(t.insertBeforeSelector),t}function Ce(e,t={}){if(e.renderGuard&&!t.requireUniqueTargets)throw new Error("IAM render guard requires the source release fence");if(t.requireUniqueTargets)return yt(e,t);let r=e.domMutations.map(De),n=[],o=!1,a=!1,s,i=()=>{if(!o){o=!0,s?.disconnect();for(let c of n.reverse())c()}},u=()=>{o||a||(!r.length||e.css||t.allowJs&&e.js||r.some(c=>document.querySelector(c.selector)))&&(a=!0,t.onApplied?.())};try{if(e.css){let d=document.createElement("style");t.nonce&&(d.nonce=t.nonce),d.textContent=e.css,document.head.append(d),n.push(()=>d.remove())}for(let d of r){let m=ne.declarative(d);n.push(()=>m.revert())}if(t.allowJs&&e.js){let d=document.createElement("script");t.nonce&&(d.nonce=t.nonce),d.textContent=e.js,document.head.append(d),n.push(()=>d.remove())}let c=performance.now(),g=new WeakMap;s=new MutationObserver(d=>{if(!o){performance.now()-c>1e3&&(c=performance.now(),g=new WeakMap);for(let m of d){let b=(g.get(m.target)??0)+1;if(g.set(m.target,b),b>40){i(),t.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}u()}}),s.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),u()}catch(c){throw i(),c}return{revert:i,get applied(){return a}}}function yt(e,t){let r=t?.boundVariations??[e],n=new Set,o=new Set,a=[],s=new Map,i=r.flatMap(l=>l.renderGuard?[j(l.renderGuard)]:[]),u=i[0];if(i.some(l=>JSON.stringify(l)!==JSON.stringify(u)))throw new Error("IAM variations use different render states");if(e.js||r.some(l=>l.js))throw Error("IAM scripts cannot execute");if(r.length>20||r.reduce((l,f)=>l+f.css.length,0)>262144)throw Error("IAM target budget");let c=(l,f)=>{for(let h of l.domMutations){if(h.action!=="set"||h.attribute!=="html")throw Error("Unsupported IAM mutation");n.add(h.selector),o.add(h.selector)}if(!l.css)return;let p=document.createElement("style");Q(p),p.media="not all",t?.nonce&&(p.nonce=t.nonce),p.textContent=l.css;try{if(document.head.append(p),!p.sheet)throw Error("IAM CSS is blocked");for(let h of p.sheet.cssRules){if(!("selectorText"in h)||typeof h.selectorText!="string")throw Error("Unsupported IAM style rule");n.add(h.selectorText),f&&a.push({selector:h.selectorText,css:h.cssText})}}finally{p.remove()}};for(let l of r)c(l,!1);if(c(e,!0),n.size>200)throw Error("IAM target budget");let g=e.domMutations.map(De),d=!1,m=!1,b=!1,M={},A=u?JSON.stringify(u):"",y,x="",k=()=>{if(!d){d=!0,M.unsubscribe?.();for(let l of s.values())l.revert();s.clear(),y?.remove(),y=void 0,m=!1}},L=()=>{for(let l of s.values())l.revert();s.clear(),y?.remove(),y=void 0,x="",m=!1};return M.unsubscribe=xe({fail(l){k(),t?.onError?.(l)},prepare(l){if(u&&!l.matches(u,A))return()=>{d||L()};let f=new Map;for(let p of n){let h=l.query(p);if(h.length>1)throw Error("IAM target is ambiguous in this rendered state");if(h.length){if(o.has(p)&&h[0].children.length)throw Error("IAM text target is no longer a leaf");f.set(p,h[0])}l.checkpoint()}return p=>{if(d)return;for(let[E,R]of s)f.get(E)!==R.element&&(R.revert(),s.delete(E));for(let E of new Set(g.map(R=>R.selector))){let R=f.get(E);if(!R||s.has(E))continue;let P=g.filter(N=>N.selector===E).map(N=>ne.declarative(N));s.set(E,{element:R,revert:()=>P.forEach(N=>N.revert())})}let h=a.filter(E=>f.has(E.selector)).map(E=>E.css).join(`
2
2
  `);h!==x&&(x=h,h?(y||(y=document.createElement("style"),Q(y),t?.nonce&&(y.nonce=t.nonce),document.head.append(y)),y.textContent=h):(y?.remove(),y=void 0)),m=n.size===0||f.size>0,m&&!b&&(b=!0,p(()=>{d||t?.onApplied?.()}))}}}),d&&M.unsubscribe(),{revert:k,get applied(){return m}}}var C=e=>!!e&&typeof e=="object"&&!Array.isArray(e),q=(e,t)=>typeof e=="string"&&e.length<=t,vt=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function bt(e){if(!C(e)||!q(e.css??"",1e5)||!q(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let t=e.domMutations??[];for(let r of t)if(!C(r)||!q(r.selector,2048)||!r.selector||!vt(r.attribute)||!["set","append","remove"].includes(String(r.action))||r.value!==void 0&&!q(r.value,5e4)||r.parentSelector!==void 0&&!q(r.parentSelector,2048)||r.insertBeforeSelector!==void 0&&!q(r.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:t,...e.renderGuard===void 0?{}:{renderGuard:j(e.renderGuard)}}}function Ge(e){if(!C(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!C(e.savedGroups))throw new Error("Invalid visual experiment payload");let t=e.experiments.map(r=>{if(!C(r)||!["key","changeId"].every(n=>typeof r[n]=="string"&&r[n])||!/^[a-f0-9]{64}$/.test(String(r.changeId))||["namespace","status","groups","url"].some(n=>Object.hasOwn(r,n))||r.hashVersion!==void 0&&r.hashVersion!==2||!Array.isArray(r.variations)||r.variations.length<2||r.variations.length>20||r.urlPatterns!==void 0&&!Array.isArray(r.urlPatterns))throw new Error("Invalid visual experiment");return{...r,variations:r.variations.map(bt)}});return{...e,experiments:t}}function Kt(e){let t=ge(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=Ae(r),o=`${t}/api/v1/visual-experiments/${e.environmentId}`,a=me(e.deviceIdCookie??"indiana_did"),s=he(),i=null,u=!1,c=!1,g="",d={...e.attributes??{}},m,b,M=0,A=new Map,y=new Map,x=new Set,k=[],L,l,f;function p(){clearTimeout(l),f?.remove(),f=void 0}function h(w=!1){clearTimeout(L),L=void 0;let V=k.splice(0,20);return V.length?Ve(r,`${o}/events`,JSON.stringify({events:V}),w).catch(I=>e.log?.("Visual exposure not sent",{error:I})):Promise.resolve()}function E(w,V){let I=B(w,V);x.has(I)||e.trackExposures===!1||i?.trackExposures===!1||u||(x.add(I),k.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:a,...s?{sessionId:s}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:w.key,variationKey:V.key}),k.length>=20?h():L??=setTimeout(()=>{h()},1e3))}function R(w){if(!i||u)return;let V=new Set,I={onExperimentViewed:(v,T)=>{V.add(B(v,T))},url:location.href,attributes:{...ve(a,location),...d,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:fe(i.savedGroups),log:e.log},G=new Set;for(let v of i.experiments){let T=v;try{let S=pe(T,I);if(y.set(v.changeId,S),!S.inExperiment)continue;G.add(v.changeId);let ae=JSON.stringify([S.key,S.value]),ue=A.get(v.changeId);if(ue?.signature===ae){V.has(B(T,S))&&w.push(()=>{ue.applied()&&E(T,S)});continue}A.get(v.changeId)?.revert(),A.delete(v.changeId);let le=Ce(S.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(v.condition?.$and)&&v.condition.$and.some(O=>O!==null&&typeof O=="object"&&!Array.isArray(O)&&O.indianaAppManifestRelease===e.appManifestRelease),boundVariations:v.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{V.has(B(T,S))&&E(T,S)},onError:O=>e.log?.("Visual experiment stopped",{experiment:v.key,error:String(O)})});A.set(v.changeId,{signature:ae,revert:le.revert,applied:()=>le.applied})}catch(S){e.log?.("Skipping visual experiment",{experiment:v.key,error:String(S)})}}for(let[v,T]of A)G.has(v)||(T.revert(),A.delete(v));p()}let P=()=>{let w=[];ke(()=>R(w));for(let V of w)V()};async function N(){let w=++M,V;try{V=await n.read(o,we)}catch(G){if(u||w!==M)return!1;throw G}let I=Ge(V);if(I.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return u||w!==M?!1:(i=I,!0)}let Je=()=>{g!==location.href&&(g=location.href,P())},ie=()=>{h(!0)},se=()=>{m||u||(m=ye(Je),addEventListener("pagehide",ie),g=location.href)};return{async start(){if(!(c||u)){c=!0,e.appManifestRelease&&(b=de(e.appManifestRelease)),e.antiFlicker&&(f=document.createElement("style"),e.nonce&&(f.nonce=e.nonce),f.textContent="body { visibility: hidden !important }",document.head.append(f),l=setTimeout(p,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await N()||u)return;se(),P()}finally{p()}}},async refresh(){u||await N()&&(c&&se(),P())},setAttributes(w){d={...w},P()},flush:()=>h(),getResults(){return new Map(y)},get generation(){return i?.generation??null},destroy(){u=!0,M++,n.destroy(),m?.(),b?.destroy(),removeEventListener("pagehide",ie),p();for(let w of A.values())w.revert();A.clear(),h(!0),i=null,y.clear(),x.clear(),d={}}}}export{Kt as createVisualExperiments};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkerlandai/indiana-sdk",
3
- "version": "0.6.4",
3
+ "version": "0.7.0",
4
4
  "description": "Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{a as we}from"./chunk-QG3WUJG5.js";import{$k as Ke,Bf as Ue,Ei as Ee,Ek as H,Fi as ke,Fk as je,Gd as Le,Jk as Pe,Kk as M,Lk as Je,Mk as Be,Nk as ze,Oi as Se,Ok as He,Pi as qe,Rh as be,Vf as ce,al as $e,bl as Qe,cl as Ye,hk as Ge,ui as te,xf as Ve,yf as Me}from"./chunk-HTRQPMJO.js";import{a as Ae}from"./chunk-S5TVMQRC.js";import{b as _e,h as ge}from"./chunk-ISUXYPYL.js";import{a as d}from"./chunk-5TEZEOHX.js";import{f as De,j as xe,m as Ne}from"./chunk-S2MSIA57.js";function yn(e){let n=null,i=null,t=0,m=0,y=new Set,o=null,u=null,r=new Set,s=()=>{for(let I of r)try{I()}catch{}},g={attributes:Ne.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(I,P)=>{!y.has(I)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(I,structuredClone(P))}:void 0,onExperimentViewed:e.onExperimentViewed?(I,P)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(I),structuredClone(P)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?I=>e.saveStickyBucketAssignmentDoc(structuredClone(I)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function v(I,P=new Set){return y.has(I)?!o||!o.features[I]||["unknownFeature","cyclicPrerequisite"].includes(o.features[I].source):P.has(I)?!1:(P.add(I),(n?.features[I]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(D=>D.experiment.parentConditions??[])].some(D=>v(D.id,P))))}let A=I=>{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 o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,g.features=n.features),y.has(I)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?w():structuredClone(o.features[I]??w()):v(I)?w():structuredClone(xe(I,g))};async function E(){if(!n||!y.size)return;if(!e.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let I=m;if(u?.revision===I)return u.loading;let P=t,F=n,D=[...y],T=(async()=>{let _=Ue.parse(await e.evaluateRemote({attributes:structuredClone(g.attributes),features:D}));if(!(P!==t||I!==m||F!==n)){if(e.assertUsable?.(F.generation),_.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(D.some(U=>!Object.hasOwn(_.features,U))||Object.keys(_.features).some(U=>!y.has(U)))throw new Error("Invalid remote Feature results");o=structuredClone(_),g.features={...F.features,...Object.fromEntries(Object.entries(o.features).map(([U,j])=>[U,{defaultValue:j.value}]))},s()}})();u={revision:I,loading:T};try{await T}finally{u?.loading===T&&(u=null)}}function S(){E().catch(I=>{try{e.onError?.(I)}catch{}})}async function V(){if(i)return i;let I=t,P=(async()=>{let F=await e.load(),D="remoteFeatures"in F?Ve.parse(F):null,T=D??ge.parse(F);if(T.scope.projectId!==e.scope.projectId||T.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(I!==t)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===T.generation){let{evaluatedAt:U,expiresAt:j,...oe}=n,{evaluatedAt:X,expiresAt:ee,...l}=T;if(M(oe)!==M(l))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=T.evaluatedAt,n.expiresAt=T.expiresAt,s(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&S(),structuredClone(n)}let _=new Set(D?.remoteFeatures??[]);if([..._].some(U=>Object.hasOwn(T.features,U)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in T&&!n.analyticsConfig.experimentViewsEnabled&&D?.analyticsConfig.experimentViewsEnabled&&g.trackedExperiments?.clear(),n=structuredClone(T),y=_,o=null,u=null,m++,g.features=n.features,g.savedGroups=De(n.savedGroups),g.trackedFeatureUsage={},s(),S(),structuredClone(n)})();i=P;try{return await P}finally{i===P&&(i=null)}}return{init:V,refresh:V,refreshRemote:E,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(I){return r.add(I),()=>{r.delete(I)}},setAttributes(I){g.attributes=Ne.parse(I),m++,o=null,u=null,g.features=n?.features??{},g.trackedFeatureUsage={},s(),S()},evalFeature:A,isOn(I){return A(I).on},isOff(I){return A(I).off},getFeatureValue(I,P){let F=A(I).value;return structuredClone(F===null?P:F)},reset(){t++,m++,i=null,u=null,n=null,o=null,y.clear(),g.features={},g.savedGroups={},g.stickyBucketAssignmentDocs={},g.attributes={},g.trackedFeatureUsage={},g.trackedExperiments?.clear(),s()}}}function Ze(e){let n,i,t=()=>new d("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),m=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,i=e.locks??globalThis.navigator?.locks,!n||!i||!globalThis.crypto?.subtle)throw t();let u=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??Ae).href,e.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",u));return"indiana.funnel.commands.v1."+Array.from(r,s=>s.toString(16).padStart(2,"0")).join("")});m.catch(()=>{});async function y(u){try{let r=await m;return await i.request(r,{mode:"exclusive"},()=>u(r))}catch(r){throw r instanceof d?r:t()}}function o(u){let r=n.getItem(u);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw t();let s=JSON.parse(r);if(!s||typeof s!="object"||!("revision"in s)||!("entry"in s)||!Number.isSafeInteger(s.revision)||Number(s.revision)<0)throw t();return{revision:Number(s.revision),entry:s.entry}}return{read:()=>y(o),write:(u,r)=>y(s=>{if(o(s).revision!==u)return null;if(!Number.isSafeInteger(u+1))throw t();return n.setItem(s,JSON.stringify({revision:u+1,entry:r})),u+1})}}function Rn(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ye(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((m,y)=>ye(m,n[y]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let i=Object.entries(e),t=Object.entries(n);return i.length===t.length&&i.every(([m,y])=>Object.hasOwn(n,m)&&ye(y,Reflect.get(n,m)))}var de=(e,n)=>new d(e,n);function Fn(e){return Ke(e,de)}function ln(e,n,i){return Qe(e,n,i,de)}async function We(e,n){let i=n.instruction;if(i?.type!=="evaluate")throw new Error("Evaluation instruction required");if(!e)throw new d("CONFIGURATION_UNAVAILABLE","Local conditions require the shared public configuration manager");let t=await e.funnel(n.source.id,n.source.versionId);if(!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==i.policyRevision)throw new d("EVALUATION_MODE","Refresh the original Funnel evaluation policy");let{analyticsConfig:m,remoteFeatures:y,...o}=t.growth,u=Se({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:t.document,payload:ge.parse(o)});if(e.scope.environmentId!==i.environmentId)throw new d("SCOPE_MISMATCH","Evaluation environment changed");let r=ln(u,n.nodeId,i);return e.assertFunnel(n.source.id,void 0,n.source.versionId),{generation:t.manifest.generation,result:r}}async function Xe(e,n){let i=n.instruction;if(i?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new d("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");let t=await e.funnel(n.source.id,n.source.versionId);if(!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==i.policyRevision)throw new d("EVALUATION_MODE","Refresh the original Funnel evaluation policy");if(e.scope.environmentId!==i.environmentId)throw new d("SCOPE_MISMATCH","Evaluation environment changed");let{analyticsConfig:m,remoteFeatures:y,...o}=t.growth,u=Se({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:t.document,payload:ge.parse(o)}),r=cn(u,t.document,{...n,...i});return e.assertFunnel(n.source.id,void 0,n.source.versionId),{...r,generation:t.manifest.generation,policyRevision:i.policyRevision}}function cn(e,n,i){return Ye(e,n,i,de)}import{z as Q}from"zod";var en=te.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new d("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),nn=Q.strictObject({schemaVersion:Q.literal(1),scope:_e,runId:Q.uuid(),funnelId:Q.uuid(),versionId:Q.uuid(),command:en.optional(),closeCommand:en.refine(e=>e.operation==="close").optional(),purchase:Q.strictObject({receiptId:Q.uuid(),operationId:Q.uuid(),generation:Q.number().int().nonnegative()}).optional(),closed:Q.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),J=()=>new d("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Fe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function tn(e){let n=0,i=null,t=r=>JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]),m=Promise.resolve();async function y(){let r=await e.read();if(!Number.isSafeInteger(r.revision)||r.revision<0)throw new d("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:r.revision,entry:r.entry===null?null:nn.parse(r.entry)}}function o(r){let s=m.then(r);return m=s.catch(()=>{}),s}async function u(r){for(let s=0;s<4;s++){let g=await y();if(g.entry&&i!==null&&t(g.entry)!==i)throw J();let w=r(g.entry,g.revision);if(Fe(g.entry,w)){n=g.revision;return}let v=await e.write(g.revision,w);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw J();n=v;return}}throw J()}return{bind(r){let s=JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]);if(i!==null&&i!==s)throw J();i=s},async load(){let r=await y();return n=r.revision,i=r.entry?t(r.entry):null,r.entry},retain(r){let s=nn.parse(r),g=s.command;return!g||i!==null&&t(s)!==i?Promise.reject(J()):(i??=t(s),o(()=>u((w,v)=>{if(w&&!Fe(t(w),t(s)))throw J();if(!w){if(v!==n&&g.operation!=="close")throw J();return s}if(!w.command)return{...w,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&w.command.operation!=="close"){if(w.command.requestId===g.requestId||w.closeCommand&&!Fe(w.closeCommand,g))throw J();return{...w,closeCommand:g,closed:!0}}if(!Fe(w.command,g))throw J();return w})))},observePurchase(r,s,g){return o(()=>u((w,v)=>{if(!w&&v!==n||w&&t(w)!==t({...r,schemaVersion:1}))throw J();if(w?.purchase&&w.purchase.generation>s.generation)return w;if(w?.purchase&&w.purchase.generation===s.generation&&w.purchase.operationId!==s.operationId)throw J();return g?!w?.purchase||w.purchase.operationId!==s.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...r,...w,purchase:s}}))},settle(r){return o(()=>u(s=>s?s.command&&"requestId"in s.command&&s.command.requestId===r?s.closeCommand?{...s,command:s.closeCommand,closeCommand:void 0}:s.purchase?{...s,command:void 0}:null:s.closeCommand&&"requestId"in s.closeCommand&&s.closeCommand.requestId===r?{...s,closeCommand:void 0}:s:null))}}}function fe(e){let{customerToken:n,...i}=e;return i}var dn=e=>!(e instanceof d)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function rn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new d("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.serverKey)))throw new d("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let n=we({...e,...e.serverKey?{fetch:(l,c)=>{let N=new Headers(c?.headers);return N.set(ke,e.serverKey),(e.fetch??globalThis.fetch)(l,{...c,headers:N})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let i,t=null,m=0,y=0,o=null,u=null,r=!1,s=null,g=!1,w=null,v=new Set,A=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Ze(e):void 0),E=A&&tn(A),S,V=null,I=!1,P=E?E.load().then(l=>{if(I)throw new d("IDENTITY_CHANGED","Controller was reset during command restoration");if(V=l,!l)return;if(e.scope&&(l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment))throw new d("SCOPE_MISMATCH","Pending command belongs to another scope");if(S=l.purchase,r=l.closed===!0,!l.command)return;let c=te.parse(l.command);if(c.operation==="start"||c.operation==="get"||c.operation==="review")throw new d("COMMAND_STORAGE_INVALID","Stored mutation required");o=c,l.closeCommand&&(u=l.closeCommand,r=!0),c.operation==="close"&&(r=!0),g=!0}):Promise.resolve();P.catch(()=>{});async function F(l,c,N){E&&await P;let k=m,Y=t,a=Ee.parse(await n.request("funnels",te.parse(l)));if(l.operation==="review"&&!a.review)throw new d("INVALID_RESPONSE","Historical projection is missing");if(k!==m)throw new d("IDENTITY_CHANGED","Run identity changed during the request");if(a.runToken&&a.runToken!==e.runToken)throw new d("INVALID_RESPONSE","Run credential changed");let B=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(B&&a.settlement?.requestId!==B)throw new d("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");if(V&&(a.run.id!==V.runId||a.run.source.id!==V.funnelId||a.run.source.versionId!==V.versionId))throw new d("SCOPE_MISMATCH","Stored command belongs to another Run or Version");if(t&&(a.run.id!==t.id||a.run.source.type!==t.source.type||a.run.source.id!==t.source.id||a.run.source.versionId!==t.source.versionId||a.run.locale!==t.locale||!ye(a.run.parameters,t.parameters)))throw new d("INVALID_RESPONSE","Run version changed");if(e.funnelId&&a.run.source.id!==e.funnelId)throw new d("INVALID_RESPONSE","Run belongs to another Funnel");E?.bind({scope:a.scope,runId:a.run.id,funnelId:a.run.source.id,versionId:a.run.source.versionId}),A&&!e.scope&&(e.scope=a.scope);let K=a.run.paywall,z=K??a.purchase,me=z?.operation,pe=a.settlement&&(!K||K.purchaseRequestId===a.settlement.requestId)&&(!S||S.operationId===a.settlement.operationId)?a.settlement:void 0,ie=me?.operationId??z?.quote?.operationId??pe?.operationId,ae=z?.receiptId??pe?.receiptId,Ie=K?.selectionGeneration??S?.generation??0;if(E&&ie&&ae&&l.operation!=="review"&&(!t||a.run.revision>=t.revision)&&(N===void 0||N>=y)&&(!S||Ie>=S.generation)){let $={receiptId:ae,operationId:ie,generation:Ie},Ce=me?.status==="complete"||z?.canReselect===!0;await E.observePurchase({scope:a.scope,runId:a.run.id,funnelId:a.run.source.id,versionId:a.run.source.versionId},$,Ce),Ce?S?.operationId===$.operationId&&(S=void 0):S=$}if(!a.run.stopped&&["running","waiting"].includes(a.run.status)&&l.operation==="get"&&l.settlementRequestId)return a;let se=c?.(a),he=typeof se=="boolean"?se:se?await se:!1;if(["running","waiting"].includes(a.run.status)||(r=!0),l.operation==="review"&&t&&t!==Y&&a.run.revision<=t.revision||t&&a.run.revision===t.revision&&N!==void 0&&N<y||(l.operation==="review"&&!a.run.stopped&&["running","waiting"].includes(a.run.status)&&t&&a.run.nodeId===t.nodeId&&a.run.visit===t.visit&&a.run.revision===t.revision&&(a.run.screen=t.screen,(t.paywall?.quote?.operationId===a.review?.activeOperationId||!t.paywall?.quote&&a.review?.activeOperationId===null)&&(a.run.paywall=t.paywall)),t?.paywall&&a.run.paywall&&t.paywall.receiptId===a.run.paywall.receiptId&&(a.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))return a;if(!t||a.run.revision>=t.revision)t=a.run;else if(!he)return a;if(t)for(let $ of v)try{$(structuredClone(t))}catch{}return a}async function D(l=o){if(E&&await P,!l)throw new d("INVALID_REQUEST","No command is pending");let c=l,N=m;if(E){if(!t||!e.scope)throw new d("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await E.retain({schemaVersion:1,scope:e.scope,runId:t.id,funnelId:t.source.id,versionId:t.source.versionId,command:fe(c)})}if(N!==m||o!==c&&u!==c)throw new d("IDENTITY_CHANGED","Run changed before command dispatch");let k={...c,...i?{customerToken:i}:{}},Y=g;g=!0;try{return await F(k,a=>{if(!a.settlement)throw new d("INVALID_RESPONSE","Exact command settlement is missing");if(a.settlement.requestId!==c.requestId)throw new d("INVALID_RESPONSE","Command settlement identity changed");if(N===m&&(o===c||u===c)&&a.run.pendingRequest?.requestId!==c.requestId&&a.settlement.state==="settled"&&(!r||c.operation==="close"||a.settlement?.state==="settled"&&!["running","waiting"].includes(a.run.status))){let B=()=>N!==m||o!==c&&u!==c?!1:(o===c&&(o=null),u===c&&(u=null),g=o!==null,V=null,!0);return E?E.settle(c.requestId).then(B):B()}return!1})}catch(a){throw N===m&&o===c&&!Y&&!dn(a)&&(E&&await E.settle(c.requestId),N===m&&o===c&&(o=null,g=!1,V=null)),a}}function T(l){let c=te.parse(l);if(c.operation==="start"||c.operation==="get"||c.operation==="review")throw new d("INVALID_REQUEST","Mutation required");if(t?.recoveryRestricted&&c.operation!=="close"&&c.operation!=="resume"&&o?.requestId!==c.requestId)throw new d("PRECONDITION_FAILED","Original Run requires restricted recovery");if(r&&c.operation!=="close"){if(o?.requestId===c.requestId)return ee.settle(c.requestId);throw new d("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(c.operation==="close"&&o?.operation!=="close"){if(r=!0,u&&JSON.stringify(fe(u))!==JSON.stringify(fe(c)))throw new d("COMMAND_PENDING","Retry the original Close");if(u??=c,s)return s;let k=D(u);return s=k,k.then(()=>{s===k&&(s=null)},()=>{s===k&&(s=null)}),k}if(o){if(JSON.stringify(fe(o))!==JSON.stringify(fe(c)))throw new d("COMMAND_PENDING","Retry the original command before sending another");if(w)return w}else o=c,g=!1;let N=D();return w=N,N.then(()=>{w===N&&(w=null)},()=>{w===N&&(w=null)}),N}let _=null,U=new WeakMap;function j(l){let c=U.get(l);if(c)return c;let N=X(l);return U.set(l,N),N}let oe=!1;async function X(l){let c=await l;if(c.run.recoveryRestricted||!["evaluate","evaluate_segment"].includes(c.run.instruction?.type??""))return c;if(_)return _;oe=!0;let N=m,k=(async()=>{for(let Y=0;Y<32&&["evaluate","evaluate_segment"].includes(c.run.instruction?.type??"");Y++){if(o||r)return c;let a=c.run,B=c.run.instruction;if(B?.type==="evaluate_segment"){let z=await Xe(e.configuration,a);if(N!==m)throw new d("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o||r)return c;if(t&&(t.revision!==a.revision||t.visit!==a.visit||t.nodeId!==a.nodeId))return F({operation:"get",...i?{customerToken:i}:{}});c=await T({operation:"commit_segment",requestId:be(a.id,a.visit,`segment:${a.revision}`),nodeId:a.nodeId,visit:a.visit,revision:a.revision,...z});continue}if(B?.type!=="evaluate")return c;let K=await We(e.configuration,a);if(N!==m)throw new d("IDENTITY_CHANGED","Run identity changed during evaluation");if(o||r)return c;if(t&&(t.revision!==a.revision||t.visit!==a.visit||t.nodeId!==a.nodeId))return F({operation:"get",...i?{customerToken:i}:{}});c=await T({operation:"evaluate",requestId:be(a.id,a.visit,"evaluation"),nodeId:a.nodeId,visit:a.visit,revision:a.revision,receiptId:B.receiptId,policyRevision:B.policyRevision,...K})}return c})();_=k;try{return await k}finally{_===k&&(_=null)}}let ee={get configuration(){return oe?e.configuration:void 0},get configurationReady(){return!0},get view(){return t?structuredClone(t):null},get pendingCommand(){let l=u??o;return l?structuredClone(fe(l)):null},get pendingCommands(){return[o,u].filter(l=>l!==null).map(l=>structuredClone(fe(l)))},get pendingPurchase(){return S?structuredClone(S):null},async settle(l){let c=await F({operation:"get",settlementRequestId:l,...i?{customerToken:i}:{}});if(c.settlement?.requestId!==l)throw new d("INVALID_RESPONSE","Exact command settlement is missing");return c.settlement.state==="settled"&&(E&&await E.settle(l),o?.requestId===l&&(o=null,g=!1),u?.requestId===l&&(u=null)),c},get webViewUrl(){return n.webViewUrl()},review(l){return F({operation:"review",...l?{receiptId:l}:{},...i?{customerToken:i}:{}},void 0,++y)},async get(l,c){E&&await P,c??=S&&{receiptId:S.receiptId,operationId:S.operationId};let N=++y;return j(F({operation:"get",...l?{data:l}:{},...c?{purchase:c}:{},...i?{customerToken:i}:{}},void 0,N))},resume(l=t?.pendingRequest?.requestId){return l?r?ee.settle(l):o?.requestId===l?j(T(o)):j(T({operation:"resume",requestId:l})):Promise.reject(new d("INVALID_REQUEST","No interrupted command is available"))},submit(l){return j(T(l))},retry(){return s||(u?D(u):r&&o?ee.settle(o.requestId):w?j(w):o?j(T(o)):Promise.reject(new d("INVALID_REQUEST","No command is pending")))},identify(l){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(l))throw new d("INVALID_TOKEN","Customer credential required");m++,i=l,n.identify(e.runToken)},subscribe(l){return v.add(l),()=>v.delete(l)},reset(){I=!0,m++,i=void 0,t=null,o=null,u=null,s=null,g=!1,w=null,n.reset(),v.clear()}};return ee}async function Zn(e,n){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(n.customerToken))throw new d("INVALID_TOKEN","A verified Customer credential is required");let i=we(e);i.identify(n.customerToken);let t=ce.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),m=null,y=null,o=null,u=null,r=null;async function s(){let v=ce.resolvePaywall,A=v.response.parse(await i.request(v.path,v.request.parse({...t,selector:m?{type:"version",versionId:m.id}:t.selector})));if(n.paywallVersionId?A.paywall.id!==n.paywallVersionId:A.paywall.paywallId!==n.paywallId)throw new d("INVALID_RESPONSE","The requested Paywall changed");if(m&&(A.paywall.id!==m.id||A.paywall.paywallId!==m.paywallId||A.paywall.offering.id!==m.offering.id))throw new d("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return m=A.paywall,structuredClone(m)}async function g(v){if(!y)throw new d("INVALID_REQUEST","A quoted purchase is required");let A=v==="read"?ce.readSubscriptionOperation:ce.attach,E=A.response.parse(await i.request(A.path,A.request.parse({operationId:y.operationId,...v==="read"?{}:{intent:v}})));if(E.operation.operationId!==y.operationId||E.operation.currency!==t.commerce.currency)throw new d("INVALID_RESPONSE","The purchase operation changed");return o?.status==="complete"&&E.operation.status!=="complete"||o&&o.status!=="pending"&&E.operation.status==="pending"||(o=E.operation),structuredClone(o)}let w={get view(){return m?structuredClone(m):null},get quote(){return y?structuredClone(y):null},get operation(){return o?structuredClone(o):null},get webViewUrl(){return i.webViewUrl()},refresh:s,async preview(v){if(!m)throw new d("INVALID_REQUEST","Load the Paywall first");let A=m.document.buttons[v.actionId];if(A?.type!=="checkout")throw new d("INVALID_REQUEST","Choose an authored purchase action");let E=Le(A.product,v.selection,m.capabilities);if(!E)throw new d("PRODUCT_UNAVAILABLE","Choose an available Product");let S=ce.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:v.requestId,plans:[{productVersionId:E}],provider:t.commerce.provider,currency:t.commerce.currency,...v.offerId?{offerId:v.offerId}:{},...v.nativeOffer?{nativeOffer:v.nativeOffer}:{}}),V=JSON.stringify(S);if(u&&u!==V&&(!o||o.status==="pending"))throw new d("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(u===V){if(r)return r;if(y)return structuredClone(y)}u=V;let I=(async()=>{let P=ce.previewAttach,F=P.response.parse(await i.request(P.path,S));if(F.quote.currency!==t.commerce.currency||F.quote.provider!==t.commerce.provider||F.quote.lines.length!==1||F.quote.lines[0].productVersionId!==E)throw new d("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return y=F.quote,o=null,structuredClone(y)})();r=I;try{return await I}finally{r===I&&(r=null)}},confirm:()=>g("confirm"),cancel:()=>g("cancel"),read:()=>g("read"),destroy(){i.reset(),m=null,y=null,o=null,u=null}};return await s(),w}import{z as gn}from"zod";import{z as ve}from"zod";var fn=ve.record(ve.string().regex(/^[a-f0-9]{64}$/),ve.strictObject({at:ve.number(),text:ve.string()})),on=2*1048576,mn=100;function pn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function an(e,n){let i=n===void 0?pn():n,t=Promise.resolve();async function m(o){if(!i)return null;let u;try{return await Promise.race([Promise.resolve().then(()=>i.getItem(o)),new Promise(r=>{u=setTimeout(()=>r(null),mn)})])}catch{return null}finally{clearTimeout(u)}}async function y(){try{let o=await m(`${e}:artifacts`);if(o&&o.length<=on)return fn.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return m(e)},writeManifest(o){Promise.resolve().then(()=>i?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let u=(await y())[o];return u&&Date.now()>=u.at&&Date.now()-u.at<=H.retentionMs?u.text:void 0},writeArtifact(o,u){i&&(t=t.catch(()=>{}).then(async()=>{let r=await y(),s=Date.now();r[o]={at:s,text:u};let g={},w=2,v=0;for(let[A,E]of Object.entries(r).sort(([,S],[,V])=>V.at-S.at)){if(E.at>s||s-E.at>H.retentionMs)continue;let S=new TextEncoder().encode(JSON.stringify({[A]:E})).byteLength;w+S>on||v>=128||(g[A]=E,w+=S,v++)}await i.setItem(`${e}:artifacts`,JSON.stringify(g))}).catch(()=>{}))}}}var R=(e,n)=>new d(e,n),re=()=>performance.now(),sn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function st(e){let n=je.parse(e.scope),i=new URL(e.origin??Ae);if(i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!(i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw R("INVALID_URL","Configuration requires a trusted HTTPS origin");let t=new Set([i.origin,...(e.assetOrigins??[]).map(p=>{let f=new URL(p);if(f.protocol!=="https:"||f.username||f.password||f.search||f.hash||f.pathname!=="/")throw R("INVALID_URL","Invalid configuration asset origin");return f.origin})]),m=e.fetch??globalThis.fetch.bind(globalThis),y=`/api/v1/configuration/${n.environmentId}`,o=`indiana:configuration:1:${i.origin}:${M(n)}`,u=an(o,e.storage),r,s=0,g=0,w=!1,v=!1,A=0,E=0,S,V,I,P,F=0,D=new Set,T=new Set,_=new Map,U=new Map,j=0,oe=!1;function X(){for(let p of D)try{p()}catch{}}function ee(p){try{e.onError?.(p)}catch{}}let l=()=>!v&&!w&&!!r&&re()<s&&Date.now()<g;function c(){if(!l())throw R("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function N(p,f){let C=new TextEncoder().encode(f).byteLength;if(!_.has(p)){for(;_.size&&(_.size>=128||j+C>H.maxCacheBytes);){let h=_.entries().next().value;j-=new TextEncoder().encode(h[1]).byteLength,_.delete(h[0])}_.set(p,f),j+=C}}async function k(p,f,C){if(Number(p.headers.get("content-length"))>f)throw R("INVALID_RESPONSE","Configuration exceeds its byte limit");let h=p.body?.getReader();if(!h)throw R("INVALID_RESPONSE","Configuration body is missing");let b=[],L=0;try{for(;;){C.throwIfAborted();let x=await h.read();if(x.done)break;if(L+=x.value.length,L>f)throw R("INVALID_RESPONSE","Configuration exceeds its byte limit");b.push(x.value)}}finally{await h.cancel().catch(()=>{})}C.throwIfAborted();let O=new Uint8Array(L),G=0;for(let x of b)O.set(x,G),G+=x.length;return new TextDecoder("utf-8",{fatal:!0}).decode(O)}function Y(p){let f=new URL(p,i);if(!t.has(f.origin)||f.username||f.password||f.hash||f.search)throw R("INVALID_URL","Configuration artifact origin is not trusted");return f.href}async function a(p,f,C=!1){let h=await m(Y(p),{method:"GET",credentials:"omit",redirect:"error",cache:C?"default":"no-cache",signal:f,headers:{}});if(h.status===429){let b=h.headers.get("retry-after")??"";F=/^\d+$/.test(b)?Number(b)*1e3:Math.max(0,Date.parse(b)-Date.now())||15e3}if(!h.ok&&h.status!==304)throw R(`CONFIGURATION_HTTP_${h.status}`,"Configuration synchronization failed");return h}function B(p,f,C){let h=Date.parse(p.headers.get("x-indiana-config-validated-at")??""),b=Date.parse(p.headers.get("x-indiana-config-valid-until")??""),L=Date.parse(p.headers.get("date")??""),O=p.headers.get("age"),G=O!==null&&/^\d+(\.\d+)?$/.test(O)?Number(O)*1e3:NaN;if(![h,b,L,G].every(Number.isFinite)||b<=h||b-h>H.maxControlAgeMs||h>L+1e3)throw R("INVALID_RESPONSE","Configuration freshness evidence is invalid");let q=Math.min(b-h,C.maxControlAgeSeconds*1e3,H.maxControlAgeMs)-Math.max(G,L-h,0)-(re()-f);if(q<=0)throw R("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return re()+q}function K(){if(clearTimeout(I),clearTimeout(P),v||!D.size)return;l()&&(P=setTimeout(()=>{l()?K():X()},Math.max(1,s-re())),sn(P));let p=E?Math.min(15e3,1e3*2**Math.min(E-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);I=setTimeout(()=>{z().catch(ee)},Math.max(F,p*(.8+Math.random()*.2))),sn(I)}async function z(){if(v)throw R("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(S)return S;let p=A,f=new AbortController;V=f;let C=(async()=>{if(!oe){oe=!0;try{let Re=await u.readManifest();if(Re&&!r){let W=Pe.parse(JSON.parse(Re));M(W.scope)===M(n)&&(r=W)}}catch{}}f.signal.throwIfAborted();let O=r,G=re(),x=await a(y,f.signal);x.status===304&&(!O||!x.headers.has("x-indiana-config-validated-at")||!x.headers.has("x-indiana-config-valid-until")||!x.headers.has("age"))&&(x=await a(y,f.signal));let q=x.status===304?O:Pe.parse(JSON.parse(await k(x,H.maxManifestBytes,f.signal))),{generation:Z,...ne}=q,ue=x.headers.get("etag");if(M(q.scope)!==M(n)||Be(ne)!==Z||ue!==`"${Z}"`&&ue!==`W/"${Z}"`)throw R("INVALID_RESPONSE","Configuration scope or content identity changed");if(O&&(q.revision<O.revision||q.revision===O.revision&&q.generation!==O.generation))throw R("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Re,W]of Object.entries(O?.funnels??{})){let le=q.funnels[Re];if(le&&(le.controlRevision<W.controlRevision||le.evaluationRevision<W.evaluationRevision||le.controlRevision===W.controlRevision&&le.state!==W.state||le.evaluationRevision===W.evaluationRevision&&le.evaluationMode!==W.evaluationMode))throw R("INVALID_RESPONSE","Funnel control revision changed identity")}let Te=B(x,G,q.policy);if(f.signal.throwIfAborted(),p!==A)throw R("CONFIGURATION_DISPOSED","Configuration scope changed");return r=q,s=Te,g=Date.now()+Math.max(0,Te-re()),w=!1,E=0,F=0,u.writeManifest(M(q)),X(),structuredClone(q)})(),h=setTimeout(()=>f.abort(R("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs),b=new Promise((O,G)=>f.signal.addEventListener("abort",()=>G(f.signal.reason),{once:!0})),L=Promise.race([C,b]).catch(O=>{throw E++,(O instanceof gn.ZodError||O instanceof SyntaxError||O instanceof d&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(O.code))&&(s=0,w=!0,X()),O}).finally(()=>{clearTimeout(h),S===L&&(S=void 0),K()});return S=L,L}async function me(p){let f=p.sha256,C=Z=>new TextEncoder().encode(Z).byteLength===p.byteLength&&Je(Z)===f;Y(p.url);let h=_.get(f);if(h&&C(h))return _.delete(f),_.set(f,h),h;if(U.has(f))return U.get(f);let b=new AbortController;T.add(b);let L=A,O=(async()=>{try{let ue=await u.readArtifact(f);if(ue&&C(ue))return N(f,ue),ue}catch{}b.signal.throwIfAborted();let Z=await a(p.url,b.signal,!0),ne=await k(Z,p.byteLength,b.signal);if(!C(ne))throw R("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(v||L!==A)throw R("CONFIGURATION_DISPOSED","Configuration scope changed");return N(f,ne),u.writeArtifact(f,ne),ne})(),G=setTimeout(()=>b.abort(R("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),H.initializationMs),x=new Promise((Z,ne)=>b.signal.addEventListener("abort",()=>ne(b.signal.reason),{once:!0})),q=Promise.race([O,x]).finally(()=>{clearTimeout(G),T.delete(b),U.delete(f)});return U.set(f,q),q}async function pe(){return l()||await z(),c(),r}async function ie(p){let f,C=new Promise((h,b)=>{f=setTimeout(()=>b(R("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs)});try{return await Promise.race([p(),C])}finally{clearTimeout(f)}}function ae(p,f){if(c(),r?.generation!==p.generation)throw R("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(f&&r.funnels[f]?.state!=="active")throw R("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Ie(p){let f=p.gb.features;if(!f)throw R("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let C=p.artifacts[f];if(C.formatVersion!==1)throw R("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let h=Me.parse(JSON.parse(await me(C)));if(M(h.scope)!==M({projectId:n.projectId,environment:n.environment})||h.generation!==C.generation||h.remoteFeatures.some(b=>Object.hasOwn(h.features,b)))throw R("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return ae(p),{...h,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,s-re())).toISOString()}}async function se(p,f){let C=await pe();ae(C,p);let h=C.funnels[p];if(h.evaluationMode!=="local")throw R("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let b=f??h.currentVersionId,L=h.versions[b];if(!L)throw R("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(C.artifacts[L.artifact].formatVersion!==3)throw R("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[O,G]=await Promise.all([me(C.artifacts[L.artifact]).then(x=>He(JSON.parse(x))),h.evaluationMode==="local"?Ie(C):void 0]);if(G&&M(ze(O,G))!==M(L.dependencies))throw R("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return ae(C,p),{document:O,growth:G,versionId:b,control:structuredClone(h),manifest:structuredClone(C)}}function he(){w=!0,X(),z().catch(ee)}let $=()=>{(typeof document>"u"||document.visibilityState==="visible")&&he()};function Ce(p){if(v)throw R("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return D.add(p),D.size===1&&(typeof window<"u"&&(window.addEventListener("online",he),window.addEventListener("focus",$),document.addEventListener("visibilitychange",$)),K()),()=>{D.delete(p),D.size||(clearTimeout(I),clearTimeout(P),Oe())}}function Oe(){typeof window<"u"&&(window.removeEventListener("online",he),window.removeEventListener("focus",$),document.removeEventListener("visibilitychange",$))}return{scope:Object.freeze({...n}),refresh:z,subscribe:Ce,assertFresh:c,assertFeatures(p){c();let f=r.gb.features;if(!f)throw R("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(p!==void 0&&r.artifacts[f].generation!==p)throw R("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return l()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return l()?Math.max(0,s-re()):0},async features(){return ie(async()=>Ie(await pe()))},pageExperiments:()=>ie(async()=>{let p=await pe(),f=p.gb.pageExperiments;if(!f)throw R("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let C=p.artifacts[f];if(C.formatVersion!==1)throw R("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let h=Ge.parse(JSON.parse(await me(C)));if(h.environmentId!==n.environmentId||h.generation!==C.generation)throw R("INVALID_RESPONSE","Page experiment scope or generation changed");return ae(p),h}),funnel:(p,f)=>ie(()=>se(p,f)),async localFunnel(p,f){let C=await ie(()=>se(p,f));if(!C.growth)throw R("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:h,remoteFeatures:b,...L}=C.growth;return qe({scope:{projectId:n.projectId,environment:n.environment},funnelId:p,versionId:C.versionId,evaluationMode:"local",evaluationRevision:C.control.evaluationRevision,document:C.document,payload:L})},assertFunnel(p,f,C){c();let h=r.funnels[p];if(!h||h.state!=="active")throw R("FUNNEL_STOPPED","Funnel is paused or unavailable");if(h.evaluationMode!=="local")throw R("EVALUATION_MODE","This Funnel now executes at Indiana");if(f!==void 0&&h.controlRevision!==f)throw R("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(C!==void 0&&!h.versions[C])throw R("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!v){v=!0,A++,s=0,V?.abort(R("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(I),clearTimeout(P),Oe(),X(),D.clear();for(let p of T)p.abort(R("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));_.clear(),j=0}}}}function dt(e,n,i){return $e(e,n,i,de)}function un(e){let n=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey);if(typeof window<"u"&&!n)throw new d("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new d("INVALID_TOKEN","A customer credential or server API key is required");let i=we({...e,timeoutMs:e.timeoutMs??35e3});return i.identify(e.apiKey),{async start(t){let m=te.safeParse({...t,operation:"start"});if(!m.success||m.data.operation!=="start"||(n?m.data.customer!==void 0:m.data.customer===void 0))throw new d("INVALID_REQUEST","Invalid current Funnel start");let y=m.data,o=Ee.safeParse(await i.request("funnels",y));if(!o.success||!o.data.runToken)throw new d("INVALID_RESPONSE","Funnel start credentials are missing");let u=o.data;if(u.run.source.id!==y.funnelId||u.run.locale!==(y.locale??"en")||!ye(u.run.parameters,y.parameters??{})||(y.customer?!u.customerId||y.customer.type==="id"&&u.customerId!==y.customer.value:u.customerId!==void 0))throw new d("INVALID_RESPONSE","Funnel start contract changed");return{...u,runToken:u.runToken}}}}async function Ct(e){e={...e};let n=e.configuration;if(!n)throw new d("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let i={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&M(i)!==M(e.scope))throw new d("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new d("EVALUATION_MODE","This Funnel uses Remote evaluation");let m=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.credential);if(m?!e.customerId:e.customerId!==void 0)throw new d("INVALID_REQUEST","Only Server-Key starts name their Customer");let y=un({...e,scope:i,apiKey:e.credential}),o=u=>{let r=rn({...e,scope:i,runToken:u,...m?{serverKey:e.credential}:{}});return m||r.identify(e.credential),r};return{async start(u){let r=await y.start({...u,funnelId:e.funnelId,...m?{customer:{type:"id",value:e.customerId}}:{}}),s=o(r.runToken),g=await s.get();return{...r,...g,controller:s}},async restore(u){let r=o(u),s=await r.get();if(s.run.source.id!==e.funnelId)throw r.reset(),new d("SCOPE_MISMATCH","Run belongs to another Funnel");return{...s,runToken:u,controller:r}}}}export{yn as a,Rn as b,ye as c,Fn as d,ln as e,cn as f,Ze as g,rn as h,Zn as i,st as j,dt as k,un as l,Ct as m};
@@ -1 +0,0 @@
1
- async function g(e,l,o,u={}){let a=u.message??"Invalid SDK JSON response",c=e.headers.get("content-length");if(!e.ok||u.requireJson!==!1&&!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||c!==null&&(!/^\d+$/.test(c)||Number(c)>l)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(a);let s=e.body.getReader(),b=[],i=0,h=!1,r=()=>{},f=new Promise((d,n)=>{r=()=>n(Error(a)),o.addEventListener("abort",r,{once:!0}),o.aborted&&r()});try{for(;;){let t=await Promise.race([s.read(),f]);if(t.done){h=!0;break}if(i+=t.value.byteLength,i>l)throw Error(a);b.push(t.value)}let d=new Uint8Array(i),n=0;for(let t of b)d.set(t,n),n+=t.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d))}finally{o.removeEventListener("abort",r),h||s.cancel().catch(()=>{}),s.releaseLock()}}export{g as a};
@@ -1,4 +0,0 @@
1
- import{a as L}from"./chunk-S5TVMQRC.js";import{c as T,f as A,i as U}from"./chunk-S2MSIA57.js";function _(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let r of document.cookie.split(";"))if(r.trim().startsWith(`${e}=`))try{t=decodeURIComponent(r.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function C(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function V(e=L){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var E=new Set,x;function D(e){if(E.add(e),!x){let t=history.pushState,r=history.replaceState,n=()=>{for(let c of E)c()},a=function(...c){t.apply(this,c),n()},l=function(...c){r.apply(this,c),n()};history.pushState=a,history.replaceState=l,addEventListener("popstate",n),addEventListener("hashchange",n),x=()=>{history.pushState===a&&(history.pushState=t),history.replaceState===l&&(history.replaceState=r),removeEventListener("popstate",n),removeEventListener("hashchange",n)}}return()=>{E.delete(e),E.size||(x?.(),x=void 0)}}var Y=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function q(e,t){let r=e,n=a=>Number.isInteger(a)&&a>=0;return!!r&&typeof r=="object"&&n(r.inserted)&&n(r.duplicates)&&n(r.skipped)&&Array.isArray(r.rejected)&&r.inserted+r.duplicates+r.skipped+r.rejected.length===t}function $(e){let t=[],r,n=(o,s)=>e.log?.(`${e.label} ${o}`,s);function a(o){r===void 0&&t.length&&(r=setTimeout(()=>{c()},o))}async function l(o){let s;try{s=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:o}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(g){return n("not sent",{error:g}),!1}if(s.status===408||s.status===429||s.status>=500)return n("not sent",{status:s.status}),!1;if(!s.ok)return n("rejected",{status:s.status,events:o.length}),!0;let d;try{d=await s.json()}catch{d=void 0}return q(d,o.length)?(d.rejected.length&&n("rejected",{rejected:d.rejected}),!0):(n("not acknowledged",{status:s.status}),!1)}function c(){clearTimeout(r),r=void 0;let o=[];for(;t.length&&o.length<20&&(!o.length||Y([...o,t[0]].map(s=>s.event))<=65536);)o.push(t.shift());return o.length?l(o.map(s=>s.event)).then(s=>{if(s)return a(1e3);let d=o.filter(g=>++g.attempts<5);d.length<o.length&&n("dropped after retries",{events:o.length-d.length}),t.unshift(...d),a(5e3)}):Promise.resolve()}return{push(o){t.push({event:o,attempts:0}),t.length>=20?c():a(1e3)},flush:c}}var Q="__indiana_visual_editor",f;function z(e,t){if(f&&f.origin===e&&f.environmentId===t&&f.expiresAt>Date.now())return f;try{let r=new URL(location.href).searchParams.get(Q);if(!r||r.length>2048)return null;let n=JSON.parse(r);return n.origin!==e||n.environmentId!==t||!/^[a-f0-9-]{36}$/i.test(n.nonce)||n.expiresAt<=Date.now()||n.expiresAt>Date.now()+900*1e3?null:(f=n,n)}catch{return null}}function O(e,t){return!!z(e,t)}/*!
2
- Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
- plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
- */function F(e,t){let r,n;try{r=new URL(e),n=new URL(t)}catch{return t}return r.searchParams.forEach((a,l)=>{n.searchParams.has(l)||n.searchParams.set(l,a)}),n.toString()}function W(e,t){let r=navigator.userAgent,n=new URLSearchParams(t.search),a={};for(let l of["source","medium","campaign","term","content"]){let c=n.get(`utm_${l}`);c!==null&&(a[`utm${l[0].toUpperCase()}${l.slice(1)}`]=c)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(r)?"edge":/Chrome/.test(r)?"chrome":/Firefox/.test(r)?"firefox":/Safari/.test(r)?"safari":"unknown",deviceType:/Mobi/.test(r)?"mobile":"desktop",...a}}function K(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(a=>Object.hasOwn(n,a))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(a=>!!a&&typeof a.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function oe(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=V(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=`${t}/api/v1/page-experiments/${e.environmentId}`,a=_(e.deviceIdCookie??"indiana_did"),l=C(),c=null,o={...e.attributes??{}},s="",d=!1,g=new Map,P=$({endpoint:`${n}/events`,fetch:r,log:e.log,label:"Exposure"}),w=P.flush,m={trackedExperiments:new Set,log:e.log,onExperimentViewed:(i,u)=>{e.trackExposures===!1||c?.trackExposures===!1||P.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:a,...l?{sessionId:l}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:u.key})}},j=()=>{m.url=location.href,m.attributes={...W(a,location),...o}};function N(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let u=new URL(location.href);return i.variations.some(p=>{if(!p.urlRedirect)return!1;let y=new URL(p.urlRedirect);return y.protocol!==u.protocol||y.host!==u.host})}catch{return!0}}function H(i,u){let p=e.configuration?.snapshot?.generation;s=i;let y=e.navigate??(v=>location.replace(v)),G=e.navigateDelay??(e.navigate?0:100),J=e.maxNavigateDelay??1e3;Promise.all([Promise.race([u,new Promise(v=>setTimeout(v,J))]),new Promise(v=>setTimeout(v,G))]).then(()=>{!d&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===p)&&y(i)})}function h(){if(!(!c||d||e.configuration&&!e.configuration.fresh||O(t,e.environmentId))){j();for(let i of c.experiments){if(N(i)){e.log?.("Auto experiment blocked",{id:i.key});continue}let u;try{u=U(i,m)}catch(p){e.log?.("Skipping page experiment",{id:i.key,error:String(p)});continue}if(g.set(i.key,u),!!u.inExperiment){if(u.value.urlRedirect){let p=i.persistQueryString?F(location.href,u.value.urlRedirect):u.value.urlRedirect;T(p,i.urlPatterns??[])?e.log?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):p!==s&&H(p,w())}break}}}}let b="",M=()=>{location.href!==b&&(b=location.href,s="",h())},S,k;function B(){S??=D(M),addEventListener("pagehide",I)}let I=()=>{w()};async function R(){let i=e.configuration?null:await r(n,{cache:"no-cache",credentials:"omit"});if(i&&!i.ok)throw new Error(`Page experiments unavailable (${i.status})`);let u=K(e.configuration?await e.configuration.pageExperiments():await i.json());if(u.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");c?.trackExposures===!1&&u.trackExposures&&m.trackedExperiments?.clear(),c=u,m.savedGroups=A(u.savedGroups)}return{async start(){await R(),k??=e.configuration?.subscribe(()=>{!d&&e.configuration?.fresh&&R().then(h).catch(i=>e.log?.("Page configuration unavailable",{error:String(i)}))}),B(),b=location.href,h()},async refresh(){await R(),s="",h()},setAttributes(i){o={...i},h()},getResults(){return new Map(g)},get generation(){return c?.generation??null},destroy(){d=!0,k?.(),S?.(),removeEventListener("pagehide",I),w()}}}export{_ as a,C as b,V as c,D as d,F as e,W as f,K as g,oe as h};