@alessiofrittoli/web-utils
Version:
Common TypeScript web utilities
1 lines • 2.83 kB
JavaScript
import {isValidDate}from'@alessiofrittoli/date-utils';import {isNumeric}from'@alessiofrittoli/math-utils';var m=e=>e instanceof Promise;var l=e=>typeof e=="string"||e instanceof String;var C=e=>e.trim().length>0,x=e=>!C(e);var y=e=>e.charAt(0).toUpperCase()+e.slice(1),T=e=>e.charAt(0).toLowerCase()+e.slice(1),w=e=>P(e).replace(/[-_\s](.)/g,(t,r)=>r.toUpperCase()),P=e=>e.replace(/\s+/g,"-").replace(/_/g,"-").replace(/([A-Z])/g,"-$1").replace(/[^a-zA-Z0-9-]/g,"-").replace(/--+/g,"-").toLowerCase(),k=e=>m(e)||typeof e=="function"?"":e instanceof Date&&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&&!(l(e)&&x(e))){if(isNumeric(e))return parseFloat(e);try{let t=new Date(e);return isValidDate(t)?t:JSON.parse(e)}catch{return e}}};var p=e=>new Map(e);var S=(n=>(n.Low="Low",n.Medium="Medium",n.High="High",n))(S||{}),R=(n=>(n.Strict="Strict",n.Lax="Lax",n.None="None",n))(R||{}),V=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=p();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?y(s.toString()):s,s==="Expires"&&isValidDate(i)&&(i=i.toUTCString()),s==="MaxAge"&&(s="Max-Age"),[s,k(i)].join("="))).filter(Boolean).join(";")}static fromString(t){let[r,...n]=t.split(";");if(!r)return null;let[o,f]=r.split("="),s=n.map(i=>{let[g,h]=i.split("=");if(!g||!g.trim().length)return null;let d=T(w(g)),u=e.parseValue(h,d);return u==null?null:[d,u]}).filter(Boolean);return p([["name",o],["value",e.parseValue(f)],...s])}static fromListString(t){let r=p();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 isValidDate(n)?n:void 0}return r==="httpOnly"||r==="secure"||r==="partitioned"?t!=="false":K(t)}};export{V as Cookie,S as Priority,R as SameSite};