@zogjs/http 0.4.8 → 0.4.9

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.
@@ -1 +1 @@
1
- var t=Object.defineProperty,e=Object.defineProperties,s=Object.getOwnPropertyDescriptors,r=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable,a=(e,s,r)=>s in e?t(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r,i=(t,e)=>{for(var s in e||(e={}))o.call(e,s)&&a(t,s,e[s]);if(r)for(var s of r(e))n.call(e,s)&&a(t,s,e[s]);return t},l=(t,r)=>e(t,s(r)),d=(t,e)=>{var s={};for(var a in t)o.call(t,a)&&e.indexOf(a)<0&&(s[a]=t[a]);if(null!=t&&r)for(var a of r(t))e.indexOf(a)<0&&n.call(t,a)&&(s[a]=t[a]);return s};const h={baseURL:"",timeout:3e4,headers:{"Content-Type":"application/json"},withCredentials:!1,retries:0,retryDelay:1e3},c={OK:200,CREATED:201,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,UNPROCESSABLE_ENTITY:422,INTERNAL_SERVER_ERROR:500,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503};class u extends Error{constructor(t,e,s,r){super(t),this.name="HttpError",this.status=e,this.response=s,this.request=r,this.isHttpError=!0}}class p{constructor(t){this.state=t({progress:0,loaded:0,total:0,status:"idle",error:null,startTime:null,speed:0,remainingTime:0})}start(t){this.state.progress=0,this.state.loaded=0,this.state.total=t,this.state.status="uploading",this.state.error=null,this.state.startTime=Date.now(),this.state.speed=0,this.state.remainingTime=0}update(t,e){this.state.loaded=t,this.state.total=e,this.state.progress=e>0?Math.round(t/e*100):0;const s=(Date.now()-this.state.startTime)/1e3;if(s>0){this.state.speed=Math.round(t/s);const r=e-t;this.state.remainingTime=this.state.speed>0?Math.round(r/this.state.speed):0}}complete(){this.state.progress=100,this.state.status="completed"}fail(t){this.state.status="error",this.state.error=t.message||"Upload failed"}reset(){this.state.progress=0,this.state.loaded=0,this.state.total=0,this.state.status="idle",this.state.error=null,this.state.startTime=null,this.state.speed=0,this.state.remainingTime=0}}class f{constructor(t,e,s){this.config=i(i({},h),t),this.reactive=e,this.ref=s,this.interceptors={request:[],response:[]},this.state=e({loading:!1,error:null,lastRequest:null,pendingRequests:0}),this.abortControllers=/* @__PURE__ */new Map}setBaseURL(t){return this.config.baseURL=t,this}setHeader(t,e){return this.config.headers[t]=e,this}setHeaders(t){return this.config.headers=i(i({},this.config.headers),t),this}removeHeader(t){return delete this.config.headers[t],this}setAuthToken(t){return t?this.config.headers.Authorization=`Bearer ${t}`:delete this.config.headers.Authorization,this}setBasicAuth(t,e){const s=btoa(`${t}:${e}`);return this.config.headers.Authorization=`Basic ${s}`,this}clearAuth(){return delete this.config.headers.Authorization,this}setTimeout(t){return this.config.timeout=t,this}addRequestInterceptor(t,e){const s=this.interceptors.request.length;return this.interceptors.request.push({fulfilled:t,rejected:e,id:s}),s}addResponseInterceptor(t,e){const s=this.interceptors.response.length;return this.interceptors.response.push({fulfilled:t,rejected:e,id:s}),s}removeRequestInterceptor(t){const e=this.interceptors.request.findIndex(e=>e.id===t);-1!==e&&this.interceptors.request.splice(e,1)}removeResponseInterceptor(t){const e=this.interceptors.response.findIndex(e=>e.id===t);-1!==e&&this.interceptors.response.splice(e,1)}clearInterceptors(){this.interceptors.request=[],this.interceptors.response=[]}buildURL(t,e={}){let s=t.startsWith("http")?t:`${this.config.baseURL}${t}`;const r=new URLSearchParams;for(const[n,a]of Object.entries(e))null!=a&&(Array.isArray(a)?a.forEach(t=>r.append(n,t)):r.append(n,a));const o=r.toString();return o&&(s+=(s.includes("?")?"&":"?")+o),s}async runRequestInterceptors(t){let e=i({},t);for(const r of this.interceptors.request)try{r.fulfilled&&(e=await r.fulfilled(e)||e)}catch(s){if(!r.rejected)throw s;e=await r.rejected(s)||e}return e}async runResponseInterceptors(t){let e=t;for(const r of this.interceptors.response)try{r.fulfilled&&(e=await r.fulfilled(e)||e)}catch(s){if(!r.rejected)throw s;e=await r.rejected(s)}return e}async runResponseErrorInterceptors(t){for(const s of this.interceptors.response)if(s.rejected)try{const e=await s.rejected(t);if(void 0!==e)return e}catch(e){t=e}throw t}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async request(t){const e=this.generateRequestId(),s=new AbortController;this.abortControllers.set(e,s);let r=i({method:"GET",headers:i({},this.config.headers),timeout:this.config.timeout,withCredentials:this.config.withCredentials,retries:this.config.retries,retryDelay:this.config.retryDelay},t);t.headers&&(r.headers=i(i({},r.headers),t.headers));try{r=await this.runRequestInterceptors(r)}catch(d){throw this.abortControllers.delete(e),d}const o=this.buildURL(r.url,r.params),n={method:r.method.toUpperCase(),headers:r.headers,signal:s.signal,credentials:r.withCredentials?"include":"same-origin"};void 0===r.body||["GET","HEAD"].includes(n.method)||(r.body instanceof FormData?(delete n.headers["Content-Type"],n.body=r.body):"object"==typeof r.body?n.body=JSON.stringify(r.body):n.body=r.body),this.state.loading=!0,this.state.pendingRequests++,this.state.lastRequest={url:o,method:n.method,time:Date.now()},this.state.error=null;const a=setTimeout(()=>{s.abort()},r.timeout),l=async t=>{try{const s=await fetch(o,n);let a;const d=s.headers.get("content-type");if(d&&d.includes("application/json"))a=await s.json();else if(d&&d.includes("text/"))a=await s.text();else{const t=await s.text();try{a=JSON.parse(t)}catch(e){a=t}}const h={data:a,status:s.status,statusText:s.statusText,headers:Object.fromEntries(s.headers.entries()),config:r,request:i({url:o},n)};if(!s.ok){const e=new u((null==a?void 0:a.message)||s.statusText||`Request failed with status ${s.status}`,s.status,h,i({url:o},n));if(s.status>=500&&t>0)return await new Promise(t=>setTimeout(t,r.retryDelay)),l(t-1);throw e}return await this.runResponseInterceptors(h)}catch(d){if("AbortError"===d.name)throw new u("Request timeout",408,null,i({url:o},n));if("TypeError"===d.name&&t>0)return await new Promise(t=>setTimeout(t,r.retryDelay)),l(t-1);try{return await this.runResponseErrorInterceptors(d)}catch(e){throw e}}};try{return await l(r.retries)}finally{clearTimeout(a),this.abortControllers.delete(e),this.state.pendingRequests--,this.state.loading=this.state.pendingRequests>0}}async get(t,e={}){return this.request(l(i({},e),{method:"GET",url:t}))}async post(t,e={},s={}){return this.request(l(i({},s),{method:"POST",url:t,body:e}))}async put(t,e={},s={}){return this.request(l(i({},s),{method:"PUT",url:t,body:e}))}async patch(t,e={},s={}){return this.request(l(i({},s),{method:"PATCH",url:t,body:e}))}async delete(t,e={}){return this.request(l(i({},e),{method:"DELETE",url:t}))}async head(t,e={}){return this.request(l(i({},e),{method:"HEAD",url:t}))}async options(t,e={}){return this.request(l(i({},e),{method:"OPTIONS",url:t}))}upload(t,e,s={}){const r=new p(this.reactive),o=new AbortController,n=this.generateRequestId();this.abortControllers.set(n,o);const a=s,{fieldName:l="file",additionalData:h={},headers:c={},onProgress:f,onComplete:m,onError:g}=a,b=d(a,["fieldName","additionalData","headers","onProgress","onComplete","onError"]);let w;if(e instanceof FormData)w=e;else{w=new FormData,Array.isArray(e)?e.forEach((t,e)=>{w.append(`${l}[${e}]`,t)}):w.append(l,e);for(const[t,e]of Object.entries(h))null!=e&&w.append(t,"object"==typeof e?JSON.stringify(e):e)}let y=0;for(const[,i]of w.entries())i instanceof File?y+=i.size:"string"==typeof i&&(y+=new Blob([i]).size);r.start(y);return{promise:new Promise((e,s)=>{var a;const l=new XMLHttpRequest;l.upload.addEventListener("progress",t=>{t.lengthComputable&&(r.update(t.loaded,t.total),f&&f({loaded:t.loaded,total:t.total,progress:r.state.progress,speed:r.state.speed,remainingTime:r.state.remainingTime}))}),l.addEventListener("load",async()=>{let o;this.abortControllers.delete(n);try{o=JSON.parse(l.responseText)}catch(i){o=l.responseText}const a={data:o,status:l.status,statusText:l.statusText,headers:this.parseXHRHeaders(l.getAllResponseHeaders())};if(l.status>=200&&l.status<300){r.complete();try{const t=await this.runResponseInterceptors(a);m&&m(t),e(t)}catch(d){r.fail(d),g&&g(d),s(d)}}else{const e=new u((null==o?void 0:o.message)||l.statusText||"Upload failed",l.status,a,{url:t,method:"POST"});r.fail(e);try{await this.runResponseErrorInterceptors(e)}catch(i){g&&g(i),s(i)}}}),l.addEventListener("error",()=>{this.abortControllers.delete(n);const e=new u("Network error during upload",0,null,{url:t,method:"POST"});r.fail(e),g&&g(e),s(e)}),l.addEventListener("abort",()=>{this.abortControllers.delete(n);const e=new u("Upload cancelled",0,null,{url:t,method:"POST"});r.fail(e),g&&g(e),s(e)}),l.addEventListener("timeout",()=>{this.abortControllers.delete(n);const e=new u("Upload timeout",408,null,{url:t,method:"POST"});r.fail(e),g&&g(e),s(e)}),o.signal.addEventListener("abort",()=>{l.abort()});const d=this.buildURL(t);l.open("POST",d);const h=i(i({},this.config.headers),c);delete h["Content-Type"];for(const[t,r]of Object.entries(h))l.setRequestHeader(t,r);l.timeout=b.timeout||this.config.timeout,l.withCredentials=null!=(a=b.withCredentials)?a:this.config.withCredentials,l.send(w)}),tracker:r.state,abort:()=>o.abort(),requestId:n}}parseXHRHeaders(t){const e={};return t?(t.split("\r\n").forEach(t=>{const[s,...r]=t.split(":");s&&r.length&&(e[s.trim().toLowerCase()]=r.join(":").trim())}),e):e}download(t,e={}){const s=new p(this.reactive),r=new AbortController,o=this.generateRequestId();this.abortControllers.set(o,r);const n=e,{filename:a,onProgress:l,onComplete:h,onError:c}=n;d(n,["filename","onProgress","onComplete","onError"]);return{promise:(async()=>{try{const n=await fetch(this.buildURL(t),{method:"GET",headers:i(i({},this.config.headers),e.headers),signal:r.signal,credentials:this.config.withCredentials?"include":"same-origin"});if(!n.ok)throw new u(`Download failed with status ${n.status}`,n.status,null,{url:t,method:"GET"});const d=n.headers.get("content-length"),c=d?parseInt(d,10):0;s.start(c);const p=n.body.getReader(),f=[];let m=0;for(;;){const{done:t,value:e}=await p.read();if(t)break;f.push(e),m+=e.length,c>0&&(s.update(m,c),l&&l({loaded:m,total:c,progress:s.state.progress,speed:s.state.speed,remainingTime:s.state.remainingTime}))}s.complete();const g=new Blob(f);if(a){const t=URL.createObjectURL(g),e=document.createElement("a");e.href=t,e.download=a,document.body.appendChild(e),e.click(),document.body.removeChild(e),URL.revokeObjectURL(t)}const b={blob:g,filename:a,size:g.size};return h&&h(b),this.abortControllers.delete(o),b}catch(n){if(this.abortControllers.delete(o),"AbortError"===n.name){const e=new u("Download cancelled",0,null,{url:t,method:"GET"});throw s.fail(e),c&&c(e),e}throw s.fail(n),c&&c(n),n}})(),tracker:s.state,abort:()=>r.abort(),requestId:o}}cancelRequest(t){const e=this.abortControllers.get(t);e&&(e.abort(),this.abortControllers.delete(t))}cancelAll(){for(const[t,e]of this.abortControllers)e.abort();this.abortControllers.clear(),this.state.loading=!1,this.state.pendingRequests=0}create(t={}){return new f(i(i({},this.config),t),this.reactive,this.ref)}}const m={install(t,e={}){const{reactive:s,ref:r}=t,o=new f(e,s,r);m._instance=o,t.onHook("afterCompile",(t,e,s)=>{e.$http||(e.$http=o,e.$get=o.get.bind(o),e.$post=o.post.bind(o),e.$put=o.put.bind(o),e.$patch=o.patch.bind(o),e.$delete=o.delete.bind(o),e.$upload=o.upload.bind(o),e.$download=o.download.bind(o))}),t.onHook("onError",(t,e,s)=>{t.isHttpError})},getInstance:()=>m._instance||null};function g(t={}){return new f(t,t=>t,t=>({value:t}))}export{u as HttpError,c as HttpStatus,p as UploadTracker,f as ZogHttpClient,m as ZogHttpPlugin,g as createHttpClient,m as default};
1
+ var t=Object.defineProperty,e=Object.defineProperties,s=Object.getOwnPropertyDescriptors,r=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable,a=(e,s,r)=>s in e?t(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r,i=(t,e)=>{for(var s in e||(e={}))o.call(e,s)&&a(t,s,e[s]);if(r)for(var s of r(e))n.call(e,s)&&a(t,s,e[s]);return t},l=(t,r)=>e(t,s(r)),d=(t,e)=>{var s={};for(var a in t)o.call(t,a)&&e.indexOf(a)<0&&(s[a]=t[a]);if(null!=t&&r)for(var a of r(t))e.indexOf(a)<0&&n.call(t,a)&&(s[a]=t[a]);return s};const h={baseURL:"",timeout:3e4,headers:{"Content-Type":"application/json"},withCredentials:!1,retries:0,retryDelay:1e3},c={OK:200,CREATED:201,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,UNPROCESSABLE_ENTITY:422,INTERNAL_SERVER_ERROR:500,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503};class u extends Error{constructor(t,e,s,r){super(t),this.name="HttpError",this.status=e,this.response=s,this.request=r,this.isHttpError=!0}}class p{constructor(t){this.state=t({progress:0,loaded:0,total:0,status:"idle",error:null,startTime:null,speed:0,remainingTime:0})}start(t){this.state.progress=0,this.state.loaded=0,this.state.total=t,this.state.status="uploading",this.state.error=null,this.state.startTime=Date.now(),this.state.speed=0,this.state.remainingTime=0}update(t,e){this.state.loaded=t,this.state.total=e,this.state.progress=e>0?Math.round(t/e*100):0;const s=(Date.now()-this.state.startTime)/1e3;if(s>0){this.state.speed=Math.round(t/s);const r=e-t;this.state.remainingTime=this.state.speed>0?Math.round(r/this.state.speed):0}}complete(){this.state.progress=100,this.state.status="completed"}fail(t){this.state.status="error",this.state.error=t.message||"Upload failed"}reset(){this.state.progress=0,this.state.loaded=0,this.state.total=0,this.state.status="idle",this.state.error=null,this.state.startTime=null,this.state.speed=0,this.state.remainingTime=0}}class f{constructor(t,e,s){this.config=i(i({},h),t),this.reactive=e,this.ref=s,this.interceptors={request:[],response:[]},this.state=e({loading:!1,error:null,lastRequest:null,pendingRequests:0}),this.abortControllers=/* @__PURE__ */new Map}setBaseURL(t){return this.config.baseURL=t,this}setHeader(t,e){return this.config.headers[t]=e,this}setHeaders(t){return this.config.headers=i(i({},this.config.headers),t),this}removeHeader(t){return delete this.config.headers[t],this}setAuthToken(t){return t?this.config.headers.Authorization=`Bearer ${t}`:delete this.config.headers.Authorization,this}setBasicAuth(t,e){const s=btoa(`${t}:${e}`);return this.config.headers.Authorization=`Basic ${s}`,this}clearAuth(){return delete this.config.headers.Authorization,this}setTimeout(t){return this.config.timeout=t,this}addRequestInterceptor(t,e){const s=this.interceptors.request.length;return this.interceptors.request.push({fulfilled:t,rejected:e,id:s}),s}addResponseInterceptor(t,e){const s=this.interceptors.response.length;return this.interceptors.response.push({fulfilled:t,rejected:e,id:s}),s}removeRequestInterceptor(t){const e=this.interceptors.request.findIndex(e=>e.id===t);-1!==e&&this.interceptors.request.splice(e,1)}removeResponseInterceptor(t){const e=this.interceptors.response.findIndex(e=>e.id===t);-1!==e&&this.interceptors.response.splice(e,1)}clearInterceptors(){this.interceptors.request=[],this.interceptors.response=[]}buildURL(t,e={}){let s=t.startsWith("http")?t:`${this.config.baseURL}${t}`;const r=new URLSearchParams;for(const[n,a]of Object.entries(e))null!=a&&(Array.isArray(a)?a.forEach(t=>r.append(n,t)):r.append(n,a));const o=r.toString();return o&&(s+=(s.includes("?")?"&":"?")+o),s}async runRequestInterceptors(t){let e=i({},t);for(const r of this.interceptors.request)try{r.fulfilled&&(e=await r.fulfilled(e)||e)}catch(s){if(!r.rejected)throw s;e=await r.rejected(s)||e}return e}async runResponseInterceptors(t){let e=t;for(const r of this.interceptors.response)try{r.fulfilled&&(e=await r.fulfilled(e)||e)}catch(s){if(!r.rejected)throw s;e=await r.rejected(s)}return e}async runResponseErrorInterceptors(t){for(const s of this.interceptors.response)if(s.rejected)try{const e=await s.rejected(t);if(void 0!==e)return e}catch(e){t=e}throw t}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async request(t){const e=this.generateRequestId(),s=new AbortController;this.abortControllers.set(e,s);let r=i({method:"GET",headers:i({},this.config.headers),timeout:this.config.timeout,withCredentials:this.config.withCredentials,retries:this.config.retries,retryDelay:this.config.retryDelay},t);t.headers&&(r.headers=i(i({},r.headers),t.headers));try{r=await this.runRequestInterceptors(r)}catch(d){throw this.abortControllers.delete(e),d}const o=this.buildURL(r.url,r.params),n={method:r.method.toUpperCase(),headers:r.headers,signal:s.signal,credentials:r.withCredentials?"include":"same-origin"};void 0===r.body||["GET","HEAD"].includes(n.method)||(r.body instanceof FormData?(delete n.headers["Content-Type"],n.body=r.body):"object"==typeof r.body?n.body=JSON.stringify(r.body):n.body=r.body),this.state.loading=!0,this.state.pendingRequests++,this.state.lastRequest={url:o,method:n.method,time:Date.now()},this.state.error=null;const a=setTimeout(()=>{s.abort()},r.timeout),l=async t=>{try{const s=await fetch(o,n);let a;const d=s.headers.get("content-type");if(d&&d.includes("application/json"))a=await s.json();else if(d&&d.includes("text/"))a=await s.text();else{const t=await s.text();try{a=JSON.parse(t)}catch(e){a=t}}const h={data:a,status:s.status,statusText:s.statusText,headers:Object.fromEntries(s.headers.entries()),config:r,request:i({url:o},n)};if(!s.ok){const e=new u((null==a?void 0:a.message)||s.statusText||`Request failed with status ${s.status}`,s.status,h,i({url:o},n));if(s.status>=500&&t>0)return await new Promise(t=>setTimeout(t,r.retryDelay)),l(t-1);throw e}return await this.runResponseInterceptors(h)}catch(d){if("AbortError"===d.name)throw new u("Request timeout",408,null,i({url:o},n));if("TypeError"===d.name&&t>0)return await new Promise(t=>setTimeout(t,r.retryDelay)),l(t-1);try{return await this.runResponseErrorInterceptors(d)}catch(e){throw e}}};try{return await l(r.retries)}finally{clearTimeout(a),this.abortControllers.delete(e),this.state.pendingRequests--,this.state.loading=this.state.pendingRequests>0}}async get(t,e={}){return this.request(l(i({},e),{method:"GET",url:t}))}async post(t,e={},s={}){return this.request(l(i({},s),{method:"POST",url:t,body:e}))}async put(t,e={},s={}){return this.request(l(i({},s),{method:"PUT",url:t,body:e}))}async patch(t,e={},s={}){return this.request(l(i({},s),{method:"PATCH",url:t,body:e}))}async delete(t,e={}){return this.request(l(i({},e),{method:"DELETE",url:t}))}async head(t,e={}){return this.request(l(i({},e),{method:"HEAD",url:t}))}async options(t,e={}){return this.request(l(i({},e),{method:"OPTIONS",url:t}))}upload(t,e,s={}){const r=new p(this.reactive),o=new AbortController,n=this.generateRequestId();this.abortControllers.set(n,o);const a=s,{fieldName:l="file",additionalData:h={},headers:c={},onProgress:f,onComplete:m,onError:g}=a,b=d(a,["fieldName","additionalData","headers","onProgress","onComplete","onError"]);let w;if(e instanceof FormData)w=e;else{w=new FormData,Array.isArray(e)?e.forEach((t,e)=>{w.append(`${l}[${e}]`,t)}):w.append(l,e);for(const[t,e]of Object.entries(h))null!=e&&w.append(t,"object"==typeof e?JSON.stringify(e):e)}let y=0;for(const[,i]of w.entries())i instanceof File?y+=i.size:"string"==typeof i&&(y+=new Blob([i]).size);r.start(y);return{promise:new Promise((e,s)=>{var a;const l=new XMLHttpRequest;l.upload.addEventListener("progress",t=>{t.lengthComputable&&(r.update(t.loaded,t.total),f&&f({loaded:t.loaded,total:t.total,progress:r.state.progress,speed:r.state.speed,remainingTime:r.state.remainingTime}))}),l.addEventListener("load",async()=>{let o;this.abortControllers.delete(n);try{o=JSON.parse(l.responseText)}catch(i){o=l.responseText}const a={data:o,status:l.status,statusText:l.statusText,headers:this.parseXHRHeaders(l.getAllResponseHeaders())};if(l.status>=200&&l.status<300){r.complete();try{const t=await this.runResponseInterceptors(a);m&&m(t),e(t)}catch(d){r.fail(d),g&&g(d),s(d)}}else{const e=new u((null==o?void 0:o.message)||l.statusText||"Upload failed",l.status,a,{url:t,method:"POST"});r.fail(e);try{await this.runResponseErrorInterceptors(e)}catch(i){g&&g(i),s(i)}}}),l.addEventListener("error",()=>{this.abortControllers.delete(n);const e=new u("Network error during upload",0,null,{url:t,method:"POST"});r.fail(e),g&&g(e),s(e)}),l.addEventListener("abort",()=>{this.abortControllers.delete(n);const e=new u("Upload cancelled",0,null,{url:t,method:"POST"});r.fail(e),g&&g(e),s(e)}),l.addEventListener("timeout",()=>{this.abortControllers.delete(n);const e=new u("Upload timeout",408,null,{url:t,method:"POST"});r.fail(e),g&&g(e),s(e)}),o.signal.addEventListener("abort",()=>{l.abort()});const d=this.buildURL(t);l.open("POST",d);const h=i(i({},this.config.headers),c);delete h["Content-Type"];for(const[t,r]of Object.entries(h))l.setRequestHeader(t,r);l.timeout=b.timeout||this.config.timeout,l.withCredentials=null!=(a=b.withCredentials)?a:this.config.withCredentials,l.send(w)}),tracker:r.state,abort:()=>o.abort(),requestId:n}}parseXHRHeaders(t){const e={};return t?(t.split("\r\n").forEach(t=>{const[s,...r]=t.split(":");s&&r.length&&(e[s.trim().toLowerCase()]=r.join(":").trim())}),e):e}download(t,e={}){const s=new p(this.reactive),r=new AbortController,o=this.generateRequestId();this.abortControllers.set(o,r);const n=e,{filename:a,onProgress:l,onComplete:h,onError:c}=n;d(n,["filename","onProgress","onComplete","onError"]);return{promise:(async()=>{try{const n=await fetch(this.buildURL(t),{method:"GET",headers:i(i({},this.config.headers),e.headers),signal:r.signal,credentials:this.config.withCredentials?"include":"same-origin"});if(!n.ok)throw new u(`Download failed with status ${n.status}`,n.status,null,{url:t,method:"GET"});const d=n.headers.get("content-length"),c=d?parseInt(d,10):0;s.start(c);const p=n.body.getReader(),f=[];let m=0;for(;;){const{done:t,value:e}=await p.read();if(t)break;f.push(e),m+=e.length,c>0&&(s.update(m,c),l&&l({loaded:m,total:c,progress:s.state.progress,speed:s.state.speed,remainingTime:s.state.remainingTime}))}s.complete();const g=new Blob(f);if(a){const t=URL.createObjectURL(g),e=document.createElement("a");e.href=t,e.download=a,document.body.appendChild(e),e.click(),document.body.removeChild(e),URL.revokeObjectURL(t)}const b={blob:g,filename:a,size:g.size};return h&&h(b),this.abortControllers.delete(o),b}catch(n){if(this.abortControllers.delete(o),"AbortError"===n.name){const e=new u("Download cancelled",0,null,{url:t,method:"GET"});throw s.fail(e),c&&c(e),e}throw s.fail(n),c&&c(n),n}})(),tracker:s.state,abort:()=>r.abort(),requestId:o}}cancelRequest(t){const e=this.abortControllers.get(t);e&&(e.abort(),this.abortControllers.delete(t))}cancelAll(){for(const[t,e]of this.abortControllers)e.abort();this.abortControllers.clear(),this.state.loading=!1,this.state.pendingRequests=0}create(t={}){return new f(i(i({},this.config),t),this.reactive,this.ref)}}let m=null;const g={install(t,e={}){const{reactive:s,ref:r}=t,o=new f(e,s,r);m=o,g._instance=o,t.onHook("afterCompile",(t,e,s)=>{e.$http||(e.$http=o,e.$get=o.get.bind(o),e.$post=o.post.bind(o),e.$put=o.put.bind(o),e.$patch=o.patch.bind(o),e.$delete=o.delete.bind(o),e.$upload=o.upload.bind(o),e.$download=o.download.bind(o))}),t.onHook("onError",(t,e,s)=>{t.isHttpError})},getInstance:()=>g._instance||null};function b(t={}){return new f(t,t=>t,t=>({value:t}))}export{m as $http,u as HttpError,c as HttpStatus,p as UploadTracker,f as ZogHttpClient,g as ZogHttpPlugin,b as createHttpClient,g as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zogjs/http",
3
- "version": "0.4.8",
3
+ "version": "0.4.9",
4
4
  "description": "Powerful HTTP client plugin for Zog.js - Full-featured request library with interceptors, file upload/download progress tracking, and reactive state management",
5
5
  "type": "module",
6
6
  "main": "dist/zog-http.es.js",