Commit bf137ad8 authored by Patrick's avatar Patrick
Browse files

CHANGES.md, README.md und 248 weitere dateien aktualisiert...

parent 0081cef7
Showing with 350 additions and 602 deletions
+350 -602
...@@ -18,23 +18,19 @@ var defaults = { ...@@ -18,23 +18,19 @@ var defaults = {
var parseValues = function parseQueryStringValues(str, options) { var parseValues = function parseQueryStringValues(str, options) {
var obj = {}; var obj = {};
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
var parts = cleanStr.split(options.delimiter, limit);
for (var i = 0; i < parts.length; ++i) { for (var i = 0; i < parts.length; ++i) {
var part = parts[i]; var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
var bracketEqualsPos = part.indexOf(']=');
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
var key, val; var key, val;
if (pos === -1) { if (pos === -1) {
key = options.decoder(part, defaults.decoder); key = options.decoder(part);
val = options.strictNullHandling ? null : ''; val = options.strictNullHandling ? null : '';
} else { } else {
key = options.decoder(part.slice(0, pos), defaults.decoder); key = options.decoder(part.slice(0, pos));
val = options.decoder(part.slice(pos + 1), defaults.decoder); val = options.decoder(part.slice(pos + 1));
} }
if (has.call(obj, key)) { if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val); obj[key] = [].concat(obj[key]).concat(val);
...@@ -46,38 +42,36 @@ var parseValues = function parseQueryStringValues(str, options) { ...@@ -46,38 +42,36 @@ var parseValues = function parseQueryStringValues(str, options) {
return obj; return obj;
}; };
var parseObject = function (chain, val, options) { var parseObject = function parseObjectRecursive(chain, val, options) {
var leaf = val; if (!chain.length) {
return val;
for (var i = chain.length - 1; i >= 0; --i) { }
var obj;
var root = chain[i];
if (root === '[]') { var root = chain.shift();
var obj;
if (root === '[]') {
obj = [];
obj = obj.concat(parseObject(chain, val, options));
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index) &&
root !== cleanRoot &&
String(index) === cleanRoot &&
index >= 0 &&
(options.parseArrays && index <= options.arrayLimit)
) {
obj = []; obj = [];
obj = obj.concat(leaf); obj[index] = parseObject(chain, val, options);
} else { } else {
obj = options.plainObjects ? Object.create(null) : {}; obj[cleanRoot] = parseObject(chain, val, options);
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index)
&& root !== cleanRoot
&& String(index) === cleanRoot
&& index >= 0
&& (options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = leaf;
} else {
obj[cleanRoot] = leaf;
}
} }
leaf = obj;
} }
return leaf; return obj;
}; };
var parseKeys = function parseQueryStringKeys(givenKey, val, options) { var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
...@@ -136,13 +130,12 @@ var parseKeys = function parseQueryStringKeys(givenKey, val, options) { ...@@ -136,13 +130,12 @@ var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
}; };
module.exports = function (str, opts) { module.exports = function (str, opts) {
var options = opts ? utils.assign({}, opts) : {}; var options = opts || {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.'); throw new TypeError('Decoder has to be a function.');
} }
options.ignoreQueryPrefix = options.ignoreQueryPrefix === true;
options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
......
...@@ -50,7 +50,7 @@ var stringify = function stringify( // eslint-disable-line func-name-matching ...@@ -50,7 +50,7 @@ var stringify = function stringify( // eslint-disable-line func-name-matching
obj = serializeDate(obj); obj = serializeDate(obj);
} else if (obj === null) { } else if (obj === null) {
if (strictNullHandling) { if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; return encoder && !encodeValuesOnly ? encoder(prefix) : prefix;
} }
obj = ''; obj = '';
...@@ -58,8 +58,8 @@ var stringify = function stringify( // eslint-disable-line func-name-matching ...@@ -58,8 +58,8 @@ var stringify = function stringify( // eslint-disable-line func-name-matching
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
if (encoder) { if (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); var keyValue = encodeValuesOnly ? prefix : encoder(prefix);
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; return [formatter(keyValue) + '=' + formatter(encoder(obj))];
} }
return [formatter(prefix) + '=' + formatter(String(obj))]; return [formatter(prefix) + '=' + formatter(String(obj))];
} }
...@@ -123,7 +123,7 @@ var stringify = function stringify( // eslint-disable-line func-name-matching ...@@ -123,7 +123,7 @@ var stringify = function stringify( // eslint-disable-line func-name-matching
module.exports = function (object, opts) { module.exports = function (object, opts) {
var obj = object; var obj = object;
var options = opts ? utils.assign({}, opts) : {}; var options = opts || {};
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.'); throw new TypeError('Encoder has to be a function.');
...@@ -139,7 +139,7 @@ module.exports = function (object, opts) { ...@@ -139,7 +139,7 @@ module.exports = function (object, opts) {
var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly;
if (typeof options.format === 'undefined') { if (typeof options.format === 'undefined') {
options.format = formats['default']; options.format = formats.default;
} else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
throw new TypeError('Unknown format option provided.'); throw new TypeError('Unknown format option provided.');
} }
...@@ -203,8 +203,5 @@ module.exports = function (object, opts) { ...@@ -203,8 +203,5 @@ module.exports = function (object, opts) {
)); ));
} }
var joined = keys.join(delimiter); return keys.join(delimiter);
var prefix = options.addQueryPrefix === true ? '?' : '';
return joined.length > 0 ? prefix + joined : '';
}; };
...@@ -11,30 +11,7 @@ var hexTable = (function () { ...@@ -11,30 +11,7 @@ var hexTable = (function () {
return array; return array;
}()); }());
var compactQueue = function compactQueue(queue) { exports.arrayToObject = function (source, options) {
var obj;
while (queue.length) {
var item = queue.pop();
obj = item.obj[item.prop];
if (Array.isArray(obj)) {
var compacted = [];
for (var j = 0; j < obj.length; ++j) {
if (typeof obj[j] !== 'undefined') {
compacted.push(obj[j]);
}
}
item.obj[item.prop] = compacted;
}
}
return obj;
};
var arrayToObject = function arrayToObject(source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {}; var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) { for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') { if (typeof source[i] !== 'undefined') {
...@@ -45,7 +22,7 @@ var arrayToObject = function arrayToObject(source, options) { ...@@ -45,7 +22,7 @@ var arrayToObject = function arrayToObject(source, options) {
return obj; return obj;
}; };
var merge = function merge(target, source, options) { exports.merge = function (target, source, options) {
if (!source) { if (!source) {
return target; return target;
} }
...@@ -70,14 +47,14 @@ var merge = function merge(target, source, options) { ...@@ -70,14 +47,14 @@ var merge = function merge(target, source, options) {
var mergeTarget = target; var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) { if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = arrayToObject(target, options); mergeTarget = exports.arrayToObject(target, options);
} }
if (Array.isArray(target) && Array.isArray(source)) { if (Array.isArray(target) && Array.isArray(source)) {
source.forEach(function (item, i) { source.forEach(function (item, i) {
if (has.call(target, i)) { if (has.call(target, i)) {
if (target[i] && typeof target[i] === 'object') { if (target[i] && typeof target[i] === 'object') {
target[i] = merge(target[i], item, options); target[i] = exports.merge(target[i], item, options);
} else { } else {
target.push(item); target.push(item);
} }
...@@ -91,8 +68,8 @@ var merge = function merge(target, source, options) { ...@@ -91,8 +68,8 @@ var merge = function merge(target, source, options) {
return Object.keys(source).reduce(function (acc, key) { return Object.keys(source).reduce(function (acc, key) {
var value = source[key]; var value = source[key];
if (has.call(acc, key)) { if (Object.prototype.hasOwnProperty.call(acc, key)) {
acc[key] = merge(acc[key], value, options); acc[key] = exports.merge(acc[key], value, options);
} else { } else {
acc[key] = value; acc[key] = value;
} }
...@@ -100,14 +77,7 @@ var merge = function merge(target, source, options) { ...@@ -100,14 +77,7 @@ var merge = function merge(target, source, options) {
}, mergeTarget); }, mergeTarget);
}; };
var assign = function assignSingleSource(target, source) { exports.decode = function (str) {
return Object.keys(source).reduce(function (acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
var decode = function (str) {
try { try {
return decodeURIComponent(str.replace(/\+/g, ' ')); return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) { } catch (e) {
...@@ -115,7 +85,7 @@ var decode = function (str) { ...@@ -115,7 +85,7 @@ var decode = function (str) {
} }
}; };
var encode = function encode(str) { exports.encode = function (str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library. // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986 // It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) { if (str.length === 0) {
...@@ -129,13 +99,13 @@ var encode = function encode(str) { ...@@ -129,13 +99,13 @@ var encode = function encode(str) {
var c = string.charCodeAt(i); var c = string.charCodeAt(i);
if ( if (
c === 0x2D // - c === 0x2D || // -
|| c === 0x2E // . c === 0x2E || // .
|| c === 0x5F // _ c === 0x5F || // _
|| c === 0x7E // ~ c === 0x7E || // ~
|| (c >= 0x30 && c <= 0x39) // 0-9 (c >= 0x30 && c <= 0x39) || // 0-9
|| (c >= 0x41 && c <= 0x5A) // a-z (c >= 0x41 && c <= 0x5A) || // a-z
|| (c >= 0x61 && c <= 0x7A) // A-Z (c >= 0x61 && c <= 0x7A) // A-Z
) { ) {
out += string.charAt(i); out += string.charAt(i);
continue; continue;
...@@ -158,56 +128,55 @@ var encode = function encode(str) { ...@@ -158,56 +128,55 @@ var encode = function encode(str) {
i += 1; i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)] out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; // eslint-disable-line max-len
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
+ hexTable[0x80 | (c & 0x3F)];
} }
return out; return out;
}; };
var compact = function compact(value) { exports.compact = function (obj, references) {
var queue = [{ obj: { o: value }, prop: 'o' }]; if (typeof obj !== 'object' || obj === null) {
var refs = []; return obj;
}
for (var i = 0; i < queue.length; ++i) {
var item = queue[i]; var refs = references || [];
var obj = item.obj[item.prop]; var lookup = refs.indexOf(obj);
if (lookup !== -1) {
var keys = Object.keys(obj); return refs[lookup];
for (var j = 0; j < keys.length; ++j) { }
var key = keys[j];
var val = obj[key]; refs.push(obj);
if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
queue.push({ obj: obj, prop: key }); if (Array.isArray(obj)) {
refs.push(val); var compacted = [];
for (var i = 0; i < obj.length; ++i) {
if (obj[i] && typeof obj[i] === 'object') {
compacted.push(exports.compact(obj[i], refs));
} else if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
} }
} }
return compacted;
} }
return compactQueue(queue); var keys = Object.keys(obj);
keys.forEach(function (key) {
obj[key] = exports.compact(obj[key], refs);
});
return obj;
}; };
var isRegExp = function isRegExp(obj) { exports.isRegExp = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]'; return Object.prototype.toString.call(obj) === '[object RegExp]';
}; };
var isBuffer = function isBuffer(obj) { exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') { if (obj === null || typeof obj === 'undefined') {
return false; return false;
} }
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
}; };
module.exports = {
arrayToObject: arrayToObject,
assign: assign,
compact: compact,
decode: decode,
encode: encode,
isBuffer: isBuffer,
isRegExp: isRegExp,
merge: merge
};
{ {
"_from": "qs@~6.5.2", "_from": "qs@~6.4.0",
"_id": "qs@6.5.2", "_id": "qs@6.4.0",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", "_integrity": "sha1-E+JtKK1rD/qpExLNO/cI7TUecjM=",
"_location": "/request/qs", "_location": "/request/qs",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "range", "type": "range",
"registry": true, "registry": true,
"raw": "qs@~6.5.2", "raw": "qs@~6.4.0",
"name": "qs", "name": "qs",
"escapedName": "qs", "escapedName": "qs",
"rawSpec": "~6.5.2", "rawSpec": "~6.4.0",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "~6.5.2" "fetchSpec": "~6.4.0"
}, },
"_requiredBy": [ "_requiredBy": [
"/request" "/request"
], ],
"_resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", "_resolved": "https://registry.npmjs.org/qs/-/qs-6.4.0.tgz",
"_shasum": "cb3ae806e8740444584ef154ce8ee98d403f3e36", "_shasum": "13e26d28ad6b0ffaa91312cd3bf708ed351e7233",
"_spec": "qs@~6.5.2", "_spec": "qs@~6.4.0",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\TV3\\NewVersion01\\dev\\node_modules\\request", "_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\Main\\02_Plattform_Main\\m4labplatform\\node_modules\\request",
"bugs": { "bugs": {
"url": "https://github.com/ljharb/qs/issues" "url": "https://github.com/ljharb/qs/issues"
}, },
...@@ -37,18 +37,17 @@ ...@@ -37,18 +37,17 @@
"deprecated": false, "deprecated": false,
"description": "A querystring parser that supports nesting and arrays, with a depth limit", "description": "A querystring parser that supports nesting and arrays, with a depth limit",
"devDependencies": { "devDependencies": {
"@ljharb/eslint-config": "^12.2.1", "@ljharb/eslint-config": "^11.0.0",
"browserify": "^16.2.0", "browserify": "^14.1.0",
"covert": "^1.1.0", "covert": "^1.1.0",
"editorconfig-tools": "^0.1.1", "eslint": "^3.17.0",
"eslint": "^4.19.1",
"evalmd": "^0.0.17", "evalmd": "^0.0.17",
"iconv-lite": "^0.4.21", "iconv-lite": "^0.4.15",
"mkdirp": "^0.5.1", "mkdirp": "^0.5.1",
"parallelshell": "^2.0.0",
"qs-iconv": "^1.0.4", "qs-iconv": "^1.0.4",
"safe-publish-latest": "^1.1.1", "safe-publish-latest": "^1.1.1",
"safer-buffer": "^2.1.2", "tape": "^4.6.3"
"tape": "^4.9.0"
}, },
"engines": { "engines": {
"node": ">=0.6" "node": ">=0.6"
...@@ -69,12 +68,11 @@ ...@@ -69,12 +68,11 @@
"coverage": "covert test", "coverage": "covert test",
"dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js", "dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js",
"lint": "eslint lib/*.js test/*.js", "lint": "eslint lib/*.js test/*.js",
"prelint": "editorconfig-tools check * lib/* test/*",
"prepublish": "safe-publish-latest && npm run dist", "prepublish": "safe-publish-latest && npm run dist",
"pretest": "npm run --silent readme && npm run --silent lint", "pretest": "npm run --silent readme && npm run --silent lint",
"readme": "evalmd README.md", "readme": "evalmd README.md",
"test": "npm run --silent coverage", "test": "npm run --silent coverage",
"tests-only": "node test" "tests-only": "node test"
}, },
"version": "6.5.2" "version": "6.4.0"
} }
{ {
"rules": { "rules": {
"array-bracket-newline": 0,
"array-element-newline": 0,
"consistent-return": 2, "consistent-return": 2,
"max-lines": 0, "max-lines": 0,
"max-nested-callbacks": [2, 3], "max-nested-callbacks": [2, 3],
"max-statements": 0, "max-statements": 0,
"no-buffer-constructor": 0,
"no-extend-native": 0, "no-extend-native": 0,
"no-magic-numbers": 0, "no-magic-numbers": 0,
"object-curly-newline": 0,
"sort-keys": 0 "sort-keys": 0
} }
} }
...@@ -2,9 +2,7 @@ ...@@ -2,9 +2,7 @@
var test = require('tape'); var test = require('tape');
var qs = require('../'); var qs = require('../');
var utils = require('../lib/utils');
var iconv = require('iconv-lite'); var iconv = require('iconv-lite');
var SaferBuffer = require('safer-buffer').Buffer;
test('parse()', function (t) { test('parse()', function (t) {
t.test('parses a simple string', function (st) { t.test('parses a simple string', function (st) {
...@@ -232,7 +230,7 @@ test('parse()', function (t) { ...@@ -232,7 +230,7 @@ test('parse()', function (t) {
}); });
t.test('parses buffers correctly', function (st) { t.test('parses buffers correctly', function (st) {
var b = SaferBuffer.from('test'); var b = new Buffer('test');
st.deepEqual(qs.parse({ a: b }), { a: b }); st.deepEqual(qs.parse({ a: b }), { a: b });
st.end(); st.end();
}); });
...@@ -306,13 +304,6 @@ test('parse()', function (t) { ...@@ -306,13 +304,6 @@ test('parse()', function (t) {
st.end(); st.end();
}); });
t.test('allows for query string prefix', function (st) {
st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' });
st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' });
st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' });
st.end();
});
t.test('parses an object', function (st) { t.test('parses an object', function (st) {
var input = { var input = {
'user[name]': { 'pop[bob]': 3 }, 'user[name]': { 'pop[bob]': 3 },
...@@ -397,33 +388,6 @@ test('parse()', function (t) { ...@@ -397,33 +388,6 @@ test('parse()', function (t) {
st.end(); st.end();
}); });
t.test('does not crash when parsing deep objects', function (st) {
var parsed;
var str = 'foo';
for (var i = 0; i < 5000; i++) {
str += '[p]';
}
str += '=bar';
st.doesNotThrow(function () {
parsed = qs.parse(str, { depth: 5000 });
});
st.equal('foo' in parsed, true, 'parsed has "foo" property');
var depth = 0;
var ref = parsed.foo;
while ((ref = ref.p)) {
depth += 1;
}
st.equal(depth, 5000, 'parsed is 5000 properties deep');
st.end();
});
t.test('parses null objects correctly', { skip: !Object.create }, function (st) { t.test('parses null objects correctly', { skip: !Object.create }, function (st) {
var a = Object.create(null); var a = Object.create(null);
a.b = 'c'; a.b = 'c';
...@@ -540,35 +504,16 @@ test('parse()', function (t) { ...@@ -540,35 +504,16 @@ test('parse()', function (t) {
result.push(parseInt(parts[1], 16)); result.push(parseInt(parts[1], 16));
parts = reg.exec(str); parts = reg.exec(str);
} }
return iconv.decode(SaferBuffer.from(result), 'shift_jis').toString(); return iconv.decode(new Buffer(result), 'shift_jis').toString();
} }
}), { : '大阪府' }); }), { : '大阪府' });
st.end(); st.end();
}); });
t.test('receives the default decoder as a second argument', function (st) {
st.plan(1);
qs.parse('a', {
decoder: function (str, defaultDecoder) {
st.equal(defaultDecoder, utils.decode);
}
});
st.end();
});
t.test('throws error with wrong decoder', function (st) { t.test('throws error with wrong decoder', function (st) {
st['throws'](function () { st.throws(function () {
qs.parse({}, { decoder: 'string' }); qs.parse({}, { decoder: 'string' });
}, new TypeError('Decoder has to be a function.')); }, new TypeError('Decoder has to be a function.'));
st.end(); st.end();
}); });
t.test('does not mutate the options argument', function (st) {
var options = {};
qs.parse('a[b]=true', options);
st.deepEqual(options, {});
st.end();
});
t.end();
}); });
...@@ -2,9 +2,7 @@ ...@@ -2,9 +2,7 @@
var test = require('tape'); var test = require('tape');
var qs = require('../'); var qs = require('../');
var utils = require('../lib/utils');
var iconv = require('iconv-lite'); var iconv = require('iconv-lite');
var SaferBuffer = require('safer-buffer').Buffer;
test('stringify()', function (t) { test('stringify()', function (t) {
t.test('stringifies a querystring object', function (st) { t.test('stringifies a querystring object', function (st) {
...@@ -19,16 +17,6 @@ test('stringify()', function (t) { ...@@ -19,16 +17,6 @@ test('stringify()', function (t) {
st.end(); st.end();
}); });
t.test('adds query prefix', function (st) {
st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b');
st.end();
});
t.test('with query prefix, outputs blank string given an empty object', function (st) {
st.equal(qs.stringify({}, { addQueryPrefix: true }), '');
st.end();
});
t.test('stringifies a nested object', function (st) { t.test('stringifies a nested object', function (st) {
st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e');
...@@ -337,8 +325,8 @@ test('stringify()', function (t) { ...@@ -337,8 +325,8 @@ test('stringify()', function (t) {
}); });
t.test('stringifies buffer values', function (st) { t.test('stringifies buffer values', function (st) {
st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test'); st.equal(qs.stringify({ a: new Buffer('test') }), 'a=test');
st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test'); st.equal(qs.stringify({ a: { b: new Buffer('test') } }), 'a%5Bb%5D=test');
st.end(); st.end();
}); });
...@@ -464,25 +452,15 @@ test('stringify()', function (t) { ...@@ -464,25 +452,15 @@ test('stringify()', function (t) {
st.end(); st.end();
}); });
t.test('receives the default encoder as a second argument', function (st) {
st.plan(2);
qs.stringify({ a: 1 }, {
encoder: function (str, defaultEncoder) {
st.equal(defaultEncoder, utils.encode);
}
});
st.end();
});
t.test('throws error with wrong encoder', function (st) { t.test('throws error with wrong encoder', function (st) {
st['throws'](function () { st.throws(function () {
qs.stringify({}, { encoder: 'string' }); qs.stringify({}, { encoder: 'string' });
}, new TypeError('Encoder has to be a function.')); }, new TypeError('Encoder has to be a function.'));
st.end(); st.end();
}); });
t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) { t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) {
st.equal(qs.stringify({ a: SaferBuffer.from([1]) }, { st.equal(qs.stringify({ a: new Buffer([1]) }, {
encoder: function (buffer) { encoder: function (buffer) {
if (typeof buffer === 'string') { if (typeof buffer === 'string') {
return buffer; return buffer;
...@@ -505,7 +483,7 @@ test('stringify()', function (t) { ...@@ -505,7 +483,7 @@ test('stringify()', function (t) {
mutatedDate.toISOString = function () { mutatedDate.toISOString = function () {
throw new SyntaxError(); throw new SyntaxError();
}; };
st['throws'](function () { st.throws(function () {
mutatedDate.toISOString(); mutatedDate.toISOString();
}, SyntaxError); }, SyntaxError);
st.equal( st.equal(
...@@ -547,7 +525,7 @@ test('stringify()', function (t) { ...@@ -547,7 +525,7 @@ test('stringify()', function (t) {
t.test('Edge cases and unknown formats', function (st) { t.test('Edge cases and unknown formats', function (st) {
['UFO1234', false, 1234, null, {}, []].forEach( ['UFO1234', false, 1234, null, {}, []].forEach(
function (format) { function (format) {
st['throws']( st.throws(
function () { function () {
qs.stringify({ a: 'b c' }, { format: format }); qs.stringify({ a: 'b c' }, { format: format });
}, },
...@@ -586,12 +564,4 @@ test('stringify()', function (t) { ...@@ -586,12 +564,4 @@ test('stringify()', function (t) {
st.end(); st.end();
}); });
t.test('does not mutate the options argument', function (st) {
var options = {};
qs.stringify({}, options);
st.deepEqual(options, {});
st.end();
});
t.end();
}); });
...@@ -20,15 +20,3 @@ test('merge()', function (t) { ...@@ -20,15 +20,3 @@ test('merge()', function (t) {
t.end(); t.end();
}); });
test('assign()', function (t) {
var target = { a: 1, b: 2 };
var source = { b: 3, c: 4 };
var result = utils.assign(target, source);
t.equal(result, target, 'returns the target');
t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged');
t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched');
t.end();
});
{ {
"_from": "request@>=2.9.0", "_from": "request@2.81.0",
"_id": "request@2.88.2", "_id": "request@2.81.0",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", "_integrity": "sha1-xpKJRqDgbF+Nb4qTM0af/aRimKA=",
"_location": "/request", "_location": "/request",
"_phantomChildren": { "_phantomChildren": {
"asynckit": "0.4.0", "asynckit": "0.4.0",
...@@ -10,22 +10,24 @@ ...@@ -10,22 +10,24 @@
"mime-types": "2.1.25" "mime-types": "2.1.25"
}, },
"_requested": { "_requested": {
"type": "range", "type": "version",
"registry": true, "registry": true,
"raw": "request@>=2.9.0", "raw": "request@2.81.0",
"name": "request", "name": "request",
"escapedName": "request", "escapedName": "request",
"rawSpec": ">=2.9.0", "rawSpec": "2.81.0",
"saveSpec": null, "saveSpec": null,
"fetchSpec": ">=2.9.0" "fetchSpec": "2.81.0"
}, },
"_requiredBy": [ "_requiredBy": [
"#USER",
"/",
"/soap" "/soap"
], ],
"_resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", "_resolved": "https://registry.npmjs.org/request/-/request-2.81.0.tgz",
"_shasum": "d73c918731cb5a87da047e207234146f664d12b3", "_shasum": "c6928946a0e06c5f8d6f8a9333469ffda46298a0",
"_spec": "request@>=2.9.0", "_spec": "request@2.81.0",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\TV3\\NewVersion01\\dev\\node_modules\\soap", "_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\Main\\02_Plattform_Main\\m4labplatform",
"author": { "author": {
"name": "Mikeal Rogers", "name": "Mikeal Rogers",
"email": "mikeal.rogers@gmail.com" "email": "mikeal.rogers@gmail.com"
...@@ -35,26 +37,28 @@ ...@@ -35,26 +37,28 @@
}, },
"bundleDependencies": false, "bundleDependencies": false,
"dependencies": { "dependencies": {
"aws-sign2": "~0.7.0", "aws-sign2": "~0.6.0",
"aws4": "^1.8.0", "aws4": "^1.2.1",
"caseless": "~0.12.0", "caseless": "~0.12.0",
"combined-stream": "~1.0.6", "combined-stream": "~1.0.5",
"extend": "~3.0.2", "extend": "~3.0.0",
"forever-agent": "~0.6.1", "forever-agent": "~0.6.1",
"form-data": "~2.3.2", "form-data": "~2.1.1",
"har-validator": "~5.1.3", "har-validator": "~4.2.1",
"http-signature": "~1.2.0", "hawk": "~3.1.3",
"http-signature": "~1.1.0",
"is-typedarray": "~1.0.0", "is-typedarray": "~1.0.0",
"isstream": "~0.1.2", "isstream": "~0.1.2",
"json-stringify-safe": "~5.0.1", "json-stringify-safe": "~5.0.1",
"mime-types": "~2.1.19", "mime-types": "~2.1.7",
"oauth-sign": "~0.9.0", "oauth-sign": "~0.8.1",
"performance-now": "^2.1.0", "performance-now": "^0.2.0",
"qs": "~6.5.2", "qs": "~6.4.0",
"safe-buffer": "^5.1.2", "safe-buffer": "^5.0.1",
"tough-cookie": "~2.5.0", "stringstream": "~0.0.4",
"tough-cookie": "~2.3.0",
"tunnel-agent": "^0.6.0", "tunnel-agent": "^0.6.0",
"uuid": "^3.3.2" "uuid": "^3.0.0"
}, },
"deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142", "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142",
"description": "Simplified HTTP request client.", "description": "Simplified HTTP request client.",
...@@ -63,25 +67,25 @@ ...@@ -63,25 +67,25 @@
"browserify": "^13.0.1", "browserify": "^13.0.1",
"browserify-istanbul": "^2.0.0", "browserify-istanbul": "^2.0.0",
"buffer-equal": "^1.0.0", "buffer-equal": "^1.0.0",
"codecov": "^3.0.4", "codecov": "^1.0.1",
"coveralls": "^3.0.2", "coveralls": "^2.11.4",
"eslint": "^2.5.3",
"function-bind": "^1.0.2", "function-bind": "^1.0.2",
"karma": "^3.0.0", "istanbul": "^0.4.0",
"karma": "^1.1.1",
"karma-browserify": "^5.0.1", "karma-browserify": "^5.0.1",
"karma-cli": "^1.0.0", "karma-cli": "^1.0.0",
"karma-coverage": "^1.0.0", "karma-coverage": "^1.0.0",
"karma-phantomjs-launcher": "^1.0.0", "karma-phantomjs-launcher": "^1.0.0",
"karma-tap": "^3.0.1", "karma-tap": "^3.0.1",
"nyc": "^14.1.1",
"phantomjs-prebuilt": "^2.1.3", "phantomjs-prebuilt": "^2.1.3",
"rimraf": "^2.2.8", "rimraf": "^2.2.8",
"server-destroy": "^1.0.1", "server-destroy": "^1.0.1",
"standard": "^9.0.0",
"tape": "^4.6.0", "tape": "^4.6.0",
"taper": "^0.5.0" "taper": "^0.5.0"
}, },
"engines": { "engines": {
"node": ">= 6" "node": ">= 4"
}, },
"files": [ "files": [
"lib/", "lib/",
...@@ -90,6 +94,7 @@ ...@@ -90,6 +94,7 @@
], ],
"greenkeeper": { "greenkeeper": {
"ignore": [ "ignore": [
"eslint",
"hawk", "hawk",
"har-validator" "har-validator"
] ]
...@@ -109,11 +114,11 @@ ...@@ -109,11 +114,11 @@
"url": "git+https://github.com/request/request.git" "url": "git+https://github.com/request/request.git"
}, },
"scripts": { "scripts": {
"lint": "standard", "lint": "eslint lib/ *.js tests/ && echo Lint passed.",
"test": "npm run lint && npm run test-ci && npm run test-browser", "test": "npm run lint && npm run test-ci && npm run test-browser",
"test-browser": "node tests/browser/start.js", "test-browser": "node tests/browser/start.js",
"test-ci": "taper tests/test-*.js", "test-ci": "taper tests/test-*.js",
"test-cov": "nyc --reporter=lcov tape tests/test-*.js" "test-cov": "istanbul cover tape tests/test-*.js"
}, },
"version": "2.88.2" "version": "2.81.0"
} }
'use strict' 'use strict'
var http = require('http') var http = require('http')
var https = require('https') , https = require('https')
var url = require('url') , url = require('url')
var util = require('util') , util = require('util')
var stream = require('stream') , stream = require('stream')
var zlib = require('zlib') , zlib = require('zlib')
var aws2 = require('aws-sign2') , hawk = require('hawk')
var aws4 = require('aws4') , aws2 = require('aws-sign2')
var httpSignature = require('http-signature') , aws4 = require('aws4')
var mime = require('mime-types') , httpSignature = require('http-signature')
var caseless = require('caseless') , mime = require('mime-types')
var ForeverAgent = require('forever-agent') , stringstream = require('stringstream')
var FormData = require('form-data') , caseless = require('caseless')
var extend = require('extend') , ForeverAgent = require('forever-agent')
var isstream = require('isstream') , FormData = require('form-data')
var isTypedArray = require('is-typedarray').strict , extend = require('extend')
var helpers = require('./lib/helpers') , isstream = require('isstream')
var cookies = require('./lib/cookies') , isTypedArray = require('is-typedarray').strict
var getProxyFromURI = require('./lib/getProxyFromURI') , helpers = require('./lib/helpers')
var Querystring = require('./lib/querystring').Querystring , cookies = require('./lib/cookies')
var Har = require('./lib/har').Har , getProxyFromURI = require('./lib/getProxyFromURI')
var Auth = require('./lib/auth').Auth , Querystring = require('./lib/querystring').Querystring
var OAuth = require('./lib/oauth').OAuth , Har = require('./lib/har').Har
var hawk = require('./lib/hawk') , Auth = require('./lib/auth').Auth
var Multipart = require('./lib/multipart').Multipart , OAuth = require('./lib/oauth').OAuth
var Redirect = require('./lib/redirect').Redirect , Multipart = require('./lib/multipart').Multipart
var Tunnel = require('./lib/tunnel').Tunnel , Redirect = require('./lib/redirect').Redirect
var now = require('performance-now') , Tunnel = require('./lib/tunnel').Tunnel
var Buffer = require('safe-buffer').Buffer , now = require('performance-now')
, Buffer = require('safe-buffer').Buffer
var safeStringify = helpers.safeStringify var safeStringify = helpers.safeStringify
var isReadStream = helpers.isReadStream , isReadStream = helpers.isReadStream
var toBase64 = helpers.toBase64 , toBase64 = helpers.toBase64
var defer = helpers.defer , defer = helpers.defer
var copy = helpers.copy , copy = helpers.copy
var version = helpers.version , version = helpers.version
var globalCookieJar = cookies.jar() , globalCookieJar = cookies.jar()
var globalPool = {} var globalPool = {}
function filterForNonReserved (reserved, options) { function filterForNonReserved(reserved, options) {
// Filter out properties that are not reserved. // Filter out properties that are not reserved.
// Reserved values are passed in at call site. // Reserved values are passed in at call site.
...@@ -54,7 +56,7 @@ function filterForNonReserved (reserved, options) { ...@@ -54,7 +56,7 @@ function filterForNonReserved (reserved, options) {
return object return object
} }
function filterOutReservedFunctions (reserved, options) { function filterOutReservedFunctions(reserved, options) {
// Filter out properties that are functions and are reserved. // Filter out properties that are functions and are reserved.
// Reserved values are passed in at call site. // Reserved values are passed in at call site.
...@@ -67,10 +69,11 @@ function filterOutReservedFunctions (reserved, options) { ...@@ -67,10 +69,11 @@ function filterOutReservedFunctions (reserved, options) {
} }
} }
return object return object
} }
// Return a simpler request object to allow serialization // Return a simpler request object to allow serialization
function requestToJSON () { function requestToJSON() {
var self = this var self = this
return { return {
uri: self.uri, uri: self.uri,
...@@ -80,7 +83,7 @@ function requestToJSON () { ...@@ -80,7 +83,7 @@ function requestToJSON () {
} }
// Return a simpler response object to allow serialization // Return a simpler response object to allow serialization
function responseToJSON () { function responseToJSON() {
var self = this var self = this
return { return {
statusCode: self.statusCode, statusCode: self.statusCode,
...@@ -131,7 +134,7 @@ util.inherits(Request, stream.Stream) ...@@ -131,7 +134,7 @@ util.inherits(Request, stream.Stream)
// Debugging // Debugging
Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG) Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
function debug () { function debug() {
if (Request.debug) { if (Request.debug) {
console.error('REQUEST %s', util.format.apply(util, arguments)) console.error('REQUEST %s', util.format.apply(util, arguments))
} }
...@@ -255,7 +258,7 @@ Request.prototype.init = function (options) { ...@@ -255,7 +258,7 @@ Request.prototype.init = function (options) {
self.rejectUnauthorized = false self.rejectUnauthorized = false
} }
if (!self.uri.pathname) { self.uri.pathname = '/' } if (!self.uri.pathname) {self.uri.pathname = '/'}
if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) { if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
// Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
...@@ -287,21 +290,18 @@ Request.prototype.init = function (options) { ...@@ -287,21 +290,18 @@ Request.prototype.init = function (options) {
self.setHost = false self.setHost = false
if (!self.hasHeader('host')) { if (!self.hasHeader('host')) {
var hostHeaderName = self.originalHostHeaderName || 'host' var hostHeaderName = self.originalHostHeaderName || 'host'
// When used with an IPv6 address, `host` will provide
// the correct bracketed format, unlike using `hostname` and
// optionally adding the `port` when necessary.
self.setHeader(hostHeaderName, self.uri.host) self.setHeader(hostHeaderName, self.uri.host)
// Drop :port suffix from Host header if known protocol.
if (self.uri.port) {
if ((self.uri.port === '80' && self.uri.protocol === 'http:') ||
(self.uri.port === '443' && self.uri.protocol === 'https:')) {
self.setHeader(hostHeaderName, self.uri.hostname)
}
}
self.setHost = true self.setHost = true
} }
self.jar(self._jar || options.jar) self.jar(self._jar || options.jar)
if (!self.uri.port) { if (!self.uri.port) {
if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 } if (self.uri.protocol === 'http:') {self.uri.port = 80}
else if (self.uri.protocol === 'https:') {self.uri.port = 443}
} }
if (self.proxy && !self.tunnel) { if (self.proxy && !self.tunnel) {
...@@ -388,12 +388,12 @@ Request.prototype.init = function (options) { ...@@ -388,12 +388,12 @@ Request.prototype.init = function (options) {
} }
if (self.uri.auth && !self.hasHeader('authorization')) { if (self.uri.auth && !self.hasHeader('authorization')) {
var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) }) var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true) self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
} }
if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) { if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) }) var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':')) var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
self.setHeader('proxy-authorization', authHeader) self.setHeader('proxy-authorization', authHeader)
} }
...@@ -425,9 +425,11 @@ Request.prototype.init = function (options) { ...@@ -425,9 +425,11 @@ Request.prototype.init = function (options) {
var length var length
if (typeof self.body === 'string') { if (typeof self.body === 'string') {
length = Buffer.byteLength(self.body) length = Buffer.byteLength(self.body)
} else if (Array.isArray(self.body)) { }
length = self.body.reduce(function (a, b) { return a + b.length }, 0) else if (Array.isArray(self.body)) {
} else { length = self.body.reduce(function (a, b) {return a + b.length}, 0)
}
else {
length = self.body.length length = self.body.length
} }
...@@ -449,8 +451,8 @@ Request.prototype.init = function (options) { ...@@ -449,8 +451,8 @@ Request.prototype.init = function (options) {
} }
var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
var defaultModules = {'http:': http, 'https:': https} , defaultModules = {'http:':http, 'https:':https}
var httpModules = self.httpModules || {} , httpModules = self.httpModules || {}
self.httpModule = httpModules[protocol] || defaultModules[protocol] self.httpModule = httpModules[protocol] || defaultModules[protocol]
...@@ -515,9 +517,9 @@ Request.prototype.init = function (options) { ...@@ -515,9 +517,9 @@ Request.prototype.init = function (options) {
} }
} }
// self.on('pipe', function () { // self.on('pipe', function () {
// console.error('You have already piped to this stream. Pipeing twice is likely to break the request.') // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
// }) // })
}) })
defer(function () { defer(function () {
...@@ -529,7 +531,8 @@ Request.prototype.init = function (options) { ...@@ -529,7 +531,8 @@ Request.prototype.init = function (options) {
if (self._form) { if (self._form) {
if (!self._auth.hasAuth) { if (!self._auth.hasAuth) {
self._form.pipe(self) self._form.pipe(self)
} else if (self._auth.hasAuth && self._auth.sentAuth) { }
else if (self._auth.hasAuth && self._auth.sentAuth) {
self._form.pipe(self) self._form.pipe(self)
} }
} }
...@@ -580,6 +583,7 @@ Request.prototype.init = function (options) { ...@@ -580,6 +583,7 @@ Request.prototype.init = function (options) {
self.ntick = true self.ntick = true
}) })
} }
Request.prototype.getNewAgent = function () { Request.prototype.getNewAgent = function () {
...@@ -774,22 +778,21 @@ Request.prototype.start = function () { ...@@ -774,22 +778,21 @@ Request.prototype.start = function () {
self.req.on('response', self.onRequestResponse.bind(self)) self.req.on('response', self.onRequestResponse.bind(self))
self.req.on('error', self.onRequestError.bind(self)) self.req.on('error', self.onRequestError.bind(self))
self.req.on('drain', function () { self.req.on('drain', function() {
self.emit('drain') self.emit('drain')
}) })
self.req.on('socket', function(socket) {
self.req.on('socket', function (socket) {
// `._connecting` was the old property which was made public in node v6.1.0 // `._connecting` was the old property which was made public in node v6.1.0
var isConnecting = socket._connecting || socket.connecting var isConnecting = socket._connecting || socket.connecting
if (self.timing) { if (self.timing) {
self.timings.socket = now() - self.startTimeNow self.timings.socket = now() - self.startTimeNow
if (isConnecting) { if (isConnecting) {
var onLookupTiming = function () { var onLookupTiming = function() {
self.timings.lookup = now() - self.startTimeNow self.timings.lookup = now() - self.startTimeNow
} }
var onConnectTiming = function () { var onConnectTiming = function() {
self.timings.connect = now() - self.startTimeNow self.timings.connect = now() - self.startTimeNow
} }
...@@ -797,14 +800,14 @@ Request.prototype.start = function () { ...@@ -797,14 +800,14 @@ Request.prototype.start = function () {
socket.once('connect', onConnectTiming) socket.once('connect', onConnectTiming)
// clean up timing event listeners if needed on error // clean up timing event listeners if needed on error
self.req.once('error', function () { self.req.once('error', function() {
socket.removeListener('lookup', onLookupTiming) socket.removeListener('lookup', onLookupTiming)
socket.removeListener('connect', onConnectTiming) socket.removeListener('connect', onConnectTiming)
}) })
} }
} }
var setReqTimeout = function () { var setReqTimeout = function() {
// This timeout sets the amount of time to wait *between* bytes sent // This timeout sets the amount of time to wait *between* bytes sent
// from the server once connected. // from the server once connected.
// //
...@@ -826,15 +829,16 @@ Request.prototype.start = function () { ...@@ -826,15 +829,16 @@ Request.prototype.start = function () {
// keep-alive connection) do not bother. This is important since we won't // keep-alive connection) do not bother. This is important since we won't
// get a 'connect' event for an already connected socket. // get a 'connect' event for an already connected socket.
if (isConnecting) { if (isConnecting) {
var onReqSockConnect = function () { var onReqSockConnect = function() {
socket.removeListener('connect', onReqSockConnect) socket.removeListener('connect', onReqSockConnect)
self.clearTimeout() clearTimeout(self.timeoutTimer)
self.timeoutTimer = null
setReqTimeout() setReqTimeout()
} }
socket.on('connect', onReqSockConnect) socket.on('connect', onReqSockConnect)
self.req.on('error', function (err) { // eslint-disable-line handle-callback-err self.req.on('error', function(err) {
socket.removeListener('connect', onReqSockConnect) socket.removeListener('connect', onReqSockConnect)
}) })
...@@ -866,14 +870,17 @@ Request.prototype.onRequestError = function (error) { ...@@ -866,14 +870,17 @@ Request.prototype.onRequestError = function (error) {
if (self._aborted) { if (self._aborted) {
return return
} }
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' && if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
self.agent.addRequestNoreuse) { && self.agent.addRequestNoreuse) {
self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
self.start() self.start()
self.req.end() self.req.end()
return return
} }
self.clearTimeout() if (self.timeout && self.timeoutTimer) {
clearTimeout(self.timeoutTimer)
self.timeoutTimer = null
}
self.emit('error', error) self.emit('error', error)
} }
...@@ -885,7 +892,7 @@ Request.prototype.onRequestResponse = function (response) { ...@@ -885,7 +892,7 @@ Request.prototype.onRequestResponse = function (response) {
} }
debug('onRequestResponse', self.uri.href, response.statusCode, response.headers) debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
response.on('end', function () { response.on('end', function() {
if (self.timing) { if (self.timing) {
self.timings.end = now() - self.startTimeNow self.timings.end = now() - self.startTimeNow
response.timingStart = self.startTime response.timingStart = self.startTime
...@@ -941,8 +948,8 @@ Request.prototype.onRequestResponse = function (response) { ...@@ -941,8 +948,8 @@ Request.prototype.onRequestResponse = function (response) {
// XXX This is different on 0.10, because SSL is strict by default // XXX This is different on 0.10, because SSL is strict by default
if (self.httpModule === https && if (self.httpModule === https &&
self.strictSSL && (!response.hasOwnProperty('socket') || self.strictSSL && (!response.hasOwnProperty('socket') ||
!response.socket.authorized)) { !response.socket.authorized)) {
debug('strict ssl error', self.uri.href) debug('strict ssl error', self.uri.href)
var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL' var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
self.emit('error', new Error('SSL Error: ' + sslErr)) self.emit('error', new Error('SSL Error: ' + sslErr))
...@@ -960,11 +967,14 @@ Request.prototype.onRequestResponse = function (response) { ...@@ -960,11 +967,14 @@ Request.prototype.onRequestResponse = function (response) {
if (self.setHost) { if (self.setHost) {
self.removeHeader('host') self.removeHeader('host')
} }
self.clearTimeout() if (self.timeout && self.timeoutTimer) {
clearTimeout(self.timeoutTimer)
self.timeoutTimer = null
}
var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
var addCookie = function (cookie) { var addCookie = function (cookie) {
// set the cookie if it's domain in the href's domain. //set the cookie if it's domain in the href's domain.
try { try {
targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true}) targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
} catch (e) { } catch (e) {
...@@ -1000,13 +1010,13 @@ Request.prototype.onRequestResponse = function (response) { ...@@ -1000,13 +1010,13 @@ Request.prototype.onRequestResponse = function (response) {
var noBody = function (code) { var noBody = function (code) {
return ( return (
self.method === 'HEAD' || self.method === 'HEAD'
// Informational // Informational
(code >= 100 && code < 200) || || (code >= 100 && code < 200)
// No Content // No Content
code === 204 || || code === 204
// Not Modified // Not Modified
code === 304 || code === 304
) )
} }
...@@ -1020,8 +1030,8 @@ Request.prototype.onRequestResponse = function (response) { ...@@ -1020,8 +1030,8 @@ Request.prototype.onRequestResponse = function (response) {
// by common browsers. // by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does. // Always using Z_SYNC_FLUSH is what cURL does.
var zlibOptions = { var zlibOptions = {
flush: zlib.Z_SYNC_FLUSH, flush: zlib.Z_SYNC_FLUSH
finishFlush: zlib.Z_SYNC_FLUSH , finishFlush: zlib.Z_SYNC_FLUSH
} }
if (contentEncoding === 'gzip') { if (contentEncoding === 'gzip') {
...@@ -1045,8 +1055,13 @@ Request.prototype.onRequestResponse = function (response) { ...@@ -1045,8 +1055,13 @@ Request.prototype.onRequestResponse = function (response) {
if (self.encoding) { if (self.encoding) {
if (self.dests.length !== 0) { if (self.dests.length !== 0) {
console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.') console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
} else { } else if (responseContent.setEncoding) {
responseContent.setEncoding(self.encoding) responseContent.setEncoding(self.encoding)
} else {
// Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
// zlib streams.
// If/When support for 0.9.4 is dropped, this should be unnecessary.
responseContent = responseContent.pipe(stringstream(self.encoding))
} }
} }
...@@ -1078,11 +1093,13 @@ Request.prototype.onRequestResponse = function (response) { ...@@ -1078,11 +1093,13 @@ Request.prototype.onRequestResponse = function (response) {
responseContent.on('error', function (error) { responseContent.on('error', function (error) {
self.emit('error', error) self.emit('error', error)
}) })
responseContent.on('close', function () { self.emit('close') }) responseContent.on('close', function () {self.emit('close')})
if (self.callback) { if (self.callback) {
self.readResponseBody(response) self.readResponseBody(response)
} else { // if no callback }
//if no callback
else {
self.on('end', function () { self.on('end', function () {
if (self._aborted) { if (self._aborted) {
debug('aborted', self.uri.href) debug('aborted', self.uri.href)
...@@ -1097,10 +1114,10 @@ Request.prototype.onRequestResponse = function (response) { ...@@ -1097,10 +1114,10 @@ Request.prototype.onRequestResponse = function (response) {
Request.prototype.readResponseBody = function (response) { Request.prototype.readResponseBody = function (response) {
var self = this var self = this
debug("reading response's body") debug('reading response\'s body')
var buffers = [] var buffers = []
var bufferLength = 0 , bufferLength = 0
var strings = [] , strings = []
self.on('data', function (chunk) { self.on('data', function (chunk) {
if (!Buffer.isBuffer(chunk)) { if (!Buffer.isBuffer(chunk)) {
...@@ -1161,11 +1178,11 @@ Request.prototype.abort = function () { ...@@ -1161,11 +1178,11 @@ Request.prototype.abort = function () {
if (self.req) { if (self.req) {
self.req.abort() self.req.abort()
} else if (self.response) { }
else if (self.response) {
self.response.destroy() self.response.destroy()
} }
self.clearTimeout()
self.emit('abort') self.emit('abort')
} }
...@@ -1178,7 +1195,8 @@ Request.prototype.pipeDest = function (dest) { ...@@ -1178,7 +1195,8 @@ Request.prototype.pipeDest = function (dest) {
var ctname = response.caseless.has('content-type') var ctname = response.caseless.has('content-type')
if (dest.setHeader) { if (dest.setHeader) {
dest.setHeader(ctname, response.headers[ctname]) dest.setHeader(ctname, response.headers[ctname])
} else { }
else {
dest.headers[ctname] = response.headers[ctname] dest.headers[ctname] = response.headers[ctname]
} }
} }
...@@ -1249,7 +1267,7 @@ Request.prototype.form = function (form) { ...@@ -1249,7 +1267,7 @@ Request.prototype.form = function (form) {
} }
// create form-data object // create form-data object
self._form = new FormData() self._form = new FormData()
self._form.on('error', function (err) { self._form.on('error', function(err) {
err.message = 'form-data: ' + err.message err.message = 'form-data: ' + err.message
self.emit('error', err) self.emit('error', err)
self.abort() self.abort()
...@@ -1324,8 +1342,8 @@ Request.prototype.getHeader = function (name, headers) { ...@@ -1324,8 +1342,8 @@ Request.prototype.getHeader = function (name, headers) {
Request.prototype.enableUnixSocket = function () { Request.prototype.enableUnixSocket = function () {
// Get the socket & request paths from the URL // Get the socket & request paths from the URL
var unixParts = this.uri.path.split(':') var unixParts = this.uri.path.split(':')
var host = unixParts[0] , host = unixParts[0]
var path = unixParts[1] , path = unixParts[1]
// Apply unix properties to request // Apply unix properties to request
this.socketPath = host this.socketPath = host
this.uri.pathname = path this.uri.pathname = path
...@@ -1335,6 +1353,7 @@ Request.prototype.enableUnixSocket = function () { ...@@ -1335,6 +1353,7 @@ Request.prototype.enableUnixSocket = function () {
this.uri.isUnix = true this.uri.isUnix = true
} }
Request.prototype.auth = function (user, pass, sendImmediately, bearer) { Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
var self = this var self = this
...@@ -1350,18 +1369,17 @@ Request.prototype.aws = function (opts, now) { ...@@ -1350,18 +1369,17 @@ Request.prototype.aws = function (opts, now) {
return self return self
} }
if (opts.sign_version === 4 || opts.sign_version === '4') { if (opts.sign_version == 4 || opts.sign_version == '4') {
// use aws4 // use aws4
var options = { var options = {
host: self.uri.host, host: self.uri.host,
path: self.uri.path, path: self.uri.path,
method: self.method, method: self.method,
headers: self.headers, headers: {
'content-type': self.getHeader('content-type') || ''
},
body: self.body body: self.body
} }
if (opts.service) {
options.service = opts.service
}
var signRes = aws4.sign(options, { var signRes = aws4.sign(options, {
accessKeyId: opts.key, accessKeyId: opts.key,
secretAccessKey: opts.secret, secretAccessKey: opts.secret,
...@@ -1372,19 +1390,20 @@ Request.prototype.aws = function (opts, now) { ...@@ -1372,19 +1390,20 @@ Request.prototype.aws = function (opts, now) {
if (signRes.headers['X-Amz-Security-Token']) { if (signRes.headers['X-Amz-Security-Token']) {
self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token']) self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
} }
} else { }
else {
// default: use aws-sign2 // default: use aws-sign2
var date = new Date() var date = new Date()
self.setHeader('date', date.toUTCString()) self.setHeader('date', date.toUTCString())
var auth = { var auth =
key: opts.key, { key: opts.key
secret: opts.secret, , secret: opts.secret
verb: self.method.toUpperCase(), , verb: self.method.toUpperCase()
date: date, , date: date
contentType: self.getHeader('content-type') || '', , contentType: self.getHeader('content-type') || ''
md5: self.getHeader('content-md5') || '', , md5: self.getHeader('content-md5') || ''
amazonHeaders: aws2.canonicalizeHeaders(self.headers) , amazonHeaders: aws2.canonicalizeHeaders(self.headers)
} }
var path = self.uri.path var path = self.uri.path
if (opts.bucket && path) { if (opts.bucket && path) {
auth.resource = '/' + opts.bucket + path auth.resource = '/' + opts.bucket + path
...@@ -1404,10 +1423,10 @@ Request.prototype.aws = function (opts, now) { ...@@ -1404,10 +1423,10 @@ Request.prototype.aws = function (opts, now) {
Request.prototype.httpSignature = function (opts) { Request.prototype.httpSignature = function (opts) {
var self = this var self = this
httpSignature.signRequest({ httpSignature.signRequest({
getHeader: function (header) { getHeader: function(header) {
return self.getHeader(header, self.headers) return self.getHeader(header, self.headers)
}, },
setHeader: function (header, value) { setHeader: function(header, value) {
self.setHeader(header, value) self.setHeader(header, value)
}, },
method: self.method, method: self.method,
...@@ -1419,7 +1438,7 @@ Request.prototype.httpSignature = function (opts) { ...@@ -1419,7 +1438,7 @@ Request.prototype.httpSignature = function (opts) {
} }
Request.prototype.hawk = function (opts) { Request.prototype.hawk = function (opts) {
var self = this var self = this
self.setHeader('Authorization', hawk.header(self.uri, self.method, opts)) self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
} }
Request.prototype.oauth = function (_oauth) { Request.prototype.oauth = function (_oauth) {
var self = this var self = this
...@@ -1442,15 +1461,15 @@ Request.prototype.jar = function (jar) { ...@@ -1442,15 +1461,15 @@ Request.prototype.jar = function (jar) {
cookies = false cookies = false
self._disableCookies = true self._disableCookies = true
} else { } else {
var targetCookieJar = jar.getCookieString ? jar : globalCookieJar var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
var urihref = self.uri.href var urihref = self.uri.href
// fetch cookie in the Specified host //fetch cookie in the Specified host
if (targetCookieJar) { if (targetCookieJar) {
cookies = targetCookieJar.getCookieString(urihref) cookies = targetCookieJar.getCookieString(urihref)
} }
} }
// if need cookie and cookie is not empty //if need cookie and cookie is not empty
if (cookies && cookies.length) { if (cookies && cookies.length) {
if (self.originalCookieHeader) { if (self.originalCookieHeader) {
// Don't overwrite existing Cookie header // Don't overwrite existing Cookie header
...@@ -1463,6 +1482,7 @@ Request.prototype.jar = function (jar) { ...@@ -1463,6 +1482,7 @@ Request.prototype.jar = function (jar) {
return self return self
} }
// Stream API // Stream API
Request.prototype.pipe = function (dest, opts) { Request.prototype.pipe = function (dest, opts) {
var self = this var self = this
...@@ -1485,7 +1505,7 @@ Request.prototype.pipe = function (dest, opts) { ...@@ -1485,7 +1505,7 @@ Request.prototype.pipe = function (dest, opts) {
} }
Request.prototype.write = function () { Request.prototype.write = function () {
var self = this var self = this
if (self._aborted) { return } if (self._aborted) {return}
if (!self._started) { if (!self._started) {
self.start() self.start()
...@@ -1496,7 +1516,7 @@ Request.prototype.write = function () { ...@@ -1496,7 +1516,7 @@ Request.prototype.write = function () {
} }
Request.prototype.end = function (chunk) { Request.prototype.end = function (chunk) {
var self = this var self = this
if (self._aborted) { return } if (self._aborted) {return}
if (chunk) { if (chunk) {
self.write(chunk) self.write(chunk)
...@@ -1526,7 +1546,6 @@ Request.prototype.resume = function () { ...@@ -1526,7 +1546,6 @@ Request.prototype.resume = function () {
} }
Request.prototype.destroy = function () { Request.prototype.destroy = function () {
var self = this var self = this
this.clearTimeout()
if (!self._ended) { if (!self._ended) {
self.end() self.end()
} else if (self.response) { } else if (self.response) {
...@@ -1534,13 +1553,6 @@ Request.prototype.destroy = function () { ...@@ -1534,13 +1553,6 @@ Request.prototype.destroy = function () {
} }
} }
Request.prototype.clearTimeout = function () {
if (this.timeoutTimer) {
clearTimeout(this.timeoutTimer)
this.timeoutTimer = null
}
}
Request.defaultProxyHeaderWhiteList = Request.defaultProxyHeaderWhiteList =
Tunnel.defaultProxyHeaderWhiteList.slice() Tunnel.defaultProxyHeaderWhiteList.slice()
......
...@@ -10,3 +10,18 @@ Redistribution and use in source and binary forms, with or without modification, ...@@ -10,3 +10,18 @@ Redistribution and use in source and binary forms, with or without modification,
3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===
The following exceptions apply:
===
`public_suffix_list.dat` was obtained from
<https://publicsuffix.org/list/public_suffix_list.dat> via
<http://publicsuffix.org>. The license for this file is MPL/2.0. The header of
that file reads as follows:
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
...@@ -57,7 +57,7 @@ Transforms a domain-name into a canonical domain-name. The canonical domain-nam ...@@ -57,7 +57,7 @@ Transforms a domain-name into a canonical domain-name. The canonical domain-nam
Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match".
The `canonicalize` parameter will run the other two parameters through `canonicalDomain` or not. The `canonicalize` parameter will run the other two paramters through `canonicalDomain` or not.
### `defaultPath(path)` ### `defaultPath(path)`
...@@ -85,7 +85,7 @@ Returns the public suffix of this hostname. The public suffix is the shortest d ...@@ -85,7 +85,7 @@ Returns the public suffix of this hostname. The public suffix is the shortest d
For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`. For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`.
For further information, see http://publicsuffix.org/. This module derives its list from that site. This call is currently a wrapper around [`psl`](https://www.npmjs.com/package/psl)'s [get() method](https://www.npmjs.com/package/psl#pslgetdomain). For further information, see http://publicsuffix.org/. This module derives its list from that site.
### `cookieCompare(a,b)` ### `cookieCompare(a,b)`
...@@ -186,7 +186,7 @@ sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` ...@@ -186,7 +186,7 @@ sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity`
expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds. expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds.
Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` parameter -- is used to offset the `.maxAge` attribute. Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` paramter -- is used to offset the `.maxAge` attribute.
If Expires (`.expires`) is set, that's returned. If Expires (`.expires`) is set, that's returned.
...@@ -198,7 +198,7 @@ compute the TTL relative to `now` (milliseconds). The same precedence rules as ...@@ -198,7 +198,7 @@ compute the TTL relative to `now` (milliseconds). The same precedence rules as
The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned. The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned.
### `.canonicalizedDomain()` ### `.canonicalizedDoman()`
### `.cdomain()` ### `.cdomain()`
...@@ -354,16 +354,6 @@ The `store` argument is optional, but must be a _synchronous_ `Store` instance i ...@@ -354,16 +354,6 @@ The `store` argument is optional, but must be a _synchronous_ `Store` instance i
The _source_ and _destination_ must both be synchronous `Store`s. If one or both stores are asynchronous, use `.clone` instead. Recall that `MemoryCookieStore` supports both synchronous and asynchronous API calls. The _source_ and _destination_ must both be synchronous `Store`s. If one or both stores are asynchronous, use `.clone` instead. Recall that `MemoryCookieStore` supports both synchronous and asynchronous API calls.
### `.removeAllCookies(cb(err))`
Removes all cookies from the jar.
This is a new backwards-compatible feature of `tough-cookie` version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement `removeAllCookies`, the fallback is to call `removeCookie` after `getAllCookies`. If `getAllCookies` fails or isn't implemented in the Store, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned.
### `.removeAllCookiesSync()`
Sync version of `.removeAllCookies()`
## Store ## Store
Base class for CookieJar stores. Available as `tough.Store`. Base class for CookieJar stores. Available as `tough.Store`.
...@@ -428,29 +418,19 @@ Removes matching cookies from the store. The `path` parameter is optional, and ...@@ -428,29 +418,19 @@ Removes matching cookies from the store. The `path` parameter is optional, and
Pass an error ONLY if removing any existing cookies failed. Pass an error ONLY if removing any existing cookies failed.
### `store.removeAllCookies(cb(err))`
_Optional_. Removes all cookies from the store.
Pass an error if one or more cookies can't be removed.
**Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this.
### `store.getAllCookies(cb(err, cookies))` ### `store.getAllCookies(cb(err, cookies))`
_Optional_. Produces an `Array` of all cookies during `jar.serialize()`. The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format] data structure. Produces an `Array` of all cookies during `jar.serialize()`. The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format] data structure.
Cookies SHOULD be returned in creation order to preserve sorting via `compareCookies()`. For reference, `MemoryCookieStore` will sort by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1ms. See `compareCookies` for more detail. Cookies SHOULD be returned in creation order to preserve sorting via `compareCookies()`. For reference, `MemoryCookieStore` will sort by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1ms. See `compareCookies` for more detail.
Pass an error if retrieval fails. Pass an error if retrieval fails.
**Note**: not all Stores can implement this due to technical limitations, so it is optional.
## MemoryCookieStore ## MemoryCookieStore
Inherits from `Store`. Inherits from `Store`.
A just-in-memory CookieJar synchronous store implementation, used by default. Despite being a synchronous implementation, it's usable with both the synchronous and asynchronous forms of the `CookieJar` API. Supports serialization, `getAllCookies`, and `removeAllCookies`. A just-in-memory CookieJar synchronous store implementation, used by default. Despite being a synchronous implementation, it's usable with both the synchronous and asynchronous forms of the `CookieJar` API.
## Community Cookie Stores ## Community Cookie Stores
...@@ -493,7 +473,7 @@ These are some Store implementations authored and maintained by the community. T ...@@ -493,7 +473,7 @@ These are some Store implementations authored and maintained by the community. T
# Copyright and License # Copyright and License
BSD-3-Clause: (tl;dr: BSD-3-Clause with some MPL/2.0)
```text ```text
Copyright (c) 2015, Salesforce.com, Inc. Copyright (c) 2015, Salesforce.com, Inc.
...@@ -525,3 +505,5 @@ BSD-3-Clause: ...@@ -525,3 +505,5 @@ BSD-3-Clause:
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. POSSIBILITY OF SUCH DAMAGE.
``` ```
Portions may be licensed under different licenses (in particular `public_suffix_list.dat` is MPL/2.0); please read that file and the LICENSE file for full details.
...@@ -31,18 +31,17 @@ ...@@ -31,18 +31,17 @@
'use strict'; 'use strict';
var net = require('net'); var net = require('net');
var urlParse = require('url').parse; var urlParse = require('url').parse;
var util = require('util'); var pubsuffix = require('./pubsuffix');
var pubsuffix = require('./pubsuffix-psl');
var Store = require('./store').Store; var Store = require('./store').Store;
var MemoryCookieStore = require('./memstore').MemoryCookieStore; var MemoryCookieStore = require('./memstore').MemoryCookieStore;
var pathMatch = require('./pathMatch').pathMatch; var pathMatch = require('./pathMatch').pathMatch;
var VERSION = require('./version'); var VERSION = require('../package.json').version;
var punycode; var punycode;
try { try {
punycode = require('punycode'); punycode = require('punycode');
} catch(e) { } catch(e) {
console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization"); console.warn("cookie: can't load punycode; won't use punycode for domain normalization");
} }
// From RFC6265 S4.1.1 // From RFC6265 S4.1.1
...@@ -757,12 +756,6 @@ Cookie.prototype.inspect = function inspect() { ...@@ -757,12 +756,6 @@ Cookie.prototype.inspect = function inspect() {
'"'; '"';
}; };
// Use the new custom inspection symbol to add the custom inspect function if
// available.
if (util.inspect.custom) {
Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect;
}
Cookie.prototype.toJSON = function() { Cookie.prototype.toJSON = function() {
var obj = {}; var obj = {};
...@@ -1371,6 +1364,7 @@ CookieJar.deserializeSync = function(strOrObj, store) { ...@@ -1371,6 +1364,7 @@ CookieJar.deserializeSync = function(strOrObj, store) {
}; };
CookieJar.fromJSON = CookieJar.deserializeSync; CookieJar.fromJSON = CookieJar.deserializeSync;
CAN_BE_SYNC.push('clone');
CookieJar.prototype.clone = function(newStore, cb) { CookieJar.prototype.clone = function(newStore, cb) {
if (arguments.length === 1) { if (arguments.length === 1) {
cb = newStore; cb = newStore;
...@@ -1381,61 +1375,10 @@ CookieJar.prototype.clone = function(newStore, cb) { ...@@ -1381,61 +1375,10 @@ CookieJar.prototype.clone = function(newStore, cb) {
if (err) { if (err) {
return cb(err); return cb(err);
} }
CookieJar.deserialize(serialized, newStore, cb); CookieJar.deserialize(newStore, serialized, cb);
});
};
CAN_BE_SYNC.push('removeAllCookies');
CookieJar.prototype.removeAllCookies = function(cb) {
var store = this.store;
// Check that the store implements its own removeAllCookies(). The default
// implementation in Store will immediately call the callback with a "not
// implemented" Error.
if (store.removeAllCookies instanceof Function &&
store.removeAllCookies !== Store.prototype.removeAllCookies)
{
return store.removeAllCookies(cb);
}
store.getAllCookies(function(err, cookies) {
if (err) {
return cb(err);
}
if (cookies.length === 0) {
return cb(null);
}
var completedCount = 0;
var removeErrors = [];
function removeCookieCb(removeErr) {
if (removeErr) {
removeErrors.push(removeErr);
}
completedCount++;
if (completedCount === cookies.length) {
return cb(removeErrors.length ? removeErrors[0] : null);
}
}
cookies.forEach(function(cookie) {
store.removeCookie(cookie.domain, cookie.path, cookie.key, removeCookieCb);
});
}); });
}; };
CookieJar.prototype._cloneSync = syncWrap('clone');
CookieJar.prototype.cloneSync = function(newStore) {
if (!newStore.synchronous) {
throw new Error('CookieJar clone destination store is not synchronous; use async API instead.');
}
return this._cloneSync(newStore);
};
// Use a closure to provide a true imperative API for synchronous stores. // Use a closure to provide a true imperative API for synchronous stores.
function syncWrap(method) { function syncWrap(method) {
return function() { return function() {
...@@ -1463,20 +1406,21 @@ CAN_BE_SYNC.forEach(function(method) { ...@@ -1463,20 +1406,21 @@ CAN_BE_SYNC.forEach(function(method) {
CookieJar.prototype[method+'Sync'] = syncWrap(method); CookieJar.prototype[method+'Sync'] = syncWrap(method);
}); });
exports.version = VERSION; module.exports = {
exports.CookieJar = CookieJar; CookieJar: CookieJar,
exports.Cookie = Cookie; Cookie: Cookie,
exports.Store = Store; Store: Store,
exports.MemoryCookieStore = MemoryCookieStore; MemoryCookieStore: MemoryCookieStore,
exports.parseDate = parseDate; parseDate: parseDate,
exports.formatDate = formatDate; formatDate: formatDate,
exports.parse = parse; parse: parse,
exports.fromJSON = fromJSON; fromJSON: fromJSON,
exports.domainMatch = domainMatch; domainMatch: domainMatch,
exports.defaultPath = defaultPath; defaultPath: defaultPath,
exports.pathMatch = pathMatch; pathMatch: pathMatch,
exports.getPublicSuffix = pubsuffix.getPublicSuffix; getPublicSuffix: pubsuffix.getPublicSuffix,
exports.cookieCompare = cookieCompare; cookieCompare: cookieCompare,
exports.permuteDomain = require('./permuteDomain').permuteDomain; permuteDomain: require('./permuteDomain').permuteDomain,
exports.permutePath = permutePath; permutePath: permutePath,
exports.canonicalDomain = canonicalDomain; canonicalDomain: canonicalDomain
};
...@@ -50,12 +50,6 @@ MemoryCookieStore.prototype.inspect = function() { ...@@ -50,12 +50,6 @@ MemoryCookieStore.prototype.inspect = function() {
return "{ idx: "+util.inspect(this.idx, false, 2)+' }'; return "{ idx: "+util.inspect(this.idx, false, 2)+' }';
}; };
// Use the new custom inspection symbol to add the custom inspect function if
// available.
if (util.inspect.custom) {
MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect;
}
MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) { MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) {
if (!this.idx[domain]) { if (!this.idx[domain]) {
return cb(null,undefined); return cb(null,undefined);
...@@ -149,11 +143,6 @@ MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) { ...@@ -149,11 +143,6 @@ MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) {
return cb(null); return cb(null);
}; };
MemoryCookieStore.prototype.removeAllCookies = function(cb) {
this.idx = {};
return cb(null);
}
MemoryCookieStore.prototype.getAllCookies = function(cb) { MemoryCookieStore.prototype.getAllCookies = function(cb) {
var cookies = []; var cookies = [];
var idx = this.idx; var idx = this.idx;
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
* POSSIBILITY OF SUCH DAMAGE. * POSSIBILITY OF SUCH DAMAGE.
*/ */
"use strict"; "use strict";
var pubsuffix = require('./pubsuffix-psl'); var pubsuffix = require('./pubsuffix');
// Gives the permutation of all possible domainMatch()es of a given domain. The // Gives the permutation of all possible domainMatch()es of a given domain. The
// array is in shortest-to-longest order. Handy for indexing. // array is in shortest-to-longest order. Handy for indexing.
......
/*!
* Copyright (c) 2018, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var psl = require('psl');
function getPublicSuffix(domain) {
return psl.get(domain);
}
exports.getPublicSuffix = getPublicSuffix;
...@@ -66,10 +66,6 @@ Store.prototype.removeCookies = function(domain, path, cb) { ...@@ -66,10 +66,6 @@ Store.prototype.removeCookies = function(domain, path, cb) {
throw new Error('removeCookies is not implemented'); throw new Error('removeCookies is not implemented');
}; };
Store.prototype.removeAllCookies = function(cb) {
throw new Error('removeAllCookies is not implemented');
}
Store.prototype.getAllCookies = function(cb) { Store.prototype.getAllCookies = function(cb) {
throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)'); throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)');
}; };
// generated by genversion
module.exports = '2.5.0'
{ {
"_from": "tough-cookie@~2.5.0", "_from": "tough-cookie@~2.3.0",
"_id": "tough-cookie@2.5.0", "_id": "tough-cookie@2.3.4",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", "_integrity": "sha512-TZ6TTfI5NtZnuyy/Kecv+CnoROnyXn2DN97LontgQpCwsX2XyLYCC0ENhYkehSOwAp8rTQKc/NUIF7BkQ5rKLA==",
"_location": "/tough-cookie", "_location": "/tough-cookie",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "range", "type": "range",
"registry": true, "registry": true,
"raw": "tough-cookie@~2.5.0", "raw": "tough-cookie@~2.3.0",
"name": "tough-cookie", "name": "tough-cookie",
"escapedName": "tough-cookie", "escapedName": "tough-cookie",
"rawSpec": "~2.5.0", "rawSpec": "~2.3.0",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "~2.5.0" "fetchSpec": "~2.3.0"
}, },
"_requiredBy": [ "_requiredBy": [
"/request" "/request"
], ],
"_resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", "_resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.4.tgz",
"_shasum": "cd9fb2a0aa1d5a12b473bd9fb96fa3dcff65ade2", "_shasum": "ec60cee38ac675063ffc97a5c18970578ee83655",
"_spec": "tough-cookie@~2.5.0", "_spec": "tough-cookie@~2.3.0",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\TV3\\NewVersion01\\dev\\node_modules\\request", "_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\Main\\02_Plattform_Main\\m4labplatform\\node_modules\\request",
"author": { "author": {
"name": "Jeremy Stashewsky", "name": "Jeremy Stashewsky",
"email": "jstash@gmail.com" "email": "jstashewsky@salesforce.com"
}, },
"bugs": { "bugs": {
"url": "https://github.com/salesforce/tough-cookie/issues" "url": "https://github.com/salesforce/tough-cookie/issues"
...@@ -51,17 +51,14 @@ ...@@ -51,17 +51,14 @@
} }
], ],
"dependencies": { "dependencies": {
"psl": "^1.1.28", "punycode": "^1.4.1"
"punycode": "^2.1.1"
}, },
"deprecated": false, "deprecated": false,
"description": "RFC6265 Cookies and Cookie Jar for node.js", "description": "RFC6265 Cookies and Cookie Jar for node.js",
"devDependencies": { "devDependencies": {
"async": "^1.4.2", "async": "^1.4.2",
"genversion": "^2.1.0",
"nyc": "^11.6.0",
"string.prototype.repeat": "^0.2.0", "string.prototype.repeat": "^0.2.0",
"vows": "^0.8.2" "vows": "^0.8.1"
}, },
"engines": { "engines": {
"node": ">=0.8" "node": ">=0.8"
...@@ -88,9 +85,8 @@ ...@@ -88,9 +85,8 @@
"url": "git://github.com/salesforce/tough-cookie.git" "url": "git://github.com/salesforce/tough-cookie.git"
}, },
"scripts": { "scripts": {
"cover": "nyc --reporter=lcov --reporter=html vows test/*_test.js", "suffixup": "curl -o public_suffix_list.dat https://publicsuffix.org/list/public_suffix_list.dat && ./generate-pubsuffix.js",
"test": "vows test/*_test.js", "test": "vows test/*_test.js"
"version": "genversion lib/version.js && git add lib/version.js"
}, },
"version": "2.5.0" "version": "2.3.4"
} }
sudo: false
language: node_js
node_js:
- '0.10'
- '0.12'
- '4'
- '6'
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment