@tinkerlandai/indiana-sdk 0.6.0 → 0.6.2

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.
@@ -0,0 +1,4 @@
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 q=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||q([...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 O="__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(O);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 j(e,t){return!!z(e,t)}function te(){let e=new URL(location.href);e.searchParams.delete(O),history.replaceState(history.state,"",e.href)}/*!
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 se(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})}},N=()=>{m.url=location.href,m.attributes={...W(a,location),...o}};function H(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 M(i,u){let p=e.configuration?.snapshot?.generation;s=i;let y=e.navigate??(v=>location.replace(v)),J=e.navigateDelay??(e.navigate?0:100),Y=e.maxNavigateDelay??1e3;Promise.all([Promise.race([u,new Promise(v=>setTimeout(v,Y))]),new Promise(v=>setTimeout(v,J))]).then(()=>{!d&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===p)&&y(i)})}function h(){if(!(!c||d||e.configuration&&!e.configuration.fresh||j(t,e.environmentId))){N();for(let i of c.experiments){if(H(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&&M(p,w())}break}}}}let b="",B=()=>{location.href!==b&&(b=location.href,s="",h())},S,k;function G(){S??=D(B),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)}))}),G(),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,$ as e,z as f,te as g,F as h,W as i,K as j,se as k};