UNPKG

@uploadx/client

Version:

Resumable upload client for browser and Node.js

3 lines (2 loc) 15.7 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("axios")):"function"==typeof define&&define.amd?define(["axios"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).UploadxClient=t(e.axios)}(this,(function(e){"use strict";var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},t(e,n)};var n,r,o=function(){return o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},o.apply(this,arguments)};function i(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{u(r.next(e))}catch(e){i(e)}}function a(e){try{u(r.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((r=r.apply(e,t||[])).next())}))}function s(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(u){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var u=a(function(){if(r)return n;r=1;const e=new Set(["ENOTFOUND","ENETUNREACH","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_CRL","UNABLE_TO_DECRYPT_CERT_SIGNATURE","UNABLE_TO_DECRYPT_CRL_SIGNATURE","UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY","CERT_SIGNATURE_FAILURE","CRL_SIGNATURE_FAILURE","CERT_NOT_YET_VALID","CERT_HAS_EXPIRED","CRL_NOT_YET_VALID","CRL_HAS_EXPIRED","ERROR_IN_CERT_NOT_BEFORE_FIELD","ERROR_IN_CERT_NOT_AFTER_FIELD","ERROR_IN_CRL_LAST_UPDATE_FIELD","ERROR_IN_CRL_NEXT_UPDATE_FIELD","OUT_OF_MEM","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_CHAIN_TOO_LONG","CERT_REVOKED","INVALID_CA","PATH_LENGTH_EXCEEDED","INVALID_PURPOSE","CERT_UNTRUSTED","CERT_REJECTED","HOSTNAME_MISMATCH"]);return n=t=>!e.has(t&&t.code)}());const c="axios-retry";function l(e){return!e.response&&(!!e.code&&(!["ERR_CANCELED","ECONNABORTED"].includes(e.code)&&u(e)))}const d=["get","head","options"],p=d.concat(["put","delete"]);function f(e){return"ECONNABORTED"!==e.code&&(!e.response||429===e.response.status||e.response.status>=500&&e.response.status<=599)}function h(e){return!!e.config?.method&&(f(e)&&-1!==p.indexOf(e.config.method))}function E(e){return l(e)||h(e)}function v(e=void 0){const t=e?.response?.headers["retry-after"];if(!t)return 0;let n=1e3*(Number(t)||0);return 0===n&&(n=(new Date(t).valueOf()||0)-Date.now()),Math.max(0,n)}function y(e=0,t=void 0,n=100){const r=2**e*n,o=Math.max(r,v(t));return o+.2*o*Math.random()}const _={retries:3,retryCondition:E,retryDelay:function(e=0,t=void 0){return Math.max(0,v(t))},shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function b(e,t,n=!1){const r=function(e,t){return{..._,...t,...e[c]}}(e,t||{});return r.retryCount=r.retryCount||0,r.lastRequestTime&&!n||(r.lastRequestTime=Date.now()),e[c]=r,r}const R=(e,t)=>{const n=e.interceptors.request.use((e=>(b(e,t,!0),e[c]?.validateResponse&&(e.validateStatus=()=>!1),e))),r=e.interceptors.response.use(null,(async n=>{const{config:r}=n;if(!r)return Promise.reject(n);const o=b(r,t);return n.response&&o.validateResponse?.(n.response)?n.response:await async function(e,t){const{retries:n,retryCondition:r}=e,o=(e.retryCount||0)<n&&r(t);if("object"==typeof o)try{return!1!==await o}catch(e){return!1}return o}(o,n)?async function(e,t,n,r){t.retryCount+=1;const{retryDelay:o,shouldResetTimeout:i,onRetry:s}=t,a=o(t.retryCount,n);if(function(e,t){e.defaults.agent===t.agent&&delete t.agent,e.defaults.httpAgent===t.httpAgent&&delete t.httpAgent,e.defaults.httpsAgent===t.httpsAgent&&delete t.httpsAgent}(e,r),!i&&r.timeout&&t.lastRequestTime){const e=Date.now()-t.lastRequestTime,o=r.timeout-e-a;if(o<=0)return Promise.reject(n);r.timeout=o}return r.transformRequest=[e=>e],await s(t.retryCount,n,r),r.signal?.aborted?Promise.resolve(e(r)):new Promise((t=>{const n=()=>{clearTimeout(o),t(e(r))},o=setTimeout((()=>{t(e(r)),r.signal?.removeEventListener&&r.signal.removeEventListener("abort",n)}),a);r.signal?.addEventListener&&r.signal.addEventListener("abort",n,{once:!0})}))}(e,o,n,r):(await async function(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}(o,n),Promise.reject(n))}));return{requestInterceptorId:n,responseInterceptorId:r}};R.isNetworkError=l,R.isSafeRequestError=function(e){return!!e.config?.method&&(f(e)&&-1!==d.indexOf(e.config.method))},R.isIdempotentRequestError=h,R.isNetworkOrIdempotentRequestError=E,R.exponentialDelay=y,R.linearDelay=function(e=100){return(t=0,n=void 0)=>{const r=t*e;return Math.max(r,v(n))}},R.isRetryableError=f;var C="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,m=function(e){function n(t){void 0===t&&(t="Operation aborted");var n=e.call(this,t)||this;return n.name="AbortError",n}return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}(n,e),n}(Error),T=function(){function t(t){void 0===t&&(t={}),this.abortController=new AbortController,this.chunkSize=t.chunkSize||5242880,this.client=e.create(o({maxBodyLength:Number.POSITIVE_INFINITY,maxContentLength:Number.POSITIVE_INFINITY,timeout:6e4,validateStatus:function(e){return e>=200&&e<400||308===e},signal:this.abortController.signal},t.requestConfig)),R(this.client,o({retries:5,retryDelay:y,retryCondition:function(e){var t,n;return R.isNetworkError(e)||"ECONNRESET"===e.code||R.isRetryableError(e)||429===(null===(t=e.response)||void 0===t?void 0:t.status)||((null===(n=e.response)||void 0===n?void 0:n.status)||0)>=500}},t.retryConfig))}return t.prototype.abort=function(){this.abortController.abort(),this.abortController=new AbortController},t.prototype.deleteUpload=function(e,t){return i(this,void 0,void 0,(function(){var n;return s(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this.client.delete(e,{signal:t})];case 1:return r.sent(),[3,3];case 2:throw n=r.sent(),this.handleError(n,"Failed to delete upload");case 3:return[2]}}))}))},t.prototype.updateUpload=function(e,t,n){return i(this,void 0,void 0,(function(){var r;return s(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this.client.patch(e,t,{headers:{"Content-Type":"application/json"},signal:n})];case 1:return o.sent(),[3,3];case 2:throw r=o.sent(),this.handleError(r,"Failed to update metadata");case 3:return[2]}}))}))},t.prototype.createUpload=function(e,t,n){return i(this,void 0,void 0,(function(){var r,o,i,a;return s(this,(function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,this.client.post(e,t,{headers:{"X-Upload-Content-Length":t.size,"X-Upload-Content-Type":t.mimeType||"application/octet-stream","Content-Type":"application/json"},signal:n})];case 1:if(!(r=s.sent()).headers.location)throw new Error("Missing Location header in response");return o=null===(a=null==r?void 0:r.headers)||void 0===a?void 0:a.range,[2,{url:new URL(r.headers.location,e).toString(),uploadedBytes:this.parseRangeHeader(o)}];case 2:throw i=s.sent(),this.handleError(i,"Session creation failed");case 3:return[2]}}))}))},t.prototype.createFileUpload=function(e,t,n,r){return i(this,void 0,void 0,(function(){var i,a,u;return s(this,(function(s){switch(s.label){case 0:if(!C)throw new Error("uploadAsFile is only available in Node.js environment");return[4,import("node:fs/promises")];case 1:return[4,s.sent().stat(e)];case 2:return i=s.sent(),a=i.size,u=o(o({},t),{size:a,lastModified:t.lastModified||i.mtimeMs}),[2,this.createUpload(n,u,r)]}}))}))},t.prototype.fileUpload=function(e,t,n,r,o){return i(this,void 0,void 0,(function(){var i,a,u,c,l;return s(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this.createFileUpload(t,n,e,o)];case 1:return i=s.sent(),a=i.url,u=i.uploadedBytes||0,c=n.size,[4,this.uploadFileInChunks(a,t,u,c,r,o)];case 2:return s.sent(),[3,4];case 3:if((l=s.sent())instanceof m)return[2];throw this.handleError(l,"File upload failed for ".concat(t));case 4:return[2]}}))}))},t.prototype.upload=function(e,t,n,r,o){return i(this,void 0,void 0,(function(){var i,a,u,c,l,d;return s(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this.createUpload(e,n,o)];case 1:return i=s.sent(),a=i.url,u=i.uploadedBytes,c=u||0,l=n.size,[4,this.uploadDataInChunks(t,a,c,l,r,o)];case 2:return s.sent(),[3,4];case 3:if((d=s.sent())instanceof m)return[2];throw this.handleError(d,"Upload failed");case 4:return[2]}}))}))},t.prototype.resumeUpload=function(e,t,n,r,o){return i(this,void 0,void 0,(function(){var i,a,u,c;return s(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this.getUploadStatus(e,n,o)];case 1:return i=s.sent(),a=i.uploadedBytes,u=n.size,[4,this.uploadDataInChunks(t,e,a,u,r,o)];case 2:return s.sent(),[3,4];case 3:if((c=s.sent())instanceof m)return[2];throw this.handleError(c,"Upload failed");case 4:return[2]}}))}))},t.prototype.resumeFileUpload=function(e,t,n,r,o){return i(this,void 0,void 0,(function(){var i,a,u,c;return s(this,(function(s){switch(s.label){case 0:if(!C)throw new Error("uploadAsFile is only available in Node.js environment");s.label=1;case 1:return s.trys.push([1,4,,5]),[4,this.getUploadStatus(e,n,o)];case 2:return i=s.sent(),a=i.uploadedBytes,u=n.size,[4,this.uploadFileInChunks(e,t,a,u,r,o)];case 3:return s.sent(),[3,5];case 4:if((c=s.sent())instanceof m)return[2];throw this.handleError(c,"File upload failed for ".concat(t));case 5:return[2]}}))}))},t.prototype.getUploadStatus=function(e,t,n){return i(this,void 0,void 0,(function(){var r,o,i,a;return s(this,(function(s){switch(s.label){case 0:return r={"Content-Type":"application/octet-stream","Content-Range":"bytes */".concat((null==t?void 0:t.size)||"*")},[4,this.client.put(e,null,{headers:r,signal:n})];case 1:return o=s.sent(),i=null===(a=null==o?void 0:o.headers)||void 0===a?void 0:a.range,[2,{uploadedBytes:this.parseRangeHeader(i)}]}}))}))},t.prototype.uploadChunk=function(e,t,n,r,o,a,u){return i(this,void 0,void 0,(function(){var i,c,l,d;return s(this,(function(s){switch(s.label){case 0:return i={"Content-Type":"application/octet-stream","Content-Range":"bytes ".concat(n,"-").concat(r-1,"/").concat(o)},[4,this.client.put(e,t,{headers:i,signal:u,onUploadProgress:a?function(e){var t=e.loaded,r=(n+t)/o;a(Math.min(r,1))}:void 0})];case 1:return c=s.sent(),l=null===(d=null==c?void 0:c.headers)||void 0===d?void 0:d.range,[2,{uploadedBytes:this.parseRangeHeader(l)}]}}))}))},t.prototype.uploadDataInChunks=function(e,t,n,r,o,a){return i(this,void 0,void 0,(function(){return s(this,(function(i){switch(i.label){case 0:return this.isBlob(e)?[4,this.uploadBlobInChunks(t,e,n,r,o,a)]:[3,2];case 1:return i.sent(),[3,6];case 2:return this.isStream(e)?[4,this.uploadStreamInChunks(t,e,n,r,o,a)]:[3,4];case 3:return i.sent(),[3,6];case 4:return[4,this.uploadBufferInChunks(t,e,n,r,o,a)];case 5:i.sent(),i.label=6;case 6:return[2]}}))}))},t.prototype.uploadFileInChunks=function(e,t,n,r,o,a){return i(this,void 0,void 0,(function(){var i,u,c,l,d,p;return s(this,(function(s){switch(s.label){case 0:if(!C)throw new Error("uploadAsFile is only available in Node.js environment");return[4,import("node:fs")];case 1:i=s.sent().createReadStream,u=n,s.label=2;case 2:if(!(u<r))return[3,4];if(null==a?void 0:a.aborted)throw new m;return c=Math.min(u+this.chunkSize,r),l=i(t,{start:u,end:c}),[4,this.uploadChunk(e,l,u,c,r,o,a)];case 3:return d=s.sent(),u=c,void 0!==d.uploadedBytes&&(p=d.uploadedBytes)>u&&(u=p),[3,2];case 4:return[2]}}))}))},t.prototype.uploadBlobInChunks=function(e,t,n,r,o,a){return i(this,void 0,void 0,(function(){var i,u,c;return s(this,(function(s){switch(s.label){case 0:i=n,s.label=1;case 1:if(!(i<r))return[3,3];if(null==a?void 0:a.aborted)throw new m;return u=Math.min(i+this.chunkSize,r),c=t.slice(i,u),[4,this.uploadChunk(e,c,i,u,r,o,a)];case 2:return s.sent(),i=u,[3,1];case 3:return[2]}}))}))},t.prototype.uploadStreamInChunks=function(e,t,n,r,o,a){return i(this,void 0,void 0,(function(){var u,c,l,d=this;return s(this,(function(p){if(!C)throw new Error("Stream uploads are only available in Node.js environment");return u=n,c=[],l=0,[2,new Promise((function(n,p){var f=function(){p(new m)};if(a){if(a.aborted)return void f();a.addEventListener("abort",f)}t.on("data",(function(n){c.push(n),l+=n.length;for(var i=function(){var n=Math.min(u+d.chunkSize,r),i=Buffer.concat(c);c=[i.slice(n-u)],l=i.length-(n-u),t.pause(),d.uploadChunk(e,i.slice(0,n-u),u,n,r,o,a).then((function(e){u=n,t.resume()})).catch((function(e){p(e)}))};l>=d.chunkSize;)i()})),t.on("end",(function(){return i(d,void 0,void 0,(function(){var t,i,d;return s(this,(function(s){switch(s.label){case 0:if(a&&a.removeEventListener("abort",f),!(c.length>0))return[3,4];if(null==a?void 0:a.aborted)return p(new m),[2];t=Math.min(u+l,r),i=Buffer.concat(c),s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this.uploadChunk(e,i,u,t,r,o,a)];case 2:return s.sent(),u+=l,[3,4];case 3:return d=s.sent(),p(d),[2];case 4:return n(),[2]}}))}))})),t.on("error",(function(e){a&&a.removeEventListener("abort",f),p(e)}))}))]}))}))},t.prototype.uploadBufferInChunks=function(e,t,n,r,o,a){return i(this,void 0,void 0,(function(){var i,u,c,l;return s(this,(function(s){switch(s.label){case 0:i=t instanceof ArrayBuffer?new Uint8Array(t):t,u=n,s.label=1;case 1:if(!(u<r))return[3,3];if(null==a?void 0:a.aborted)throw new m;return c=Math.min(u+this.chunkSize,r),l=i.subarray(u,c),[4,this.uploadChunk(e,l,u,c,r,o,a)];case 2:return s.sent(),u=c,[3,1];case 3:return[2]}}))}))},t.prototype.isBlob=function(e){return"undefined"!=typeof Blob&&e instanceof Blob},t.prototype.isStream=function(e){return!!e&&"function"==typeof e.pipe},t.prototype.parseRangeHeader=function(e){if(!e)return 0;var t=e.match(/bytes=\d+-(\d+)/);return t?Number.parseInt(t[1],10)+1:0},t.prototype.handleError=function(t,n){var r,o,i;return t instanceof m?t:e.isAxiosError(t)?new Error("".concat(n,": ").concat(t.message," ").concat((null===(i=null===(o=null===(r=t.response)||void 0===r?void 0:r.data)||void 0===o?void 0:o.error)||void 0===i?void 0:i.message)||t.cause," ")):t instanceof Error?new Error("".concat(n,": ").concat(t.message)):new Error(n)},t}();return window.UploadxClient=T,T})); //# sourceMappingURL=index.min.js.map