UNPKG

@expofp/floorplan

Version:

Interactive floor plan library for expos and events

2 lines (1 loc) 1.68 kB
const _="efp-telemetry",M=3e5,N=1e3;function g(s=_){return{get(){try{const r=localStorage.getItem(s);return r?JSON.parse(r):null}catch{return null}},set(r){try{localStorage.setItem(s,JSON.stringify(r))}catch(n){console.error("Failed to persist telemetry data",n)}},clear(){try{localStorage.removeItem(s)}catch(r){console.error("Failed to clear telemetry data",r)}}}}function R(s){const r=s.headers.get("Retry-After");if(!r)return 0;let n=0;const a=Number(r);if(Number.isFinite(a))n=a*1e3;else{const o=Date.parse(r);isNaN(o)||(n=Math.max(0,o-Date.now()))}return Math.min(n,3e5)}export function createTelemetry(s){const{url:r,expo:n,expoId:a,storage:o=g()}=s;let c=s.kioskId??"";function l(){const e=o.get();return e?(e.expo=n,e.expoId=a,e.kioskId=c,e):{expo:n,expoId:a,kioskId:c,items:[]}}function y(e){c=e}let u=!1,f=!1,d=0;async function m(){if(u){f=!0;return}u=!0;do{if(f=!1,performance.now()<d)break;let e=null;try{if(e=l(),e.items.length===0)break;o.clear();const t=JSON.stringify(e),p=new TextEncoder().encode(t).byteLength,i=await fetch(r,{method:"POST",body:t,headers:{"Content-Type":"application/json"},credentials:"omit",keepalive:p<63e3});if(!i.ok){if(i.status===429||i.status===503){const h=R(i);h>0&&(d=performance.now()+h)}E(e),console.error(`Failed to send telemetry: HTTP ${i.status}`)}}catch(t){e&&E(e),console.error("Failed to send telemetry",t)}}while(f);u=!1}function E(e){const t=l();t.items=[...e.items,...t.items],t.items.length>1e3&&(t.items=t.items.slice(-1e3)),o.set(t)}function T(e){const t=l();t.items.push(e),t.items.length>1e3&&(t.items=t.items.slice(-1e3)),o.set(t)}async function S(e){T(e),await m()}return{enqueue:T,send:S,flush:m,setKioskId:y}}