!function(){"use strict";function t(t,e,o){this.fileTotalBytesUploaded=0,this.s3Parts=[],this.partsOnS3=[],this.partsInProcess=[],this.partsToUpload=[],this.numParts=-1,this.con=S({},e),this.evaporate=o,this.localTimeOffset=o.localTimeOffset,this.deferredCompletion=v(),S(this,t),this.id=decodeURIComponent(this.con.bucket+"/"+this.name),this.signParams=e.signParams}function e(t,e){this.fileUpload=t,this.con=t.con,this.attempts=1,this.localTimeOffset=this.fileUpload.localTimeOffset,this.awsDeferred=v(),this.started=v(),this.awsUrl=h(this.con),this.awsHost=f(this.awsUrl).hostname;var o=S({},e);t.contentType&&(o.contentType=t.contentType),this.updateRequest(o)}function o(t,o){e.call(this,t,o)}function r(t,o,r){r>-1&&(this.maxRetries=r),e.call(this,t,o)}function s(t,e){var r={method:"POST",path:"?uploads",step:"initiate",x_amz_headers:t.xAmzHeadersAtInitiate,not_signed_headers:t.notSignedHeadersAtInitiate,response_match:"(.+)"};o.call(this,t,r),this.awsKey=e}function i(t){t.info("will attempt to complete upload");var e={method:"POST",contentType:"application/xml; charset=UTF-8",path:"?uploadId="+t.uploadId,x_amz_headers:t.xAmzHeadersCommon||t.xAmzHeadersAtComplete,step:"complete"};o.call(this,t,e)}function n(t,e){this.awsKey=e,t.info("will attempt to verify existence of the file");var o={method:"HEAD",path:"",x_amz_headers:t.xAmzHeadersCommon,success404:!0,step:"head_object"};r.call(this,t,o)}function a(t){r.call(this,t),this.updateRequest(this.setupRequest(0))}function p(t,o){this.part=o,this.partNumber=o.partNumber,this.start=(this.partNumber-1)*t.con.partSize,this.end=Math.min(this.partNumber*t.con.partSize,t.sizeBytes);var r={method:"PUT",path:"?partNumber="+this.partNumber+"&uploadId="+t.uploadId,step:"upload #"+this.partNumber,x_amz_headers:t.xAmzHeadersCommon||t.xAmzHeadersAtUpload,contentSha256:"UNSIGNED-PAYLOAD",onProgress:this.onProgress.bind(this)};e.call(this,t,r)}function u(t){t.info("will attempt to abort the upload"),t.abortParts();var o={method:"DELETE",path:"?uploadId="+t.uploadId,x_amz_headers:t.xAmzHeadersCommon,success404:!0,step:"abort"};e.call(this,t,o)}function d(t,e){function o(t){this.request=t}function r(t){o.call(this,t)}function s(t){this._cr=void 0,o.call(this,t)}var i=t.con;return o.prototype.request={},o.prototype.error=function(){},o.prototype.authorizationString=function(){},o.prototype.stringToSign=function(){},o.prototype.canonicalRequest=function(){},o.prototype.setHeaders=function(){},o.prototype.datetime=function(t){return new Date((new Date).getTime()+t)},o.prototype.dateString=function(t){return this.datetime(t).toISOString().slice(0,19).replace(/-|:/g,"")+"Z"},r.prototype=Object.create(o.prototype),r.prototype.constructor=r,r.prototype.authorizationString=function(){return["AWS ",i.aws_key,":",this.request.auth].join("")},r.prototype.stringToSign=function(){var o,r="",s=[];for(var n in this.request.x_amz_headers)this.request.x_amz_headers.hasOwnProperty(n)&&s.push(n);return s.sort(),s.forEach(function(t){r+=t+":"+this.request.x_amz_headers[t]+"\n"}.bind(this)),o=this.request.method+"\n"+(this.request.md5_digest||"")+"\n"+(this.request.contentType||"")+"\n\n"+r+(i.cloudfront?"/"+i.bucket:"")+t.getPath()+this.request.path,e.d("V2 stringToSign:",o),o},r.prototype.dateString=function(t){return this.datetime(t).toUTCString()},r.prototype.getPayload=function(){return Promise.resolve()},s.prototype=Object.create(o.prototype),s.prototype.constructor=s,s.prototype._cr=void 0,s.prototype.payload=null,s.prototype.error=function(){this._cr=void 0},s.prototype.getPayload=function(){return t.getPayload().then(function(t){this.payload=t}.bind(this))},s.prototype.authorizationString=function(){var t=[],e=this.credentialString(),o=this.canonicalHeaders();return t.push(["AWS4-HMAC-SHA256 Credential=",i.aws_key,"/",e].join("")),t.push("SignedHeaders="+o.signedHeaders),t.push("Signature="+this.request.auth),t.join(", ")},s.prototype.stringToSign=function(){var t=[];t.push("AWS4-HMAC-SHA256"),t.push(this.request.dateString),t.push(this.credentialString()),t.push(i.cryptoHexEncodedHash256(this.canonicalRequest()));var o=t.join("\n");return e.d("V4 stringToSign:",o),o},s.prototype.credentialString=function(){var t=[];return t.push(this.request.dateString.slice(0,8)),t.push(i.awsRegion),t.push("s3"),t.push("aws4_request"),t.join("/")},s.prototype.canonicalQueryString=function(){var e,o,r=t.request.query_string||"",s=f([t.awsUrl,this.request.path,r].join("")).search,i=s.length?s.split("&"):[],n=[];for(o=0;o1?encodeURIComponent(e[1]):null});var a=n.sort(function(t,e){return t.namee.name?1:0}),p=[];for(o=0;oe?1:0}),p=[],u=[],d=this.request.not_signed_headers||[],l=[];for(o=0;o-1){var e="status:"+a.status;return r.deferredCompletion.reject("Permission denied "+e),n(e)}n("Signature fetch returned status: "+a.status)}},a.onerror=function(t){n("authorizedSend transport error: "+t.responseText)},a.open("GET",u);var h=e.makeSignParamsObject(s.signHeaders);for(var c in h)h.hasOwnProperty(c)&&a.setRequestHeader(c,h[c]);"function"==typeof r.beforeSigner&&r.beforeSigner(a,u),a.send()})},o.prototype=Object.create(e.prototype),o.prototype.authorize=function(){return s.customAuthMethod(e.makeSignParamsObject(r.signParams),e.makeSignParamsObject(s.signHeaders),t.stringToSign(),i.dateString,t.canonicalRequest()).catch(function(t){throw r.deferredCompletion.reject(t),t})},"function"==typeof s.customAuthMethod?new o:new e}function h(t){var e;return t.aws_url?e=[t.aws_url]:(t.s3Acceleration?(e=["https://",t.bucket,".s3-accelerate"],t.cloudfront=!0):(e=["https://",t.cloudfront?t.bucket+".":"","s3"],"us-east-1"!==t.awsRegion&&e.push("-",t.awsRegion)),e.push(".amazonaws.com")),e.join("")}function c(t){var e=[];return t.split("/").forEach(function(t){for(var o=[],r=encodeURIComponent(t),s=0;s(.+)",e,">"].join(""));return o?o[1]:""}function v(){var t,e={};return t=new Promise(function(t,o){e={resolve:t,reject:o}}),{resolve:e.resolve,reject:e.reject,promise:t}}function S(t,e,o){function r(t,e){if("object"==typeof e)for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])}return t=t||{},e=e||{},o=o||{},r(e,o),r(t,e),t}function P(t){var e=JSON.parse(H.getItem("awsUploads")||"{}");if(t){for(var o in e)if(e.hasOwnProperty(o)){var r=e[o];new Date(r.completedAt||_)-1)return t.splice(o,1),!0}function q(t){for(var e=["B","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb"],o=0;t>=1024;)t/=1024,++o;return[t.toFixed(2).replace(".00",""),e[o]].join(" ")}function x(t){var e=x.supported();this.cacheStore=t?{}:e?localStorage:void 0}function C(){return{d:function(){},w:function(){},e:function(){}}}var O,I,_=new Date("2060-10-22"),F=[4,30],R=[0,2,10],z=["maxConcurrentParts","logging","cloudfront","encodeFilename","computeContentMd5","allowS3ExistenceOptimization","onlyRetryForSameFileName","timeUrl","cryptoMd5Method","cryptoHexEncodedHash256","awsRegion","awsSignatureVersion","evaporateChanged"],M={33:"%21",39:"%27",40:"%28",41:"%29",42:"%2A"},j=function(t){if(this.config=S({readableStreams:!1,readableStreamPartMethod:null,bucket:null,logging:!0,maxConcurrentParts:5,partSize:6291456,retryBackoffPower:2,maxRetryBackoffSecs:300,progressIntervalMS:1e3,cloudfront:!1,s3Acceleration:!1,mockLocalStorage:!1,encodeFilename:!0,computeContentMd5:!1,allowS3ExistenceOptimization:!1,onlyRetryForSameFileName:!1,timeUrl:null,cryptoMd5Method:null,cryptoHexEncodedHash256:null,aws_key:null,awsRegion:"us-east-1",awsSignatureVersion:"4",sendCanonicalRequestToSignerUrl:!1,s3FileCacheHoursAgo:null,signParams:{},signHeaders:{},customAuthMethod:void 0,maxFileSize:null,signResponseHandler:null,xhrWithCredentials:!1,localTimeOffset:void 0,evaporateChanged:function(){},abortCompletionThrottlingMs:1e3},t),"undefined"!=typeof window&&window.console&&((I=window.console).d=I.log,I.w=window.console.warn?I.warn:I.d,I.e=window.console.error?I.error:I.d),this._instantiationError=this.validateEvaporateOptions(),"string"!=typeof this._instantiationError){delete this._instantiationError,this.config.logging||(I=C());var e=new Date;if(O=new Date(e.setHours(e.getHours()-(this.config.s3FileCacheHoursAgo||-100))),"number"==typeof t.localTimeOffset)this.localTimeOffset=t.localTimeOffset;else{var o=this;j.getLocalTimeOffset(this.config).then(function(t){o.localTimeOffset=t})}this.pendingFiles={},this.queuedFiles=[],this.filesInProcess=[],H=new x(this.config.mockLocalStorage)}else this.supported=!1};j.create=function(t){var e=S({},t);return j.getLocalTimeOffset(e).then(function(t){return e.localTimeOffset=t,new Promise(function(t,o){var r=new j(e);!0===r.supported?t(r):o(r._instantiationError)})})},j.getLocalTimeOffset=function(t){return new Promise(function(e,o){if("number"==typeof t.localTimeOffset)return e(t.localTimeOffset);if(t.timeUrl){var r=new XMLHttpRequest;r.open("GET",t.timeUrl+"?requestTime="+(new Date).getTime()),r.onreadystatechange=function(){if(4===r.readyState&&200===r.status){var t=new Date(Date.parse(r.responseText))-new Date;I.d("localTimeOffset is",t,"ms"),e(t)}},r.onerror=function(t){I.e("xhr error timeUrl",t),o("Fetching offset time failed with status: "+t.status)},r.send()}else e(0)})},j.prototype.config={},j.prototype.localTimeOffset=0,j.prototype.supported=!1,j.prototype._instantiationError=void 0,j.prototype.evaporatingCount=0,j.prototype.pendingFiles={},j.prototype.filesInProcess=[],j.prototype.queuedFiles=[],j.prototype.startNextFile=function(t){if(this.queuedFiles.length&&!(this.evaporatingCount>=this.config.maxConcurrentParts)){var e=this.queuedFiles.shift();0===e.status?(I.d("Starting",decodeURIComponent(e.name),"reason:",t),this.evaporatingCnt(1),e.start()):(I.d("Requeued",decodeURIComponent(e.name),"status:",e.status,"reason:",t),this.queuedFiles.push(e))}},j.prototype.fileCleanup=function(t){T(this.queuedFiles,t),T(this.filesInProcess,t)&&this.evaporatingCnt(-1),t.done(),this.consumeRemainingSlots()},j.prototype.queueFile=function(t){this.filesInProcess.push(t),this.queuedFiles.push(t),1===this.filesInProcess.length&&this.startNextFile("first file")},j.prototype.add=function(e,o){var r,s=this;return new Promise(function(i,n){var a=S(o,{});if(z.forEach(function(t){delete a[t]}),r=S(s.config,a),void 0===e||void 0===e.file)return n("Missing file");if(r.maxFileSize&&e.file.size>r.maxFileSize)return n("File size too large. Maximum size allowed is "+r.maxFileSize);if(void 0===e.name)return n("Missing attribute: name");r.encodeFilename&&(e.name=c(e.name));var p=new t(S({started:function(){},uploadInitiated:function(){},progress:function(){},complete:function(){},cancelled:function(){},paused:function(){},resumed:function(){},pausing:function(){},nameChanged:function(){},info:function(){},warn:function(){},error:function(){},beforeSigner:void 0,xAmzHeadersAtInitiate:{},notSignedHeadersAtInitiate:{},xAmzHeadersCommon:null,xAmzHeadersAtUpload:{},xAmzHeadersAtComplete:{}},e,{status:0,priority:0,loadedBytes:0,sizeBytes:e.file.size,eTag:""}),r,s),u=p.id;s.pendingFiles[u]=p,s.queueFile(p),p.deferredCompletion.promise.then(function(){s.fileCleanup(p),i(decodeURIComponent(p.name))},function(t){s.fileCleanup(p),n(t)})})},j.prototype.cancel=function(t){return void 0===t?this._cancelAll():this._cancelOne(t)},j.prototype._cancelAll=function(){I.d("Canceling all file uploads");var t=[];for(var e in this.pendingFiles)if(this.pendingFiles.hasOwnProperty(e)){var o=this.pendingFiles[e];R.indexOf(o.status)>-1&&t.push(o.stop())}return t.length||t.push(Promise.reject("No files to cancel.")),Promise.all(t)},j.prototype._cancelOne=function(t){var e=[];return this.pendingFiles[t]?e.push(this.pendingFiles[t].stop()):e.push(Promise.reject("File does not exist")),Promise.all(e)},j.prototype.pause=function(t,e){var o=void 0!==(e=e||{}).force&&e.force;return void 0===t?this._pauseAll(o):this._pauseOne(t,o)},j.prototype._pauseAll=function(t){I.d("Pausing all file uploads");var e=[];for(var o in this.pendingFiles)if(this.pendingFiles.hasOwnProperty(o)){var r=this.pendingFiles[o];R.indexOf(r.status)>-1&&this._pause(r,t,e)}return Promise.all(e)},j.prototype._pauseOne=function(t,e){var o=[],r=this.pendingFiles[t];return void 0===r?o.push(Promise.reject("Cannot pause a file that has not been added.")):4===r.status&&o.push(Promise.reject("Cannot pause a file that is already paused.")),o.length||this._pause(r,e,o),Promise.all(o)},j.prototype._pause=function(t,e,o){o.push(t.pause(e)),T(this.filesInProcess,t),T(this.queuedFiles,t)},j.prototype.resume=function(t){return void 0===t?this._resumeAll():this._resumeOne(t)},j.prototype._resumeAll=function(){I.d("Resuming all file uploads");for(var t in this.pendingFiles)if(this.pendingFiles.hasOwnProperty(t)){var e=this.pendingFiles[t];F.indexOf(e.status)>-1&&this.resumeFile(e)}return Promise.resolve()},j.prototype._resumeOne=function(t){var e=this.pendingFiles[t],o=[];return void 0===e?o.push(Promise.reject("Cannot pause a file that does not exist.")):-1===F.indexOf(e.status)?o.push(Promise.reject("Cannot resume a file that has not been paused.")):this.resumeFile(e),Promise.all(o)},j.prototype.resumeFile=function(t){t.resume(),this.queueFile(t)},j.prototype.forceRetry=function(){},j.prototype.consumeRemainingSlots=function(){var t=this.config.maxConcurrentParts-this.evaporatingCount;if(t)for(var e=0;e0&&(r.secondsLeft=Math.round(o/e)),r},t.prototype.onProgress=function(){-1===[20,4].indexOf(this.status)&&(this.progress(this.fileTotalBytesUploaded/this.sizeBytes,this.progessStats()),this.loaded=0)},t.prototype.startMonitor=function(){clearInterval(this.progressInterval),this.startTime=new Date,this.loaded=0,this.totalUploaded=0,this.onProgress(),this.progressInterval=setInterval(this.onProgress.bind(this),this.con.progressIntervalMS)},t.prototype.stopMonitor=function(){clearInterval(this.progressInterval)},t.prototype.startNextFile=function(t){this.evaporate.startNextFile(t)},t.prototype.evaporatingCnt=function(t){this.evaporate.evaporatingCnt(t)},t.prototype.consumeRemainingSlots=function(){this.evaporate.consumeRemainingSlots()},t.prototype.getRemainingSlots=function(){var t=this.evaporate.evaporatingCount;return!this.partsInProcess.length&&t>0&&(t-=1),this.con.maxConcurrentParts-t},t.prototype.lastPartSatisfied=Promise.resolve("onStart"),t.prototype.start=function(){if(this.status=2,this.startMonitor(),this.started(this.id),this.uploadId)return I.d("resuming FileUpload ",this.id),this.consumeSlots();var t=this.name;this.getUnfinishedFileUpload();var e=this.con.computeContentMd5&&this.con.allowS3ExistenceOptimization&&void 0!==this.firstMd5Digest&&void 0!==this.eTag;if(this.uploadId){if(e)return this.reuseS3Object(t).then(this.deferredCompletion.resolve).catch(this.uploadFileFromScratch.bind(this));this.resumeInterruptedUpload().then(this._uploadComplete.bind(this)).catch(this.uploadFileFromScratch.bind(this))}else this.uploadFileFromScratch("")},t.prototype.uploadFileFromScratch=function(t){if(-1!==R.indexOf(this.status))return I.d(t),this.uploadId=void 0,this.uploadFile(this.name).then(this._uploadComplete.bind(this)).catch(this._abortUpload.bind(this))},t.prototype._uploadComplete=function(){this.completeUpload().then(this.deferredCompletion.resolve)},t.prototype.stop=function(){I.d("stopping FileUpload ",this.id),this.setStatus(5),this.info("Canceling uploads..."),this.abortedByUser=!0;var t=this;return this.abortUpload().then(function(){throw"User aborted the upload"}).catch(function(e){t.deferredCompletion.reject(e)})},t.prototype.pause=function(t){I.d("pausing FileUpload, force:",!!t,this.id);var e=[];return this.info("Pausing uploads..."),this.status=30,t?this.abortParts(!0):(e=this.partsInProcess.map(function(t){return this.s3Parts[t].awsRequest.awsDeferred.promise},this),this.pausing()),Promise.all(e).then(function(){this.stopMonitor(),this.status=4,this.startNextFile("pause"),this.paused()}.bind(this))},t.prototype.resume=function(){this.status=0,this.resumed()},t.prototype.done=function(){clearInterval(this.progressInterval),this.startNextFile("file done"),this.partsOnS3=[],this.s3Parts=[]},t.prototype._startCompleteUpload=function(t){return function(){(t?this.completeUpload():Promise.resolve()).then(this.deferredCompletion.resolve.bind(this))}},t.prototype._abortUpload=function(){if(!this.abortedByUser){var t=this;this.abortUpload().then(function(){t.deferredCompletion.reject("File upload aborted due to a part failing to upload")},this.deferredCompletion.reject.bind(this))}},t.prototype.abortParts=function(t){var e=this;this.partsInProcess.slice(0).forEach(function(o){var r=e.s3Parts[o];r&&(r.awsRequest.abort(),t&&(r.status=0),T(e.partsInProcess,r.partNumber),e.partsToUpload.length&&e.evaporatingCnt(-1))})},t.prototype.makeParts=function(t){function e(t){T(r.partsToUpload,t.partNumber),T(r.partsInProcess,t.partNumber),r.partsToUpload.length&&r.evaporatingCnt(-1)}this.numParts=Math.ceil(this.sizeBytes/this.con.partSize)||1;for(var o=[],r=this,s=t?1:this.numParts,i=1;i<=s;i++){var n=this.s3Parts[i];if(void 0!==n){if(3===n.status)continue}else n=this.makePart(i,0,this.sizeBytes);n.awsRequest=new p(this,n),n.awsRequest.awsDeferred.promise.then(function(t){return function(){e(t),r.partsToUpload.length&&r.consumeRemainingSlots(),r.partsToUpload.lengthO&&this.con.bucket===t.bucket&&(!this.con.onlyRetryForSameFileName||this.name===t.awsKey)},t.prototype.partSuccess=function(t,e){var o=e.part;if(I.d(e.request.step,"ETag:",t),o.isEmpty||'"d41d8cd98f00b204e9800998ecf8427e"'!==t)return o.eTag=t,o.status=3,this.partsOnS3.push(o),!0;o.status=10,e.resetLoadedBytes();var r=["eTag matches MD5 of 0 length blob for part #",e.partNumber,"Retrying part."].join(" ");I.w(r),this.warn(r)},t.prototype.listPartsSuccess=function(t,e){this.info("uploadId",this.uploadId,"is not complete. Fetching parts from part marker",t.partNumberMarker),e=e.replace(/(\r\n|\n|\r)/gm,"");for(var o=/(.+?)<\/Part\>/g;;){var r=(o.exec(e)||[])[1];if(!r)break;var s=parseInt(g(r,"Size"),10);this.fileTotalBytesUploaded+=s,this.partsOnS3.push({eTag:g(r,"ETag").replace(/"/g,'"'),partNumber:parseInt(g(r,"PartNumber"),10),size:s,LastModified:g(r,"LastModified")})}return"true"===g(e,"IsTruncated")?g(e,"NextPartNumberMarker"):void 0},t.prototype.makePartsfromPartsOnS3=function(){-1!==R.indexOf(this.status)&&(this.nameChanged(this.name),this.partsOnS3.forEach(function(t){var e=this.makePart(t.partNumber,3,t.size);e.eTag=t.eTag,e.loadedBytes=t.size,e.loadedBytesPrevious=t.size,e.finishedUploadingAt=t.LastModified}.bind(this)))},t.prototype.completeUpload=function(){var t=this;return new i(this).send().then(function(e){t.eTag=g(e.responseText,"ETag").replace(/"/g,'"'),t.completeUploadFile(e)})},t.prototype.getCompletedPayload=function(){var t=[];return t.push(""),this.s3Parts.forEach(function(e,o){o>0&&["",o,"",e.eTag,""].forEach(function(e){t.push(e)})}),t.push(""),t.join("")},t.prototype.consumeSlots=function(){if(0===this.partsToUpload.length)return-1;if(this.partsToUpload.length!==this.partsInProcess.length&&2===this.status){var t=Math.min(this.getRemainingSlots(),this.partsToUpload.length);if(!t)return-1;for(var e=0,o=0;o1&&this.evaporatingCnt(1),this.partsInProcess.push(r.partNumber);var s=r.awsRequest;if(this.lastPartSatisfied.then(s.delaySend.bind(s)),this.lastPartSatisfied=s.getStartedPromise(),(e+=1)===t)break}}var i=this.partsToUpload.length===this.partsInProcess.length,n=this.getRemainingSlots();return i&&n>0&&this.startNextFile("consume slots"),n}return 0},t.prototype.canStartPart=function(t){return-1===this.partsInProcess.indexOf(t.partNumber)&&!t.awsRequest.errorExceptionStatus()},t.prototype.uploadFile=function(t){this.removeUploadFile();var e=this;return new s(e,t).send().then(function(){return e.uploadInitiated(e.uploadId),e.partsToUpload=[],e.uploadParts().then(function(){},function(t){throw t})})},t.prototype.uploadParts=function(){if(this.loaded=0,this.totalUploaded=0,-1===R.indexOf(this.status))return Promise.reject("Part uploading stopped because the file was canceled");var t=this.makeParts();return this.setStatus(2),this.startTime=new Date,this.consumeSlots(),Promise.all(t)},t.prototype.abortUpload=function(){return new Promise(function(t,e){void 0!==this.uploadId?new u(this).send().then(t,e):t()}.bind(this)).then(function(){this.setStatus(20),this.cancelled(),this.removeUploadFile()}.bind(this),this.deferredCompletion.reject.bind(this))},t.prototype.resumeInterruptedUpload=function(){return new a(this).send().then(this.uploadParts.bind(this))},t.prototype.reuseS3Object=function(t){function e(e){throw o.name=t,e}var o=this;this.makeParts(1),this.partsToUpload=[];var r=this.s3Parts[1];return r.awsRequest.getPartMd5Digest().then(function(){if(o.firstMd5Digest===r.md5_digest)return new n(o,t).send().then(function(t){I.d("headObject found matching object on S3."),o.completeUploadFile(t),o.nameChanged(o.name)}).catch(e);e(o.con.allowS3ExistenceOptimization?"File's first part MD5 digest does not match what was stored.":"allowS3ExistenceOptimization is not enabled.")})},e.prototype.fileUpload=void 0,e.prototype.con=void 0,e.prototype.awsUrl=void 0,e.prototype.awsHost=void 0,e.prototype.authorize=function(){},e.prototype.localTimeOffset=0,e.prototype.awsDeferred=void 0,e.prototype.started=void 0,e.prototype.getPath=function(){var t="/"+this.con.bucket+"/"+this.fileUpload.name;return(this.con.cloudfront||this.awsUrl.indexOf("cloudfront")>-1)&&(t="/"+this.fileUpload.name),t},e.prototype.updateRequest=function(t){this.request=t;var e=d(this,I);this.signer=new e(t)},e.prototype.success=function(){this.awsDeferred.resolve(this.currentXhr)},e.prototype.backOffWait=function(){return 1===this.attempts?0:1e3*Math.min(this.con.maxRetryBackoffSecs,Math.pow(this.con.retryBackoffPower,this.attempts-2))},e.prototype.error=function(t){if(!this.errorExceptionStatus()&&(this.signer.error(),I.d(this.request.step,"error:",this.fileUpload.id,t),void 0===this.errorHandler(t))){this.fileUpload.warn("Error in ",this.request.step,t),this.fileUpload.setStatus(10);var e=this,o=this.backOffWait();this.attempts+=1,setTimeout(function(){e.errorExceptionStatus()||e.trySend()},o)}},e.prototype.errorHandler=function(){},e.prototype.errorExceptionStatus=function(){return!1},e.prototype.getPayload=function(){return Promise.resolve(null)},e.prototype.success_status=function(t){return t.status>=200&&t.status<=299||this.request.success404&&404===t.status},e.prototype.stringToSign=function(){return encodeURIComponent(this.signer.stringToSign())},e.prototype.canonicalRequest=function(){return this.signer.canonicalRequest()},e.prototype.signResponse=function(t,e,o){var r=this;return new Promise(function(s){if("function"==typeof r.con.signResponseHandler)return r.con.signResponseHandler(t,e,o).then(s);s(t)})},e.prototype.sendRequestToAWS=function(){var t=this;return new Promise(function(e,o){var r=new XMLHttpRequest;t.currentXhr=r;var s=[t.awsUrl,t.getPath(),t.request.path].join(""),i={};t.request.query_string&&(s+=t.request.query_string),S(i,t.request.not_signed_headers),S(i,t.request.x_amz_headers),r.onreadystatechange=function(){if(4===r.readyState)if(t.success_status(r))t.request.response_match&&void 0===r.response.match(new RegExp(t.request.response_match))?o("AWS response does not match set pattern: "+t.request.response_match):e();else{var s=r.responseText?y(r):" ";s+="status:"+r.status,o(s)}},r.open(t.request.method,s),r.setRequestHeader("Authorization",t.signer.authorizationString());for(var n in i)i.hasOwnProperty(n)&&r.setRequestHeader(n,i[n]);t.signer.setHeaders(r),t.request.contentType&&r.setRequestHeader("Content-Type",t.request.contentType),t.request.md5_digest&&r.setRequestHeader("Content-MD5",t.request.md5_digest),r.onerror=function(t){var e=t.responseText?y(t):"transport error";o(e)},"function"==typeof t.request.onProgress&&(r.upload.onprogress=t.request.onProgress),t.getPayload().then(r.send.bind(r),o),setTimeout(function(){t.started.resolve("request sent "+t.request.step)},20),t.signer.payload=null,t.payloadPromise=void 0})},e.prototype.authorize=function(){return this.request.dateString=this.signer.dateString(this.localTimeOffset),this.request.x_amz_headers=S(this.request.x_amz_headers,{"x-amz-date":this.request.dateString}),this.signer.getPayload().then(function(){return l(this).authorize()}.bind(this))},e.prototype.authorizationSuccess=function(t){I.d(this.request.step,"signature:",t),this.request.auth=t},e.prototype.trySend=function(){var t=this;return this.authorize().then(function(e){t.authorizationSuccess(e),20!==t.fileUpload.status&&t.sendRequestToAWS().then(t.success.bind(t),t.error.bind(t))},t.error.bind(t))},e.prototype.send=function(){return this.trySend(),this.awsDeferred.promise},o.prototype=Object.create(e.prototype),o.prototype.constructor=o,o.prototype.errorExceptionStatus=function(){return[20,5].indexOf(this.fileUpload.status)>-1},r.prototype=Object.create(o.prototype),r.prototype.constructor=r,r.prototype.maxRetries=1,r.prototype.errorHandler=function(t){if(this.attempts>this.maxRetries){var e=["MaxRetries exceeded. Will re-upload file id ",this.fileUpload.id,", ",t].join("");return I.w(e),this.awsDeferred.reject(e),!0}},r.prototype.rejectedSuccess=function(){var t=Array.prototype.slice.call(arguments,1).join("");return this.awsDeferred.reject(t),!1},(s.prototype=Object.create(o.prototype)).constructor=s,s.prototype.success=function(){var t=this.currentXhr.response.match(new RegExp(this.request.response_match));this.fileUpload.uploadId=t[1],this.fileUpload.awsKey=this.awsKey,I.d("InitiateMultipartUpload ID is",this.fileUpload.uploadId),this.fileUpload.createUploadFile(),this.awsDeferred.resolve(this.currentXhr)},(i.prototype=Object.create(o.prototype)).constructor=i,i.prototype.getPayload=function(){return Promise.resolve(this.fileUpload.getCompletedPayload())},(n.prototype=Object.create(r.prototype)).constructor=n,n.prototype.awsKey=void 0,n.prototype.success=function(){(this.currentXhr.getResponseHeader("Etag")===this.fileUpload.eTag||this.rejectedSuccess("uploadId ",this.fileUpload.id," found on S3 but the Etag doesn't match."))&&this.awsDeferred.resolve(this.currentXhr)},(a.prototype=Object.create(r.prototype)).constructor=a,a.prototype.awsKey=void 0,a.prototype.partNumberMarker=0,a.prototype.setupRequest=function(t){var e=["setupRequest() for uploadId:",this.fileUpload.uploadId,"for part marker:",t].join(" ");I.d(e),this.fileUpload.info(e),this.awsKey=this.fileUpload.name,this.partNumberMarker=t;var o={method:"GET",path:["?uploadId=",this.fileUpload.uploadId].join(""),query_string:"&part-number-marker="+t,x_amz_headers:this.fileUpload.xAmzHeadersCommon,step:"get upload parts",success404:!0};return this.request=o,o},a.prototype.success=function(){if(404!==this.currentXhr.status){var t=this.fileUpload.listPartsSuccess(this,this.currentXhr.responseText);if(t){var e=this.setupRequest(t);this.updateRequest(e),this.trySend()}else this.fileUpload.makePartsfromPartsOnS3(),this.awsDeferred.resolve(this.currentXhr)}else this.rejectedSuccess("uploadId ",this.fileUpload.id," not found on S3.")&&this.awsDeferred.resolve(this.currentXhr)},(p.prototype=Object.create(e.prototype)).constructor=p,p.prototype.part=1,p.prototype.payloadPromise=void 0,p.prototype.start=0,p.prototype.end=0,p.prototype.partNumber=void 0,p.prototype.getPartMd5Digest=function(){var t=this,e=this.part;return new Promise(function(o,r){t.con.computeContentMd5&&!e.md5_digest?t.getPayload().then(function(e){var r=t.con.cryptoMd5Method(e);1===t.partNumber&&t.con.computeContentMd5&&void 0===t.fileUpload.firstMd5Digest&&(t.fileUpload.firstMd5Digest=r,t.fileUpload.updateUploadFile({firstMd5Digest:r})),o(r)},r):o(e.md5_digest)}).then(function(e){e&&(I.d(t.request.step,"MD5 digest:",e),t.request.md5_digest=e,t.part.md5_digest=e)})},p.prototype.sendRequestToAWS=function(){return this.stalledInterval=setInterval(this.stalledPartMonitor(),12e4),this.stalledPartMonitor(),e.prototype.sendRequestToAWS.call(this)},p.prototype.send=function(){if(3!==this.part.status&&-1===[20,4,5].indexOf(this.fileUpload.status)){I.d("uploadPart #",this.partNumber,1===this.attempts?"submitting":"retrying"),this.part.status=2,this.attempts+=1,this.part.loadedBytesPrevious=null;var t=this;return this.getPartMd5Digest().then(function(){I.d("Sending",t.request.step),e.prototype.send.call(t)})}},p.prototype.success=function(){clearInterval(this.stalledInterval);var t=this.currentXhr.getResponseHeader("ETag");this.currentXhr=null,this.fileUpload.partSuccess(t,this)&&this.awsDeferred.resolve(this.currentXhr)},p.prototype.onProgress=function(t){if(t.loaded>0){var e=t.loaded-this.part.loadedBytes;e&&(this.part.loadedBytes=t.loaded,this.fileUpload.updateLoaded(e))}},p.prototype.stalledPartMonitor=function(){var t=this.part.loadedBytes,e=this;return function(){clearInterval(e.stalledInterval),-1===[2,10,30,4].indexOf(e.fileUpload.status)&&20!==e.part.status&&e.part.loadedBytes-1},p.prototype.delaySend=function(){var t=this.backOffWait();this.attempts+=1,setTimeout(this.send.bind(this),t)},p.prototype.errorHandler=function(t){if(clearInterval(this.stalledInterval),t.match(/status:404/)){var e="404 error on part PUT. The part and the file will abort. "+t;return I.w(e),this.fileUpload.error(e),this.part.status=20,this.awsDeferred.reject(e),!0}return this.resetLoadedBytes(),this.part.status=10,this.errorExceptionStatus()||this.delaySend(),!0},p.prototype.abort=function(){this.currentXhr&&this.currentXhr.abort(),this.resetLoadedBytes(),this.attempts=1},p.size=0,p.prototype.streamToArrayBuffer=function(t){return new Promise(function(e,o){function r(t){1!==t.byteLength&&(a.set(t,p),p+=t.byteLength)}function s(t){t?o(t):e(a),n()}function i(){e(a),n()}function n(){a=null,t.removeListener("data",r),t.removeListener("end",s),t.removeListener("error",s),t.removeListener("close",i)}if(!t.readable)return e([]);var a=new Uint8Array(Math.min(this.con.partSize,this.end-this.start)),p=0;t.on("data",r),t.on("end",s),t.on("error",s),t.on("close",i)}.bind(this))},p.prototype.getPayload=function(){return void 0===this.payloadPromise&&(this.payloadPromise=this.con.readableStreams?this.payloadFromStream():this.payloadFromBlob()),this.payloadPromise},p.prototype.payloadFromStream=function(){var t=this.con.readableStreamPartMethod(this.fileUpload.file,this.start,this.end-1);return new Promise(function(e,o){this.streamToArrayBuffer(t).then(function(t){e(t)}.bind(this),o)}.bind(this))},p.prototype.payloadFromBlob=function(){var t=this.fileUpload.file,e=t[t.slice?"slice":t.mozSlice?"mozSlice":"webkitSlice"](this.start,this.end);return this.con.computeContentMd5?new Promise(function(t){var o=new FileReader;o.onloadend=function(){var e=this.result&&void 0!==this.result.buffer?new Uint8Array(this.result.buffer):this.result;t(e)},o.readAsArrayBuffer(e)}):Promise.resolve(e)},p.prototype.stalledInterval=-1,p.prototype.getStartedPromise=function(){return this.started.promise},(u.prototype=Object.create(e.prototype)).constructor=u,u.prototype.maxRetries=1,u.prototype.success=function(){this.fileUpload.setStatus(20),this.awsDeferred.resolve(this.currentXhr)},u.prototype.errorHandler=function(t){if(this.attempts>this.maxRetries){var e="Error aborting upload, Exceeded retries deleting the file upload: "+t;return I.w(e),this.fileUpload.error(e),this.awsDeferred.reject(e),!0}};var H;x.prototype.supported=!1,x.prototype.cacheStore=void 0,x.prototype.getItem=function(t){if(this.cacheStore)return this.cacheStore[t]},x.prototype.setItem=function(t,e){this.cacheStore&&(this.cacheStore[t]=e)},x.prototype.removeItem=function(t){if(this.cacheStore)return delete this.cacheStore[t]},x.supported=function(){if("undefined"==typeof window)return!1;if(!("localStorage"in window))return!1;try{var t="___test";localStorage[t]="OK";var e=localStorage[t];return delete localStorage[t],"OK"===e}catch(t){return!1}},I=C(),"undefined"!=typeof module&&module.exports?module.exports=j:"undefined"!=typeof window&&(window.Evaporate=j)}();