UNPKG

@alessiofrittoli/web-utils

Version:
1 lines 2.9 kB
'use strict';var dateUtils=require('@alessiofrittoli/date-utils'),mathUtils=require('@alessiofrittoli/math-utils');var d=e=>e instanceof Promise;var m=e=>typeof e=="string"||e instanceof String;var h=e=>e.trim().length>0,l=e=>!h(e);var b=e=>e.charAt(0).toUpperCase()+e.slice(1),y=e=>e.charAt(0).toLowerCase()+e.slice(1),T=e=>A(e).replace(/[-_\s](.)/g,(t,r)=>r.toUpperCase()),A=e=>e.replace(/\s+/g,"-").replace(/_/g,"-").replace(/([A-Z])/g,"-$1").replace(/[^a-zA-Z0-9-]/g,"-").replace(/--+/g,"-").toLowerCase(),w=e=>d(e)||typeof e=="function"?"":e instanceof Date&&dateUtils.isValidDate(e)?e.toISOString():e instanceof Map||e instanceof Headers?JSON.stringify(Array.from(e.entries())):typeof e=="object"?JSON.stringify(e):e?.toString()||"",k=e=>{if(e&&!(m(e)&&l(e))){if(mathUtils.isNumeric(e))return parseFloat(e);try{let t=new Date(e);return dateUtils.isValidDate(t)?t:JSON.parse(e)}catch{return e}}};var c=e=>new Map(e);var R=(n=>(n.Low="Low",n.Medium="Medium",n.High="High",n))(R||{}),S=(n=>(n.Strict="Strict",n.Lax="Lax",n.None="None",n))(S||{}),E=class e{static get(t){return e.fromListString(document.cookie).get(t)}static getAll(){return e.fromListString(document.cookie)}static set(t){let r=e.parse(t);return r.has("path")||r.set("path","/"),typeof document<"u"?(document.cookie=e.toString(r),r):false}static delete(t){return !!e.set({name:t,maxAge:0})}static parse(t){if(t instanceof Map)return t;let r=typeof t.expires<"u"?new Date(t.expires):void 0,n=c();return n.set("name",t.name).set("value",t.value),r&&n.set("expires",r),typeof t.maxAge<"u"&&n.set("maxAge",t.maxAge),t.path&&n.set("path",t.path),t.priority&&n.set("priority",t.priority),t.domain&&n.set("domain",t.domain),typeof t.httpOnly<"u"&&n.set("httpOnly",t.httpOnly),typeof t.secure<"u"&&n.set("secure",t.secure),t.sameSite&&n.set("sameSite",t.sameSite),typeof t.partitioned<"u"&&n.set("partitioned",t.partitioned),n}static toString(t){let r=e.parse(t),n=Array.from(r).filter(([s])=>s!=="name"&&s!=="value").filter(([,s])=>typeof s!="boolean"||!!s),o=r.get("name");return [[o,r.get("value")],...n].map(([s,i])=>(s=s!==o?b(s.toString()):s,s==="Expires"&&dateUtils.isValidDate(i)&&(i=i.toUTCString()),s==="MaxAge"&&(s="Max-Age"),[s,w(i)].join("="))).filter(Boolean).join(";")}static fromString(t){let[r,...n]=t.split(";");if(!r)return null;let[o,g]=r.split("="),s=n.map(i=>{let[p,V]=i.split("=");if(!p||!p.trim().length)return null;let f=y(T(p)),u=e.parseValue(V,f);return u==null?null:[f,u]}).filter(Boolean);return c([["name",o],["value",e.parseValue(g)],...s])}static fromListString(t){let r=c();return t.split("; ").map(n=>{let o=e.fromString(n);if(!o)return null;r.set(o.get("name"),o);}),r}static parseValue(t,r){if(r==="expires"&&t){let n=new Date(t);return dateUtils.isValidDate(n)?n:void 0}return r==="httpOnly"||r==="secure"||r==="partitioned"?t!=="false":k(t)}};exports.Cookie=E;exports.Priority=R;exports.SameSite=S;