plugeen 0.0.10 → 0.0.11
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.
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/plugeen.global.js +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -56,6 +56,8 @@ type ClientModules = (typeof modules)[number];
|
|
|
56
56
|
type SdkOptions = {
|
|
57
57
|
apiUrl: string;
|
|
58
58
|
debug: boolean;
|
|
59
|
+
environment?: string;
|
|
60
|
+
service?: string;
|
|
59
61
|
} & Record<ClientModules, boolean>;
|
|
60
62
|
type TrackFn = (event: string, data: Record<string, unknown>) => void;
|
|
61
63
|
type TupleResponse<T> = Promise<[T, null] | [null, unknown]>;
|
package/dist/index.d.ts
CHANGED
|
@@ -56,6 +56,8 @@ type ClientModules = (typeof modules)[number];
|
|
|
56
56
|
type SdkOptions = {
|
|
57
57
|
apiUrl: string;
|
|
58
58
|
debug: boolean;
|
|
59
|
+
environment?: string;
|
|
60
|
+
service?: string;
|
|
59
61
|
} & Record<ClientModules, boolean>;
|
|
60
62
|
type TrackFn = (event: string, data: Record<string, unknown>) => void;
|
|
61
63
|
type TupleResponse<T> = Promise<[T, null] | [null, unknown]>;
|
package/dist/plugeen.global.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/* plugeen v0.1.0 | https://plugeen.app */
|
|
2
|
-
"use strict";var plugeen=(()=>{function S(){if(typeof document>"u")return null;let
|
|
2
|
+
"use strict";var plugeen=(()=>{function S(){if(typeof document>"u")return null;let e=document.currentScript;if(!e){let o=document.getElementsByTagName("script");for(let i of Array.from(o))if(i.src&&(i.src.includes("/plugeen.global")||i.src.includes("/plugeen."))){e=i;break}}if(!e)return null;let r={},t=e.getAttribute("data-api-key")??void 0;r.apiUrl=e.getAttribute("data-api-url")??e.getAttribute("data-service")??"",r.analytics=e.getAttribute("data-analytics")==="true",r.webVitals=e.getAttribute("data-web-vitals")==="true",r.errors=e.getAttribute("data-errors")==="true";let n=e.getAttribute("data-debug");return n!==null&&(r.debug=n==="true"||n===""),{apiKey:t,...r}}function h(e){return e?{log:(...r)=>console.log("[plugeen]",...r),warn:(...r)=>console.warn("[plugeen]",...r),error:(...r)=>console.error("[plugeen]",...r)}:{log:()=>{},warn:()=>{},error:()=>{}}}function f(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let r=Math.floor(Math.random()*16);return(e==="x"?r:r&3|8).toString(16)})}var p="plugeen_anon_id",g="plugeen_session_id",d="plugeen_session_ts";var P=18e5,l={};function E(){try{let e=localStorage.getItem(p);return e||(e=`anon_${f()}`,localStorage.setItem(p,e)),e}catch{return l[p]||(l[p]=`anon_${f()}`),l[p]}}function I(e){try{localStorage.setItem(p,e)}catch{l[p]=e}}function m(){try{let e=sessionStorage.getItem(g),r=sessionStorage.getItem(d);if(e&&r&&Date.now()-parseInt(r,10)<P)return sessionStorage.setItem(d,String(Date.now())),e;sessionStorage.removeItem(g),sessionStorage.removeItem(d);let t=`sess_${f()}`;return sessionStorage.setItem(g,t),sessionStorage.setItem(d,String(Date.now())),t}catch{let e=l[g],r=l[d];if(e&&r&&Date.now()-parseInt(r,10)<P)return l[d]=String(Date.now()),e;let t=`sess_${f()}`;return l[g]=t,l[d]=String(Date.now()),t}}var k=e=>new Promise(r=>setTimeout(r,e)),w=class{constructor(r,t,n=3){this.baseUrl=r;this.apiKey=t;this.maxRetries=n}headers(r){let t={Authorization:`Bearer ${this.apiKey}`,"x-identity-id":E(),"x-session-id":m()};return r!=="GET"&&(t["Content-Type"]="application/json"),t}async request(r,{attempt:t=0,method:n,body:o,searchParams:i}){let s=i?`?${new URLSearchParams(i).toString()}`:"",u=`${this.baseUrl}${r}${s}`;try{let a=await fetch(u,{method:n,headers:this.headers(n),credentials:"omit",body:o?JSON.stringify(o):void 0});if(a.status===401||a.status===404)return[null,a.status];if((a.status>=500||a.status===429)&&t<this.maxRetries){let c=.85+Math.random()*.3;return await k(500*2**t*c),this.request(r,{body:o,attempt:t+1,method:n})}if(a.status>=200&&a.status<300)try{return[(await a.json()).data,null]}catch{return[null,"Failed to parse json"]}return[null,"Error"]}catch(a){if(a instanceof TypeError&&t<this.maxRetries){let c=.85+Math.random()*.3;return await k(500*2**t*c),this.get(r,{attempt:t+1})}return[null,a]}}async post(r,t,n){return this.request(r,{attempt:n?.attempt??0,body:t,method:"POST"})}async get(r,t){return this.request(r,{attempt:t?.attempt??0,method:"GET"})}beacon(r,t){if(typeof navigator>"u"||!navigator.sendBeacon)return!1;try{let n=new Blob([JSON.stringify(t)],{type:"application/json"});return navigator.sendBeacon(`${this.baseUrl}${r}`,n)}catch{return!1}}};function T(e,r){if(typeof window>"u")return;r.log("Analytics module started");let t=Date.now(),n=0,o=window.location.href,i=()=>{n++,e.post("/v1/analytics",{event:"page_view",url:window.location.href,title:document.title,sessionId:m(),referrer:document.referrer||void 0,screenWidth:window.innerWidth,screenHeight:window.innerHeight})},s=(c=!1)=>{let y={event:"page_exit",url:window.location.href,title:document.title,sessionId:m(),referrer:document.referrer||void 0,screenWidth:window.innerWidth,screenHeight:window.innerHeight,metadata:{timeOnPage:Math.round((Date.now()-t)/1e3),pageCount:n}};c?e.beacon("/v1/analytics",y):e.post("/v1/analytics",y)},u=()=>{window.location.href!==o&&(s(),t=Date.now(),o=window.location.href,i())},a=c=>{let y=history[c].bind(history);history[c]=(...F)=>{y(...F),u()}};a("pushState"),a("replaceState"),window.addEventListener("popstate",u),window.addEventListener("beforeunload",()=>s(!0)),document.addEventListener("visibilitychange",()=>document.visibilityState==="hidden"&&s(!0)),i()}var V=["chrome-extension://","moz-extension://","safari-extension://","edge-extension://"];function v(e){if(!e)return!1;let r=e.toLowerCase();return V.some(t=>r.includes(t))}function M(e,r){typeof window>"u"||(r.log("Errors module started"),window.addEventListener("error",t=>{v(t.filename)||v(t.error?.stack)||t.error===null&&t.message==="Script error."||e.post("/v1/logs",{message:t.message||"Unknown Error",level:"error",url:window.location.href,source:"client",metadata:{stack:t.error?.stack,type:t.error?.name}})}),window.addEventListener("unhandledrejection",t=>{let{reason:n}=t;if(v(n?.stack))return;let o="Unknown Error",i;n instanceof Error?(o=n.message,i=n.stack):typeof n=="string"?o=n:n!==null&&typeof n=="object"&&"message"in n&&(o=String(n.message)),e.post("/v1/logs",{message:o,url:window.location.href,source:"client",level:"error",metadata:{stack:i,type:"UnhandledRejection"}})}))}function x(){return performance.getEntriesByType("navigation")[0]?.activationStart??0}function H(){let e=performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e}function b(e,r,t){try{if(!PerformanceObserver.supportedEntryTypes.includes(e))return;let n=new PerformanceObserver(o=>{Promise.resolve().then(()=>r(o.getEntries()))});return n.observe({type:e,buffered:!0,...t??{}}),n}catch{return}}function D(e){let r=new Set;b("paint",t=>{for(let n of t)if(n.name==="first-contentful-paint"&&!r.has("first-contentful-paint")){r.add("first-contentful-paint");let o=Math.max(n.startTime-x(),0);e("first-contentful-paint",Math.round(o))}})}function N(e){let r=!1,t=b("largest-contentful-paint",o=>{if(r)return;let i=o[o.length-1];if(i){let s=Math.max(i.startTime-x(),0);e("largest-contentful-paint",Math.round(s))}});if(!t)return;let n=()=>{if(r)return;r=!0;let o=t.takeRecords();if(o.length>0){let i=o[o.length-1],s=Math.max(i.startTime-x(),0);e("largest-contentful-paint",Math.round(s))}t.disconnect()};for(let o of["keydown","click","visibilitychange"])addEventListener(o,n,{capture:!0,once:!0})}function $(e){let r=0,t=[],n=0;b("layout-shift",o=>{for(let i of o){let s=i;if(s.hadRecentInput)continue;let u=t[t.length-1],a=t[0];if(t.length>0&&u&&a&&s.startTime-u.startTime<1e3&&s.startTime-a.startTime<5e3?(r+=s.value,t.push(s)):(r=s.value,t=[s]),r>n){n=r;let c=Math.round(n*1e4)/1e4;e("cumulative-layout-shift",c)}}})}function j(e){let r=H();if(!r)return;let t=Math.max(r.responseStart-x(),0);e("time-to-first-byte",Math.round(t))}function W(e){let r=new Map,t=0;b("event",n=>{for(let o of n){let i=o;if(!i.interactionId)continue;let s=r.get(i.interactionId)??0;i.duration>s&&(r.set(i.interactionId,i.duration),i.duration>t&&(t=i.duration,e("interaction-to-next-paint",Math.round(i.duration))))}},{durationThreshold:40})}function B(e){if(typeof requestAnimationFrame>"u")return;let r=0,t=2e3,n=performance.now(),o=()=>{r++,performance.now()-n<t?requestAnimationFrame(o):e("frames-per-second",Math.round(r/t*1e3))};document.readyState==="complete"?requestAnimationFrame(o):window.addEventListener("load",()=>requestAnimationFrame(o),{once:!0})}function L(){if(!(typeof window<"u")||!(typeof PerformanceObserver<"u"))return[];let t=new Map;return D((n,o)=>t.set(n,o)),N((n,o)=>t.set(n,o)),$((n,o)=>t.set(n,o)),j((n,o)=>t.set(n,o)),W((n,o)=>t.set(n,o)),B((n,o)=>t.set(n,o)),Array.from(t).map(([n,o])=>({name:n,value:o}))}function O(e,r){r.log("Web Vitals module started"),e.post("/v1/web-vitals",{url:window.location.href,metrics:L()})}function C(e,r){return r.log("Identities module started"),{async identify(t,n){let o=await e.post("/v1/identities",{body:{...n,id:t}});return I(t),o}}}function _(e,r){return r.log("Events module started"),{track:async(t,n={})=>e.post("/v1/events",{name:t,data:n,source:"sdk"})}}function R(e,r){return r.log("Feature Flags module started"),{get:async t=>e.get("/v1/feature-flags",{searchParams:{key:t}})}}function U(e,r){return r.log("Logs module started"),{send:t=>e.post("/v1/logs",t)}}function A(e,r){let t={apiUrl:"https://dev.plugeen.app/api",debug:!1,analytics:!1,webVitals:!1,errors:!1,...r},n=h(t.debug);if(!e)throw new TypeError("[plugeen] data-api-key is required");let o=new w(t.apiUrl,e),i={track:_(o,n).track,identify:C(o,n).identify,featureFlags:R(o,n),logs:U(o,n)};return typeof window<"u"&&(t.analytics&&T(o,n),t.webVitals&&O(o,n),t.errors&&M(o,n)),n.log(`Running on ${typeof window>"u"?"server":"client"} side`),i}function q(){let e=S(),r=h(!!e?.debug);if(e){if(!e.apiKey)return r.warn("Data-api-key is required.")}else return r.warn("Failed to start script");r.log("Started");let t=A(e.apiKey,e);return window.plugeen=t,t}window.plugeen||q();})();
|