Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

upload-js

Package Overview
Dependencies
Maintainers
1
Versions
150
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

upload-js - npm Package Compare versions

Comparing version 1.25.0 to 1.26.0

1

dist/dtos/SetAccessTokenRequestDto.d.ts

@@ -6,3 +6,2 @@ /**

accessToken: string;
accountId: string;
}

2

dist/main.js

@@ -1,1 +0,1 @@

module.exports=(()=>{"use strict";var e={675:(e,t,n)=>{function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?i(e):t}function i(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function a(e){var t="function"==typeof Map?new Map:void 0;return(a=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return s(e,arguments,l(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),c(r,e)})(e)}function s(e,t,n){return(s=u()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&c(o,n.prototype),o}).apply(null,arguments)}function u(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function c(e,t){return(c=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function l(e){return(l=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}n.r(t),n.d(t,{Upload:()=>y});var p=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&c(e,t)}(a,e);var t,n,r=(t=a,n=u(),function(){var e,r=l(t);if(n){var i=l(this).constructor;e=Reflect.construct(r,arguments,i)}else e=r.apply(this,arguments);return o(this,e)});function a(e){var t;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a),t=r.call(this,e),Object.setPrototypeOf(i(t),a.prototype),t}return a}(a(Error));const d=require("upload-api-client-upload-js");function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function h(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var v=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{u(r.next(e))}catch(e){i(e)}}function s(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(a,s)}u((r=r.apply(e,t||[])).next())}))},y=function(){function e(t){var n,r,o,i,a,s,u,c;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=t,this.accountIdLength=7,this.apiKeyPrefix="public_",this.maxUploadConcurrency=5,this.refreshBeforeExpirySeconds=20,this.retryAuthAfterErrorSeconds=5,this.setAccessTokenPath="/api/v1/access_tokens",this.lastAuthSession=void 0,!0===t.debug&&console.log("[upload-js] Initialized with API key '".concat(t.apiKey,"'")),this.apiUrl=null!==(r=null===(n=t.internal)||void 0===n?void 0:n.apiUrl)&&void 0!==r?r:"https://api.upload.io",this.cdnUrl=null!==(i=null===(o=t.internal)||void 0===o?void 0:o.cdnUrl)&&void 0!==i?i:"https://cdn.upload.io",this.authenticateWithApiKey=null===(s=null===(a=t.internal)||void 0===a?void 0:a.authenticateWithApiKey)||void 0===s||s,this.headers=null===(u=t.internal)||void 0===u?void 0:u.headers,this.debugMode=!0===t.debug,t.apiKey.trim()!==t.apiKey)throw new Error("[upload-js] Invalid API key. Whitespace detected: please remove whitespace from the API key and try again.");if(!1===(null===(c=t.internal)||void 0===c?void 0:c.authenticateWithApiKey))this.accountId=t.internal.accountId;else{if(!t.apiKey.startsWith(this.apiKeyPrefix))throw new Error("[upload-js] Invalid API key. API keys must start with '".concat(this.apiKeyPrefix,"'"));if(this.accountId=t.apiKey.substr(this.apiKeyPrefix.length,this.accountIdLength),this.accountId.length!==this.accountIdLength)throw new Error("[upload-js] Invalid API key. API keys must be at least ".concat(this.apiKeyPrefix.length+this.accountIdLength," characters long, but the API key you provided is ").concat(this.apiKeyPrefix.length+this.accountId.length,"."))}}var t,n;return t=e,(n=[{key:"beginAuthSession",value:function(e,t){return v(this,void 0,void 0,regeneratorRuntime.mark((function n(){var r;return regeneratorRuntime.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return this.endAuthSession(),r={accessToken:void 0,accessTokenRefreshHandle:void 0,isActive:!0},this.lastAuthSession=r,n.next=5,this.refreshAccessToken(e,t,r);case 5:case"end":return n.stop()}}),n,this)})))}},{key:"endAuthSession",value:function(){if(void 0!==this.lastAuthSession){var e=this.lastAuthSession;this.lastAuthSession=void 0,void 0!==e.accessTokenRefreshHandle&&clearTimeout(e.accessTokenRefreshHandle),e.isActive=!1}}},{key:"close",value:function(){this.endAuthSession()}},{key:"createFileInputHandler",value:function(e){var t=this;return function(n){var r=n.target;if(void 0===r.files||null===r.files)throw new Error("No property 'files' on input element: ensure 'createFileInputHandler' is set to the 'onchange' attribute on an input of type 'file'.");if(void 0===r.files[0])throw new Error("No file selected.");t.uploadFile(Object.assign(Object.assign({},e),{file:r.files[0]})).then(e.onUploaded,(function(t){void 0!==e.onError?e.onError(t):console.error("Cannot upload file. To remove this console message, handle the error explicitly by providing an 'onError' parameter: upload.createFileInputHandler({onUploaded, onError})",t)}))}}},{key:"uploadFile",value:function(e){return v(this,void 0,void 0,regeneratorRuntime.mark((function t(){var n,r,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=[],r=function(e){n.push(e)},o=function(){return n.forEach((function(e){return e()}))},void 0!==e.onBegin&&e.onBegin({cancel:o}),t.prev=4,t.next=7,this.beginFileUpload(e.file,e,r);case 7:return t.abrupt("return",t.sent);case 10:throw t.prev=10,t.t0=t.catch(4),o(),t.t0;case 14:case"end":return t.stop()}}),t,this,[[4,10]])})))}},{key:"url",value:function(e){return"".concat(this.cdnUrl,"/").concat(e)}},{key:"beginFileUpload",value:function(e,t,n){return v(this,void 0,void 0,regeneratorRuntime.mark((function r(){var o,i,a,s,u,c,l,p,h,y=this;return regeneratorRuntime.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return void 0!==t.onProgress&&t.onProgress({bytesSent:0,bytesTotal:e.size}),o={accountId:this.accountId,fileSize:e.size,fileName:e.name,mime:this.normalizeMimeType(e.type),tag:t.tag,userId:t.userId},this.debug("Initiating file upload. Params = ".concat(JSON.stringify(o))),this.preflight(),r.next=6,d.FilesService.beginUpload(o);case 6:return i=r.sent,a=i.uploadParts.count>1,this.debug("Initiated file upload. Metadata = ".concat(JSON.stringify(i))),s=function(){var e=0;return function(){if(e!==i.uploadParts.count-1)return++e}}(),u=[i.uploadParts.first],c=function(e){return v(y,void 0,void 0,regeneratorRuntime.mark((function t(){var n,r;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(void 0===(n=u.pop())){t.next=4;break}return this.debug("Dequeued part ".concat(n.uploadPartIndex,"."),e),t.abrupt("return",n);case 4:if(void 0!==(r=s())){t.next=8;break}return this.debug("No parts remaining.",e),t.abrupt("return",void 0);case 8:return this.preflight(),this.debug("Fetching metadata for part ".concat(r,"."),e),t.next=12,d.FilesService.getUploadPart(i.file.fileId,r);case 12:return t.abrupt("return",t.sent);case 13:case"end":return t.stop()}}),t,this)})))},l=[],p=function r(o){return v(y,void 0,void 0,regeneratorRuntime.mark((function s(){var u,p,d;return regeneratorRuntime.wrap((function(s){for(;;)switch(s.prev=s.next){case 0:return s.next=2,c(o);case 2:if(void 0===(u=s.sent)){s.next=10;break}return p=0,d=function(n){var r=n.bytesSent;if(void 0===l[o]?l[o]=r:(l[o]-=p,l[o]+=r),p=r,void 0!==t.onProgress){var i=l.reduce((function(e,t){return e+t}));t.onProgress({bytesSent:i,bytesTotal:e.size})}},s.next=8,this.uploadPart(e,i.file,a,u,d,n,o);case 8:return s.next=10,r(o);case 10:case"end":return s.stop()}}),s,this)})))},r.next=16,Promise.all((g=Array(this.maxUploadConcurrency).keys(),function(e){if(Array.isArray(e))return f(e)}(g)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(g)||function(e,t){if(e){if("string"==typeof e)return f(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?f(e,t):void 0}}(g)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()).map((function(e){return v(y,void 0,void 0,regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,p(e);case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}}),t)})))})));case 16:return h={accountId:o.accountId,file:e,fileId:i.file.fileId,fileSize:i.file.size,fileUrl:this.url(i.file.fileId),tag:o.tag,userId:o.userId,mime:i.file.mime},this.debug("File upload completed. File = ".concat(JSON.stringify(h))),r.abrupt("return",h);case 19:case"end":return r.stop()}var g}),r,this)})))}},{key:"debug",value:function(e,t){this.debugMode&&console.log("[upload-js] ".concat(e).concat(void 0!==t?" (Worker ".concat(t,")"):""))}},{key:"error",value:function(e){console.error("[upload-js] ".concat(e))}},{key:"normalizeMimeType",value:function(e){var t=e.toLowerCase();return/^[a-z0-9]+\/[a-z0-9+\-._]+$/.test(t)?t:void 0}},{key:"preflight",value:function(){var e,t=this;d.OpenAPI.BASE=this.apiUrl,this.authenticateWithApiKey?(d.OpenAPI.WITH_CREDENTIALS=!0,d.OpenAPI.USERNAME="apikey",d.OpenAPI.PASSWORD=this.config.apiKey):(d.OpenAPI.WITH_CREDENTIALS=!1,delete d.OpenAPI.USERNAME,delete d.OpenAPI.PASSWORD);var n=this.headers,r=null===(e=this.lastAuthSession)||void 0===e?void 0:e.accessToken;void 0!==n||void 0!==r?d.OpenAPI.HEADERS=function(){return v(t,void 0,void 0,regeneratorRuntime.mark((function e(){var t,r,o;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(void 0!==n){e.next=4;break}e.t0={},e.next=7;break;case 4:return e.next=6,n();case 6:e.t0=e.sent;case 7:return r=e.t0,o=null===(t=this.lastAuthSession)||void 0===t?void 0:t.accessToken,e.abrupt("return",Object.assign(Object.assign({},r),void 0===o?{}:{"authorization-user":o}));case 10:case"end":return e.stop()}}),e,this)})))}:delete d.OpenAPI.HEADERS}},{key:"preflightExternalApi",value:function(e,t){d.OpenAPI.BASE=e,d.OpenAPI.WITH_CREDENTIALS=t,delete d.OpenAPI.USERNAME,delete d.OpenAPI.PASSWORD,delete d.OpenAPI.HEADERS}},{key:"putUploadPart",value:function(e,t,n,r,o,i){return v(this,void 0,void 0,regeneratorRuntime.mark((function a(){var s,u;return regeneratorRuntime.wrap((function(a){for(;;)switch(a.prev=a.next){case 0:return s=new XMLHttpRequest,u=!0,i((function(){u&&s.abort()})),a.prev=3,a.next=6,new Promise((function(i,a){s.upload.addEventListener("progress",(function(e){e.lengthComputable&&o({bytesSent:e.loaded,bytesTotal:e.total})}),!1),s.addEventListener("load",(function(){if(o({bytesSent:r.size,bytesTotal:r.size}),2===Math.floor(s.status/100)){var e=s.getResponseHeader("etag");null==e?a(new Error("File upload error: no etag header in upload response.")):i({etag:e})}else a(new Error("File upload error: status code ".concat(s.status)))})),s.onabort=function(){return a(new p("File upload cancelled."))},s.onerror=function(){return a(new Error("File upload error."))},s.ontimeout=function(){return a(new Error("File upload timeout."))},s.open("PUT",e),n||(s.setRequestHeader("content-type",t.mime),null!==t.name&&s.setRequestHeader("content-disposition",'attachment; filename="'.concat(encodeURIComponent(t.name),"\"; filename*=UTF-8''").concat(encodeURIComponent(t.name)))),s.send(r)}));case 6:return a.abrupt("return",a.sent);case 7:return a.prev=7,u=!1,a.finish(7);case 10:case"end":return a.stop()}}),a,null,[[3,,7,10]])})))}},{key:"uploadPart",value:function(e,t,n,r,o,i,a){return v(this,void 0,void 0,regeneratorRuntime.mark((function s(){var u,c,l;return regeneratorRuntime.wrap((function(s){for(;;)switch(s.prev=s.next){case 0:return u=-1===r.range.inclusiveEnd?new Blob:e.slice(r.range.inclusiveStart,r.range.inclusiveEnd+1),this.debug("Uploading part ".concat(r.uploadPartIndex,"."),a),s.next=4,this.putUploadPart(r.uploadUrl,t,n,u,o,i);case 4:return c=s.sent,l=c.etag,this.preflight(),s.next=9,d.FilesService.completeUploadPart(r.fileId,r.uploadPartIndex,{etag:l});case 9:this.debug("Uploaded part ".concat(r.uploadPartIndex,"."),a);case 10:case"end":return s.stop()}}),s,this)})))}},{key:"refreshAccessToken",value:function(e,t,n){return v(this,void 0,void 0,regeneratorRuntime.mark((function r(){var o,i,a,s=this;return regeneratorRuntime.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(n.isActive){r.next=2;break}return r.abrupt("return");case 2:return r.prev=2,r.t0=this,r.t1=e,r.next=7,t();case 7:return r.t2=r.sent,r.next=10,r.t0.getText.call(r.t0,r.t1,r.t2);case 10:if(o=r.sent,n.isActive){r.next=13;break}return r.abrupt("return");case 13:return i="".concat(this.cdnUrl).concat(this.setAccessTokenPath),r.t3=this,r.next=17,this.postJsonGetJson(i,{},{accessToken:o,accountId:this.accountId},!0);case 17:if(r.t4=r.sent,a=r.t3.handleApiError.call(r.t3,r.t4),n.isActive){r.next=21;break}return r.abrupt("return");case 21:n.accessToken=a.accessToken,n.accessTokenRefreshHandle=window.setTimeout((function(){s.refreshAccessToken(e,t,n).then((function(){}),(function(e){return s.error("Permanent error when refreshing access token: ".concat(e))}))}),Math.max(0,1e3*(a.ttlSeconds-this.refreshBeforeExpirySeconds))),r.next=32;break;case 25:return r.prev=25,r.t5=r.catch(2),this.debug("Error when refreshing access token: ".concat(r.t5)),r.next=30,new Promise((function(e){return setTimeout(e,1e3*s.retryAuthAfterErrorSeconds)}));case 30:return r.next=32,this.refreshAccessToken(e,t,n);case 32:case"end":return r.stop()}}),r,this,[[2,25]])})))}},{key:"postJsonGetJson",value:function(e,t,n,r){return v(this,void 0,void 0,regeneratorRuntime.mark((function o(){return regeneratorRuntime.wrap((function(o){for(;;)switch(o.prev=o.next){case 0:return o.next=2,this.nonUploadApiRequest({method:"POST",path:e,headers:t,body:n},r);case 2:return o.abrupt("return",o.sent.body);case 3:case"end":return o.stop()}}),o,this)})))}},{key:"getText",value:function(e,t){return v(this,void 0,void 0,regeneratorRuntime.mark((function n(){return regeneratorRuntime.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,this.nonUploadApiRequest({method:"GET",path:e,headers:t},!1);case 2:return n.abrupt("return",n.sent.body);case 3:case"end":return n.stop()}}),n,this)})))}},{key:"handleApiError",value:function(e){var t=e;if(void 0!==t.error)throw new Error("[upload-js] ".concat(t.error.message,". (Code: ").concat(t.error.code,")"));return e}},{key:"nonUploadApiRequest",value:function(e,t){return v(this,void 0,void 0,regeneratorRuntime.mark((function n(){return regeneratorRuntime.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return this.preflightExternalApi(e.path,t),n.next=3,(0,d.request)(Object.assign(Object.assign({},e),{path:""}));case 3:return n.abrupt("return",n.sent);case 4:case"end":return n.stop()}}),n,this)})))}}])&&h(t.prototype,n),e}()}},t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={exports:{}};return e[r](o,o.exports,n),o.exports}return n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n(675)})();
module.exports=(()=>{"use strict";var e={675:(e,t,n)=>{function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?i(e):t}function i(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function a(e){var t="function"==typeof Map?new Map:void 0;return(a=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return s(e,arguments,l(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),c(r,e)})(e)}function s(e,t,n){return(s=u()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&c(o,n.prototype),o}).apply(null,arguments)}function u(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function c(e,t){return(c=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function l(e){return(l=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}n.r(t),n.d(t,{Upload:()=>y});var p=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&c(e,t)}(a,e);var t,n,r=(t=a,n=u(),function(){var e,r=l(t);if(n){var i=l(this).constructor;e=Reflect.construct(r,arguments,i)}else e=r.apply(this,arguments);return o(this,e)});function a(e){var t;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a),t=r.call(this,e),Object.setPrototypeOf(i(t),a.prototype),t}return a}(a(Error));const d=require("upload-api-client-upload-js");function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function h(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var v=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{u(r.next(e))}catch(e){i(e)}}function s(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(a,s)}u((r=r.apply(e,t||[])).next())}))},y=function(){function e(t){var n,r,o,i,a,s,u,c;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=t,this.accountIdLength=7,this.apiKeyPrefix="public_",this.maxUploadConcurrency=5,this.refreshBeforeExpirySeconds=20,this.retryAuthAfterErrorSeconds=5,this.accessTokenPathBase="/api/v1/access_tokens/",this.lastAuthSession=void 0,!0===t.debug&&console.log("[upload-js] Initialized with API key '".concat(t.apiKey,"'")),this.apiUrl=null!==(r=null===(n=t.internal)||void 0===n?void 0:n.apiUrl)&&void 0!==r?r:"https://api.upload.io",this.cdnUrl=null!==(i=null===(o=t.internal)||void 0===o?void 0:o.cdnUrl)&&void 0!==i?i:"https://cdn.upload.io",this.authenticateWithApiKey=null===(s=null===(a=t.internal)||void 0===a?void 0:a.authenticateWithApiKey)||void 0===s||s,this.headers=null===(u=t.internal)||void 0===u?void 0:u.headers,this.debugMode=!0===t.debug,t.apiKey.trim()!==t.apiKey)throw new Error("[upload-js] Invalid API key. Whitespace detected: please remove whitespace from the API key and try again.");if(!1===(null===(c=t.internal)||void 0===c?void 0:c.authenticateWithApiKey))this.accountId=t.internal.accountId;else{if(!t.apiKey.startsWith(this.apiKeyPrefix))throw new Error("[upload-js] Invalid API key. API keys must start with '".concat(this.apiKeyPrefix,"'"));if(this.accountId=t.apiKey.substr(this.apiKeyPrefix.length,this.accountIdLength),this.accountId.length!==this.accountIdLength)throw new Error("[upload-js] Invalid API key. API keys must be at least ".concat(this.apiKeyPrefix.length+this.accountIdLength," characters long, but the API key you provided is ").concat(this.apiKeyPrefix.length+this.accountId.length,"."))}}var t,n;return t=e,(n=[{key:"beginAuthSession",value:function(e,t){return v(this,void 0,void 0,regeneratorRuntime.mark((function n(){var r;return regeneratorRuntime.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,this.endAuthSession();case 2:return r={accessToken:void 0,accessTokenRefreshHandle:void 0,isActive:!0},this.lastAuthSession=r,n.next=6,this.refreshAccessToken(e,t,r);case 6:case"end":return n.stop()}}),n,this)})))}},{key:"endAuthSession",value:function(){return v(this,void 0,void 0,regeneratorRuntime.mark((function e(){var t;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(void 0!==this.lastAuthSession){e.next=2;break}return e.abrupt("return");case 2:return t=this.lastAuthSession,this.lastAuthSession=void 0,void 0!==t.accessTokenRefreshHandle&&clearTimeout(t.accessTokenRefreshHandle),t.isActive=!1,e.next=8,this.deleteAccessToken();case 8:case"end":return e.stop()}}),e,this)})))}},{key:"createFileInputHandler",value:function(e){var t=this;return function(n){var r=n.target;if(void 0===r.files||null===r.files)throw new Error("No property 'files' on input element: ensure 'createFileInputHandler' is set to the 'onchange' attribute on an input of type 'file'.");if(void 0===r.files[0])throw new Error("No file selected.");t.uploadFile(Object.assign(Object.assign({},e),{file:r.files[0]})).then(e.onUploaded,(function(t){void 0!==e.onError?e.onError(t):console.error("Cannot upload file. To remove this console message, handle the error explicitly by providing an 'onError' parameter: upload.createFileInputHandler({onUploaded, onError})",t)}))}}},{key:"uploadFile",value:function(e){return v(this,void 0,void 0,regeneratorRuntime.mark((function t(){var n,r,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=[],r=function(e){n.push(e)},o=function(){return n.forEach((function(e){return e()}))},void 0!==e.onBegin&&e.onBegin({cancel:o}),t.prev=4,t.next=7,this.beginFileUpload(e.file,e,r);case 7:return t.abrupt("return",t.sent);case 10:throw t.prev=10,t.t0=t.catch(4),o(),t.t0;case 14:case"end":return t.stop()}}),t,this,[[4,10]])})))}},{key:"url",value:function(e){return"".concat(this.cdnUrl,"/").concat(e)}},{key:"beginFileUpload",value:function(e,t,n){return v(this,void 0,void 0,regeneratorRuntime.mark((function r(){var o,i,a,s,u,c,l,p,h,y=this;return regeneratorRuntime.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return void 0!==t.onProgress&&t.onProgress({bytesSent:0,bytesTotal:e.size}),o={accountId:this.accountId,fileSize:e.size,fileName:e.name,mime:this.normalizeMimeType(e.type),tag:t.tag,userId:t.userId},this.debug("Initiating file upload. Params = ".concat(JSON.stringify(o))),this.preflight(),r.next=6,d.FilesService.beginUpload(o);case 6:return i=r.sent,a=i.uploadParts.count>1,this.debug("Initiated file upload. Metadata = ".concat(JSON.stringify(i))),s=function(){var e=0;return function(){if(e!==i.uploadParts.count-1)return++e}}(),u=[i.uploadParts.first],c=function(e){return v(y,void 0,void 0,regeneratorRuntime.mark((function t(){var n,r;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(void 0===(n=u.pop())){t.next=4;break}return this.debug("Dequeued part ".concat(n.uploadPartIndex,"."),e),t.abrupt("return",n);case 4:if(void 0!==(r=s())){t.next=8;break}return this.debug("No parts remaining.",e),t.abrupt("return",void 0);case 8:return this.preflight(),this.debug("Fetching metadata for part ".concat(r,"."),e),t.next=12,d.FilesService.getUploadPart(i.file.fileId,r);case 12:return t.abrupt("return",t.sent);case 13:case"end":return t.stop()}}),t,this)})))},l=[],p=function r(o){return v(y,void 0,void 0,regeneratorRuntime.mark((function s(){var u,p,d;return regeneratorRuntime.wrap((function(s){for(;;)switch(s.prev=s.next){case 0:return s.next=2,c(o);case 2:if(void 0===(u=s.sent)){s.next=10;break}return p=0,d=function(n){var r=n.bytesSent;if(void 0===l[o]?l[o]=r:(l[o]-=p,l[o]+=r),p=r,void 0!==t.onProgress){var i=l.reduce((function(e,t){return e+t}));t.onProgress({bytesSent:i,bytesTotal:e.size})}},s.next=8,this.uploadPart(e,i.file,a,u,d,n,o);case 8:return s.next=10,r(o);case 10:case"end":return s.stop()}}),s,this)})))},r.next=16,Promise.all((g=Array(this.maxUploadConcurrency).keys(),function(e){if(Array.isArray(e))return f(e)}(g)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(g)||function(e,t){if(e){if("string"==typeof e)return f(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?f(e,t):void 0}}(g)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()).map((function(e){return v(y,void 0,void 0,regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,p(e);case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}}),t)})))})));case 16:return h={accountId:o.accountId,file:e,fileId:i.file.fileId,fileSize:i.file.size,fileUrl:this.url(i.file.fileId),tag:o.tag,userId:o.userId,mime:i.file.mime},this.debug("File upload completed. File = ".concat(JSON.stringify(h))),r.abrupt("return",h);case 19:case"end":return r.stop()}var g}),r,this)})))}},{key:"debug",value:function(e,t){this.debugMode&&console.log("[upload-js] ".concat(e).concat(void 0!==t?" (Worker ".concat(t,")"):""))}},{key:"error",value:function(e){console.error("[upload-js] ".concat(e))}},{key:"normalizeMimeType",value:function(e){var t=e.toLowerCase();return/^[a-z0-9]+\/[a-z0-9+\-._]+$/.test(t)?t:void 0}},{key:"preflight",value:function(){var e,t=this;d.OpenAPI.BASE=this.apiUrl,this.authenticateWithApiKey?(d.OpenAPI.WITH_CREDENTIALS=!0,d.OpenAPI.USERNAME="apikey",d.OpenAPI.PASSWORD=this.config.apiKey):(d.OpenAPI.WITH_CREDENTIALS=!1,delete d.OpenAPI.USERNAME,delete d.OpenAPI.PASSWORD);var n=this.headers,r=null===(e=this.lastAuthSession)||void 0===e?void 0:e.accessToken;void 0!==n||void 0!==r?d.OpenAPI.HEADERS=function(){return v(t,void 0,void 0,regeneratorRuntime.mark((function e(){var t,r,o;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(void 0!==n){e.next=4;break}e.t0={},e.next=7;break;case 4:return e.next=6,n();case 6:e.t0=e.sent;case 7:return r=e.t0,o=null===(t=this.lastAuthSession)||void 0===t?void 0:t.accessToken,e.abrupt("return",Object.assign(Object.assign({},r),void 0===o?{}:{"authorization-user":o}));case 10:case"end":return e.stop()}}),e,this)})))}:delete d.OpenAPI.HEADERS}},{key:"preflightExternalApi",value:function(e,t){d.OpenAPI.BASE=e,d.OpenAPI.WITH_CREDENTIALS=t,delete d.OpenAPI.USERNAME,delete d.OpenAPI.PASSWORD,delete d.OpenAPI.HEADERS}},{key:"putUploadPart",value:function(e,t,n,r,o,i){return v(this,void 0,void 0,regeneratorRuntime.mark((function a(){var s,u;return regeneratorRuntime.wrap((function(a){for(;;)switch(a.prev=a.next){case 0:return s=new XMLHttpRequest,u=!0,i((function(){u&&s.abort()})),a.prev=3,a.next=6,new Promise((function(i,a){s.upload.addEventListener("progress",(function(e){e.lengthComputable&&o({bytesSent:e.loaded,bytesTotal:e.total})}),!1),s.addEventListener("load",(function(){if(o({bytesSent:r.size,bytesTotal:r.size}),2===Math.floor(s.status/100)){var e=s.getResponseHeader("etag");null==e?a(new Error("File upload error: no etag header in upload response.")):i({etag:e})}else a(new Error("File upload error: status code ".concat(s.status)))})),s.onabort=function(){return a(new p("File upload cancelled."))},s.onerror=function(){return a(new Error("File upload error."))},s.ontimeout=function(){return a(new Error("File upload timeout."))},s.open("PUT",e),n||(s.setRequestHeader("content-type",t.mime),null!==t.name&&s.setRequestHeader("content-disposition",'attachment; filename="'.concat(encodeURIComponent(t.name),"\"; filename*=UTF-8''").concat(encodeURIComponent(t.name)))),s.send(r)}));case 6:return a.abrupt("return",a.sent);case 7:return a.prev=7,u=!1,a.finish(7);case 10:case"end":return a.stop()}}),a,null,[[3,,7,10]])})))}},{key:"uploadPart",value:function(e,t,n,r,o,i,a){return v(this,void 0,void 0,regeneratorRuntime.mark((function s(){var u,c,l;return regeneratorRuntime.wrap((function(s){for(;;)switch(s.prev=s.next){case 0:return u=-1===r.range.inclusiveEnd?new Blob:e.slice(r.range.inclusiveStart,r.range.inclusiveEnd+1),this.debug("Uploading part ".concat(r.uploadPartIndex,"."),a),s.next=4,this.putUploadPart(r.uploadUrl,t,n,u,o,i);case 4:return c=s.sent,l=c.etag,this.preflight(),s.next=9,d.FilesService.completeUploadPart(r.fileId,r.uploadPartIndex,{etag:l});case 9:this.debug("Uploaded part ".concat(r.uploadPartIndex,"."),a);case 10:case"end":return s.stop()}}),s,this)})))}},{key:"accessTokenPath",value:function(){return"".concat(this.cdnUrl).concat(this.accessTokenPathBase).concat(this.accountId)}},{key:"deleteAccessToken",value:function(){return v(this,void 0,void 0,regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.deleteNoResponse(this.accessTokenPath(),{},!0);case 2:case"end":return e.stop()}}),e,this)})))}},{key:"refreshAccessToken",value:function(e,t,n){return v(this,void 0,void 0,regeneratorRuntime.mark((function r(){var o,i,a=this;return regeneratorRuntime.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(n.isActive){r.next=2;break}return r.abrupt("return");case 2:return r.prev=2,r.t0=this,r.t1=e,r.next=7,t();case 7:return r.t2=r.sent,r.next=10,r.t0.getText.call(r.t0,r.t1,r.t2);case 10:if(o=r.sent,n.isActive){r.next=13;break}return r.abrupt("return");case 13:return r.t3=this,r.next=16,this.putJsonGetJson(this.accessTokenPath(),{},{accessToken:o},!0);case 16:if(r.t4=r.sent,i=r.t3.handleApiError.call(r.t3,r.t4),n.isActive){r.next=20;break}return r.abrupt("return");case 20:n.accessToken=i.accessToken,n.accessTokenRefreshHandle=window.setTimeout((function(){a.refreshAccessToken(e,t,n).then((function(){}),(function(e){return a.error("Permanent error when refreshing access token: ".concat(e))}))}),Math.max(0,1e3*(i.ttlSeconds-this.refreshBeforeExpirySeconds))),r.next=31;break;case 24:return r.prev=24,r.t5=r.catch(2),this.debug("Error when refreshing access token: ".concat(r.t5)),r.next=29,new Promise((function(e){return setTimeout(e,1e3*a.retryAuthAfterErrorSeconds)}));case 29:return r.next=31,this.refreshAccessToken(e,t,n);case 31:case"end":return r.stop()}}),r,this,[[2,24]])})))}},{key:"putJsonGetJson",value:function(e,t,n,r){return v(this,void 0,void 0,regeneratorRuntime.mark((function o(){return regeneratorRuntime.wrap((function(o){for(;;)switch(o.prev=o.next){case 0:return o.next=2,this.nonUploadApiRequest({method:"PUT",path:e,headers:t,body:n},r);case 2:return o.abrupt("return",o.sent.body);case 3:case"end":return o.stop()}}),o,this)})))}},{key:"getText",value:function(e,t){return v(this,void 0,void 0,regeneratorRuntime.mark((function n(){return regeneratorRuntime.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,this.nonUploadApiRequest({method:"GET",path:e,headers:t},!1);case 2:return n.abrupt("return",n.sent.body);case 3:case"end":return n.stop()}}),n,this)})))}},{key:"deleteNoResponse",value:function(e,t,n){return v(this,void 0,void 0,regeneratorRuntime.mark((function r(){return regeneratorRuntime.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,this.nonUploadApiRequest({method:"DELETE",path:e,headers:t},n);case 2:case"end":return r.stop()}}),r,this)})))}},{key:"handleApiError",value:function(e){var t=e;if(void 0!==t.error)throw new Error("[upload-js] ".concat(t.error.message,". (Code: ").concat(t.error.code,")"));return e}},{key:"nonUploadApiRequest",value:function(e,t){return v(this,void 0,void 0,regeneratorRuntime.mark((function n(){return regeneratorRuntime.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return this.preflightExternalApi(e.path,t),n.next=3,(0,d.request)(Object.assign(Object.assign({},e),{path:""}));case 3:return n.abrupt("return",n.sent);case 4:case"end":return n.stop()}}),n,this)})))}}])&&h(t.prototype,n),e}()}},t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={exports:{}};return e[r](o,o.exports,n),o.exports}return n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n(675)})();

@@ -18,3 +18,3 @@ import { UploadConfig } from "./UploadConfig";

private readonly retryAuthAfterErrorSeconds;
private readonly setAccessTokenPath;
private readonly accessTokenPathBase;
private lastAuthSession;

@@ -37,11 +37,3 @@ constructor(config: UploadConfig);

*/
endAuthSession(): void;
/**
* This method unregisters any background timers that may have been created by the object.
*
* Must be called when the object is no-longer required.
*
* You should not attempt to continue using this object after calling this method.
*/
close(): void;
endAuthSession(): Promise<void>;
createFileInputHandler(params: UploadParams & {

@@ -71,7 +63,10 @@ onError?: (reason: any) => void;

private uploadPart;
private accessTokenPath;
private deleteAccessToken;
private refreshAccessToken;
private postJsonGetJson;
private putJsonGetJson;
private getText;
private deleteNoResponse;
private handleApiError;
private nonUploadApiRequest;
}
{
"name": "upload-js",
"version": "1.25.0",
"version": "1.26.0",
"author": "Upload <hello@upload.io> (https://upload.io)",

@@ -5,0 +5,0 @@ "description": "Upload.js JavaScript Library",

@@ -6,3 +6,2 @@ /**

accessToken: string;
accountId: string;
}

@@ -29,3 +29,3 @@ import { Cancellation } from "upload-js/Errors";

private readonly retryAuthAfterErrorSeconds = 5;
private readonly setAccessTokenPath = "/api/v1/access_tokens";
private readonly accessTokenPathBase = "/api/v1/access_tokens/";

@@ -83,3 +83,3 @@ private lastAuthSession: AuthSession | undefined = undefined;

async beginAuthSession(authUrl: string, authHeaders: () => Promise<Record<string, string>>): Promise<void> {
this.endAuthSession();
await this.endAuthSession();

@@ -103,3 +103,3 @@ const authSession: AuthSession = {

*/
endAuthSession(): void {
async endAuthSession(): Promise<void> {
if (this.lastAuthSession === undefined) {

@@ -117,13 +117,4 @@ return;

authSession.isActive = false;
}
/**
* This method unregisters any background timers that may have been created by the object.
*
* Must be called when the object is no-longer required.
*
* You should not attempt to continue using this object after calling this method.
*/
close(): void {
this.endAuthSession();
await this.deleteAccessToken();
}

@@ -457,3 +448,14 @@

// Todo: keep attempting until succeeded (user might be in a tunnel!)
private accessTokenPath(): string {
return `${this.cdnUrl}${this.accessTokenPathBase}${this.accountId}`;
}
private async deleteAccessToken(): Promise<void> {
await this.deleteNoResponse(
this.accessTokenPath(),
{},
true // Required, else CDN response's `Set-Cookie` header will be silently ignored.
);
}
private async refreshAccessToken(

@@ -477,10 +479,8 @@ authUrl: string,

const setTokenUrl = `${this.cdnUrl}${this.setAccessTokenPath}`;
const setTokenResult = this.handleApiError(
await this.postJsonGetJson<SetAccessTokenResponseDto | ErrorResponse, SetAccessTokenRequestDto>(
setTokenUrl,
await this.putJsonGetJson<SetAccessTokenResponseDto | ErrorResponse, SetAccessTokenRequestDto>(
this.accessTokenPath(),
{},
{
accessToken: token,
accountId: this.accountId
accessToken: token
},

@@ -508,2 +508,4 @@ true // Required, else CDN response's `Set-Cookie` header will be silently ignored.

await new Promise(resolve => setTimeout(resolve, this.retryAuthAfterErrorSeconds * 1000));
// Todo: is this stack safe?
await this.refreshAccessToken(authUrl, authHeaders, authSession);

@@ -513,3 +515,3 @@ }

private async postJsonGetJson<TGet, TPost>(
private async putJsonGetJson<TGet, TPost>(
url: string,

@@ -523,3 +525,3 @@ headers: Record<string, string>,

{
method: "POST",
method: "PUT",
path: url,

@@ -547,2 +549,17 @@ headers,

private async deleteNoResponse(
url: string,
headers: Record<string, string>,
withCredentials: boolean
): Promise<void> {
await this.nonUploadApiRequest(
{
method: "DELETE",
path: url,
headers
},
withCredentials
);
}
private handleApiError<T>(result: T | ErrorResponse): T {

@@ -549,0 +566,0 @@ const errorMaybe: Partial<ErrorResponse> = result;

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc