UNPKG

@elysiajs/eden

Version:

Fully type-safe Elysia client

2 lines (1 loc) 10.5 kB
"use strict";var P=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var ae=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},ie=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of re(t))!se.call(e,s)&&s!==n&&P(e,s,{get:()=>t[s],enumerable:!(r=ne(t,s))||r.enumerable});return e};var oe=e=>ie(P({},"__esModule",{value:!0}),e);var be={};ae(be,{edenFetch:()=>te,edenTreaty:()=>ee,treaty:()=>z});module.exports=oe(be);var T=class extends Error{constructor(n,r){super(r+"");this.status=n;this.value=r}};var ce=/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/,fe=/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT(?:\+|-)\d{4}\s\([^)]+\)/,de=/^(?:(?:(?:(?:0?[1-9]|[12][0-9]|3[01])[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:19|20)\d{2})|(?:(?:19|20)\d{2}[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:0?[1-9]|[12][0-9]|3[01]))))(?:\s(?:1[012]|0?[1-9]):[0-5][0-9](?::[0-5][0-9])?(?:\s[AP]M)?)?$/,ye=e=>e.trim().length!==0&&!Number.isNaN(Number(e)),_=e=>{if(typeof e!="string")return null;let t=e.replace(/"/g,"");if(ce.test(t)||fe.test(t)||de.test(t)){let n=new Date(t);if(!Number.isNaN(n.getTime()))return n}return null},ue=e=>{let t=e.charCodeAt(0),n=e.charCodeAt(e.length-1);return t===123&&n===125||t===91&&n===93},pe=e=>JSON.parse(e,(t,n)=>{let r=_(n);return r||n}),L=e=>{if(!e)return e;if(ye(e))return+e;if(e==="true")return!0;if(e==="false")return!1;let t=_(e);if(t)return t;if(ue(e))try{return pe(e)}catch{}return e},D=e=>{let t=e.data.toString();return t==="null"?null:L(t)};var I=class{constructor(t){this.url=t;this.ws=new WebSocket(t)}ws;send(t){return Array.isArray(t)?(t.forEach(n=>this.send(n)),this):(this.ws.send(typeof t=="object"?JSON.stringify(t):t.toString()),this)}on(t,n,r){return this.addEventListener(t,n,r)}off(t,n,r){return this.ws.removeEventListener(t,n,r),this}subscribe(t,n){return this.addEventListener("message",t,n)}addEventListener(t,n,r){return this.ws.addEventListener(t,s=>{if(t==="message"){let i=D(s);n({...s,data:i})}else n(s)},r),this}removeEventListener(t,n,r){return this.off(t,n,r),this}close(){return this.ws.close(),this}};var le=["get","post","put","delete","patch","options","head","connect","subscribe"],Z=["localhost","127.0.0.1","0.0.0.0"],U=typeof FileList>"u",G=e=>U?e instanceof Blob:e instanceof FileList||e instanceof File,he=e=>{if(!e)return!1;for(let t in e)if(G(e[t])||Array.isArray(e[t])&&e[t].find(G))return!0;return!1},J=e=>U?e:new Promise(t=>{let n=new FileReader;n.onload=()=>{let r=new File([n.result],e.name,{lastModified:e.lastModified,type:e.type});t(r)},n.readAsArrayBuffer(e)}),j=(e,t,n={},r={})=>{if(Array.isArray(e)){for(let s of e)if(!Array.isArray(s))r=j(s,t,n,r);else{let i=s[0];if(typeof i=="string")r[i.toLowerCase()]=s[1];else for(let[o,y]of i)r[o.toLowerCase()]=y}return r}if(!e)return r;switch(typeof e){case"function":if(e instanceof Headers)return j(e,t,n,r);let s=e(t,n);return s?j(s,t,n,r):r;case"object":if(e instanceof Headers)return e.forEach((i,o)=>{r[o.toLowerCase()]=i}),r;for(let[i,o]of Object.entries(e))r[i.toLowerCase()]=o;return r;default:return r}};async function*ge(e){let t=e.body;if(!t)return;let n=t.getReader(),r=new TextDecoder;try{for(;;){let{done:s,value:i}=await n.read();if(s)break;let o=r.decode(i);yield L(o)}}finally{n.releaseLock()}}var K=(e,t,n=[],r)=>new Proxy(()=>{},{get(s,i){return K(e,t,i==="index"?n:[...n,i],r)},apply(s,i,[o,y]){if(!o||y||typeof o=="object"&&Object.keys(o).length!==1||le.includes(n.at(-1))){let M=[...n],v=M.pop(),E="/"+M.join("/"),{fetcher:F=fetch,headers:R,onRequest:l,onResponse:g,fetch:O}=t,x=v==="get"||v==="head"||v==="subscribe";R=j(R,E,y);let N=x?o?.query:y?.query,b="";if(N){let a=(A,w)=>{b+=(b?"&":"?")+`${encodeURIComponent(A)}=${encodeURIComponent(w)}`};for(let[A,w]of Object.entries(N)){if(Array.isArray(w)){for(let c of w)a(A,c);continue}if(typeof w=="object"){a(A,JSON.stringify(w));continue}a(A,`${w}`)}}if(v==="subscribe"){let a=e.replace(/^([^]+):\/\//,e.startsWith("https://")?"wss://":e.startsWith("http://")||Z.find(A=>e.includes(A))?"ws://":"wss://")+E+b;return new I(a)}return(async()=>{let a={method:v?.toUpperCase(),body:o,...O,headers:R};a.headers={...R,...j(x?o?.headers:y?.headers,E,a)};let A=x&&typeof o=="object"?o.fetch:y?.fetch;if(a={...a,...A},x&&delete a.body,l){Array.isArray(l)||(l=[l]);for(let d of l){let f=await d(E,a);typeof f=="object"&&(a={...a,...f,headers:{...a.headers,...j(f.headers,E,a)}})}}if(x&&delete a.body,he(o)){let d=new FormData;for(let[f,p]of Object.entries(a.body)){if(U){d.append(f,p);continue}if(p instanceof File){d.append(f,await J(p));continue}if(p instanceof FileList){for(let m=0;m<p.length;m++)d.append(f,await J(p[m]));continue}if(Array.isArray(p)){for(let m=0;m<p.length;m++){let S=p[m];d.append(f,S instanceof File?await J(S):S)}continue}d.append(f,p)}a.body=d}else typeof o=="object"?(a.headers["content-type"]="application/json",a.body=JSON.stringify(o)):o!=null&&(a.headers["content-type"]="text/plain");if(x&&delete a.body,l){Array.isArray(l)||(l=[l]);for(let d of l){let f=await d(E,a);typeof f=="object"&&(a={...a,...f,headers:{...a.headers,...j(f.headers,E,a)}})}}let w=e+E+b,c=await(r?.handle(new Request(w,a))??F(w,a)),h=null,u=null;if(g){Array.isArray(g)||(g=[g]);for(let d of g)try{let f=await d(c.clone());if(f!=null){h=f;break}}catch(f){f instanceof T?u=f:u=new T(422,f);break}}if(h!==null)return{data:h,error:u,response:c,status:c.status,headers:c.headers};switch(c.headers.get("Content-Type")?.split(";")[0]){case"text/event-stream":h=ge(c);break;case"application/json":h=await c.json();break;case"application/octet-stream":h=await c.arrayBuffer();break;case"multipart/form-data":let d=await c.formData();h={},d.forEach((f,p)=>{h[p]=f});break;default:h=await c.text().then(L)}return(c.status>=300||c.status<200)&&(u=new T(c.status,h),h=null),{data:h,error:u,response:c,status:c.status,headers:c.headers}})()}return typeof o=="object"?K(e,t,[...n,Object.values(o)[0]],r):K(e,t,n)}}),z=(e,t={})=>typeof e=="string"?(t.keepDomain||(e.includes("://")||(e=(Z.find(n=>e.includes(n))?"http://":"https://")+e),e.endsWith("/")&&(e=e.slice(0,-1))),K(e,t)):(typeof window<"u"&&console.warn("Elysia instance server found on client side, this is not recommended for security reason. Use generic type instead."),K("http://e.ly",t,[],e));var Q=(e,t,n)=>{if(e.endsWith("/")||(e+="/"),t==="index"&&(t=""),!n||!Object.keys(n).length)return`${e}${t}`;let r="";for(let[s,i]of Object.entries(n))r+=`${s}=${i}&`;return`${e}${t}?${r.slice(0,-1)}`};var V=typeof FileList>"u",X=e=>V?e instanceof Blob:e instanceof FileList||e instanceof File,me=e=>{if(!e)return!1;for(let t in e){if(X(e[t]))return!0;if(Array.isArray(e[t])&&e[t].find(n=>X(n)))return!0}return!1},B=e=>V?e:new Promise(t=>{let n=new FileReader;n.onload=()=>{let r=new File([n.result],e.name,{lastModified:e.lastModified,type:e.type});t(r)},n.readAsArrayBuffer(e)}),H=class{ws;url;constructor(t){this.ws=new WebSocket(t),this.url=t}send(t){return Array.isArray(t)?(t.forEach(n=>this.send(n)),this):(this.ws.send(typeof t=="object"?JSON.stringify(t):t.toString()),this)}on(t,n,r){return this.addEventListener(t,n,r)}off(t,n,r){return this.ws.removeEventListener(t,n,r),this}subscribe(t,n){return this.addEventListener("message",t,n)}addEventListener(t,n,r){return this.ws.addEventListener(t,s=>{if(t==="message"){let i=D(s);n({...s,data:i})}else n(s)},r),this}removeEventListener(t,n,r){return this.off(t,n,r),this}close(){return this.ws.close(),this}},Y=(e,t="",n)=>new Proxy(()=>{},{get(r,s,i){return Y(e,`${t}/${s.toString()}`,n)},apply(r,s,[i,o={}]=[{},{}]){let y=i!==void 0&&(typeof i!="object"||Array.isArray(i))?i:void 0,{$query:M,$fetch:v,$headers:E,$transform:F,getRaw:R,...l}=i??{};y??=l;let g=t.lastIndexOf("/"),O=t.slice(g+1).toUpperCase(),x=Q(e,g===-1?"/":t.slice(0,g),Object.assign(o.query??{},M)),N=n.fetcher??fetch,b=n.transform?Array.isArray(n.transform)?n.transform:[n.transform]:void 0,a=F?Array.isArray(F)?F:[F]:void 0;return a&&(b?b=a.concat(b):b=a),O==="SUBSCRIBE"?new H(x.replace(/^([^]+):\/\//,x.startsWith("https://")?"wss://":"ws://")):(async w=>{let c,h={...n.$fetch?.headers,...v?.headers,...o.headers,...E};if(O!=="GET"&&O!=="HEAD"){c=Object.keys(y).length||Array.isArray(y)?y:void 0;let m=c&&(typeof c=="object"||Array.isArray(y));if(m&&me(c)){let $=new FormData;for(let[C,k]of Object.entries(c))if(V)$.append(C,k);else if(k instanceof File)$.append(C,await B(k));else if(k instanceof FileList)for(let W=0;W<k.length;W++)$.append(C,await B(k[W]));else if(Array.isArray(k))for(let W=0;W<k.length;W++){let q=k[W];$.append(C,q instanceof File?await B(q):q)}else $.append(C,k);c=$}else c!=null&&(h["content-type"]=m?"application/json":"text/plain",c=m?JSON.stringify(c):y)}let u=await N(x,{method:O,body:c,...n.$fetch,...o.fetch,...v,headers:h}),d;if(w.getRaw)return u;switch(u.headers.get("Content-Type")?.split(";")[0]){case"application/json":d=await u.json();break;default:d=await u.text().then(L)}let f=u.status>=300||u.status<200?new T(u.status,d):null,p={data:d,error:f,response:u,status:u.status,headers:u.headers};if(b)for(let m of b){let S=m(p);S instanceof Promise&&(S=await S),S!=null&&(p=S)}return p})({getRaw:R})}}),ee=(e,t={fetcher:fetch})=>new Proxy({},{get(n,r){return Y(e,r,t)}});var Ee=async e=>{switch(e.headers.get("Content-Type")?.split(";")[0]){case"application/json":return e.json();case"application/octet-stream":return e.arrayBuffer();case"multipart/form-data":{let n=await e.formData(),r={};return n.forEach((s,i)=>{r[i]=s}),r}}return e.text().then(L)},we=async(e,t)=>{let n=await Ee(e);return e.status>300?{data:null,status:e.status,headers:e.headers,retry:t,error:new T(e.status,n)}:{data:n,error:null,status:e.status,headers:e.headers,retry:t}},te=(e,t)=>(n,{query:r,params:s,body:i,...o}={})=>{s&&Object.entries(s).forEach(([g,O])=>{n=n.replace(`:${g}`,O)});let y=o.headers?.["Content-Type"];if(!y||y==="application/json")try{i=JSON.stringify(i)}catch{}let M=t?.fetcher||globalThis.fetch,v=r?`?${new URLSearchParams(r).toString()}`:"",E=`${e}${n}${v}`,F=i?{"content-type":"application/json",...o.headers}:o.headers,R={...o,method:o.method?.toUpperCase()||"GET",headers:F,body:i},l=()=>M(E,R).then(g=>we(g,l));return l()};0&&(module.exports={edenFetch,edenTreaty,treaty});