!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,this.updateRequest(e)}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:"(.+)"};t.contentType&&(r.contentType=t.contentType),o.call(this,t,r),this.awsKey=e}function n(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 i(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.part,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 n=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 ",n.aws_key,":",this.request.auth].join("")},r.prototype.stringToSign=function(){var o,r="",s=[];for(var i in this.request.x_amz_headers)this.request.x_amz_headers.hasOwnProperty(i)&&s.push(i);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+(n.cloudfront?"/"+n.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=",n.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(n.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(n.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,n=s.length?s.split("&"):[],i=[];for(o=0;o1?encodeURIComponent(e[1]):null});var a=i.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),i(e)}i("Signature fetch returned status: "+a.status)}},a.onerror=function(t){i("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(),n.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=t.split("/"),o=[];return e.forEach(function(t){o.push(encodeURIComponent(t).replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/'/g,"%27"))}),o.join("/")}function f(t){var e,o=t||"/";try{e=new URL(o)}catch(t){e=document.createElement("a"),e.href=o}return{protocol:e.protocol,hostname:e.hostname,pathname:e.pathname.replace(/(^\/?)/,"/"),port:e.port,search:"?"===e.search[0]?e.search.substr(1):e.search,hash:e.hash,host:e.host}}function m(t){return t?new Date(t).toISOString():""}function y(t){var e=g(t.responseText,"Code"),o=g(t.responseText,"Message");return e.length?["AWS Code: ",e,", Message:",o].join(""):""}function g(t,e){var o=t.match(["<",e,">(.+)",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(K.getItem("awsUploads")||"{}");if(t){for(var o in e)if(e.hasOwnProperty(o)){var r=e[o],s=new Date(r.completedAt||R);s-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 O(){return{d:function(){},w:function(){},e:function(){}}}var I,C,R=new Date("2060-10-22"),_=0,M=2,F=3,z=4,j=5,H=10,A=20,E=30,B=[z,E],D=[_,M,H],k='"d41d8cd98f00b204e9800998ecf8427e"',N=12e4,L=["maxConcurrentParts","logging","cloudfront","encodeFilename","computeContentMd5","allowS3ExistenceOptimization","onlyRetryForSameFileName","timeUrl","cryptoMd5Method","cryptoHexEncodedHash256","awsRegion","awsSignatureVersion","evaporateChanged"],W=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&&(C=window.console,C.d=C.log,C.w=window.console.warn?C.warn:C.d,C.e=window.console.error?C.error:C.d),this._instantiationError=this.validateEvaporateOptions(),"string"==typeof this._instantiationError)return void(this.supported=!1);delete this._instantiationError,this.config.logging||(C=O());var e=new Date;if(I=new Date(e.setHours(e.getHours()-(this.config.s3FileCacheHoursAgo||-100))),"number"==typeof t.localTimeOffset)this.localTimeOffset=t.localTimeOffset;else{var o=this;W.getLocalTimeOffset(this.config).then(function(t){o.localTimeOffset=t})}this.pendingFiles={},this.queuedFiles=[],this.filesInProcess=[],K=new x(this.config.mockLocalStorage)};W.create=function(t){var e=S({},t);return W.getLocalTimeOffset(e).then(function(t){return e.localTimeOffset=t,new Promise(function(t,o){var r=new W(e);r.supported===!0?t(r):o(r._instantiationError)})})},W.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)),o=new Date;e(t-o)}},r.onerror=function(t){C.e("xhr error timeUrl",t),o("Fetching offset time failed with status: "+t.status)},r.send()}else e(0)}).then(function(t){return C.d("localTimeOffset is",t,"ms"),new Promise(function(e){e(t)})})},W.prototype.config={},W.prototype.localTimeOffset=0,W.prototype.supported=!1,W.prototype._instantiationError=void 0,W.prototype.evaporatingCount=0,W.prototype.pendingFiles={},W.prototype.filesInProcess=[],W.prototype.queuedFiles=[],W.prototype.startNextFile=function(t){if(this.queuedFiles.length&&!(this.evaporatingCount>=this.config.maxConcurrentParts)){var e=this.queuedFiles.shift();e.status===_?(C.d("Starting",decodeURIComponent(e.name),"reason:",t),this.evaporatingCnt(1),e.start()):(C.d("Requeued",decodeURIComponent(e.name),"status:",e.status,"reason:",t),this.queuedFiles.push(e))}},W.prototype.fileCleanup=function(t){T(this.queuedFiles,t),T(this.filesInProcess,t)&&this.evaporatingCnt(-1),t.done(),this.consumeRemainingSlots()},W.prototype.queueFile=function(t){this.filesInProcess.push(t),this.queuedFiles.push(t),1===this.filesInProcess.length&&this.startNextFile("first file")},W.prototype.add=function(e,o){var r,s=this;return new Promise(function(n,i){var a=S(o,{});if(L.forEach(function(t){delete a[t]}),r=S(s.config,a),"undefined"==typeof e||"undefined"==typeof e.file)return i("Missing file");if(r.maxFileSize&&e.file.size>r.maxFileSize)return i("File size too large. Maximum size allowed is "+r.maxFileSize);if("undefined"==typeof e.name)return i("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:_,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),n(decodeURIComponent(p.name))},function(t){s.fileCleanup(p),i(t)})})},W.prototype.cancel=function(t){return"undefined"==typeof t?this._cancelAll():this._cancelOne(t)},W.prototype._cancelAll=function(){C.d("Canceling all file uploads");var t=[];for(var e in this.pendingFiles)if(this.pendingFiles.hasOwnProperty(e)){var o=this.pendingFiles[e];D.indexOf(o.status)>-1&&t.push(o.stop())}return t.length||t.push(Promise.reject("No files to cancel.")),Promise.all(t)},W.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)},W.prototype.pause=function(t,e){e=e||{};var o="undefined"!=typeof e.force&&e.force;return"undefined"==typeof t?this._pauseAll(o):this._pauseOne(t,o)},W.prototype._pauseAll=function(t){C.d("Pausing all file uploads");var e=[];for(var o in this.pendingFiles)if(this.pendingFiles.hasOwnProperty(o)){var r=this.pendingFiles[o];D.indexOf(r.status)>-1&&this._pause(r,t,e)}return Promise.all(e)},W.prototype._pauseOne=function(t,e){var o=[],r=this.pendingFiles[t];return"undefined"==typeof r?o.push(Promise.reject("Cannot pause a file that has not been added.")):r.status===z&&o.push(Promise.reject("Cannot pause a file that is already paused.")),o.length||this._pause(r,e,o),Promise.all(o)},W.prototype._pause=function(t,e,o){o.push(t.pause(e)),T(this.filesInProcess,t),T(this.queuedFiles,t)},W.prototype.resume=function(t){return"undefined"==typeof t?this._resumeAll():this._resumeOne(t)},W.prototype._resumeAll=function(){C.d("Resuming all file uploads");for(var t in this.pendingFiles)if(this.pendingFiles.hasOwnProperty(t)){var e=this.pendingFiles[t];B.indexOf(e.status)>-1&&this.resumeFile(e)}return Promise.resolve()},W.prototype._resumeOne=function(t){var e=this.pendingFiles[t],o=[];return"undefined"==typeof e?o.push(Promise.reject("Cannot pause a file that does not exist.")):B.indexOf(e.status)===-1?o.push(Promise.reject("Cannot resume a file that has not been paused.")):this.resumeFile(e),Promise.all(o)},W.prototype.resumeFile=function(t){t.resume(),this.queueFile(t)},W.prototype.forceRetry=function(){},W.prototype.consumeRemainingSlots=function(){var t=this.config.maxConcurrentParts-this.evaporatingCount;if(t)for(var e=0;e0&&(o.secondsLeft=Math.round(r/e)),o},t.prototype.onProgress=function(){[A,z].indexOf(this.status)===-1&&(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.totalUpoaded=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=M,this.startMonitor(),this.started(this.id),this.uploadId)return C.d("resuming FileUpload ",this.id),this.consumeSlots();var t=this.name;this.getUnfinishedFileUpload();var e=this.con.computeContentMd5&&this.con.allowS3ExistenceOptimization&&"undefined"!=typeof this.firstMd5Digest&&"undefined"!=typeof this.eTag,o=this,r=!1;new Promise(function(s,n){new Promise(function(s,n){if(!o.uploadId)throw"";return e?o.reuseS3Object(t).then(s,n):(r=!0,void o.resumeInterruptedUpload().then(s,n))}).then(s,function(e){D.indexOf(o.status)!==-1&&(C.d(e),o.uploadId=void 0,r=!0,o.uploadFile(t).then(s,n))})}).then(function(){var t=r?o.completeUpload():Promise.resolve();t.then(o.deferredCompletion.resolve.bind(o))},function(){o.abortedByUser||o.abortUpload().then(function(){o.deferredCompletion.reject("File upload aborted due to a part failing to upload")},o.deferredCompletion.reject.bind(o))})},t.prototype.stop=function(){C.d("stopping FileUpload ",this.id),this.setStatus(j),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){C.d("pausing FileUpload, force:",!!t,this.id);var e=[];return this.info("Pausing uploads..."),this.status=E,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=z,this.startNextFile("pause"),this.paused()}.bind(this))},t.prototype.resume=function(){this.status=_,this.resumed()},t.prototype.done=function(){clearInterval(this.progressInterval),this.startNextFile("file done"),this.partsOnS3=[],this.s3Parts=[]},t.prototype.startPartUpload=function(t){this.lastPartSatisfied.then(t.delaySend.bind(t)),this.lastPartSatisfied=t.getStartedPromise()},t.prototype.abortParts=function(t){var e=this,o=this.partsInProcess.slice(0);o.forEach(function(o){var r=e.s3Parts[o];r&&(r.awsRequest.abort(),t&&(r.status=_),T(e.partsInProcess,r.part),e.partsToUpload.length&&e.evaporatingCnt(-1))})},t.prototype.makeParts=function(t){function e(t){T(n.partsToUpload,t.part),T(n.partsInProcess,t.part),n.partsToUpload.length&&n.evaporatingCnt(-1)}function o(t){return function(){e(t),n.partsToUpload.length&&n.consumeRemainingSlots(),n.partsToUpload.lengthI&&this.con.bucket===t.bucket&&(!this.con.onlyRetryForSameFileName||this.name===t.awsKey)},t.prototype.partSuccess=function(t,e){var o=e.part;if(C.d(e.request.step,"ETag:",t),o.isEmpty||t!==k)return o.eTag=t,o.status=F,this.partsOnS3.push(o),!0;o.status=H,e.resetLoadedBytes();var r=["eTag matches MD5 of 0 length blob for part #",e.partNumber,"Retrying part."].join(" ");C.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(){D.indexOf(this.status)!==-1&&(this.nameChanged(this.name),this.partsOnS3.forEach(function(t){var e=this.makePart(t.partNumber,F,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 n(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&&this.status===M){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.part),this.startPartUpload(r.awsRequest),e+=1,e===t))break}var s=this.partsToUpload.length===this.partsInProcess.length,n=this.getRemainingSlots();return s&&n>0&&this.startNextFile("consume slots"),n}return 0},t.prototype.canStartPart=function(t){return this.partsInProcess.indexOf(t.part)===-1&&!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.totalUpoaded=0,D.indexOf(this.status)===-1)return Promise.reject("Part uploading stopped because the file was canceled");var t=this.makeParts();return this.setStatus(M),this.startTime=new Date,this.consumeSlots(),Promise.all(t)},t.prototype.abortUpload=function(){return new Promise(function(t,e){return"undefined"==typeof this.uploadId?void t():void new u(this).send().then(t,e)}.bind(this)).then(function(){this.setStatus(A),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===o.s3Parts[1].md5_digest)return new i(o,t).send().then(function(t){C.d("headObject found matching object on S3."),o.completeUploadFile(t),o.nameChanged(o.name)}).catch(e);var r=o.con.allowS3ExistenceOptimization?"File's first part MD5 digest does not match what was stored.":"allowS3ExistenceOptimization is not enabled.";e(r)})},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,C);this.signer=new e(t)},e.prototype.success=function(){return!0},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(),C.d(this.request.step,"error:",this.fileUpload.id,t),"undefined"==typeof this.errorHandler(t))){this.fileUpload.warn("Error in ",this.request.step,t),this.fileUpload.setStatus(H);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){return"function"==typeof r.con.signResponseHandler?r.con.signResponseHandler(t,e,o).then(s):void 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(""),n={};t.request.query_string&&(s+=t.request.query_string),S(n,t.request.not_signed_headers),S(n,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(r);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 i in n)n.hasOwnProperty(i)&&r.setRequestHeader(i,n[i]);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){C.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),t.fileUpload.status!==A&&t.sendRequestToAWS().then(function(e){t.success(e)&&t.awsDeferred.resolve(e)},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[A,j].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 C.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),s.prototype.constructor=s,s.prototype.success=function(t){var e=t.response.match(new RegExp(this.request.response_match));return this.fileUpload.uploadId=e[1],this.fileUpload.awsKey=this.awsKey,C.d("InitiateMultipartUpload ID is",this.fileUpload.uploadId),this.fileUpload.createUploadFile(),!0},n.prototype=Object.create(o.prototype),n.prototype.constructor=n,n.prototype.getPayload=function(){return Promise.resolve(this.fileUpload.getCompletedPayload())},i.prototype=Object.create(r.prototype),i.prototype.constructor=i,i.prototype.awsKey=void 0,i.prototype.success=function(t){var e=t.getResponseHeader("Etag");return e===this.fileUpload.eTag||this.rejectedSuccess("uploadId ",this.fileUpload.id," found on S3 but the Etag doesn't match.")},a.prototype=Object.create(r.prototype),a.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(" ");C.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(t){if(404===t.status)return this.rejectedSuccess("uploadId ",this.fileUpload.id," not found on S3.");var e=this.fileUpload.listPartsSuccess(this,t.responseText);if(!e)return this.fileUpload.makePartsfromPartsOnS3(),!0;var o=this.setupRequest(e);this.updateRequest(o),this.trySend()},p.prototype=Object.create(e.prototype),p.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&&"undefined"==typeof t.fileUpload.firstMd5Digest&&(t.fileUpload.firstMd5Digest=r,t.fileUpload.updateUploadFile({firstMd5Digest:r})),o(r)},r):o(e.md5_digest)}).then(function(e){e&&(C.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(),N),this.stalledPartMonitor(),e.prototype.sendRequestToAWS.call(this)},p.prototype.send=function(){if(this.part.status!==F&&[A,z,j].indexOf(this.fileUpload.status)===-1){C.d("uploadPart #",this.partNumber,1===this.attempts?"submitting":"retrying"),this.part.status=M,this.attempts+=1,this.part.loadedBytesPrevious=null;var t=this;return this.getPartMd5Digest().then(function(){C.d("Sending",t.request.step),e.prototype.send.call(t)})}},p.prototype.success=function(t){clearInterval(this.stalledInterval);var e=t.getResponseHeader("ETag");return this.fileUpload.partSuccess(e,this)},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),[M,H,E,z].indexOf(e.fileUpload.status)===-1&&e.part.status!==A&&e.part.loadedBytes-1},p.prototype.delaySend=function(){var t;this.part.status===H?(t=this.backOffWait(),this.attempts+=1):t=0,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 C.w(e),this.fileUpload.error(e),this.part.status=A,this.awsDeferred.reject(e),!0}return this.resetLoadedBytes(),this.part.status=H,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){var e=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),i()}function n(){e(a),i()}function i(){a=null,t.removeListener("data",r),t.removeListener("end",s),t.removeListener("error",s),t.removeListener("close",n)}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",n)}.bind(this));return e},p.prototype.getPayload=function(){return"undefined"==typeof this.payloadPromise&&(this.payloadPromise=new Promise(function(t,e){var o=this.con.readableStreams?this.payloadFromStream():this.payloadFromBlob();o.then(t,e)}.bind(this))),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){var r=this.streamToArrayBuffer(t);r.then(function(t){e(t)}.bind(this),o)}.bind(this))},p.prototype.payloadFromBlob=function(){var t=this.fileUpload.file,e=t.slice?"slice":t.mozSlice?"mozSlice":"webkitSlice",o=t[e](this.start,this.end);return this.con.computeContentMd5?new Promise(function(t){var e=new FileReader;e.onloadend=function(){var e=this.result&&"undefined"!=typeof this.result.buffer,o=e?new Uint8Array(this.result.buffer):this.result;t(o)},e.readAsArrayBuffer(o)}):Promise.resolve(o)},p.prototype.stalledInterval=-1,p.prototype.getStartedPromise=function(){return this.started.promise},u.prototype=Object.create(e.prototype),u.prototype.constructor=u,u.prototype.maxRetries=1,u.prototype.success=function(){return this.fileUpload.setStatus(A),!0},u.prototype.errorHandler=function(t){if(this.attempts>this.maxRetries){var e="Error aborting upload, Exceeded retries deleting the file upload: "+t;return C.w(e),this.fileUpload.error(e),this.awsDeferred.reject(e),!0}};var K;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(){var t=!1;if("undefined"==typeof window)return t;if(!("localStorage"in window))return t;try{var e="___test";localStorage[e]="OK";var o=localStorage[e];return delete localStorage[e],"OK"===o}catch(e){return t}},C=O(),"undefined"!=typeof module&&module.exports?module.exports=W:"undefined"!=typeof window&&(window.Evaporate=W)}();
//# sourceMappingURL=evaporate.min.js.map