Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@heimdallr-sdk/utils

Package Overview
Dependencies
Maintainers
0
Versions
21
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@heimdallr-sdk/utils - npm Package Compare versions

Comparing version 0.0.19 to 0.0.20

2

dist/utils.iife.js

@@ -1,1 +0,1 @@

var HEIMDALLR_UTILS=function(e){"use strict";var t;(t||(t={})).NAME="@heimdallr-sdk";var n,r,o,c,s,i,a,u,l,E,f,O,p,R,C,S,d,g,x,h,T,m,D,y,I,L,A,U,N,$,b,w,M,P,H="[".concat(t.NAME,"]:");(r=n||(n={})).FATAL="fatal",r.ERROR="error",r.WARN="warn",r.INFO="info",r.DEBUG="debug",(c=o||(o={})).SESSION="HEIMDALLR_SDK_SESSION_ID",c.APP="HEIMDALLR_SDK_APP_ID",(i=s||(s={})).GET="GET",i.POST="POST",i.PUT="PUT",i.DELETE="DELETE",(u=a||(a={})).API="api",u.DOM="dom",u.PERFORMANCE="performance",u.ROUTE="route",u.ERROR="error",u.CONSOLE="console",u.CUSTOMER="customer",u.VUE="vue",u.LIFECYCLE="lifeCycle",u.EXTEND="extend",u.RECORD="record",(E=l||(l={})).CODEERROR="code",E.RESOURCEERROR="resource",E.UNHANDLEDREJECTION="unhandledrejection",E.PAGECRASH="pageCrash",(O=f||(f={})).BEACON="beacon",O.IMG="img",O.GET="get",O.POST="post",(p||(p={})).CLICK="click",(C=R||(R={})).LOG="log",C.INFO="info",C.WARN="warn",C.ERROR="error",C.ASSERT="assert",(d=S||(S={})).FETCH="fetch",d.XHR="xhr",(x=g||(g={})).FMP="fmp",x.FPS="fps",x.BASIC="basic",x.VITALS="vitals",x.RESOURCE="resource",(T=h||(h={})).HASH="hash",T.HISTORY="history",(m||(m={})).CUSTOMER="customer",(y=D||(D={})).LOCAL="local",y.SESSION="session",y.COOKIE="cookie",y.GLOBAL="global",(L=I||(I={})).LOAD="enter",L.UNLOAD="leave",(U=A||(A={})).MOBILE="mobile",U.PC="pc",($=N||(N={})).BROWSER="browser",$.NODE="nodejs",$.WECHAT="wechat",(w=b||(b={})).ROUTE="Route",w.CLICK="UI.Click",w.CONSOLE="Console",w.XHR="Xhr",w.FETCH="Fetch",w.UNHANDLEDREJECTION="Unhandledrejection",w.RESOURCE="Resource",w.CODE_ERROR="CodeError",w.CUSTOMER="Customer",w.FRAMEWORK="Framework",w.LIFECYCLE="LifeCycle",w.CRASH="Crash",(P=M||(M={})).API="Api",P.ROUTE="Route",P.CLICK="UI.Click",P.ERROR="Error",P.LIFECYCLE="LifeCycle",P.CUSTOMER="Customer";var F=Object.defineProperty,k=Object.getOwnPropertySymbols,j=Object.prototype.hasOwnProperty,v=Object.prototype.propertyIsEnumerable,B=(e,t,n)=>t in e?F(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;function Y(e){return Object.keys(e).reduce(((t,n)=>{const r=e[n];return t+=`${t?"&":""}${n}=${"object"==typeof r?JSON.stringify(r):r}`}),"")}function _(e){let t=null;switch(e){case D.LOCAL:t=localStorage;break;case D.SESSION:t=sessionStorage}return t}function G(e){if(!e)return"";const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]*)(;|$)`));return null!=t?decodeURIComponent(t[2]):""}function J(e,t,n){return new Promise(((r,o)=>{try{const o=new XMLHttpRequest;o.open(e,t),o.setRequestHeader("Content-Type","application/json;charset=UTF-8"),e===s.POST?(o.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),o.send(n)):o.send(),o.onreadystatechange=()=>{o.readyState==XMLHttpRequest.DONE&&200==o.status?r(JSON.parse(o.response)):new Error(o.response)}}catch(e){o(e)}}))}return e.beacon=function(e,t){const n=new FormData;return Object.keys(t).forEach((e=>{let r=t[e];"string"!=typeof r&&(r=JSON.stringify(r)),n.append(e,r)})),navigator.sendBeacon(e,n)},e.countBytes=function(e){return(new TextEncoder).encode(e).length},e.delCookie=function(e){if(!e)return;const t=new Date;t.setTime(t.getTime()-1);const n=G(e);null!=n&&(document.cookie=`${e}=${n};expires=${t.toUTCString()}`)},e.formatDate=(e="Y-M-D h:m:s",t=Date.now())=>{const n=new Date(t||Date.now()),r={Y:`${n.getFullYear()}`,M:`${n.getMonth()+1}`,D:`${n.getDate()}`,h:n.getHours(),m:n.getMinutes(),s:n.getSeconds()},o=e=>e>=10?e:"0"+e;return(e||"Y-M-D h:m:s").replace("Y",r.Y).replace("M",r.M).replace("D",r.D).replace("h",o(r.h)).replace("m",o(r.m)).replace("s",o(r.s))},e.formatDecimal=function(e,t){if(!e)return e;let n=e.toString();const r=n.indexOf(".");return n=-1!==r?n.substring(0,t+r+1):n.substring(0),parseFloat(n)},e.formateUrlPath=(e,t)=>`${/^http(s|):\/\//.test(e||"")?e:`//${(e||"").replace(/^http(s|):\/\//,"")}`}/${"/"===(t||"")[0]?t.substring(1):t}`,e.generateUUID=function(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){const n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?n:3&n|8).toString(16)}))},e.get=function(e,t){return J(s.GET,`${e}${-1===e.indexOf("?")?"?":""}${Y(t)}`,"")},e.getCookie=G,e.getDeepPropByDot=function(e,t){if(!e||!t)return null;const n=((e,t)=>{for(var n in t||(t={}))j.call(t,n)&&B(e,n,t[n]);if(k)for(var n of k(t))v.call(t,n)&&B(e,n,t[n]);return e})({},t),r=e.split(".");let o=n;for(const e of r){const t=o[e];if(!t)return console.warn(H,`${e} does not exist`),null;o=t}return o},e.getStore=function(e,t,n=!0){if(!e||!t)return"";const r=_(e);if(!r)return"";let o="";try{const e=t.split("."),[c]=e;o=r.getItem(c),n&&(o=JSON.parse(o),e.length>1&&(o=e.slice(1).reduce(((e,t)=>e[t]),o)))}catch(e){console.error(H,e)}return o},e.getUrlPath=e=>{const t=`${(e||"").replace(/^http(s|):/,"").split("?")[0]}`,n=t.length-1;return"/"===t[n]?t.substring(0,n):t},e.hasConsole=()=>"undefined"!=typeof console,e.imgRequest=function(e,t){let n=new Image;const r=-1===e.indexOf("?")?"?":"&";n.src=`${e}${r}data=${encodeURIComponent(JSON.stringify(t))}`,n=null},e.obj2query=Y,e.post=function(e,t){return J(s.POST,e,Y(t))},e.replaceOld=function(e,t,n,r){if(void 0!==e&&(t in e||r)){const r=n(e[t]);"function"==typeof r&&(e[t]=r)}},e.setCookie=function(e,t,n){if(!e||!t||!n)return;const r=new Date;r.setTime(r.getTime()+24*n*60*60*1e3),document.cookie=`${e}=${encodeURIComponent(t)};expires=${r.toUTCString()}`},e.setStore=function(e,t,n){if(!t)return;const r=_(e);r&&r.setItem(t,JSON.stringify(n))},e.setUrlQuery=function(e,t={}){const n=[];return Object.keys(t).forEach((e=>{n.push(`${e}=${t[e]}`)})),`${e}${-1!==e.indexOf("?")?"&":"?"}${n.join("&")}`},e.splitStringByBytes=function(e,t){const n=(new TextEncoder).encode(e),r=new TextDecoder,o=[];let c=0;for(;c<n.length;){let e=c+t;for(;e>c&&128==(192&n[e]);)e--;o.push(r.decode(n.subarray(c,e))),c=e}return o},e.throttle=function(e,t){let n=!0;return function(...r){n&&(e.apply(this,r),n=!1,setTimeout((()=>{n=!0}),t))}},e.xhr=J,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
var HEIMDALLR_UTILS=function(e){"use strict";var t=Object.defineProperty,r=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable,s=(e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n;const E=e=>Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&");var R;(R||(R={})).NAME="@heimdallr-sdk";var a,O,c,i,C,l,S,u,T,p,I,L,d,A,U,f,x,D,N,y,g,P,h,m,H,M,F,$,w,b,B,_,j,G,k,v,K="[".concat(R.NAME,"]:");(O=a||(a={}))[O.FATAL=1]="FATAL",O[O.ERROR=2]="ERROR",O[O.WARN=3]="WARN",O[O.INFO=4]="INFO",O[O.DEBUG=5]="DEBUG",(i=c||(c={})).SESSION_ID="HEIMDALLR_SDK_SESSION_ID",i.USER_ID="HEIMDALLR_SDK_USER_ID",i.APP="HEIMDALLR_SDK_APP_ID",(l=C||(C={})).GET="GET",l.POST="POST",l.PUT="PUT",l.DELETE="DELETE",(u=S||(S={}))[u.LIFECYCLE=1]="LIFECYCLE",u[u.ERROR=2]="ERROR",u[u.PERFORMANCE=3]="PERFORMANCE",u[u.API=4]="API",u[u.DOM=5]="DOM",u[u.ROUTE=6]="ROUTE",u[u.CONSOLE=7]="CONSOLE",u[u.RECORD=8]="RECORD",u[u.VUE=9]="VUE",u[u.CUSTOMER=10]="CUSTOMER",u[u.EXTEND=11]="EXTEND",(p=T||(T={}))[p.CODEERROR=21]="CODEERROR",p[p.RESOURCEERROR=22]="RESOURCEERROR",p[p.UNHANDLEDREJECTION=23]="UNHANDLEDREJECTION",p[p.PAGECRASH=24]="PAGECRASH",(L=I||(I={}))[L.BEACON=1]="BEACON",L[L.IMG=2]="IMG",L[L.GET=3]="GET",L[L.POST=4]="POST",(A=d||(d={}))[A.CLICK=51]="CLICK",(f=U||(U={})).LOG="log",f.INFO="info",f.WARN="warn",f.ERROR="error",f.ASSERT="assert",(D=x||(x={}))[D.XHR=41]="XHR",D[D.FETCH=42]="FETCH",(y=N||(N={}))[y.FMP=31]="FMP",y[y.FPS=32]="FPS",y[y.BASIC=33]="BASIC",y[y.VITALS=34]="VITALS",y[y.RESOURCE=35]="RESOURCE",(P=g||(g={}))[P.HASH=61]="HASH",P[P.HISTORY=62]="HISTORY",(m=h||(h={}))[m.CUSTOMER=111]="CUSTOMER",(M=H||(H={})).LOCAL="local",M.SESSION="session",M.COOKIE="cookie",M.GLOBAL="global",($=F||(F={}))[$.LOAD=11]="LOAD",$[$.UNLOAD=12]="UNLOAD",(b=w||(w={}))[b.MOBILE=1]="MOBILE",b[b.PC=2]="PC",(_=B||(B={}))[_.BROWSER=1]="BROWSER",_[_.WECHAT=2]="WECHAT",_[_.NODE=3]="NODE",(G=j||(j={}))[G.ROUTE=11]="ROUTE",G[G.CLICK=12]="CLICK",G[G.CONSOLE=13]="CONSOLE",G[G.XHR=14]="XHR",G[G.FETCH=15]="FETCH",G[G.UNHANDLEDREJECTION=16]="UNHANDLEDREJECTION",G[G.RESOURCE=17]="RESOURCE",G[G.CODE_ERROR=18]="CODE_ERROR",G[G.CUSTOMER=19]="CUSTOMER",G[G.FRAMEWORK=20]="FRAMEWORK",G[G.LIFECYCLE=21]="LIFECYCLE",G[G.CRASH=22]="CRASH",(v=k||(k={}))[v.API=21]="API",v[v.ROUTE=22]="ROUTE",v[v.CLICK=23]="CLICK",v[v.ERROR=24]="ERROR",v[v.LIFECYCLE=25]="LIFECYCLE",v[v.CUSTOMER=26]="CUSTOMER";const W=e=>{let t=null;switch(e){case H.LOCAL:t=localStorage;break;case H.SESSION:t=sessionStorage}return t},J=e=>{if(!e)return"";const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]*)(;|$)`));return null!=t?decodeURIComponent(t[2]):""},X=(e,t,r)=>new Promise(((n,o)=>{const s=new XMLHttpRequest;s.open(e,t,!0),e===C.POST&&("string"==typeof r||r instanceof URLSearchParams?s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):s.setRequestHeader("Content-Type","application/json;charset=UTF-8")),s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE){const e=(e=>{const t={};return e.trim().split(/[\r\n]+/).forEach((e=>{const[r,n]=e.split(": ");t[r]=n})),t})(s.getAllResponseHeaders());if(s.status>=200&&s.status<300)try{const t=s.responseText?JSON.parse(s.responseText):null;n({status:s.status,statusText:s.statusText,headers:e,data:t})}catch(e){o(new Error(`Failed to parse response: ${s.responseText}`))}else o({status:s.status,statusText:s.statusText,headers:e,data:s.responseText})}},s.onerror=()=>{o(new Error("Network error"))};try{e===C.POST?"string"==typeof r||r instanceof URLSearchParams?s.send(r):s.send(JSON.stringify(r)):s.send()}catch(e){o(e)}}));return e.beacon=(e,t)=>{if(!e||"string"!=typeof e)return console.error("Invalid URL"),!1;if(!t||"object"!=typeof t)return console.error("Invalid data"),!1;const r=new FormData;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let n=t[e];"string"==typeof n||n instanceof Blob||(n=JSON.stringify(n)),r.append(e,n)}return navigator.sendBeacon(e,r)},e.countBytes=e=>(new TextEncoder).encode(e).length,e.delCookie=e=>{if(!e)return;const t=new Date;t.setTime(t.getTime()-1);const r=J(e);null!=r&&(document.cookie=`${e}=${r};expires=${t.toUTCString()}`)},e.formatDecimal=(e,t)=>!isFinite(e)||isNaN(e)||!Number.isInteger(t)||t<0?e:parseFloat(e.toFixed(t)),e.formateUrlPath=(e,t)=>`${/^http(s|):\/\//.test(e||"")?e:`//${(e||"").replace(/^http(s|):\/\//,"")}`}/${"/"===(t||"")[0]?t.substring(1):t}`,e.generateUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),e.get=(e,t)=>{const r=E(t),n=e.includes("?")?"&":"?";return X(C.GET,`${e}${n}${r}`,null)},e.getCookie=J,e.getDeepPropByDot=(e,t)=>{if(!e||!t)return null;const E=((e,t)=>{for(var E in t||(t={}))n.call(t,E)&&s(e,E,t[E]);if(r)for(var E of r(t))o.call(t,E)&&s(e,E,t[E]);return e})({},t),R=e.split(".");let a=E;for(const e of R){const t=a[e];if(!t)return null;a=t}return a},e.getStore=(e,t,r=!0)=>{if(!e||!t)return"";const n=W(e);if(!n)return"";let o="";try{const e=t.split("."),[s]=e;o=n.getItem(s),r&&(o=JSON.parse(o),e.length>1&&(o=e.slice(1).reduce(((e,t)=>e[t]),o)))}catch(e){console.error(K,e)}return o},e.getUrlPath=e=>{try{const{pathname:t}=new URL(e);return t.endsWith("/")&&t.length>1?t.slice(0,-1):t}catch(e){return""}},e.hasConsole=()=>"undefined"!=typeof console,e.imgRequest=(e,t)=>{const r=E(t),n=e.includes("?")?"&":"?",o=`${e}${n}${r}`,s=new Image;s.src=o,setTimeout((()=>{s.src=""}),0)},e.obj2query=E,e.post=(e,t)=>X(C.POST,e,t),e.replaceOld=(e,t,r,n)=>{if(void 0!==e&&(t in e||n)){const n=r(e[t]);"function"==typeof n&&(e[t]=n)}},e.setCookie=(e,t,r)=>{if(!e||!t||!r)return;const n=new Date;n.setTime(n.getTime()+24*r*60*60*1e3),document.cookie=`${e}=${encodeURIComponent(t)};expires=${n.toUTCString()}`},e.setStore=(e,t,r)=>{if(!t)return;const n=W(e);n&&n.setItem(t,JSON.stringify(r))},e.setUrlQuery=(e,t={})=>{const r=[];return Object.keys(t).forEach((e=>{r.push(`${e}=${t[e]}`)})),`${e}${-1!==e.indexOf("?")?"&":"?"}${r.join("&")}`},e.splitStringByBytes=(e,t)=>{const r=(new TextEncoder).encode(e),n=new TextDecoder,o=[];let s=0;for(;s<r.length;){let e=s+t;for(;e>s&&128==(192&r[e]);)e--;o.push(n.decode(r.subarray(s,e))),s=e}return o},e.throttle=(e,t)=>{let r=0;return function(...n){const o=Date.now();o-r>=t&&(r=o,e.apply(this,n))}},e.xhr=X,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.HEIMDALLR_UTILS = {}));
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.HEIMDALLR_UTILS = {}));
})(this, (function (exports) { 'use strict';
var SDK;
(function(SDK2) {
SDK2["NAME"] = "@heimdallr-sdk";
})(SDK || (SDK = {}));
var TAG = "[".concat(SDK.NAME, "]:");
var BreadcrumbLevel;
(function(BreadcrumbLevel2) {
BreadcrumbLevel2["FATAL"] = "fatal";
BreadcrumbLevel2["ERROR"] = "error";
BreadcrumbLevel2["WARN"] = "warn";
BreadcrumbLevel2["INFO"] = "info";
BreadcrumbLevel2["DEBUG"] = "debug";
})(BreadcrumbLevel || (BreadcrumbLevel = {}));
var StoreKeyType;
(function(StoreKeyType2) {
StoreKeyType2["SESSION"] = "HEIMDALLR_SDK_SESSION_ID";
StoreKeyType2["APP"] = "HEIMDALLR_SDK_APP_ID";
})(StoreKeyType || (StoreKeyType = {}));
var MethodTypes;
(function(MethodTypes2) {
MethodTypes2["GET"] = "GET";
MethodTypes2["POST"] = "POST";
MethodTypes2["PUT"] = "PUT";
MethodTypes2["DELETE"] = "DELETE";
})(MethodTypes || (MethodTypes = {}));
var EventTypes;
(function(EventTypes2) {
EventTypes2["API"] = "api";
EventTypes2["DOM"] = "dom";
EventTypes2["PERFORMANCE"] = "performance";
EventTypes2["ROUTE"] = "route";
EventTypes2["ERROR"] = "error";
EventTypes2["CONSOLE"] = "console";
EventTypes2["CUSTOMER"] = "customer";
EventTypes2["VUE"] = "vue";
EventTypes2["LIFECYCLE"] = "lifeCycle";
EventTypes2["EXTEND"] = "extend";
EventTypes2["RECORD"] = "record";
})(EventTypes || (EventTypes = {}));
var BrowserErrorTypes;
(function(BrowserErrorTypes2) {
BrowserErrorTypes2["CODEERROR"] = "code";
BrowserErrorTypes2["RESOURCEERROR"] = "resource";
BrowserErrorTypes2["UNHANDLEDREJECTION"] = "unhandledrejection";
BrowserErrorTypes2["PAGECRASH"] = "pageCrash";
})(BrowserErrorTypes || (BrowserErrorTypes = {}));
var BrowserReportType;
(function(BrowserReportType2) {
BrowserReportType2["BEACON"] = "beacon";
BrowserReportType2["IMG"] = "img";
BrowserReportType2["GET"] = "get";
BrowserReportType2["POST"] = "post";
})(BrowserReportType || (BrowserReportType = {}));
var DomTypes;
(function(DomTypes2) {
DomTypes2["CLICK"] = "click";
})(DomTypes || (DomTypes = {}));
var ConsoleTypes;
(function(ConsoleTypes2) {
ConsoleTypes2["LOG"] = "log";
ConsoleTypes2["INFO"] = "info";
ConsoleTypes2["WARN"] = "warn";
ConsoleTypes2["ERROR"] = "error";
ConsoleTypes2["ASSERT"] = "assert";
})(ConsoleTypes || (ConsoleTypes = {}));
var HttpTypes;
(function(HttpTypes2) {
HttpTypes2["FETCH"] = "fetch";
HttpTypes2["XHR"] = "xhr";
})(HttpTypes || (HttpTypes = {}));
var PerTypes;
(function(PerTypes2) {
PerTypes2["FMP"] = "fmp";
PerTypes2["FPS"] = "fps";
PerTypes2["BASIC"] = "basic";
PerTypes2["VITALS"] = "vitals";
PerTypes2["RESOURCE"] = "resource";
})(PerTypes || (PerTypes = {}));
var RouteTypes;
(function(RouteTypes2) {
RouteTypes2["HASH"] = "hash";
RouteTypes2["HISTORY"] = "history";
})(RouteTypes || (RouteTypes = {}));
var CustomerTypes;
(function(CustomerTypes2) {
CustomerTypes2["CUSTOMER"] = "customer";
})(CustomerTypes || (CustomerTypes = {}));
var StoreType;
(function(StoreType2) {
StoreType2["LOCAL"] = "local";
StoreType2["SESSION"] = "session";
StoreType2["COOKIE"] = "cookie";
StoreType2["GLOBAL"] = "global";
})(StoreType || (StoreType = {}));
var PageLifeType;
(function(PageLifeType2) {
PageLifeType2["LOAD"] = "enter";
PageLifeType2["UNLOAD"] = "leave";
})(PageLifeType || (PageLifeType = {}));
var DeviceType;
(function(DeviceType2) {
DeviceType2["MOBILE"] = "mobile";
DeviceType2["PC"] = "pc";
})(DeviceType || (DeviceType = {}));
var PlatformTypes;
(function(PlatformTypes2) {
PlatformTypes2["BROWSER"] = "browser";
PlatformTypes2["NODE"] = "nodejs";
PlatformTypes2["WECHAT"] = "wechat";
})(PlatformTypes || (PlatformTypes = {}));
var BrowserBreadcrumbTypes;
(function(BrowserBreadcrumbTypes2) {
BrowserBreadcrumbTypes2["ROUTE"] = "Route";
BrowserBreadcrumbTypes2["CLICK"] = "UI.Click";
BrowserBreadcrumbTypes2["CONSOLE"] = "Console";
BrowserBreadcrumbTypes2["XHR"] = "Xhr";
BrowserBreadcrumbTypes2["FETCH"] = "Fetch";
BrowserBreadcrumbTypes2["UNHANDLEDREJECTION"] = "Unhandledrejection";
BrowserBreadcrumbTypes2["RESOURCE"] = "Resource";
BrowserBreadcrumbTypes2["CODE_ERROR"] = "CodeError";
BrowserBreadcrumbTypes2["CUSTOMER"] = "Customer";
BrowserBreadcrumbTypes2["FRAMEWORK"] = "Framework";
BrowserBreadcrumbTypes2["LIFECYCLE"] = "LifeCycle";
BrowserBreadcrumbTypes2["CRASH"] = "Crash";
})(BrowserBreadcrumbTypes || (BrowserBreadcrumbTypes = {}));
var WxBreadcrumbTypes;
(function(WxBreadcrumbTypes2) {
WxBreadcrumbTypes2["API"] = "Api";
WxBreadcrumbTypes2["ROUTE"] = "Route";
WxBreadcrumbTypes2["CLICK"] = "UI.Click";
WxBreadcrumbTypes2["ERROR"] = "Error";
WxBreadcrumbTypes2["LIFECYCLE"] = "LifeCycle";
WxBreadcrumbTypes2["CUSTOMER"] = "Customer";
})(WxBreadcrumbTypes || (WxBreadcrumbTypes = {}));
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
const hasConsole = () => typeof console !== "undefined";
const formateUrlPath = (host, path) => `${/^http(s|):\/\//.test(host || "") ? host : `//${(host || "").replace(/^http(s|):\/\//, "")}`}/${(path || "")[0] === "/" ? path.substring(1) : path}`;
const getUrlPath = (url) => {
const path = `${(url || "").replace(/^http(s|):/, "").split("?")[0]}`;
const endIndex = path.length - 1;
return path[endIndex] === "/" ? path.substring(0, endIndex) : path;
};
function setUrlQuery(url, query = {}) {
const queryArr = [];
Object.keys(query).forEach((k) => {
queryArr.push(`${k}=${query[k]}`);
});
return `${url}${url.indexOf("?") !== -1 ? "&" : "?"}${queryArr.join("&")}`;
}
return a;
};
const hasConsole = () => typeof console !== "undefined";
const formateUrlPath = (host, path) => `${/^http(s|):\/\//.test(host || "") ? host : `//${(host || "").replace(/^http(s|):\/\//, "")}`}/${(path || "")[0] === "/" ? path.substring(1) : path}`;
const getUrlPath = (url) => {
try {
const { pathname } = new URL(url);
return pathname.endsWith("/") && pathname.length > 1 ? pathname.slice(0, -1) : pathname;
} catch (error) {
return "";
}
function getDeepPropByDot(keyPath, obj) {
if (!keyPath || !obj) {
};
const setUrlQuery = (url, query = {}) => {
const queryArr = [];
Object.keys(query).forEach((k) => {
queryArr.push(`${k}=${query[k]}`);
});
return `${url}${url.indexOf("?") !== -1 ? "&" : "?"}${queryArr.join("&")}`;
};
const getDeepPropByDot = (keyPath, obj) => {
if (!keyPath || !obj) {
return null;
}
const copyTarget = __spreadValues({}, obj);
const paths = keyPath.split(".");
let result = copyTarget;
for (const key of paths) {
const value = result[key];
if (!value) {
return null;
}
const copyTarget = __spreadValues({}, obj);
const paths = keyPath.split(".");
let result = copyTarget;
for (const key of paths) {
const value = result[key];
if (!value) {
console.warn(TAG, `${key} does not exist`);
return null;
}
result = value;
}
return result;
result = value;
}
function obj2query(data) {
return Object.keys(data).reduce((pre, cur) => {
const val = data[cur];
pre += `${pre ? "&" : ""}${cur}=${typeof val === "object" ? JSON.stringify(val) : val}`;
return pre;
}, "");
}
return result;
};
const obj2query = (params) => Object.keys(params).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join("&");
function generateUUID() {
let d = new Date().getTime();
const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
const r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == "x" ? r : r & 3 | 8).toString(16);
});
return uuid;
}
const formatDate = (format = "Y-M-D h:m:s", timestamp = Date.now()) => {
const date = new Date(timestamp || Date.now());
const dateInfo = {
Y: `${date.getFullYear()}`,
M: `${date.getMonth() + 1}`,
D: `${date.getDate()}`,
h: date.getHours(),
m: date.getMinutes(),
s: date.getSeconds()
};
const formatNumber = (n) => n >= 10 ? n : "0" + n;
const res = (format || "Y-M-D h:m:s").replace("Y", dateInfo.Y).replace("M", dateInfo.M).replace("D", dateInfo.D).replace("h", formatNumber(dateInfo.h)).replace("m", formatNumber(dateInfo.m)).replace("s", formatNumber(dateInfo.s));
return res;
};
function throttle(fn, delay) {
let canRun = true;
return function(...args) {
if (!canRun)
return;
const generateUUID = () => {
const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
return template.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === "x" ? r : r & 3 | 8;
return v.toString(16);
});
};
const throttle = (fn, delay) => {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn.apply(this, args);
canRun = false;
setTimeout(() => {
canRun = true;
}, delay);
};
}
function replaceOld(source, name, replacement, isForced) {
if (source === void 0)
return;
if (name in source || isForced) {
const original = source[name];
const wrapped = replacement(original);
if (typeof wrapped === "function") {
source[name] = wrapped;
}
}
}
function formatDecimal(num, decimal) {
if (!num) {
return num;
};
};
const replaceOld = (source, name, replacement, isForced) => {
if (source === void 0)
return;
if (name in source || isForced) {
const original = source[name];
const wrapped = replacement(original);
if (typeof wrapped === "function") {
source[name] = wrapped;
}
let str = num.toString();
const index = str.indexOf(".");
if (index !== -1) {
str = str.substring(0, decimal + index + 1);
} else {
str = str.substring(0);
}
return parseFloat(str);
}
function countBytes(str) {
const encoder = new TextEncoder();
return encoder.encode(str).length;
};
const formatDecimal = (num, decimal) => {
if (!isFinite(num) || isNaN(num)) {
return num;
}
function splitStringByBytes(str, maxBytes) {
const encoder = new TextEncoder();
const bytes = encoder.encode(str);
const decoder = new TextDecoder();
const chunks = [];
let start = 0;
while (start < bytes.length) {
let end = start + maxBytes;
while (end > start && (bytes[end] & 192) === 128) {
end--;
}
chunks.push(decoder.decode(bytes.subarray(start, end)));
start = end;
if (!Number.isInteger(decimal) || decimal < 0) {
return num;
}
return parseFloat(num.toFixed(decimal));
};
const countBytes = (str) => {
const encoder = new TextEncoder();
return encoder.encode(str).length;
};
const splitStringByBytes = (str, maxBytes) => {
const encoder = new TextEncoder();
const bytes = encoder.encode(str);
const decoder = new TextDecoder();
const chunks = [];
let start = 0;
while (start < bytes.length) {
let end = start + maxBytes;
while (end > start && (bytes[end] & 192) === 128) {
end--;
}
return chunks;
chunks.push(decoder.decode(bytes.subarray(start, end)));
start = end;
}
return chunks;
};
function getStoreIns(type) {
let store = null;
switch (type) {
case StoreType.LOCAL:
store = localStorage;
break;
case StoreType.SESSION:
store = sessionStorage;
break;
}
return store;
var SDK;
(function(SDK2) {
SDK2["NAME"] = "@heimdallr-sdk";
})(SDK || (SDK = {}));
var TAG = "[".concat(SDK.NAME, "]:");
var BreadcrumbLevel;
(function(BreadcrumbLevel2) {
BreadcrumbLevel2[BreadcrumbLevel2["FATAL"] = 1] = "FATAL";
BreadcrumbLevel2[BreadcrumbLevel2["ERROR"] = 2] = "ERROR";
BreadcrumbLevel2[BreadcrumbLevel2["WARN"] = 3] = "WARN";
BreadcrumbLevel2[BreadcrumbLevel2["INFO"] = 4] = "INFO";
BreadcrumbLevel2[BreadcrumbLevel2["DEBUG"] = 5] = "DEBUG";
})(BreadcrumbLevel || (BreadcrumbLevel = {}));
var StoreKeyType;
(function(StoreKeyType2) {
StoreKeyType2["SESSION_ID"] = "HEIMDALLR_SDK_SESSION_ID";
StoreKeyType2["USER_ID"] = "HEIMDALLR_SDK_USER_ID";
StoreKeyType2["APP"] = "HEIMDALLR_SDK_APP_ID";
})(StoreKeyType || (StoreKeyType = {}));
var MethodTypes;
(function(MethodTypes2) {
MethodTypes2["GET"] = "GET";
MethodTypes2["POST"] = "POST";
MethodTypes2["PUT"] = "PUT";
MethodTypes2["DELETE"] = "DELETE";
})(MethodTypes || (MethodTypes = {}));
var EventTypes;
(function(EventTypes2) {
EventTypes2[EventTypes2["LIFECYCLE"] = 1] = "LIFECYCLE";
EventTypes2[EventTypes2["ERROR"] = 2] = "ERROR";
EventTypes2[EventTypes2["PERFORMANCE"] = 3] = "PERFORMANCE";
EventTypes2[EventTypes2["API"] = 4] = "API";
EventTypes2[EventTypes2["DOM"] = 5] = "DOM";
EventTypes2[EventTypes2["ROUTE"] = 6] = "ROUTE";
EventTypes2[EventTypes2["CONSOLE"] = 7] = "CONSOLE";
EventTypes2[EventTypes2["RECORD"] = 8] = "RECORD";
EventTypes2[EventTypes2["VUE"] = 9] = "VUE";
EventTypes2[EventTypes2["CUSTOMER"] = 10] = "CUSTOMER";
EventTypes2[EventTypes2["EXTEND"] = 11] = "EXTEND";
})(EventTypes || (EventTypes = {}));
var BrowserErrorTypes;
(function(BrowserErrorTypes2) {
BrowserErrorTypes2[BrowserErrorTypes2["CODEERROR"] = 21] = "CODEERROR";
BrowserErrorTypes2[BrowserErrorTypes2["RESOURCEERROR"] = 22] = "RESOURCEERROR";
BrowserErrorTypes2[BrowserErrorTypes2["UNHANDLEDREJECTION"] = 23] = "UNHANDLEDREJECTION";
BrowserErrorTypes2[BrowserErrorTypes2["PAGECRASH"] = 24] = "PAGECRASH";
})(BrowserErrorTypes || (BrowserErrorTypes = {}));
var BrowserReportType;
(function(BrowserReportType2) {
BrowserReportType2[BrowserReportType2["BEACON"] = 1] = "BEACON";
BrowserReportType2[BrowserReportType2["IMG"] = 2] = "IMG";
BrowserReportType2[BrowserReportType2["GET"] = 3] = "GET";
BrowserReportType2[BrowserReportType2["POST"] = 4] = "POST";
})(BrowserReportType || (BrowserReportType = {}));
var DomTypes;
(function(DomTypes2) {
DomTypes2[DomTypes2["CLICK"] = 51] = "CLICK";
})(DomTypes || (DomTypes = {}));
var ConsoleTypes;
(function(ConsoleTypes2) {
ConsoleTypes2["LOG"] = "log";
ConsoleTypes2["INFO"] = "info";
ConsoleTypes2["WARN"] = "warn";
ConsoleTypes2["ERROR"] = "error";
ConsoleTypes2["ASSERT"] = "assert";
})(ConsoleTypes || (ConsoleTypes = {}));
var HttpTypes;
(function(HttpTypes2) {
HttpTypes2[HttpTypes2["XHR"] = 41] = "XHR";
HttpTypes2[HttpTypes2["FETCH"] = 42] = "FETCH";
})(HttpTypes || (HttpTypes = {}));
var PerTypes;
(function(PerTypes2) {
PerTypes2[PerTypes2["FMP"] = 31] = "FMP";
PerTypes2[PerTypes2["FPS"] = 32] = "FPS";
PerTypes2[PerTypes2["BASIC"] = 33] = "BASIC";
PerTypes2[PerTypes2["VITALS"] = 34] = "VITALS";
PerTypes2[PerTypes2["RESOURCE"] = 35] = "RESOURCE";
})(PerTypes || (PerTypes = {}));
var RouteTypes;
(function(RouteTypes2) {
RouteTypes2[RouteTypes2["HASH"] = 61] = "HASH";
RouteTypes2[RouteTypes2["HISTORY"] = 62] = "HISTORY";
})(RouteTypes || (RouteTypes = {}));
var CustomerTypes;
(function(CustomerTypes2) {
CustomerTypes2[CustomerTypes2["CUSTOMER"] = 111] = "CUSTOMER";
})(CustomerTypes || (CustomerTypes = {}));
var StoreType;
(function(StoreType2) {
StoreType2["LOCAL"] = "local";
StoreType2["SESSION"] = "session";
StoreType2["COOKIE"] = "cookie";
StoreType2["GLOBAL"] = "global";
})(StoreType || (StoreType = {}));
var PageLifeType;
(function(PageLifeType2) {
PageLifeType2[PageLifeType2["LOAD"] = 11] = "LOAD";
PageLifeType2[PageLifeType2["UNLOAD"] = 12] = "UNLOAD";
})(PageLifeType || (PageLifeType = {}));
var DeviceType;
(function(DeviceType2) {
DeviceType2[DeviceType2["MOBILE"] = 1] = "MOBILE";
DeviceType2[DeviceType2["PC"] = 2] = "PC";
})(DeviceType || (DeviceType = {}));
var PlatformTypes;
(function(PlatformTypes2) {
PlatformTypes2[PlatformTypes2["BROWSER"] = 1] = "BROWSER";
PlatformTypes2[PlatformTypes2["WECHAT"] = 2] = "WECHAT";
PlatformTypes2[PlatformTypes2["NODE"] = 3] = "NODE";
})(PlatformTypes || (PlatformTypes = {}));
var BrowserBreadcrumbTypes;
(function(BrowserBreadcrumbTypes2) {
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["ROUTE"] = 11] = "ROUTE";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CLICK"] = 12] = "CLICK";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CONSOLE"] = 13] = "CONSOLE";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["XHR"] = 14] = "XHR";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["FETCH"] = 15] = "FETCH";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["UNHANDLEDREJECTION"] = 16] = "UNHANDLEDREJECTION";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["RESOURCE"] = 17] = "RESOURCE";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CODE_ERROR"] = 18] = "CODE_ERROR";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CUSTOMER"] = 19] = "CUSTOMER";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["FRAMEWORK"] = 20] = "FRAMEWORK";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["LIFECYCLE"] = 21] = "LIFECYCLE";
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CRASH"] = 22] = "CRASH";
})(BrowserBreadcrumbTypes || (BrowserBreadcrumbTypes = {}));
var WxBreadcrumbTypes;
(function(WxBreadcrumbTypes2) {
WxBreadcrumbTypes2[WxBreadcrumbTypes2["API"] = 21] = "API";
WxBreadcrumbTypes2[WxBreadcrumbTypes2["ROUTE"] = 22] = "ROUTE";
WxBreadcrumbTypes2[WxBreadcrumbTypes2["CLICK"] = 23] = "CLICK";
WxBreadcrumbTypes2[WxBreadcrumbTypes2["ERROR"] = 24] = "ERROR";
WxBreadcrumbTypes2[WxBreadcrumbTypes2["LIFECYCLE"] = 25] = "LIFECYCLE";
WxBreadcrumbTypes2[WxBreadcrumbTypes2["CUSTOMER"] = 26] = "CUSTOMER";
})(WxBreadcrumbTypes || (WxBreadcrumbTypes = {}));
const getStoreIns = (type) => {
let store = null;
switch (type) {
case StoreType.LOCAL:
store = localStorage;
break;
case StoreType.SESSION:
store = sessionStorage;
break;
}
function getStore(type, keyPath, needParse = true) {
if (!type || !keyPath) {
return "";
}
const store = getStoreIns(type);
if (!store) {
return "";
}
let result = "";
try {
const paths = keyPath.split(".");
const [key] = paths;
result = store.getItem(key);
if (needParse) {
result = JSON.parse(result);
if (paths.length > 1) {
result = paths.slice(1).reduce((pre, cur) => pre[cur], result);
}
return store;
};
const getStore = (type, keyPath, needParse = true) => {
if (!type || !keyPath) {
return "";
}
const store = getStoreIns(type);
if (!store) {
return "";
}
let result = "";
try {
const paths = keyPath.split(".");
const [key] = paths;
result = store.getItem(key);
if (needParse) {
result = JSON.parse(result);
if (paths.length > 1) {
result = paths.slice(1).reduce((pre, cur) => pre[cur], result);
}
} catch (err) {
console.error(TAG, err);
}
return result;
} catch (err) {
console.error(TAG, err);
}
function setStore(type, key, data) {
if (!key) {
return;
}
const store = getStoreIns(type);
if (!store) {
return;
}
store.setItem(key, JSON.stringify(data));
return result;
};
const setStore = (type, key, data) => {
if (!key) {
return;
}
function setCookie(key, value, days) {
if (!key || !value || !days) {
return;
}
const exp = new Date();
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1e3);
document.cookie = `${key}=${encodeURIComponent(value)};expires=${exp.toUTCString()}`;
const store = getStoreIns(type);
if (!store) {
return;
}
function getCookie(key) {
if (!key) {
return "";
}
const arr = document.cookie.match(new RegExp(`(^| )${key}=([^;]*)(;|$)`));
if (arr != null) {
return decodeURIComponent(arr[2]);
} else {
return "";
}
store.setItem(key, JSON.stringify(data));
};
const setCookie = (key, value, days) => {
if (!key || !value || !days) {
return;
}
function delCookie(key) {
if (!key) {
return;
}
const exp = new Date();
exp.setTime(exp.getTime() - 1);
const cval = getCookie(key);
if (cval != null) {
document.cookie = `${key}=${cval};expires=${exp.toUTCString()}`;
}
const exp = new Date();
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1e3);
document.cookie = `${key}=${encodeURIComponent(value)};expires=${exp.toUTCString()}`;
};
const getCookie = (key) => {
if (!key) {
return "";
}
const arr = document.cookie.match(new RegExp(`(^| )${key}=([^;]*)(;|$)`));
if (arr != null) {
return decodeURIComponent(arr[2]);
}
return "";
};
const delCookie = (key) => {
if (!key) {
return;
}
const exp = new Date();
exp.setTime(exp.getTime() - 1);
const cval = getCookie(key);
if (cval != null) {
document.cookie = `${key}=${cval};expires=${exp.toUTCString()}`;
}
};
function beacon(url, data) {
const formData = new FormData();
Object.keys(data).forEach((key) => {
const parseHeaders = (headers) => {
const headerObj = {};
headers.trim().split(/[\r\n]+/).forEach((line) => {
const [key, value] = line.split(": ");
headerObj[key] = value;
});
return headerObj;
};
const beacon = (url, data) => {
if (!url || typeof url !== "string") {
console.error("Invalid URL");
return false;
}
if (!data || typeof data !== "object") {
console.error("Invalid data");
return false;
}
const formData = new FormData();
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
let value = data[key];
if (typeof value !== "string") {
if (typeof value !== "string" && !(value instanceof Blob)) {
value = JSON.stringify(value);
}
formData.append(key, value);
});
return navigator.sendBeacon(url, formData);
}
}
function get(url, data) {
return xhr(MethodTypes.GET, `${url}${url.indexOf("?") === -1 ? "?" : ""}${obj2query(data)}`, "");
}
function post(url, data) {
return xhr(MethodTypes.POST, url, obj2query(data));
}
function xhr(method, url, data) {
return new Promise((rs, rj) => {
try {
const xhr2 = new XMLHttpRequest();
xhr2.open(method, url);
return navigator.sendBeacon(url, formData);
};
const get = (url, data) => {
const queryString = obj2query(data);
const separator = url.includes("?") ? "&" : "?";
return xhr(MethodTypes.GET, `${url}${separator}${queryString}`, null);
};
const post = (url, data) => xhr(MethodTypes.POST, url, data);
const xhr = (method, url, data) => {
return new Promise((resolve, reject) => {
const xhr2 = new XMLHttpRequest();
xhr2.open(method, url, true);
if (method === MethodTypes.POST) {
if (typeof data === "string" || data instanceof URLSearchParams) {
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
} else {
xhr2.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
if (method === MethodTypes.POST) {
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
}
xhr2.onreadystatechange = () => {
if (xhr2.readyState === XMLHttpRequest.DONE) {
const responseHeaders = parseHeaders(xhr2.getAllResponseHeaders());
if (xhr2.status >= 200 && xhr2.status < 300) {
try {
const responseData = xhr2.responseText ? JSON.parse(xhr2.responseText) : null;
resolve({
status: xhr2.status,
statusText: xhr2.statusText,
headers: responseHeaders,
data: responseData
});
} catch (error) {
reject(new Error(`Failed to parse response: ${xhr2.responseText}`));
}
} else {
reject({
status: xhr2.status,
statusText: xhr2.statusText,
headers: responseHeaders,
data: xhr2.responseText
});
}
}
};
xhr2.onerror = () => {
reject(new Error("Network error"));
};
try {
if (method === MethodTypes.POST) {
if (typeof data === "string" || data instanceof URLSearchParams) {
xhr2.send(data);
} else {
xhr2.send();
xhr2.send(JSON.stringify(data));
}
xhr2.onreadystatechange = () => {
if (xhr2.readyState == XMLHttpRequest.DONE && xhr2.status == 200) {
rs(JSON.parse(xhr2.response));
} else {
new Error(xhr2.response);
}
};
} catch (error) {
rj(error);
} else {
xhr2.send();
}
});
}
function imgRequest(url, data) {
let img = new Image();
const spliceStr = url.indexOf("?") === -1 ? "?" : "&";
img.src = `${url}${spliceStr}data=${encodeURIComponent(JSON.stringify(data))}`;
img = null;
}
} catch (error) {
reject(error);
}
});
};
const imgRequest = (url, data) => {
const queryString = obj2query(data);
const separator = url.includes("?") ? "&" : "?";
const fullUrl = `${url}${separator}${queryString}`;
const img = new Image();
img.src = fullUrl;
setTimeout(() => {
img.src = "";
}, 0);
};
exports.beacon = beacon;
exports.countBytes = countBytes;
exports.delCookie = delCookie;
exports.formatDate = formatDate;
exports.formatDecimal = formatDecimal;
exports.formateUrlPath = formateUrlPath;
exports.generateUUID = generateUUID;
exports.get = get;
exports.getCookie = getCookie;
exports.getDeepPropByDot = getDeepPropByDot;
exports.getStore = getStore;
exports.getUrlPath = getUrlPath;
exports.hasConsole = hasConsole;
exports.imgRequest = imgRequest;
exports.obj2query = obj2query;
exports.post = post;
exports.replaceOld = replaceOld;
exports.setCookie = setCookie;
exports.setStore = setStore;
exports.setUrlQuery = setUrlQuery;
exports.splitStringByBytes = splitStringByBytes;
exports.throttle = throttle;
exports.xhr = xhr;
exports.beacon = beacon;
exports.countBytes = countBytes;
exports.delCookie = delCookie;
exports.formatDecimal = formatDecimal;
exports.formateUrlPath = formateUrlPath;
exports.generateUUID = generateUUID;
exports.get = get;
exports.getCookie = getCookie;
exports.getDeepPropByDot = getDeepPropByDot;
exports.getStore = getStore;
exports.getUrlPath = getUrlPath;
exports.hasConsole = hasConsole;
exports.imgRequest = imgRequest;
exports.obj2query = obj2query;
exports.post = post;
exports.replaceOld = replaceOld;
exports.setCookie = setCookie;
exports.setStore = setStore;
exports.setUrlQuery = setUrlQuery;
exports.splitStringByBytes = splitStringByBytes;
exports.throttle = throttle;
exports.xhr = xhr;
Object.defineProperty(exports, '__esModule', { value: true });
Object.defineProperty(exports, '__esModule', { value: true });
}));
/* follow me on Github! @LuciferHuang */

@@ -5,4 +5,12 @@ import { IAnyObject } from '@heimdallr-sdk/types';

export declare const getUrlPath: (url: string) => string;
export declare function setUrlQuery(url: string, query?: {}): string;
export declare function getDeepPropByDot(keyPath: string, obj: Object): any;
export declare function obj2query(data: IAnyObject): string;
export declare const setUrlQuery: (url: string, query?: {}) => string;
export declare const getDeepPropByDot: (keyPath: string, obj: Object) => {
constructor: Function;
toString(): string;
toLocaleString(): string;
valueOf(): Object;
hasOwnProperty(v: PropertyKey): boolean;
isPrototypeOf(v: Object): boolean;
propertyIsEnumerable(v: PropertyKey): boolean;
};
export declare const obj2query: (params: IAnyObject) => string;

@@ -12,3 +12,2 @@ var __assign = (this && this.__assign) || function () {

};
import { TAG } from '@heimdallr-sdk/types';
export var hasConsole = function () { return typeof console !== 'undefined'; };

@@ -19,7 +18,11 @@ export var formateUrlPath = function (host, path) {

export var getUrlPath = function (url) {
var path = "".concat((url || '').replace(/^http(s|):/, '').split('?')[0]);
var endIndex = path.length - 1;
return path[endIndex] === '/' ? path.substring(0, endIndex) : path;
try {
var pathname = new URL(url).pathname;
return pathname.endsWith('/') && pathname.length > 1 ? pathname.slice(0, -1) : pathname;
}
catch (error) {
return '';
}
};
export function setUrlQuery(url, query) {
export var setUrlQuery = function (url, query) {
if (query === void 0) { query = {}; }

@@ -31,4 +34,4 @@ var queryArr = [];

return "".concat(url).concat(url.indexOf('?') !== -1 ? '&' : '?').concat(queryArr.join('&'));
}
export function getDeepPropByDot(keyPath, obj) {
};
export var getDeepPropByDot = function (keyPath, obj) {
if (!keyPath || !obj) {

@@ -44,3 +47,2 @@ return null;

if (!value) {
console.warn(TAG, "".concat(key, " does not exist"));
return null;

@@ -51,9 +53,7 @@ }

return result;
}
export function obj2query(data) {
return Object.keys(data).reduce(function (pre, cur) {
var val = data[cur];
pre += "".concat(pre ? '&' : '').concat(cur, "=").concat(typeof val === 'object' ? JSON.stringify(val) : val);
return pre;
}, '');
}
};
export var obj2query = function (params) {
return Object.keys(params)
.map(function (key) { return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(params[key])); })
.join('&');
};
import { StoreType, StoreTypes } from '@heimdallr-sdk/types';
export declare function getStore(type: StoreTypes, keyPath: string, needParse?: boolean): any;
export declare function setStore(type: StoreType, key: string, data: any): void;
export declare function setCookie(key: string, value: any, days: number): void;
export declare function getCookie(key: string): string;
export declare function delCookie(key: string): void;
export declare const getStore: <T>(type: StoreTypes, keyPath: string, needParse?: boolean) => "" | T;
export declare const setStore: (type: StoreType, key: string, data: any) => void;
export declare const setCookie: (key: string, value: any, days: number) => void;
export declare const getCookie: (key: string) => string;
export declare const delCookie: (key: string) => void;
import { StoreType, TAG } from '@heimdallr-sdk/types';
function getStoreIns(type) {
var getStoreIns = function (type) {
var store = null;

@@ -15,4 +15,4 @@ switch (type) {

return store;
}
export function getStore(type, keyPath, needParse) {
};
export var getStore = function (type, keyPath, needParse) {
if (needParse === void 0) { needParse = true; }

@@ -42,4 +42,4 @@ if (!type || !keyPath) {

return result;
}
export function setStore(type, key, data) {
};
export var setStore = function (type, key, data) {
if (!key) {

@@ -53,4 +53,4 @@ return;

store.setItem(key, JSON.stringify(data));
}
export function setCookie(key, value, days) {
};
export var setCookie = function (key, value, days) {
if (!key || !value || !days) {

@@ -62,4 +62,4 @@ return;

document.cookie = "".concat(key, "=").concat(encodeURIComponent(value), ";expires=").concat(exp.toUTCString());
}
export function getCookie(key) {
};
export var getCookie = function (key) {
if (!key) {

@@ -72,7 +72,5 @@ return '';

}
else {
return '';
}
}
export function delCookie(key) {
return '';
};
export var delCookie = function (key) {
if (!key) {

@@ -87,2 +85,2 @@ return;

}
}
};
import { IAnyObject } from '@heimdallr-sdk/types';
export declare function generateUUID(): string;
export declare const formatDate: (format?: string, timestamp?: number) => string;
export declare function throttle(fn: Function, delay: number): Function;
export declare function replaceOld(source: IAnyObject, name: string, replacement: (...args: any[]) => any, isForced?: boolean): void;
export declare function formatDecimal(num: number, decimal: number): number;
export declare function countBytes(str: string): number;
export declare function splitStringByBytes(str: string, maxBytes: number): Array<string>;
export declare const generateUUID: () => string;
export declare const throttle: <T extends (...args: any[]) => void>(fn: T, delay: number) => (...args: Parameters<T>) => void;
export declare const replaceOld: (source: IAnyObject, name: string, replacement: (...args: any[]) => any, isForced?: boolean) => void;
export declare const formatDecimal: (num: number, decimal: number) => number;
export declare const countBytes: (str: string) => number;
export declare const splitStringByBytes: (str: string, maxBytes: number) => Array<string>;

@@ -1,34 +0,11 @@

export function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);
export var generateUUID = function () {
var template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
return template.replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0;
var v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
return uuid;
}
export var formatDate = function (format, timestamp) {
if (format === void 0) { format = 'Y-M-D h:m:s'; }
if (timestamp === void 0) { timestamp = Date.now(); }
var date = new Date(timestamp || Date.now());
var dateInfo = {
Y: "".concat(date.getFullYear()),
M: "".concat(date.getMonth() + 1),
D: "".concat(date.getDate()),
h: date.getHours(),
m: date.getMinutes(),
s: date.getSeconds()
};
var formatNumber = function (n) { return (n >= 10 ? n : '0' + n); };
var res = (format || 'Y-M-D h:m:s')
.replace('Y', dateInfo.Y)
.replace('M', dateInfo.M)
.replace('D', dateInfo.D)
.replace('h', formatNumber(dateInfo.h))
.replace('m', formatNumber(dateInfo.m))
.replace('s', formatNumber(dateInfo.s));
return res;
};
export function throttle(fn, delay) {
var canRun = true;
export var throttle = function (fn, delay) {
var lastCall = 0;
return function () {

@@ -39,12 +16,10 @@ var args = [];

}
if (!canRun)
return;
fn.apply(this, args);
canRun = false;
setTimeout(function () {
canRun = true;
}, delay);
var now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn.apply(this, args);
}
};
}
export function replaceOld(source, name, replacement, isForced) {
};
export var replaceOld = function (source, name, replacement, isForced) {
if (source === undefined)

@@ -59,22 +34,17 @@ return;

}
}
export function formatDecimal(num, decimal) {
if (!num) {
};
export var formatDecimal = function (num, decimal) {
if (!isFinite(num) || isNaN(num)) {
return num;
}
var str = num.toString();
var index = str.indexOf('.');
if (index !== -1) {
str = str.substring(0, decimal + index + 1);
if (!Number.isInteger(decimal) || decimal < 0) {
return num;
}
else {
str = str.substring(0);
}
return parseFloat(str);
}
export function countBytes(str) {
return parseFloat(num.toFixed(decimal));
};
export var countBytes = function (str) {
var encoder = new TextEncoder();
return encoder.encode(str).length;
}
export function splitStringByBytes(str, maxBytes) {
};
export var splitStringByBytes = function (str, maxBytes) {
var encoder = new TextEncoder();

@@ -94,2 +64,2 @@ var bytes = encoder.encode(str);

return chunks;
}
};

@@ -1,6 +0,6 @@

import { IAnyObject, MethodTypes } from '@heimdallr-sdk/types';
export declare function beacon(url: string, data: IAnyObject): boolean;
export declare function get(url: string, data: IAnyObject): Promise<any>;
export declare function post(url: string, data: IAnyObject): Promise<any>;
export declare function xhr(method: MethodTypes, url: string, data: any): Promise<any>;
export declare function imgRequest(url: string, data: IAnyObject): void;
import { MethodTypes, XhrResponse, HttpCommonRes } from '@heimdallr-sdk/types';
export declare const beacon: (url: string, data: Record<string, any>) => boolean;
export declare const get: (url: string, data: Record<string, any>) => Promise<XhrResponse<HttpCommonRes<any>>>;
export declare const post: (url: string, data: Record<string, any>) => Promise<XhrResponse<HttpCommonRes<any>>>;
export declare const xhr: (method: MethodTypes, url: string, data: any) => Promise<XhrResponse<HttpCommonRes>>;
export declare const imgRequest: (url: string, data: Record<string, any>) => void;
import { MethodTypes } from '@heimdallr-sdk/types';
import { obj2query } from './base';
export function beacon(url, data) {
var parseHeaders = function (headers) {
var headerObj = {};
headers.trim().split(/[\r\n]+/).forEach(function (line) {
var _a = line.split(': '), key = _a[0], value = _a[1];
headerObj[key] = value;
});
return headerObj;
};
export var beacon = function (url, data) {
if (!url || typeof url !== 'string') {
console.error('Invalid URL');
return false;
}
if (!data || typeof data !== 'object') {
console.error('Invalid data');
return false;
}
var formData = new FormData();
Object.keys(data).forEach(function (key) {
var value = data[key];
if (typeof value !== 'string') {
value = JSON.stringify(value);
for (var key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
var value = data[key];
if (typeof value !== 'string' && !(value instanceof Blob)) {
value = JSON.stringify(value);
}
formData.append(key, value);
}
formData.append(key, value);
});
}
return navigator.sendBeacon(url, formData);
}
export function get(url, data) {
return xhr(MethodTypes.GET, "".concat(url).concat(url.indexOf('?') === -1 ? '?' : '').concat(obj2query(data)), '');
}
export function post(url, data) {
return xhr(MethodTypes.POST, url, obj2query(data));
}
export function xhr(method, url, data) {
return new Promise(function (rs, rj) {
try {
var xhr_1 = new XMLHttpRequest();
xhr_1.open(method, url);
xhr_1.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
if (method === MethodTypes.POST) {
xhr_1.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr_1.send(data);
};
export var get = function (url, data) {
var queryString = obj2query(data);
var separator = url.includes('?') ? '&' : '?';
return xhr(MethodTypes.GET, "".concat(url).concat(separator).concat(queryString), null);
};
export var post = function (url, data) { return xhr(MethodTypes.POST, url, data); };
export var xhr = function (method, url, data) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
if (method === MethodTypes.POST) {
if (typeof data === 'string' || data instanceof URLSearchParams) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
else {
xhr_1.send();
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
}
xhr_1.onreadystatechange = function () {
if (xhr_1.readyState == XMLHttpRequest.DONE && xhr_1.status == 200) {
rs(JSON.parse(xhr_1.response));
}
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
var responseHeaders = parseHeaders(xhr.getAllResponseHeaders());
if (xhr.status >= 200 && xhr.status < 300) {
try {
var responseData = xhr.responseText ? JSON.parse(xhr.responseText) : null;
resolve({
status: xhr.status,
statusText: xhr.statusText,
headers: responseHeaders,
data: responseData,
});
}
catch (error) {
reject(new Error("Failed to parse response: ".concat(xhr.responseText)));
}
}
else {
new Error(xhr_1.response);
reject({
status: xhr.status,
statusText: xhr.statusText,
headers: responseHeaders,
data: xhr.responseText,
});
}
};
}
};
xhr.onerror = function () {
reject(new Error('Network error'));
};
try {
if (method === MethodTypes.POST) {
if (typeof data === 'string' || data instanceof URLSearchParams) {
xhr.send(data);
}
else {
xhr.send(JSON.stringify(data));
}
}
else {
xhr.send();
}
}
catch (error) {
rj(error);
reject(error);
}
});
}
export function imgRequest(url, data) {
};
export var imgRequest = function (url, data) {
var queryString = obj2query(data);
var separator = url.includes('?') ? '&' : '?';
var fullUrl = "".concat(url).concat(separator).concat(queryString);
var img = new Image();
var spliceStr = url.indexOf('?') === -1 ? '?' : '&';
img.src = "".concat(url).concat(spliceStr, "data=").concat(encodeURIComponent(JSON.stringify(data)));
img = null;
}
img.src = fullUrl;
setTimeout(function () {
img.src = '';
}, 0);
};
{
"name": "@heimdallr-sdk/utils",
"version": "0.0.19",
"version": "0.0.20",
"description": "@heimdallr-sdk/utils",

@@ -32,5 +32,5 @@ "license": "MIT",

"dependencies": {
"@heimdallr-sdk/types": "^0.0.15"
"@heimdallr-sdk/types": "^0.0.16"
},
"gitHead": "5d0e586ccee1cecb03db963054065e6b125b7ca3"
"gitHead": "cd187687df2e4fe32756115e220be5d72c4152b0"
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc