New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

httpinvoke

Package Overview
Dependencies
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

httpinvoke - npm Package Compare versions

Comparing version 1.2.1 to 1.3.0

test/hook.js

4

bower.json
{
"name": "httpinvoke",
"version": "1.2.1",
"version": "1.3.0",
"main": "httpinvoke-browser.js",
"description": "A 5.7kb no-dependencies HTTP client library for browsers and Node.js with a promise-based or Node.js-style callback-based API to progress events, text and binary file upload and download, partial response body, request and response headers, status code.",
"description": "A no-dependencies HTTP client library for browsers and Node.js with a promise-based or Node.js-style callback-based API to progress events, text and binary file upload and download, partial response body, request and response headers, status code.",
"location": "https://github.com/jakutis/httpinvoke",

@@ -7,0 +7,0 @@ "homepage": "https://github.com/jakutis/httpinvoke",

{
"name": "httpinvoke",
"repo": "jakutis/httpinvoke",
"version": "1.2.1",
"description": "A 5.7kb no-dependencies HTTP client library for browsers and Node.js with a promise-based or Node.js-style callback-based API to progress events, text and binary file upload and download, partial response body, request and response headers, status code.",
"version": "1.3.0",
"description": "A no-dependencies HTTP client library for browsers and Node.js with a promise-based or Node.js-style callback-based API to progress events, text and binary file upload and download, partial response body, request and response headers, status code.",
"keywords": [

@@ -7,0 +7,0 @@ "http",

@@ -16,6 +16,6 @@ var fs = require('fs');

return replace(contents, ';', [{
from: 'var mixInPromise, pass, isArray, isArrayBufferView, _undefined, nextTick, isFormData;',
from: 'var addHook, initHooks, mixInPromise, pass, isArray, isArrayBufferView, _undefined, nextTick, isFormData;',
to: globalVar + ';' + fs.readFileSync('./src/common/static.js').toString()
}, {
from: 'var promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode;',
from: 'var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode;',
to: fs.readFileSync('./src/common/closures.js').toString()

@@ -22,0 +22,0 @@ }]);

@@ -36,12 +36,12 @@ (function (root, factory) {

var makeState = function(newstate) {
o[newstate] = function(newvalue) {
o[newstate] = function() {
var i, p;
if(queue) {
value = newvalue;
value = [].slice.call(arguments);
state = newstate;
for(i = 0; i < queue.length; i++) {
for(i = 0; i < queue.length; i += 1) {
if(typeof queue[i][state] === 'function') {
try {
p = queue[i][state].call(null, value);
p = queue[i][state].apply(null, value);
if(state < progress) {

@@ -54,3 +54,3 @@ chain(p, queue[i]._);

} else if(state < progress) {
queue[i]._[state](value);
queue[i]._[state].apply(null, value);
}

@@ -74,3 +74,3 @@ }

nextTick(function() {
chain(item[state](value), item._);
chain(item[state].apply(null, value), item._);
});

@@ -110,3 +110,26 @@ }

return value;
}, _undefined;
}, _undefined, addHook = function(type, hook) {
'use strict';
if(typeof hook !== 'function') {
throw new Error('TODO error');
}
if(!this._hooks[type]) {
throw new Error('TODO error');
}
var httpinvoke = build();
for(var i in this._hooks) {
if(this._hooks.hasOwnProperty(i)) {
httpinvoke._hooks[i].push.apply(httpinvoke._hooks[i], this._hooks[i]);
}
}
httpinvoke._hooks[type].push(hook);
return httpinvoke;
}, initHooks = function() {
return {
finished:[],
downloading:[],
uploading:[],
gotStatus:[]
};
};
;

@@ -191,2 +214,4 @@ /* jshint unused:false */

};
var build = function() {
var createXHR;

@@ -200,3 +225,10 @@ var httpinvoke = function(uri, method, options, cb) {

/* jshint -W020 */
var promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter;
hook = function(type, args) {
var hooks = httpinvoke._hooks[type];
for(var i = 0; i < hooks.length; i += 1) {
args = hooks[i].apply(null, args);
}
return args;
};
/*************** COMMON initialize parameters **************/

@@ -244,20 +276,32 @@ var downloadTimeout, uploadTimeout, timeout;

var safeCallback = function(name, aspectBefore, aspectAfter) {
return function(a, b, c, d) {
var _cb;
aspectBefore(a, b, c, d);
return function() {
var args, _cb, failedOnHook = false, fail = function(err, args) {
_cb = cb;
cb = null;
nextTick(function() {
/* jshint expr:true */
_cb && _cb(err);
/* jshint expr:false */
promise();
if(!_cb && !failedOnHook) {
throw err;
}
});
return name === 'finished' ? [err] : args;
};
aspectBefore.apply(null, args);
try {
args = hook(name, [].slice.call(arguments));
} catch(err) {
failedOnHook = true;
args = fail(err, args);
}
if(options[name]) {
try {
options[name](a, b, c, d);
options[name].apply(null, args);
} catch(err) {
_cb = cb;
cb = null;
nextTick(function() {
/* jshint expr:true */
_cb && _cb(err);
/* jshint expr:false */
promise();
});
args = fail(err, args);
}
}
aspectAfter(a, b, c, d);
aspectAfter.apply(null, args);
};

@@ -317,22 +361,12 @@ };

}, function(err, body, statusCode, headers) {
if(err) {
return promise[reject](err);
}
promise[resolve]({
var res = {
body: body,
statusCode: statusCode,
headers: headers
});
};
if(err) {
return promise[reject](err, res);
}
promise[resolve](res);
});
var fixPositiveOpt = function(opt) {
if(options[opt] === _undefined) {
options[opt] = 0;
} else if(typeof options[opt] === 'number') {
if(options[opt] < 0) {
return failWithoutRequest(cb, [1, opt]);
}
} else {
return failWithoutRequest(cb, [2, opt]);
}
};
var converters = options.converters || {};

@@ -1152,5 +1186,9 @@ var inputConverter;

})();
httpinvoke._hooks = initHooks();
httpinvoke.hook = addHook;
return httpinvoke;
};
return build();
})
));

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

(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.httpinvoke=factory()}})(this,function(){"use strict";var global;global=window;var resolve=0,reject=1,progress=2,chain=function(a,b){if(a&&a.then){a.then(function(){b[resolve].apply(null,arguments)},function(){b[reject].apply(null,arguments)},function(){b[progress].apply(null,arguments)})}else{b[resolve](a)}},nextTick=global.process&&global.process.nextTick||global.setImmediate||global.setTimeout,mixInPromise=function(o){var value,queue=[],state=progress;var makeState=function(newstate){o[newstate]=function(newvalue){var i,p;if(queue){value=newvalue;state=newstate;for(i=0;i<queue.length;i++){if(typeof queue[i][state]==="function"){try{p=queue[i][state].call(null,value);if(state<progress){chain(p,queue[i]._)}}catch(err){queue[i]._[reject](err)}}else if(state<progress){queue[i]._[state](value)}}if(state<progress){queue=null}}}};makeState(progress);makeState(resolve);makeState(reject);o.then=function(){var item=[].slice.call(arguments);item._=mixInPromise({});if(queue){queue.push(item)}else if(typeof item[state]==="function"){nextTick(function(){chain(item[state](value),item._)})}return item._};return o},isArrayBufferView=function(input){return typeof input==="object"&&input!==null&&(global.ArrayBufferView&&input instanceof ArrayBufferView||global.Int8Array&&input instanceof Int8Array||global.Uint8Array&&input instanceof Uint8Array||global.Uint8ClampedArray&&input instanceof Uint8ClampedArray||global.Int16Array&&input instanceof Int16Array||global.Uint16Array&&input instanceof Uint16Array||global.Int32Array&&input instanceof Int32Array||global.Uint32Array&&input instanceof Uint32Array||global.Float32Array&&input instanceof Float32Array||global.Float64Array&&input instanceof Float64Array)},isArray=function(object){return Object.prototype.toString.call(object)==="[object Array]"},isFormData=function(input){return typeof input==="object"&&input!==null&&global.FormData&&input instanceof global.FormData},isByteArray=function(input){return typeof input==="object"&&input!==null&&(global.Buffer&&input instanceof Buffer||global.Blob&&input instanceof Blob||global.File&&input instanceof File||global.ArrayBuffer&&input instanceof ArrayBuffer||isArrayBufferView(input)||isArray(input))},supportedMethods=",GET,HEAD,PATCH,POST,PUT,DELETE,",pass=function(value){return value},_undefined;var statusTextToCode=function(){for(var group=arguments.length,map={};group--;){for(var texts=arguments[group].split(","),index=texts.length;index--;){map[texts[index]]=(group+1)*100+index}}return map}("Continue,Switching Protocols","OK,Created,Accepted,Non-Authoritative Information,No Content,Reset Content,Partial Content","Multiple Choices,Moved Permanently,Found,See Other,Not Modified,Use Proxy,_,Temporary Redirect","Bad Request,Unauthorized,Payment Required,Forbidden,Not Found,Method Not Allowed,Not Acceptable,Proxy Authentication Required,Request Timeout,Conflict,Gone,Length Required,Precondition Failed,Request Entity Too Large,Request-URI Too Long,Unsupported Media Type,Requested Range Not Satisfiable,Expectation Failed","Internal Server Error,Not Implemented,Bad Gateway,Service Unavailable,Gateway Time-out,HTTP Version Not Supported");var upgradeByteArray=global.Uint8Array?function(array){return new Uint8Array(array)}:pass;var binaryStringToByteArray=function(str,bytearray){for(var i=bytearray.length;i<str.length;){bytearray.push(str.charCodeAt(i++)&255)}return bytearray};var countStringBytes=function(string){for(var c,n=0,i=string.length;i--;){c=string.charCodeAt(i);n+=c<128?1:c<2048?2:3}return n};var responseBodyToBytes,responseBodyLength;try{execScript("Function httpinvoke0(B,A,C)\r\nDim i\r\nFor i=C to LenB(B)\r\nA.push(AscB(MidB(B,i,1)))\r\nNext\r\nEnd Function\r\nFunction httpinvoke1(B)\r\nhttpinvoke1=LenB(B)\r\nEnd Function","vbscript");responseBodyToBytes=function(binary,bytearray){httpinvoke0(binary,bytearray,bytearray.length+1);return bytearray};responseBodyLength=function(binary){return httpinvoke1(binary)}}catch(err){}var responseByteArray=function(xhr,bytearray){return"responseBody"in xhr&&responseBodyToBytes?responseBodyToBytes(xhr.responseBody,bytearray):binaryStringToByteArray(xhr.responseText,bytearray)};var responseByteArrayLength=function(xhr){return"responseBody"in xhr&&responseBodyLength?responseBodyLength(xhr.responseBody):xhr.responseText.length};var fillOutputHeaders=function(xhr,outputHeaders){var headers=xhr.getAllResponseHeaders().split(/\r?\n/);var atLeastOne=false;for(var i=headers.length,colon,header;i--;){if((colon=headers[i].indexOf(":"))>=0){outputHeaders[headers[i].substr(0,colon).toLowerCase()]=headers[i].substr(colon+2);atLeastOne=true}}return atLeastOne};var urlPartitioningRegExp=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/;var isCrossDomain=function(location,uri){uri=urlPartitioningRegExp.exec(uri.toLowerCase());location=urlPartitioningRegExp.exec(location.toLowerCase())||[];return!!(uri&&(uri[1]!==location[1]||uri[2]!==location[2]||(uri[3]||(uri[1]==="http:"?"80":"443"))!==(location[3]||(location[1]==="http:"?"80":"443"))))};var createXHR;var httpinvoke=function(uri,method,options,cb){var promise,failWithoutRequest,uploadProgressCb,downloadProgressCb,inputLength,inputHeaders,statusCb,outputHeaders,exposedHeaders,status,outputBinary,input,outputLength,outputConverter;var downloadTimeout,uploadTimeout,timeout;if(!method){method="GET";options={}}else if(!options){if(typeof method==="string"){options={}}else if(typeof method==="object"){options=method;method="GET"}else{options={finished:method};method="GET"}}else if(!cb){if(typeof method==="object"){method.finished=options;options=method;method="GET"}else if(typeof options==="function"){options={finished:options}}}else{options.finished=cb}var safeCallback=function(name,aspectBefore,aspectAfter){return function(a,b,c,d){var _cb;aspectBefore(a,b,c,d);if(options[name]){try{options[name](a,b,c,d)}catch(err){_cb=cb;cb=null;nextTick(function(){_cb&&_cb(err);promise()})}}aspectAfter(a,b,c,d)}};failWithoutRequest=function(cb,err){if(!(err instanceof Error)){err=new Error("Error code #"+err+". See https://github.com/jakutis/httpinvoke#error-codes")}nextTick(function(){if(cb===null){return}cb(err)});promise=function(){};return mixInPromise(promise)};uploadProgressCb=safeCallback("uploading",pass,function(current,total){promise[progress]({type:"upload",current:current,total:total})});downloadProgressCb=safeCallback("downloading",pass,function(current,total,partial){promise[progress]({type:"download",current:current,total:total,partial:partial})});statusCb=safeCallback("gotStatus",function(){statusCb=null;if(downloadTimeout){setTimeout(function(){if(cb){cb(new Error("download timeout"));promise()}},downloadTimeout)}},function(statusCode,headers){promise[progress]({type:"headers",statusCode:statusCode,headers:headers})});cb=safeCallback("finished",function(){cb=null;promise()},function(err,body,statusCode,headers){if(err){return promise[reject](err)}promise[resolve]({body:body,statusCode:statusCode,headers:headers})});var fixPositiveOpt=function(opt){if(options[opt]===_undefined){options[opt]=0}else if(typeof options[opt]==="number"){if(options[opt]<0){return failWithoutRequest(cb,[1,opt])}}else{return failWithoutRequest(cb,[2,opt])}};var converters=options.converters||{};var inputConverter;inputHeaders=options.headers||{};outputHeaders={};exposedHeaders=options.corsExposedHeaders||[];exposedHeaders.push.apply(exposedHeaders,["Cache-Control","Content-Language","Content-Type","Content-Length","Expires","Last-Modified","Pragma","Content-Range","Content-Encoding"]);var partialOutputMode=options.partialOutputMode||"disabled";if(partialOutputMode.indexOf(",")>=0||",disabled,chunked,joined,".indexOf(","+partialOutputMode+",")<0){return failWithoutRequest(cb,[3])}if(method.indexOf(",")>=0||!httpinvoke.anyMethod&&supportedMethods.indexOf(","+method+",")<0){return failWithoutRequest(cb,[4,method])}var optionsOutputType=options.outputType;outputBinary=optionsOutputType==="bytearray";if(!optionsOutputType||optionsOutputType==="text"||outputBinary){outputConverter=pass}else if(converters["text "+optionsOutputType]){outputConverter=converters["text "+optionsOutputType];outputBinary=false}else if(converters["bytearray "+optionsOutputType]){outputConverter=converters["bytearray "+optionsOutputType];outputBinary=true}else{return failWithoutRequest(cb,[5,optionsOutputType])}inputConverter=pass;var optionsInputType=options.inputType;input=options.input;if(input!==_undefined){if(!optionsInputType||optionsInputType==="auto"){if(typeof input!=="string"&&!isByteArray(input)&&!isFormData(input)){return failWithoutRequest(cb,[6])}}else if(optionsInputType==="text"){if(typeof input!=="string"){return failWithoutRequest(cb,[7])}}else if(optionsInputType==="formdata"){if(!isFormData(input)){return failWithoutRequest(cb,[8])}}else if(optionsInputType==="bytearray"){if(!isByteArray(input)){return failWithoutRequest(cb,[9])}}else if(converters[optionsInputType+" text"]){inputConverter=converters[optionsInputType+" text"]}else if(converters[optionsInputType+" bytearray"]){inputConverter=converters[optionsInputType+" bytearray"]}else if(converters[optionsInputType+" formdata"]){inputConverter=converters[optionsInputType+" formdata"]}else{return failWithoutRequest(cb,[10,optionsInputType])}if(typeof input==="object"&&!isFormData(input)){if(global.ArrayBuffer&&input instanceof global.ArrayBuffer){input=new global.Uint8Array(input)}else if(isArrayBufferView(input)){input=new global.Uint8Array(input.buffer,input.byteOffset,input.byteLength)}}try{input=inputConverter(input)}catch(err){return failWithoutRequest(cb,err)}}else{if(optionsInputType&&optionsInputType!=="auto"){return failWithoutRequest(cb,[11])}if(inputHeaders["Content-Type"]){return failWithoutRequest(cb,[12])}}var isValidTimeout=function(timeout){return timeout>0&&timeout<1073741824};var optionsTimeout=options.timeout;if(optionsTimeout!==_undefined){if(typeof optionsTimeout==="number"&&isValidTimeout(optionsTimeout)){timeout=optionsTimeout}else if(isArray(optionsTimeout)&&optionsTimeout.length===2&&isValidTimeout(optionsTimeout[0])&&isValidTimeout(optionsTimeout[1])){if(httpinvoke.corsFineGrainedTimeouts||!crossDomain){uploadTimeout=optionsTimeout[0];downloadTimeout=optionsTimeout[1]}else{timeout=optionsTimeout[0]+optionsTimeout[1]}}else{return failWithoutRequest(cb,[13])}}if(uploadTimeout){setTimeout(function(){if(statusCb){cb(new Error("upload timeout"));promise()}},uploadTimeout)}if(timeout){setTimeout(function(){if(cb){cb(new Error("timeout"));promise()}},timeout)}var xhr,i,j,currentLocation,crossDomain,output,uploadProgressCbCalled=false,partialPosition=0,partialBuffer=partialOutputMode==="disabled"?_undefined:outputBinary?[]:"",partial=partialBuffer,partialUpdate=function(){if(partialOutputMode==="disabled"){return}if(outputBinary){responseByteArray(xhr,partialBuffer)}else{partialBuffer=xhr.responseText}partial=partialOutputMode==="joined"?partialBuffer:partialBuffer.slice(partialPosition);partialPosition=partialBuffer.length};var uploadProgress=function(uploaded){if(!uploadProgressCb){return}if(!uploadProgressCbCalled){uploadProgressCbCalled=true;uploadProgressCb(0,inputLength);if(!cb){return}}uploadProgressCb(uploaded,inputLength);if(uploaded===inputLength){uploadProgressCb=null}};try{currentLocation=location.href}catch(_){currentLocation=document.createElement("a");currentLocation.href="";currentLocation=currentLocation.href}crossDomain=isCrossDomain(currentLocation,uri);if(typeof input==="object"&&!isFormData(input)&&httpinvoke.requestTextOnly){return failWithoutRequest(cb,[17])}if(crossDomain&&!httpinvoke.cors){return failWithoutRequest(cb,[18])}for(j=["DELETE","PATCH","PUT","HEAD"],i=j.length;i-->0;){if(crossDomain&&method===j[i]&&!httpinvoke["cors"+j[i]]){return failWithoutRequest(cb,[19,method])}}if(method==="PATCH"&&!httpinvoke.PATCH){return failWithoutRequest(cb,[20])}if(!createXHR){return failWithoutRequest(cb,[21])}xhr=createXHR(crossDomain);try{xhr.open(method,uri,true)}catch(e){return failWithoutRequest(cb,[22,uri])}if(options.corsCredentials&&httpinvoke.corsCredentials&&typeof xhr.withCredentials==="boolean"){xhr.withCredentials=true}if(crossDomain&&options.corsOriginHeader){inputHeaders[options.corsOriginHeader]=location.protocol+"//"+location.host}var onuploadprogress=function(progressEvent){if(cb&&progressEvent.lengthComputable){if(inputLength===_undefined){inputLength=progressEvent.total||progressEvent.totalSize||0;uploadProgress(0)}uploadProgress(progressEvent.loaded||progressEvent.position||0)}};if("upload"in xhr){xhr.upload.onerror=function(){received.error=true;cb&&cb(new Error("network error"))};xhr.upload.onprogress=onuploadprogress}else if("onuploadprogress"in xhr){xhr.onuploadprogress=onuploadprogress}if("onerror"in xhr){xhr.onerror=function(){received.error=true;onLoad()}}var ondownloadprogress=function(progressEvent){onHeadersReceived(false);try{var current=progressEvent.loaded||progressEvent.position||0;if(progressEvent.lengthComputable){outputLength=progressEvent.total||progressEvent.totalSize||0}cb&&current<=outputLength&&!statusCb&&(partialUpdate(),downloadProgressCb(current,outputLength,partial))}catch(_){}};if("onloadstart"in xhr){xhr.onloadstart=ondownloadprogress}if("onloadend"in xhr){xhr.onloadend=ondownloadprogress}if("onprogress"in xhr){xhr.onprogress=ondownloadprogress}var received={};var mustBeIdentity;var tryHeadersAndStatus=function(lastTry){try{if(xhr.status){received.status=true}}catch(_){}try{if(xhr.statusText){received.status=true}}catch(_){}try{if(xhr.responseText){received.entity=true}}catch(_){}try{if(xhr.response){received.entity=true}}catch(_){}try{if(responseBodyLength(xhr.responseBody)){received.entity=true}}catch(_){}if(!statusCb){return}if(received.status||received.entity||received.success||lastTry){if(typeof xhr.contentType==="string"&&xhr.contentType){if(xhr.contentType!=="text/html"||xhr.responseText!==""){outputHeaders["content-type"]=xhr.contentType;received.headers=true}}for(var i=0;i<exposedHeaders.length;i++){var header;try{if(header=xhr.getResponseHeader(exposedHeaders[i])){outputHeaders[exposedHeaders[i].toLowerCase()]=header;received.headers=true}}catch(err){}}try{if(fillOutputHeaders(xhr,outputHeaders)){received.headers=true}}catch(err){}mustBeIdentity=outputHeaders["content-encoding"]==="identity"||!crossDomain&&!outputHeaders["content-encoding"];if(mustBeIdentity&&"content-length"in outputHeaders){outputLength=Number(outputHeaders["content-length"])}if(!status&&(!crossDomain||httpinvoke.corsStatus)){try{if(xhr.status){status=xhr.status}}catch(_){}if(!status){try{status=statusTextToCode[xhr.statusText]}catch(_){}}if(status===1223){status=204}if(status>=12001&&status<=12156){status=_undefined}}}};var onHeadersReceived=function(lastTry){if(!cb){return}if(!lastTry){tryHeadersAndStatus(false)}if(!statusCb||!lastTry&&!(received.status&&received.headers)){return}if(inputLength===_undefined){inputLength=0;uploadProgress(0)}uploadProgress(inputLength);if(!cb){return}statusCb(status,outputHeaders);if(!cb){return}downloadProgressCb(0,outputLength,partial);if(!cb){return}if(method==="HEAD"){downloadProgressCb(0,0,partial);return cb&&cb(null,_undefined,status,outputHeaders)}};var onLoad=function(){if(!cb){return}tryHeadersAndStatus(true);var length;try{length=partialOutputMode!=="disabled"?responseByteArrayLength(xhr):outputBinary?"response"in xhr?xhr.response?xhr.response.byteLength:0:responseByteArrayLength(xhr):countStringBytes(xhr.responseText)}catch(_){length=0}if(outputLength!==_undefined){if(mustBeIdentity){if(length!==outputLength&&method!=="HEAD"){return cb(new Error("network error"))}}else{if(received.error){return cb(new Error("network error"))}}}else{outputLength=length}var noentity=!received.entity&&outputLength===0&&outputHeaders["content-type"]===_undefined;if(noentity&&status===200||!received.success&&!status&&(received.error||"onreadystatechange"in xhr&&!received.readyStateLOADING)){return cb(new Error("network error"))}onHeadersReceived(true);if(!cb){return}if(noentity){downloadProgressCb(0,0,partial);return cb(null,_undefined,status,outputHeaders)}partialUpdate();downloadProgressCb(outputLength,outputLength,partial);if(!cb){return}try{cb(null,outputConverter(partialBuffer||(outputBinary?upgradeByteArray("response"in xhr?xhr.response||[]:responseByteArray(xhr,[])):xhr.responseText)),status,outputHeaders)}catch(err){cb(err)}};var onloadBound="onload"in xhr;if(onloadBound){xhr.onload=function(){received.success=true;onLoad()}}if("onreadystatechange"in xhr){xhr.onreadystatechange=function(){if(xhr.readyState===2){onHeadersReceived(false)}else if(xhr.readyState===3){received.readyStateLOADING=true;onHeadersReceived(false)}else if(xhr.readyState===4&&!onloadBound){onLoad()}}}if(!crossDomain||httpinvoke.corsRequestHeaders){for(var inputHeaderName in inputHeaders){if(inputHeaders.hasOwnProperty(inputHeaderName)){try{xhr.setRequestHeader(inputHeaderName,inputHeaders[inputHeaderName])}catch(err){return failWithoutRequest(cb,[23,inputHeaderName])}}}}nextTick(function(){if(!cb){return}if(outputBinary){try{if(partialOutputMode==="disabled"&&"response"in xhr){xhr.responseType="arraybuffer"}else{xhr.overrideMimeType("text/plain; charset=x-user-defined")}}catch(_){}}if(isFormData(input)){try{xhr.send(input)}catch(err){return failWithoutRequest(cb,[24])}}else if(typeof input==="object"){var triedSendArrayBufferView=false;var triedSendBlob=false;var triedSendBinaryString=false;var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MozBlobBuilder||global.MSBlobBuilder;if(isArray(input)){input=global.Uint8Array?new Uint8Array(input):String.fromCharCode.apply(String,input)}var toBlob=BlobBuilder?function(){var bb=new BlobBuilder;bb.append(input);input=bb.getBlob(inputHeaders["Content-Type"]||"application/octet-stream")}:function(){try{input=new Blob([input],{type:inputHeaders["Content-Type"]||"application/octet-stream"})}catch(_){triedSendBlob=true}};var go=function(){var reader;if(triedSendBlob&&triedSendArrayBufferView&&triedSendBinaryString){return failWithoutRequest(cb,[24])}if(isArrayBufferView(input)){if(triedSendArrayBufferView){if(!triedSendBinaryString){try{input=String.fromCharCode.apply(String,input)}catch(_){triedSendBinaryString=true}}else if(!triedSendBlob){toBlob()}}else{inputLength=input.byteLength;try{xhr.send(global.ArrayBufferView?input:input.byteOffset===0&&input.length===input.buffer.byteLength?input.buffer:input.buffer.slice?input.buffer.slice(input.byteOffset,input.byteOffset+input.length):new Uint8Array([].slice.call(new Uint8Array(input.buffer),input.byteOffset,input.byteOffset+input.length)).buffer);return}catch(_){}triedSendArrayBufferView=true}}else if(global.Blob&&input instanceof Blob){if(triedSendBlob){if(!triedSendArrayBufferView){try{reader=new FileReader;reader.onerror=function(){triedSendArrayBufferView=true;go()};reader.onload=function(){try{input=new Uint8Array(reader.result)}catch(_){triedSendArrayBufferView=true}go()};reader.readAsArrayBuffer(input);return}catch(_){triedSendArrayBufferView=true}}else if(!triedSendBinaryString){try{reader=new FileReader;reader.onerror=function(){triedSendBinaryString=true;go()};reader.onload=function(){input=reader.result;go()};reader.readAsBinaryString(input);return}catch(_){triedSendBinaryString=true}}}else{try{inputLength=input.size;xhr.send(input);return}catch(_){triedSendBlob=true}}}else{if(triedSendBinaryString){if(!triedSendArrayBufferView){try{input=binaryStringToByteArray(input,[])}catch(_){triedSendArrayBufferView=true}}else if(!triedSendBlob){toBlob()}}else{try{inputLength=input.length;xhr.sendAsBinary(input);return}catch(_){triedSendBinaryString=true}}}nextTick(go)};go();uploadProgress(0)}else{try{if(typeof input==="string"){inputLength=countStringBytes(input);xhr.send(input)}else{inputLength=0;xhr.send(null)}}catch(err){return failWithoutRequest(cb,[24])}uploadProgress(0)}});promise=function(){cb&&cb(new Error("abort"));try{xhr.abort()}catch(err){}};return mixInPromise(promise)};httpinvoke.corsResponseContentTypeOnly=false;httpinvoke.corsRequestHeaders=false;httpinvoke.corsCredentials=false;httpinvoke.cors=false;httpinvoke.corsDELETE=false;httpinvoke.corsHEAD=false;httpinvoke.corsPATCH=false;httpinvoke.corsPUT=false;httpinvoke.corsStatus=false;httpinvoke.corsResponseTextOnly=false;httpinvoke.corsFineGrainedTimeouts=true;httpinvoke.requestTextOnly=false;httpinvoke.anyMethod=false;(function(){try{createXHR=function(){return new XMLHttpRequest};var tmpxhr=createXHR();httpinvoke.requestTextOnly=!global.Uint8Array&&!tmpxhr.sendAsBinary;httpinvoke.cors="withCredentials"in tmpxhr;if(httpinvoke.cors){httpinvoke.corsRequestHeaders=true;httpinvoke.corsCredentials=true;httpinvoke.corsDELETE=true;httpinvoke.corsPATCH=true;httpinvoke.corsPUT=true;httpinvoke.corsHEAD=true;httpinvoke.corsStatus=true;return}}catch(err){}try{if(global.XDomainRequest===_undefined){createXHR=function(){return new XMLHttpRequest};createXHR()}else{createXHR=function(cors){return cors?new XDomainRequest:new XMLHttpRequest};createXHR(true);httpinvoke.cors=true;httpinvoke.corsResponseContentTypeOnly=true;httpinvoke.corsResponseTextOnly=true;httpinvoke.corsFineGrainedTimeouts=false}return}catch(err){}try{createXHR();return}catch(err){}var candidates=["Microsoft.XMLHTTP","Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP"];for(var i=candidates.length;i--;){try{createXHR=function(){return new ActiveXObject(candidates[i])};createXHR();httpinvoke.requestTextOnly=true;return}catch(err){}}createXHR=_undefined})();httpinvoke.PATCH=!!function(){try{createXHR().open("PATCH",location.href,true);return 1}catch(_){}}();return httpinvoke});
(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.httpinvoke=factory()}})(this,function(){"use strict";var global;global=window;var resolve=0,reject=1,progress=2,chain=function(a,b){if(a&&a.then){a.then(function(){b[resolve].apply(null,arguments)},function(){b[reject].apply(null,arguments)},function(){b[progress].apply(null,arguments)})}else{b[resolve](a)}},nextTick=global.process&&global.process.nextTick||global.setImmediate||global.setTimeout,mixInPromise=function(o){var value,queue=[],state=progress;var makeState=function(newstate){o[newstate]=function(){var i,p;if(queue){value=[].slice.call(arguments);state=newstate;for(i=0;i<queue.length;i+=1){if(typeof queue[i][state]==="function"){try{p=queue[i][state].apply(null,value);if(state<progress){chain(p,queue[i]._)}}catch(err){queue[i]._[reject](err)}}else if(state<progress){queue[i]._[state].apply(null,value)}}if(state<progress){queue=null}}}};makeState(progress);makeState(resolve);makeState(reject);o.then=function(){var item=[].slice.call(arguments);item._=mixInPromise({});if(queue){queue.push(item)}else if(typeof item[state]==="function"){nextTick(function(){chain(item[state].apply(null,value),item._)})}return item._};return o},isArrayBufferView=function(input){return typeof input==="object"&&input!==null&&(global.ArrayBufferView&&input instanceof ArrayBufferView||global.Int8Array&&input instanceof Int8Array||global.Uint8Array&&input instanceof Uint8Array||global.Uint8ClampedArray&&input instanceof Uint8ClampedArray||global.Int16Array&&input instanceof Int16Array||global.Uint16Array&&input instanceof Uint16Array||global.Int32Array&&input instanceof Int32Array||global.Uint32Array&&input instanceof Uint32Array||global.Float32Array&&input instanceof Float32Array||global.Float64Array&&input instanceof Float64Array)},isArray=function(object){return Object.prototype.toString.call(object)==="[object Array]"},isFormData=function(input){return typeof input==="object"&&input!==null&&global.FormData&&input instanceof global.FormData},isByteArray=function(input){return typeof input==="object"&&input!==null&&(global.Buffer&&input instanceof Buffer||global.Blob&&input instanceof Blob||global.File&&input instanceof File||global.ArrayBuffer&&input instanceof ArrayBuffer||isArrayBufferView(input)||isArray(input))},supportedMethods=",GET,HEAD,PATCH,POST,PUT,DELETE,",pass=function(value){return value},_undefined,addHook=function(type,hook){"use strict";if(typeof hook!=="function"){throw new Error("TODO error")}if(!this._hooks[type]){throw new Error("TODO error")}var httpinvoke=build();for(var i in this._hooks){if(this._hooks.hasOwnProperty(i)){httpinvoke._hooks[i].push.apply(httpinvoke._hooks[i],this._hooks[i])}}httpinvoke._hooks[type].push(hook);return httpinvoke},initHooks=function(){return{finished:[],downloading:[],uploading:[],gotStatus:[]}};var statusTextToCode=function(){for(var group=arguments.length,map={};group--;){for(var texts=arguments[group].split(","),index=texts.length;index--;){map[texts[index]]=(group+1)*100+index}}return map}("Continue,Switching Protocols","OK,Created,Accepted,Non-Authoritative Information,No Content,Reset Content,Partial Content","Multiple Choices,Moved Permanently,Found,See Other,Not Modified,Use Proxy,_,Temporary Redirect","Bad Request,Unauthorized,Payment Required,Forbidden,Not Found,Method Not Allowed,Not Acceptable,Proxy Authentication Required,Request Timeout,Conflict,Gone,Length Required,Precondition Failed,Request Entity Too Large,Request-URI Too Long,Unsupported Media Type,Requested Range Not Satisfiable,Expectation Failed","Internal Server Error,Not Implemented,Bad Gateway,Service Unavailable,Gateway Time-out,HTTP Version Not Supported");var upgradeByteArray=global.Uint8Array?function(array){return new Uint8Array(array)}:pass;var binaryStringToByteArray=function(str,bytearray){for(var i=bytearray.length;i<str.length;){bytearray.push(str.charCodeAt(i++)&255)}return bytearray};var countStringBytes=function(string){for(var c,n=0,i=string.length;i--;){c=string.charCodeAt(i);n+=c<128?1:c<2048?2:3}return n};var responseBodyToBytes,responseBodyLength;try{execScript("Function httpinvoke0(B,A,C)\r\nDim i\r\nFor i=C to LenB(B)\r\nA.push(AscB(MidB(B,i,1)))\r\nNext\r\nEnd Function\r\nFunction httpinvoke1(B)\r\nhttpinvoke1=LenB(B)\r\nEnd Function","vbscript");responseBodyToBytes=function(binary,bytearray){httpinvoke0(binary,bytearray,bytearray.length+1);return bytearray};responseBodyLength=function(binary){return httpinvoke1(binary)}}catch(err){}var responseByteArray=function(xhr,bytearray){return"responseBody"in xhr&&responseBodyToBytes?responseBodyToBytes(xhr.responseBody,bytearray):binaryStringToByteArray(xhr.responseText,bytearray)};var responseByteArrayLength=function(xhr){return"responseBody"in xhr&&responseBodyLength?responseBodyLength(xhr.responseBody):xhr.responseText.length};var fillOutputHeaders=function(xhr,outputHeaders){var headers=xhr.getAllResponseHeaders().split(/\r?\n/);var atLeastOne=false;for(var i=headers.length,colon,header;i--;){if((colon=headers[i].indexOf(":"))>=0){outputHeaders[headers[i].substr(0,colon).toLowerCase()]=headers[i].substr(colon+2);atLeastOne=true}}return atLeastOne};var urlPartitioningRegExp=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/;var isCrossDomain=function(location,uri){uri=urlPartitioningRegExp.exec(uri.toLowerCase());location=urlPartitioningRegExp.exec(location.toLowerCase())||[];return!!(uri&&(uri[1]!==location[1]||uri[2]!==location[2]||(uri[3]||(uri[1]==="http:"?"80":"443"))!==(location[3]||(location[1]==="http:"?"80":"443"))))};var build=function(){var createXHR;var httpinvoke=function(uri,method,options,cb){var hook,promise,failWithoutRequest,uploadProgressCb,downloadProgressCb,inputLength,inputHeaders,statusCb,outputHeaders,exposedHeaders,status,outputBinary,input,outputLength,outputConverter;hook=function(type,args){var hooks=httpinvoke._hooks[type];for(var i=0;i<hooks.length;i+=1){args=hooks[i].apply(null,args)}return args};var downloadTimeout,uploadTimeout,timeout;if(!method){method="GET";options={}}else if(!options){if(typeof method==="string"){options={}}else if(typeof method==="object"){options=method;method="GET"}else{options={finished:method};method="GET"}}else if(!cb){if(typeof method==="object"){method.finished=options;options=method;method="GET"}else if(typeof options==="function"){options={finished:options}}}else{options.finished=cb}var safeCallback=function(name,aspectBefore,aspectAfter){return function(){var args,_cb,failedOnHook=false,fail=function(err,args){_cb=cb;cb=null;nextTick(function(){_cb&&_cb(err);promise();if(!_cb&&!failedOnHook){throw err}});return name==="finished"?[err]:args};aspectBefore.apply(null,args);try{args=hook(name,[].slice.call(arguments))}catch(err){failedOnHook=true;args=fail(err,args)}if(options[name]){try{options[name].apply(null,args)}catch(err){args=fail(err,args)}}aspectAfter.apply(null,args)}};failWithoutRequest=function(cb,err){if(!(err instanceof Error)){err=new Error("Error code #"+err+". See https://github.com/jakutis/httpinvoke#error-codes")}nextTick(function(){if(cb===null){return}cb(err)});promise=function(){};return mixInPromise(promise)};uploadProgressCb=safeCallback("uploading",pass,function(current,total){promise[progress]({type:"upload",current:current,total:total})});downloadProgressCb=safeCallback("downloading",pass,function(current,total,partial){promise[progress]({type:"download",current:current,total:total,partial:partial})});statusCb=safeCallback("gotStatus",function(){statusCb=null;if(downloadTimeout){setTimeout(function(){if(cb){cb(new Error("download timeout"));promise()}},downloadTimeout)}},function(statusCode,headers){promise[progress]({type:"headers",statusCode:statusCode,headers:headers})});cb=safeCallback("finished",function(){cb=null;promise()},function(err,body,statusCode,headers){var res={body:body,statusCode:statusCode,headers:headers};if(err){return promise[reject](err,res)}promise[resolve](res)});var converters=options.converters||{};var inputConverter;inputHeaders=options.headers||{};outputHeaders={};exposedHeaders=options.corsExposedHeaders||[];exposedHeaders.push.apply(exposedHeaders,["Cache-Control","Content-Language","Content-Type","Content-Length","Expires","Last-Modified","Pragma","Content-Range","Content-Encoding"]);var partialOutputMode=options.partialOutputMode||"disabled";if(partialOutputMode.indexOf(",")>=0||",disabled,chunked,joined,".indexOf(","+partialOutputMode+",")<0){return failWithoutRequest(cb,[3])}if(method.indexOf(",")>=0||!httpinvoke.anyMethod&&supportedMethods.indexOf(","+method+",")<0){return failWithoutRequest(cb,[4,method])}var optionsOutputType=options.outputType;outputBinary=optionsOutputType==="bytearray";if(!optionsOutputType||optionsOutputType==="text"||outputBinary){outputConverter=pass}else if(converters["text "+optionsOutputType]){outputConverter=converters["text "+optionsOutputType];outputBinary=false}else if(converters["bytearray "+optionsOutputType]){outputConverter=converters["bytearray "+optionsOutputType];outputBinary=true}else{return failWithoutRequest(cb,[5,optionsOutputType])}inputConverter=pass;var optionsInputType=options.inputType;input=options.input;if(input!==_undefined){if(!optionsInputType||optionsInputType==="auto"){if(typeof input!=="string"&&!isByteArray(input)&&!isFormData(input)){return failWithoutRequest(cb,[6])}}else if(optionsInputType==="text"){if(typeof input!=="string"){return failWithoutRequest(cb,[7])}}else if(optionsInputType==="formdata"){if(!isFormData(input)){return failWithoutRequest(cb,[8])}}else if(optionsInputType==="bytearray"){if(!isByteArray(input)){return failWithoutRequest(cb,[9])}}else if(converters[optionsInputType+" text"]){inputConverter=converters[optionsInputType+" text"]}else if(converters[optionsInputType+" bytearray"]){inputConverter=converters[optionsInputType+" bytearray"]}else if(converters[optionsInputType+" formdata"]){inputConverter=converters[optionsInputType+" formdata"]}else{return failWithoutRequest(cb,[10,optionsInputType])}if(typeof input==="object"&&!isFormData(input)){if(global.ArrayBuffer&&input instanceof global.ArrayBuffer){input=new global.Uint8Array(input)}else if(isArrayBufferView(input)){input=new global.Uint8Array(input.buffer,input.byteOffset,input.byteLength)}}try{input=inputConverter(input)}catch(err){return failWithoutRequest(cb,err)}}else{if(optionsInputType&&optionsInputType!=="auto"){return failWithoutRequest(cb,[11])}if(inputHeaders["Content-Type"]){return failWithoutRequest(cb,[12])}}var isValidTimeout=function(timeout){return timeout>0&&timeout<1073741824};var optionsTimeout=options.timeout;if(optionsTimeout!==_undefined){if(typeof optionsTimeout==="number"&&isValidTimeout(optionsTimeout)){timeout=optionsTimeout}else if(isArray(optionsTimeout)&&optionsTimeout.length===2&&isValidTimeout(optionsTimeout[0])&&isValidTimeout(optionsTimeout[1])){if(httpinvoke.corsFineGrainedTimeouts||!crossDomain){uploadTimeout=optionsTimeout[0];downloadTimeout=optionsTimeout[1]}else{timeout=optionsTimeout[0]+optionsTimeout[1]}}else{return failWithoutRequest(cb,[13])}}if(uploadTimeout){setTimeout(function(){if(statusCb){cb(new Error("upload timeout"));promise()}},uploadTimeout)}if(timeout){setTimeout(function(){if(cb){cb(new Error("timeout"));promise()}},timeout)}var xhr,i,j,currentLocation,crossDomain,output,uploadProgressCbCalled=false,partialPosition=0,partialBuffer=partialOutputMode==="disabled"?_undefined:outputBinary?[]:"",partial=partialBuffer,partialUpdate=function(){if(partialOutputMode==="disabled"){return}if(outputBinary){responseByteArray(xhr,partialBuffer)}else{partialBuffer=xhr.responseText}partial=partialOutputMode==="joined"?partialBuffer:partialBuffer.slice(partialPosition);partialPosition=partialBuffer.length};var uploadProgress=function(uploaded){if(!uploadProgressCb){return}if(!uploadProgressCbCalled){uploadProgressCbCalled=true;uploadProgressCb(0,inputLength);if(!cb){return}}uploadProgressCb(uploaded,inputLength);if(uploaded===inputLength){uploadProgressCb=null}};try{currentLocation=location.href}catch(_){currentLocation=document.createElement("a");currentLocation.href="";currentLocation=currentLocation.href}crossDomain=isCrossDomain(currentLocation,uri);if(typeof input==="object"&&!isFormData(input)&&httpinvoke.requestTextOnly){return failWithoutRequest(cb,[17])}if(crossDomain&&!httpinvoke.cors){return failWithoutRequest(cb,[18])}for(j=["DELETE","PATCH","PUT","HEAD"],i=j.length;i-->0;){if(crossDomain&&method===j[i]&&!httpinvoke["cors"+j[i]]){return failWithoutRequest(cb,[19,method])}}if(method==="PATCH"&&!httpinvoke.PATCH){return failWithoutRequest(cb,[20])}if(!createXHR){return failWithoutRequest(cb,[21])}xhr=createXHR(crossDomain);try{xhr.open(method,uri,true)}catch(e){return failWithoutRequest(cb,[22,uri])}if(options.corsCredentials&&httpinvoke.corsCredentials&&typeof xhr.withCredentials==="boolean"){xhr.withCredentials=true}if(crossDomain&&options.corsOriginHeader){inputHeaders[options.corsOriginHeader]=location.protocol+"//"+location.host}var onuploadprogress=function(progressEvent){if(cb&&progressEvent.lengthComputable){if(inputLength===_undefined){inputLength=progressEvent.total||progressEvent.totalSize||0;uploadProgress(0)}uploadProgress(progressEvent.loaded||progressEvent.position||0)}};if("upload"in xhr){xhr.upload.onerror=function(){received.error=true;cb&&cb(new Error("network error"))};xhr.upload.onprogress=onuploadprogress}else if("onuploadprogress"in xhr){xhr.onuploadprogress=onuploadprogress}if("onerror"in xhr){xhr.onerror=function(){received.error=true;onLoad()}}var ondownloadprogress=function(progressEvent){onHeadersReceived(false);try{var current=progressEvent.loaded||progressEvent.position||0;if(progressEvent.lengthComputable){outputLength=progressEvent.total||progressEvent.totalSize||0}cb&&current<=outputLength&&!statusCb&&(partialUpdate(),downloadProgressCb(current,outputLength,partial))}catch(_){}};if("onloadstart"in xhr){xhr.onloadstart=ondownloadprogress}if("onloadend"in xhr){xhr.onloadend=ondownloadprogress}if("onprogress"in xhr){xhr.onprogress=ondownloadprogress}var received={};var mustBeIdentity;var tryHeadersAndStatus=function(lastTry){try{if(xhr.status){received.status=true}}catch(_){}try{if(xhr.statusText){received.status=true}}catch(_){}try{if(xhr.responseText){received.entity=true}}catch(_){}try{if(xhr.response){received.entity=true}}catch(_){}try{if(responseBodyLength(xhr.responseBody)){received.entity=true}}catch(_){}if(!statusCb){return}if(received.status||received.entity||received.success||lastTry){if(typeof xhr.contentType==="string"&&xhr.contentType){if(xhr.contentType!=="text/html"||xhr.responseText!==""){outputHeaders["content-type"]=xhr.contentType;received.headers=true}}for(var i=0;i<exposedHeaders.length;i++){var header;try{if(header=xhr.getResponseHeader(exposedHeaders[i])){outputHeaders[exposedHeaders[i].toLowerCase()]=header;received.headers=true}}catch(err){}}try{if(fillOutputHeaders(xhr,outputHeaders)){received.headers=true}}catch(err){}mustBeIdentity=outputHeaders["content-encoding"]==="identity"||!crossDomain&&!outputHeaders["content-encoding"];if(mustBeIdentity&&"content-length"in outputHeaders){outputLength=Number(outputHeaders["content-length"])}if(!status&&(!crossDomain||httpinvoke.corsStatus)){try{if(xhr.status){status=xhr.status}}catch(_){}if(!status){try{status=statusTextToCode[xhr.statusText]}catch(_){}}if(status===1223){status=204}if(status>=12001&&status<=12156){status=_undefined}}}};var onHeadersReceived=function(lastTry){if(!cb){return}if(!lastTry){tryHeadersAndStatus(false)}if(!statusCb||!lastTry&&!(received.status&&received.headers)){return}if(inputLength===_undefined){inputLength=0;uploadProgress(0)}uploadProgress(inputLength);if(!cb){return}statusCb(status,outputHeaders);if(!cb){return}downloadProgressCb(0,outputLength,partial);if(!cb){return}if(method==="HEAD"){downloadProgressCb(0,0,partial);return cb&&cb(null,_undefined,status,outputHeaders)}};var onLoad=function(){if(!cb){return}tryHeadersAndStatus(true);var length;try{length=partialOutputMode!=="disabled"?responseByteArrayLength(xhr):outputBinary?"response"in xhr?xhr.response?xhr.response.byteLength:0:responseByteArrayLength(xhr):countStringBytes(xhr.responseText)}catch(_){length=0}if(outputLength!==_undefined){if(mustBeIdentity){if(length!==outputLength&&method!=="HEAD"){return cb(new Error("network error"))}}else{if(received.error){return cb(new Error("network error"))}}}else{outputLength=length}var noentity=!received.entity&&outputLength===0&&outputHeaders["content-type"]===_undefined;if(noentity&&status===200||!received.success&&!status&&(received.error||"onreadystatechange"in xhr&&!received.readyStateLOADING)){return cb(new Error("network error"))}onHeadersReceived(true);if(!cb){return}if(noentity){downloadProgressCb(0,0,partial);return cb(null,_undefined,status,outputHeaders)}partialUpdate();downloadProgressCb(outputLength,outputLength,partial);if(!cb){return}try{cb(null,outputConverter(partialBuffer||(outputBinary?upgradeByteArray("response"in xhr?xhr.response||[]:responseByteArray(xhr,[])):xhr.responseText)),status,outputHeaders)}catch(err){cb(err)}};var onloadBound="onload"in xhr;if(onloadBound){xhr.onload=function(){received.success=true;onLoad()}}if("onreadystatechange"in xhr){xhr.onreadystatechange=function(){if(xhr.readyState===2){onHeadersReceived(false)}else if(xhr.readyState===3){received.readyStateLOADING=true;onHeadersReceived(false)}else if(xhr.readyState===4&&!onloadBound){onLoad()}}}if(!crossDomain||httpinvoke.corsRequestHeaders){for(var inputHeaderName in inputHeaders){if(inputHeaders.hasOwnProperty(inputHeaderName)){try{xhr.setRequestHeader(inputHeaderName,inputHeaders[inputHeaderName])}catch(err){return failWithoutRequest(cb,[23,inputHeaderName])}}}}nextTick(function(){if(!cb){return}if(outputBinary){try{if(partialOutputMode==="disabled"&&"response"in xhr){xhr.responseType="arraybuffer"}else{xhr.overrideMimeType("text/plain; charset=x-user-defined")}}catch(_){}}if(isFormData(input)){try{xhr.send(input)}catch(err){return failWithoutRequest(cb,[24])}}else if(typeof input==="object"){var triedSendArrayBufferView=false;var triedSendBlob=false;var triedSendBinaryString=false;var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MozBlobBuilder||global.MSBlobBuilder;if(isArray(input)){input=global.Uint8Array?new Uint8Array(input):String.fromCharCode.apply(String,input)}var toBlob=BlobBuilder?function(){var bb=new BlobBuilder;bb.append(input);input=bb.getBlob(inputHeaders["Content-Type"]||"application/octet-stream")}:function(){try{input=new Blob([input],{type:inputHeaders["Content-Type"]||"application/octet-stream"})}catch(_){triedSendBlob=true}};var go=function(){var reader;if(triedSendBlob&&triedSendArrayBufferView&&triedSendBinaryString){return failWithoutRequest(cb,[24])}if(isArrayBufferView(input)){if(triedSendArrayBufferView){if(!triedSendBinaryString){try{input=String.fromCharCode.apply(String,input)}catch(_){triedSendBinaryString=true}}else if(!triedSendBlob){toBlob()}}else{inputLength=input.byteLength;try{xhr.send(global.ArrayBufferView?input:input.byteOffset===0&&input.length===input.buffer.byteLength?input.buffer:input.buffer.slice?input.buffer.slice(input.byteOffset,input.byteOffset+input.length):new Uint8Array([].slice.call(new Uint8Array(input.buffer),input.byteOffset,input.byteOffset+input.length)).buffer);return}catch(_){}triedSendArrayBufferView=true}}else if(global.Blob&&input instanceof Blob){if(triedSendBlob){if(!triedSendArrayBufferView){try{reader=new FileReader;reader.onerror=function(){triedSendArrayBufferView=true;go()};reader.onload=function(){try{input=new Uint8Array(reader.result)}catch(_){triedSendArrayBufferView=true}go()};reader.readAsArrayBuffer(input);return}catch(_){triedSendArrayBufferView=true}}else if(!triedSendBinaryString){try{reader=new FileReader;reader.onerror=function(){triedSendBinaryString=true;go()};reader.onload=function(){input=reader.result;go()};reader.readAsBinaryString(input);return}catch(_){triedSendBinaryString=true}}}else{try{inputLength=input.size;xhr.send(input);return}catch(_){triedSendBlob=true}}}else{if(triedSendBinaryString){if(!triedSendArrayBufferView){try{input=binaryStringToByteArray(input,[])}catch(_){triedSendArrayBufferView=true}}else if(!triedSendBlob){toBlob()}}else{try{inputLength=input.length;xhr.sendAsBinary(input);return}catch(_){triedSendBinaryString=true}}}nextTick(go)};go();uploadProgress(0)}else{try{if(typeof input==="string"){inputLength=countStringBytes(input);xhr.send(input)}else{inputLength=0;xhr.send(null)}}catch(err){return failWithoutRequest(cb,[24])}uploadProgress(0)}});promise=function(){cb&&cb(new Error("abort"));try{xhr.abort()}catch(err){}};return mixInPromise(promise)};httpinvoke.corsResponseContentTypeOnly=false;httpinvoke.corsRequestHeaders=false;httpinvoke.corsCredentials=false;httpinvoke.cors=false;httpinvoke.corsDELETE=false;httpinvoke.corsHEAD=false;httpinvoke.corsPATCH=false;httpinvoke.corsPUT=false;httpinvoke.corsStatus=false;httpinvoke.corsResponseTextOnly=false;httpinvoke.corsFineGrainedTimeouts=true;httpinvoke.requestTextOnly=false;httpinvoke.anyMethod=false;(function(){try{createXHR=function(){return new XMLHttpRequest};var tmpxhr=createXHR();httpinvoke.requestTextOnly=!global.Uint8Array&&!tmpxhr.sendAsBinary;httpinvoke.cors="withCredentials"in tmpxhr;if(httpinvoke.cors){httpinvoke.corsRequestHeaders=true;httpinvoke.corsCredentials=true;httpinvoke.corsDELETE=true;httpinvoke.corsPATCH=true;httpinvoke.corsPUT=true;httpinvoke.corsHEAD=true;httpinvoke.corsStatus=true;return}}catch(err){}try{if(global.XDomainRequest===_undefined){createXHR=function(){return new XMLHttpRequest};createXHR()}else{createXHR=function(cors){return cors?new XDomainRequest:new XMLHttpRequest};createXHR(true);httpinvoke.cors=true;httpinvoke.corsResponseContentTypeOnly=true;httpinvoke.corsResponseTextOnly=true;httpinvoke.corsFineGrainedTimeouts=false}return}catch(err){}try{createXHR();return}catch(err){}var candidates=["Microsoft.XMLHTTP","Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP"];for(var i=candidates.length;i--;){try{createXHR=function(){return new ActiveXObject(candidates[i])};createXHR();httpinvoke.requestTextOnly=true;return}catch(err){}}createXHR=_undefined})();httpinvoke.PATCH=!!function(){try{createXHR().open("PATCH",location.href,true);return 1}catch(_){}}();httpinvoke._hooks=initHooks();httpinvoke.hook=addHook;return httpinvoke};return build()});

@@ -23,12 +23,12 @@ var http = require('http');

var makeState = function(newstate) {
o[newstate] = function(newvalue) {
o[newstate] = function() {
var i, p;
if(queue) {
value = newvalue;
value = [].slice.call(arguments);
state = newstate;
for(i = 0; i < queue.length; i++) {
for(i = 0; i < queue.length; i += 1) {
if(typeof queue[i][state] === 'function') {
try {
p = queue[i][state].call(null, value);
p = queue[i][state].apply(null, value);
if(state < progress) {

@@ -41,3 +41,3 @@ chain(p, queue[i]._);

} else if(state < progress) {
queue[i]._[state](value);
queue[i]._[state].apply(null, value);
}

@@ -61,3 +61,3 @@ }

nextTick(function() {
chain(item[state](value), item._);
chain(item[state].apply(null, value), item._);
});

@@ -97,3 +97,26 @@ }

return value;
}, _undefined;
}, _undefined, addHook = function(type, hook) {
'use strict';
if(typeof hook !== 'function') {
throw new Error('TODO error');
}
if(!this._hooks[type]) {
throw new Error('TODO error');
}
var httpinvoke = build();
for(var i in this._hooks) {
if(this._hooks.hasOwnProperty(i)) {
httpinvoke._hooks[i].push.apply(httpinvoke._hooks[i], this._hooks[i]);
}
}
httpinvoke._hooks[type].push(hook);
return httpinvoke;
}, initHooks = function() {
return {
finished:[],
downloading:[],
uploading:[],
gotStatus:[]
};
};
;

@@ -154,4 +177,6 @@ /* jshint unused:false */

var build = function() {
'use strict';
var httpinvoke = function(uri, method, options, cb) {
'use strict';
/* jshint unused:true */

@@ -163,3 +188,10 @@ ;/* global httpinvoke, url, method, options, cb */

/* jshint -W020 */
var promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter;
hook = function(type, args) {
var hooks = httpinvoke._hooks[type];
for(var i = 0; i < hooks.length; i += 1) {
args = hooks[i].apply(null, args);
}
return args;
};
/*************** COMMON initialize parameters **************/

@@ -207,20 +239,32 @@ var downloadTimeout, uploadTimeout, timeout;

var safeCallback = function(name, aspectBefore, aspectAfter) {
return function(a, b, c, d) {
var _cb;
aspectBefore(a, b, c, d);
return function() {
var args, _cb, failedOnHook = false, fail = function(err, args) {
_cb = cb;
cb = null;
nextTick(function() {
/* jshint expr:true */
_cb && _cb(err);
/* jshint expr:false */
promise();
if(!_cb && !failedOnHook) {
throw err;
}
});
return name === 'finished' ? [err] : args;
};
aspectBefore.apply(null, args);
try {
args = hook(name, [].slice.call(arguments));
} catch(err) {
failedOnHook = true;
args = fail(err, args);
}
if(options[name]) {
try {
options[name](a, b, c, d);
options[name].apply(null, args);
} catch(err) {
_cb = cb;
cb = null;
nextTick(function() {
/* jshint expr:true */
_cb && _cb(err);
/* jshint expr:false */
promise();
});
args = fail(err, args);
}
}
aspectAfter(a, b, c, d);
aspectAfter.apply(null, args);
};

@@ -280,22 +324,12 @@ };

}, function(err, body, statusCode, headers) {
if(err) {
return promise[reject](err);
}
promise[resolve]({
var res = {
body: body,
statusCode: statusCode,
headers: headers
});
};
if(err) {
return promise[reject](err, res);
}
promise[resolve](res);
});
var fixPositiveOpt = function(opt) {
if(options[opt] === _undefined) {
options[opt] = 0;
} else if(typeof options[opt] === 'number') {
if(options[opt] < 0) {
return failWithoutRequest(cb, [1, opt]);
}
} else {
return failWithoutRequest(cb, [2, opt]);
}
};
var converters = options.converters || {};

@@ -616,3 +650,8 @@ var inputConverter;

httpinvoke.anyMethod = true;
httpinvoke._hooks = initHooks();
httpinvoke.hook = addHook;
module.exports = httpinvoke;
return httpinvoke;
};
module.exports = build();
{
"name": "httpinvoke",
"version": "1.2.1",
"description": "A 5.7kb no-dependencies HTTP client library for browsers and Node.js with a promise-based or Node.js-style callback-based API to progress events, text and binary file upload and download, partial response body, request and response headers, status code.",
"version": "1.3.0",
"description": "A no-dependencies HTTP client library for browsers and Node.js with a promise-based or Node.js-style callback-based API to progress events, text and binary file upload and download, partial response body, request and response headers, status code.",
"license": "MIT",

@@ -6,0 +6,0 @@ "keywords": [

@@ -11,3 +11,3 @@ /* jshint -W030 */

/* jshint unused:true */
var mixInPromise, pass, isArray, isArrayBufferView, _undefined, nextTick, isFormData;
var addHook, initHooks, mixInPromise, pass, isArray, isArrayBufferView, _undefined, nextTick, isFormData;
/* jshint unused:false */

@@ -91,6 +91,8 @@ // this could be a simple map, but with this "compression" we save about 100 bytes, if minified (50 bytes, if also gzipped)

};
var build = function() {
var createXHR;
var httpinvoke = function(uri, method, options, cb) {
/* jshint unused:true */
var promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode;
/* jshint unused:false */

@@ -798,4 +800,8 @@ /*************** initialize helper variables **************/

})();
httpinvoke._hooks = initHooks();
httpinvoke.hook = addHook;
return httpinvoke;
};
return build();
})

@@ -6,3 +6,10 @@ /* global httpinvoke, url, method, options, cb */

/* jshint -W020 */
var promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter;
hook = function(type, args) {
var hooks = httpinvoke._hooks[type];
for(var i = 0; i < hooks.length; i += 1) {
args = hooks[i].apply(null, args);
}
return args;
};
/*************** COMMON initialize parameters **************/

@@ -50,20 +57,32 @@ var downloadTimeout, uploadTimeout, timeout;

var safeCallback = function(name, aspectBefore, aspectAfter) {
return function(a, b, c, d) {
var _cb;
aspectBefore(a, b, c, d);
return function() {
var args, _cb, failedOnHook = false, fail = function(err, args) {
_cb = cb;
cb = null;
nextTick(function() {
/* jshint expr:true */
_cb && _cb(err);
/* jshint expr:false */
promise();
if(!_cb && !failedOnHook) {
throw err;
}
});
return name === 'finished' ? [err] : args;
};
aspectBefore.apply(null, args);
try {
args = hook(name, [].slice.call(arguments));
} catch(err) {
failedOnHook = true;
args = fail(err, args);
}
if(options[name]) {
try {
options[name](a, b, c, d);
options[name].apply(null, args);
} catch(err) {
_cb = cb;
cb = null;
nextTick(function() {
/* jshint expr:true */
_cb && _cb(err);
/* jshint expr:false */
promise();
});
args = fail(err, args);
}
}
aspectAfter(a, b, c, d);
aspectAfter.apply(null, args);
};

@@ -123,22 +142,12 @@ };

}, function(err, body, statusCode, headers) {
if(err) {
return promise[reject](err);
}
promise[resolve]({
var res = {
body: body,
statusCode: statusCode,
headers: headers
});
};
if(err) {
return promise[reject](err, res);
}
promise[resolve](res);
});
var fixPositiveOpt = function(opt) {
if(options[opt] === _undefined) {
options[opt] = 0;
} else if(typeof options[opt] === 'number') {
if(options[opt] < 0) {
return failWithoutRequest(cb, [1, opt]);
}
} else {
return failWithoutRequest(cb, [2, opt]);
}
};
var converters = options.converters || {};

@@ -145,0 +154,0 @@ var inputConverter;

@@ -18,12 +18,12 @@ var resolve = 0, reject = 1, progress = 2, chain = function(a, b) {

var makeState = function(newstate) {
o[newstate] = function(newvalue) {
o[newstate] = function() {
var i, p;
if(queue) {
value = newvalue;
value = [].slice.call(arguments);
state = newstate;
for(i = 0; i < queue.length; i++) {
for(i = 0; i < queue.length; i += 1) {
if(typeof queue[i][state] === 'function') {
try {
p = queue[i][state].call(null, value);
p = queue[i][state].apply(null, value);
if(state < progress) {

@@ -36,3 +36,3 @@ chain(p, queue[i]._);

} else if(state < progress) {
queue[i]._[state](value);
queue[i]._[state].apply(null, value);
}

@@ -56,3 +56,3 @@ }

nextTick(function() {
chain(item[state](value), item._);
chain(item[state].apply(null, value), item._);
});

@@ -92,2 +92,25 @@ }

return value;
}, _undefined;
}, _undefined, addHook = function(type, hook) {
'use strict';
if(typeof hook !== 'function') {
throw new Error('TODO error');
}
if(!this._hooks[type]) {
throw new Error('TODO error');
}
var httpinvoke = build();
for(var i in this._hooks) {
if(this._hooks.hasOwnProperty(i)) {
httpinvoke._hooks[i].push.apply(httpinvoke._hooks[i], this._hooks[i]);
}
}
httpinvoke._hooks[type].push(hook);
return httpinvoke;
}, initHooks = function() {
return {
finished:[],
downloading:[],
uploading:[],
gotStatus:[]
};
};

@@ -6,3 +6,3 @@ var http = require('http');

/* jshint unused:true */
var mixInPromise, pass, isArray, isArrayBufferView, _undefined, nextTick, isFormData;
var addHook, initHooks, mixInPromise, pass, isArray, isArrayBufferView, _undefined, nextTick, isFormData;
/* jshint unused:false */

@@ -62,6 +62,8 @@

var build = function() {
'use strict';
var httpinvoke = function(uri, method, options, cb) {
'use strict';
/* jshint unused:true */
var promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode;
var hook, promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter, partialOutputMode;
/* jshint unused:false */

@@ -270,3 +272,8 @@ /*************** initialize helper variables **************/

httpinvoke.anyMethod = true;
httpinvoke._hooks = initHooks();
httpinvoke.hook = addHook;
module.exports = httpinvoke;
return httpinvoke;
};
module.exports = build();

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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