Commit bf137ad8 authored by Patrick's avatar Patrick
Browse files

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

parent 0081cef7
......@@ -18,23 +18,19 @@ var defaults = {
var parseValues = function parseQueryStringValues(str, options) {
var obj = {};
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
var parts = cleanStr.split(options.delimiter, limit);
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var bracketEqualsPos = part.indexOf(']=');
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part, defaults.decoder);
key = options.decoder(part);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults.decoder);
val = options.decoder(part.slice(pos + 1), defaults.decoder);
key = options.decoder(part.slice(0, pos));
val = options.decoder(part.slice(pos + 1));
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
......@@ -46,38 +42,36 @@ var parseValues = function parseQueryStringValues(str, options) {
return obj;
};
var parseObject = function (chain, val, options) {
var leaf = val;
var parseObject = function parseObjectRecursive(chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
for (var i = chain.length - 1; i >= 0; --i) {
var obj;
var root = chain[i];
if (root === '[]') {
obj = [];
obj = obj.concat(leaf);
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)
!isNaN(index) &&
root !== cleanRoot &&
String(index) === cleanRoot &&
index >= 0 &&
(options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = leaf;
obj[index] = parseObject(chain, val, options);
} else {
obj[cleanRoot] = leaf;
obj[cleanRoot] = parseObject(chain, val, options);
}
}
leaf = obj;
}
return leaf;
return obj;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
......@@ -136,13 +130,12 @@ var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
};
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') {
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.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
......
......@@ -50,7 +50,7 @@ var stringify = function stringify( // eslint-disable-line func-name-matching
obj = serializeDate(obj);
} else if (obj === null) {
if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix;
return encoder && !encodeValuesOnly ? encoder(prefix) : prefix;
}
obj = '';
......@@ -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 (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder);
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))];
var keyValue = encodeValuesOnly ? prefix : encoder(prefix);
return [formatter(keyValue) + '=' + formatter(encoder(obj))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
......@@ -123,7 +123,7 @@ var stringify = function stringify( // eslint-disable-line func-name-matching
module.exports = function (object, opts) {
var obj = object;
var options = opts ? utils.assign({}, opts) : {};
var options = opts || {};
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
......@@ -139,7 +139,7 @@ module.exports = function (object, opts) {
var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly;
if (typeof options.format === 'undefined') {
options.format = formats['default'];
options.format = formats.default;
} else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
throw new TypeError('Unknown format option provided.');
}
......@@ -203,8 +203,5 @@ module.exports = function (object, opts) {
));
}
var joined = keys.join(delimiter);
var prefix = options.addQueryPrefix === true ? '?' : '';
return joined.length > 0 ? prefix + joined : '';
return keys.join(delimiter);
};
......@@ -11,30 +11,7 @@ var hexTable = (function () {
return array;
}());
var compactQueue = function compactQueue(queue) {
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) {
exports.arrayToObject = function (source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
......@@ -45,7 +22,7 @@ var arrayToObject = function arrayToObject(source, options) {
return obj;
};
var merge = function merge(target, source, options) {
exports.merge = function (target, source, options) {
if (!source) {
return target;
}
......@@ -70,14 +47,14 @@ var merge = function merge(target, source, options) {
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = arrayToObject(target, options);
mergeTarget = exports.arrayToObject(target, options);
}
if (Array.isArray(target) && Array.isArray(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
if (target[i] && typeof target[i] === 'object') {
target[i] = merge(target[i], item, options);
target[i] = exports.merge(target[i], item, options);
} else {
target.push(item);
}
......@@ -91,8 +68,8 @@ var merge = function merge(target, source, options) {
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (has.call(acc, key)) {
acc[key] = merge(acc[key], value, options);
if (Object.prototype.hasOwnProperty.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
......@@ -100,14 +77,7 @@ var merge = function merge(target, source, options) {
}, mergeTarget);
};
var assign = function assignSingleSource(target, source) {
return Object.keys(source).reduce(function (acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
var decode = function (str) {
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
......@@ -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.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
......@@ -129,13 +99,13 @@ var encode = function encode(str) {
var c = string.charCodeAt(i);
if (
c === 0x2D // -
|| c === 0x2E // .
|| c === 0x5F // _
|| c === 0x7E // ~
|| (c >= 0x30 && c <= 0x39) // 0-9
|| (c >= 0x41 && c <= 0x5A) // a-z
|| (c >= 0x61 && c <= 0x7A) // A-Z
c === 0x2D || // -
c === 0x2E || // .
c === 0x5F || // _
c === 0x7E || // ~
(c >= 0x30 && c <= 0x39) || // 0-9
(c >= 0x41 && c <= 0x5A) || // a-z
(c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
......@@ -158,56 +128,55 @@ var encode = function encode(str) {
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)]
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
+ hexTable[0x80 | (c & 0x3F)];
out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; // eslint-disable-line max-len
}
return out;
};
var compact = function compact(value) {
var queue = [{ obj: { o: value }, prop: 'o' }];
var refs = [];
exports.compact = function (obj, references) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
for (var i = 0; i < queue.length; ++i) {
var item = queue[i];
var obj = item.obj[item.prop];
refs.push(obj);
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
var val = obj[key];
if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
queue.push({ obj: obj, prop: key });
refs.push(val);
if (Array.isArray(obj)) {
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]';
};
var isBuffer = function isBuffer(obj) {
exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
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",
"_id": "qs@6.5.2",
"_from": "qs@~6.4.0",
"_id": "qs@6.4.0",
"_inBundle": false,
"_integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==",
"_integrity": "sha1-E+JtKK1rD/qpExLNO/cI7TUecjM=",
"_location": "/request/qs",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "qs@~6.5.2",
"raw": "qs@~6.4.0",
"name": "qs",
"escapedName": "qs",
"rawSpec": "~6.5.2",
"rawSpec": "~6.4.0",
"saveSpec": null,
"fetchSpec": "~6.5.2"
"fetchSpec": "~6.4.0"
},
"_requiredBy": [
"/request"
],
"_resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz",
"_shasum": "cb3ae806e8740444584ef154ce8ee98d403f3e36",
"_spec": "qs@~6.5.2",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\TV3\\NewVersion01\\dev\\node_modules\\request",
"_resolved": "https://registry.npmjs.org/qs/-/qs-6.4.0.tgz",
"_shasum": "13e26d28ad6b0ffaa91312cd3bf708ed351e7233",
"_spec": "qs@~6.4.0",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\Main\\02_Plattform_Main\\m4labplatform\\node_modules\\request",
"bugs": {
"url": "https://github.com/ljharb/qs/issues"
},
......@@ -37,18 +37,17 @@
"deprecated": false,
"description": "A querystring parser that supports nesting and arrays, with a depth limit",
"devDependencies": {
"@ljharb/eslint-config": "^12.2.1",
"browserify": "^16.2.0",
"@ljharb/eslint-config": "^11.0.0",
"browserify": "^14.1.0",
"covert": "^1.1.0",
"editorconfig-tools": "^0.1.1",
"eslint": "^4.19.1",
"eslint": "^3.17.0",
"evalmd": "^0.0.17",
"iconv-lite": "^0.4.21",
"iconv-lite": "^0.4.15",
"mkdirp": "^0.5.1",
"parallelshell": "^2.0.0",
"qs-iconv": "^1.0.4",
"safe-publish-latest": "^1.1.1",
"safer-buffer": "^2.1.2",
"tape": "^4.9.0"
"tape": "^4.6.3"
},
"engines": {
"node": ">=0.6"
......@@ -69,12 +68,11 @@
"coverage": "covert test",
"dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js",
"lint": "eslint lib/*.js test/*.js",
"prelint": "editorconfig-tools check * lib/* test/*",
"prepublish": "safe-publish-latest && npm run dist",
"pretest": "npm run --silent readme && npm run --silent lint",
"readme": "evalmd README.md",
"test": "npm run --silent coverage",
"tests-only": "node test"
},
"version": "6.5.2"
"version": "6.4.0"
}
{
"rules": {
"array-bracket-newline": 0,
"array-element-newline": 0,
"consistent-return": 2,
"max-lines": 0,
"max-nested-callbacks": [2, 3],
"max-statements": 0,
"no-buffer-constructor": 0,
"no-extend-native": 0,
"no-magic-numbers": 0,
"object-curly-newline": 0,
"sort-keys": 0
}
}
......@@ -2,9 +2,7 @@
var test = require('tape');
var qs = require('../');
var utils = require('../lib/utils');
var iconv = require('iconv-lite');
var SaferBuffer = require('safer-buffer').Buffer;
test('parse()', function (t) {
t.test('parses a simple string', function (st) {
......@@ -232,7 +230,7 @@ test('parse()', function (t) {
});
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.end();
});
......@@ -306,13 +304,6 @@ test('parse()', function (t) {
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) {
var input = {
'user[name]': { 'pop[bob]': 3 },
......@@ -397,33 +388,6 @@ test('parse()', function (t) {
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) {
var a = Object.create(null);
a.b = 'c';
......@@ -540,35 +504,16 @@ test('parse()', function (t) {
result.push(parseInt(parts[1], 16));
parts = reg.exec(str);
}
return iconv.decode(SaferBuffer.from(result), 'shift_jis').toString();
return iconv.decode(new Buffer(result), 'shift_jis').toString();
}
}), { 県: '大阪府' });
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) {
st['throws'](function () {
st.throws(function () {
qs.parse({}, { decoder: 'string' });
}, new TypeError('Decoder has to be a function.'));
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 @@
var test = require('tape');
var qs = require('../');
var utils = require('../lib/utils');
var iconv = require('iconv-lite');
var SaferBuffer = require('safer-buffer').Buffer;
test('stringify()', function (t) {
t.test('stringifies a querystring object', function (st) {
......@@ -19,16 +17,6 @@ test('stringify()', function (t) {
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) {
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');
......@@ -337,8 +325,8 @@ test('stringify()', function (t) {
});
t.test('stringifies buffer values', function (st) {
st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test');
st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test');
st.equal(qs.stringify({ a: new Buffer('test') }), 'a=test');
st.equal(qs.stringify({ a: { b: new Buffer('test') } }), 'a%5Bb%5D=test');
st.end();
});
......@@ -464,25 +452,15 @@ test('stringify()', function (t) {
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) {
st['throws'](function () {
st.throws(function () {
qs.stringify({}, { encoder: 'string' });
}, new TypeError('Encoder has to be a function.'));
st.end();
});
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) {
if (typeof buffer === 'string') {
return buffer;
......@@ -505,7 +483,7 @@ test('stringify()', function (t) {
mutatedDate.toISOString = function () {
throw new SyntaxError();
};
st['throws'](function () {
st.throws(function () {
mutatedDate.toISOString();
}, SyntaxError);
st.equal(
......@@ -547,7 +525,7 @@ test('stringify()', function (t) {
t.test('Edge cases and unknown formats', function (st) {
['UFO1234', false, 1234, null, {}, []].forEach(
function (format) {
st['throws'](
st.throws(
function () {
qs.stringify({ a: 'b c' }, { format: format });
},
......@@ -586,12 +564,4 @@ test('stringify()', function (t) {
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) {
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",
"_id": "request@2.88.2",
"_from": "request@2.81.0",
"_id": "request@2.81.0",
"_inBundle": false,
"_integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==",
"_integrity": "sha1-xpKJRqDgbF+Nb4qTM0af/aRimKA=",
"_location": "/request",
"_phantomChildren": {
"asynckit": "0.4.0",
......@@ -10,22 +10,24 @@
"mime-types": "2.1.25"
},
"_requested": {
"type": "range",
"type": "version",
"registry": true,
"raw": "request@>=2.9.0",
"raw": "request@2.81.0",
"name": "request",
"escapedName": "request",
"rawSpec": ">=2.9.0",
"rawSpec": "2.81.0",
"saveSpec": null,
"fetchSpec": ">=2.9.0"
"fetchSpec": "2.81.0"
},
"_requiredBy": [
"#USER",
"/",
"/soap"
],
"_resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz",
"_shasum": "d73c918731cb5a87da047e207234146f664d12b3",
"_spec": "request@>=2.9.0",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\TV3\\NewVersion01\\dev\\node_modules\\soap",
"_resolved": "https://registry.npmjs.org/request/-/request-2.81.0.tgz",
"_shasum": "c6928946a0e06c5f8d6f8a9333469ffda46298a0",
"_spec": "request@2.81.0",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\Main\\02_Plattform_Main\\m4labplatform",
"author": {
"name": "Mikeal Rogers",
"email": "mikeal.rogers@gmail.com"
......@@ -35,26 +37,28 @@
},
"bundleDependencies": false,
"dependencies": {
"aws-sign2": "~0.7.0",
"aws4": "^1.8.0",
"aws-sign2": "~0.6.0",
"aws4": "^1.2.1",
"caseless": "~0.12.0",
"combined-stream": "~1.0.6",
"extend": "~3.0.2",
"combined-stream": "~1.0.5",
"extend": "~3.0.0",
"forever-agent": "~0.6.1",
"form-data": "~2.3.2",
"har-validator": "~5.1.3",
"http-signature": "~1.2.0",
"form-data": "~2.1.1",
"har-validator": "~4.2.1",
"hawk": "~3.1.3",
"http-signature": "~1.1.0",
"is-typedarray": "~1.0.0",
"isstream": "~0.1.2",
"json-stringify-safe": "~5.0.1",
"mime-types": "~2.1.19",
"oauth-sign": "~0.9.0",
"performance-now": "^2.1.0",
"qs": "~6.5.2",
"safe-buffer": "^5.1.2",
"tough-cookie": "~2.5.0",
"mime-types": "~2.1.7",
"oauth-sign": "~0.8.1",
"performance-now": "^0.2.0",
"qs": "~6.4.0",
"safe-buffer": "^5.0.1",
"stringstream": "~0.0.4",
"tough-cookie": "~2.3.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",
"description": "Simplified HTTP request client.",
......@@ -63,25 +67,25 @@
"browserify": "^13.0.1",
"browserify-istanbul": "^2.0.0",
"buffer-equal": "^1.0.0",
"codecov": "^3.0.4",
"coveralls": "^3.0.2",
"codecov": "^1.0.1",
"coveralls": "^2.11.4",
"eslint": "^2.5.3",
"function-bind": "^1.0.2",
"karma": "^3.0.0",
"istanbul": "^0.4.0",
"karma": "^1.1.1",
"karma-browserify": "^5.0.1",
"karma-cli": "^1.0.0",
"karma-coverage": "^1.0.0",
"karma-phantomjs-launcher": "^1.0.0",
"karma-tap": "^3.0.1",
"nyc": "^14.1.1",
"phantomjs-prebuilt": "^2.1.3",
"rimraf": "^2.2.8",
"server-destroy": "^1.0.1",
"standard": "^9.0.0",
"tape": "^4.6.0",
"taper": "^0.5.0"
},
"engines": {
"node": ">= 6"
"node": ">= 4"
},
"files": [
"lib/",
......@@ -90,6 +94,7 @@
],
"greenkeeper": {
"ignore": [
"eslint",
"hawk",
"har-validator"
]
......@@ -109,11 +114,11 @@
"url": "git+https://github.com/request/request.git"
},
"scripts": {
"lint": "standard",
"lint": "eslint lib/ *.js tests/ && echo Lint passed.",
"test": "npm run lint && npm run test-ci && npm run test-browser",
"test-browser": "node tests/browser/start.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'
var http = require('http')
var https = require('https')
var url = require('url')
var util = require('util')
var stream = require('stream')
var zlib = require('zlib')
var aws2 = require('aws-sign2')
var aws4 = require('aws4')
var httpSignature = require('http-signature')
var mime = require('mime-types')
var caseless = require('caseless')
var ForeverAgent = require('forever-agent')
var FormData = require('form-data')
var extend = require('extend')
var isstream = require('isstream')
var isTypedArray = require('is-typedarray').strict
var helpers = require('./lib/helpers')
var cookies = require('./lib/cookies')
var getProxyFromURI = require('./lib/getProxyFromURI')
var Querystring = require('./lib/querystring').Querystring
var Har = require('./lib/har').Har
var Auth = require('./lib/auth').Auth
var OAuth = require('./lib/oauth').OAuth
var hawk = require('./lib/hawk')
var Multipart = require('./lib/multipart').Multipart
var Redirect = require('./lib/redirect').Redirect
var Tunnel = require('./lib/tunnel').Tunnel
var now = require('performance-now')
var Buffer = require('safe-buffer').Buffer
, https = require('https')
, url = require('url')
, util = require('util')
, stream = require('stream')
, zlib = require('zlib')
, hawk = require('hawk')
, aws2 = require('aws-sign2')
, aws4 = require('aws4')
, httpSignature = require('http-signature')
, mime = require('mime-types')
, stringstream = require('stringstream')
, caseless = require('caseless')
, ForeverAgent = require('forever-agent')
, FormData = require('form-data')
, extend = require('extend')
, isstream = require('isstream')
, isTypedArray = require('is-typedarray').strict
, helpers = require('./lib/helpers')
, cookies = require('./lib/cookies')
, getProxyFromURI = require('./lib/getProxyFromURI')
, Querystring = require('./lib/querystring').Querystring
, Har = require('./lib/har').Har
, Auth = require('./lib/auth').Auth
, OAuth = require('./lib/oauth').OAuth
, Multipart = require('./lib/multipart').Multipart
, Redirect = require('./lib/redirect').Redirect
, Tunnel = require('./lib/tunnel').Tunnel
, now = require('performance-now')
, Buffer = require('safe-buffer').Buffer
var safeStringify = helpers.safeStringify
var isReadStream = helpers.isReadStream
var toBase64 = helpers.toBase64
var defer = helpers.defer
var copy = helpers.copy
var version = helpers.version
var globalCookieJar = cookies.jar()
, isReadStream = helpers.isReadStream
, toBase64 = helpers.toBase64
, defer = helpers.defer
, copy = helpers.copy
, version = helpers.version
, globalCookieJar = cookies.jar()
var globalPool = {}
function filterForNonReserved (reserved, options) {
function filterForNonReserved(reserved, options) {
// Filter out properties that are not reserved.
// Reserved values are passed in at call site.
......@@ -54,7 +56,7 @@ function filterForNonReserved (reserved, options) {
return object
}
function filterOutReservedFunctions (reserved, options) {
function filterOutReservedFunctions(reserved, options) {
// Filter out properties that are functions and are reserved.
// Reserved values are passed in at call site.
......@@ -67,10 +69,11 @@ function filterOutReservedFunctions (reserved, options) {
}
}
return object
}
// Return a simpler request object to allow serialization
function requestToJSON () {
function requestToJSON() {
var self = this
return {
uri: self.uri,
......@@ -80,7 +83,7 @@ function requestToJSON () {
}
// Return a simpler response object to allow serialization
function responseToJSON () {
function responseToJSON() {
var self = this
return {
statusCode: self.statusCode,
......@@ -131,7 +134,7 @@ util.inherits(Request, stream.Stream)
// Debugging
Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
function debug () {
function debug() {
if (Request.debug) {
console.error('REQUEST %s', util.format.apply(util, arguments))
}
......@@ -255,7 +258,7 @@ Request.prototype.init = function (options) {
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) {
// 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) {
self.setHost = false
if (!self.hasHeader('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)
// 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.jar(self._jar || options.jar)
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) {
......@@ -388,12 +388,12 @@ Request.prototype.init = function (options) {
}
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)
}
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(':'))
self.setHeader('proxy-authorization', authHeader)
}
......@@ -425,9 +425,11 @@ Request.prototype.init = function (options) {
var length
if (typeof self.body === 'string') {
length = Buffer.byteLength(self.body)
} else if (Array.isArray(self.body)) {
length = self.body.reduce(function (a, b) { return a + b.length }, 0)
} else {
}
else if (Array.isArray(self.body)) {
length = self.body.reduce(function (a, b) {return a + b.length}, 0)
}
else {
length = self.body.length
}
......@@ -449,8 +451,8 @@ Request.prototype.init = function (options) {
}
var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
var defaultModules = {'http:': http, 'https:': https}
var httpModules = self.httpModules || {}
, defaultModules = {'http:':http, 'https:':https}
, httpModules = self.httpModules || {}
self.httpModule = httpModules[protocol] || defaultModules[protocol]
......@@ -529,7 +531,8 @@ Request.prototype.init = function (options) {
if (self._form) {
if (!self._auth.hasAuth) {
self._form.pipe(self)
} else if (self._auth.hasAuth && self._auth.sentAuth) {
}
else if (self._auth.hasAuth && self._auth.sentAuth) {
self._form.pipe(self)
}
}
......@@ -580,6 +583,7 @@ Request.prototype.init = function (options) {
self.ntick = true
})
}
Request.prototype.getNewAgent = function () {
......@@ -774,22 +778,21 @@ Request.prototype.start = function () {
self.req.on('response', self.onRequestResponse.bind(self))
self.req.on('error', self.onRequestError.bind(self))
self.req.on('drain', function () {
self.req.on('drain', function() {
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
var isConnecting = socket._connecting || socket.connecting
if (self.timing) {
self.timings.socket = now() - self.startTimeNow
if (isConnecting) {
var onLookupTiming = function () {
var onLookupTiming = function() {
self.timings.lookup = now() - self.startTimeNow
}
var onConnectTiming = function () {
var onConnectTiming = function() {
self.timings.connect = now() - self.startTimeNow
}
......@@ -797,14 +800,14 @@ Request.prototype.start = function () {
socket.once('connect', onConnectTiming)
// 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('connect', onConnectTiming)
})
}
}
var setReqTimeout = function () {
var setReqTimeout = function() {
// This timeout sets the amount of time to wait *between* bytes sent
// from the server once connected.
//
......@@ -826,15 +829,16 @@ Request.prototype.start = function () {
// keep-alive connection) do not bother. This is important since we won't
// get a 'connect' event for an already connected socket.
if (isConnecting) {
var onReqSockConnect = function () {
var onReqSockConnect = function() {
socket.removeListener('connect', onReqSockConnect)
self.clearTimeout()
clearTimeout(self.timeoutTimer)
self.timeoutTimer = null
setReqTimeout()
}
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)
})
......@@ -866,14 +870,17 @@ Request.prototype.onRequestError = function (error) {
if (self._aborted) {
return
}
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' &&
self.agent.addRequestNoreuse) {
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
&& self.agent.addRequestNoreuse) {
self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
self.start()
self.req.end()
return
}
self.clearTimeout()
if (self.timeout && self.timeoutTimer) {
clearTimeout(self.timeoutTimer)
self.timeoutTimer = null
}
self.emit('error', error)
}
......@@ -885,7 +892,7 @@ Request.prototype.onRequestResponse = function (response) {
}
debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
response.on('end', function () {
response.on('end', function() {
if (self.timing) {
self.timings.end = now() - self.startTimeNow
response.timingStart = self.startTime
......@@ -960,11 +967,14 @@ Request.prototype.onRequestResponse = function (response) {
if (self.setHost) {
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 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 {
targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
} catch (e) {
......@@ -1000,13 +1010,13 @@ Request.prototype.onRequestResponse = function (response) {
var noBody = function (code) {
return (
self.method === 'HEAD' ||
self.method === 'HEAD'
// Informational
(code >= 100 && code < 200) ||
|| (code >= 100 && code < 200)
// No Content
code === 204 ||
|| code === 204
// Not Modified
code === 304
|| code === 304
)
}
......@@ -1020,8 +1030,8 @@ Request.prototype.onRequestResponse = function (response) {
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
var zlibOptions = {
flush: zlib.Z_SYNC_FLUSH,
finishFlush: zlib.Z_SYNC_FLUSH
flush: zlib.Z_SYNC_FLUSH
, finishFlush: zlib.Z_SYNC_FLUSH
}
if (contentEncoding === 'gzip') {
......@@ -1045,8 +1055,13 @@ Request.prototype.onRequestResponse = function (response) {
if (self.encoding) {
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.')
} else {
} else if (responseContent.setEncoding) {
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) {
responseContent.on('error', function (error) {
self.emit('error', error)
})
responseContent.on('close', function () { self.emit('close') })
responseContent.on('close', function () {self.emit('close')})
if (self.callback) {
self.readResponseBody(response)
} else { // if no callback
}
//if no callback
else {
self.on('end', function () {
if (self._aborted) {
debug('aborted', self.uri.href)
......@@ -1097,10 +1114,10 @@ Request.prototype.onRequestResponse = function (response) {
Request.prototype.readResponseBody = function (response) {
var self = this
debug("reading response's body")
debug('reading response\'s body')
var buffers = []
var bufferLength = 0
var strings = []
, bufferLength = 0
, strings = []
self.on('data', function (chunk) {
if (!Buffer.isBuffer(chunk)) {
......@@ -1161,11 +1178,11 @@ Request.prototype.abort = function () {
if (self.req) {
self.req.abort()
} else if (self.response) {
}
else if (self.response) {
self.response.destroy()
}
self.clearTimeout()
self.emit('abort')
}
......@@ -1178,7 +1195,8 @@ Request.prototype.pipeDest = function (dest) {
var ctname = response.caseless.has('content-type')
if (dest.setHeader) {
dest.setHeader(ctname, response.headers[ctname])
} else {
}
else {
dest.headers[ctname] = response.headers[ctname]
}
}
......@@ -1249,7 +1267,7 @@ Request.prototype.form = function (form) {
}
// create form-data object
self._form = new FormData()
self._form.on('error', function (err) {
self._form.on('error', function(err) {
err.message = 'form-data: ' + err.message
self.emit('error', err)
self.abort()
......@@ -1324,8 +1342,8 @@ Request.prototype.getHeader = function (name, headers) {
Request.prototype.enableUnixSocket = function () {
// Get the socket & request paths from the URL
var unixParts = this.uri.path.split(':')
var host = unixParts[0]
var path = unixParts[1]
, host = unixParts[0]
, path = unixParts[1]
// Apply unix properties to request
this.socketPath = host
this.uri.pathname = path
......@@ -1335,6 +1353,7 @@ Request.prototype.enableUnixSocket = function () {
this.uri.isUnix = true
}
Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
var self = this
......@@ -1350,18 +1369,17 @@ Request.prototype.aws = function (opts, now) {
return self
}
if (opts.sign_version === 4 || opts.sign_version === '4') {
if (opts.sign_version == 4 || opts.sign_version == '4') {
// use aws4
var options = {
host: self.uri.host,
path: self.uri.path,
method: self.method,
headers: self.headers,
headers: {
'content-type': self.getHeader('content-type') || ''
},
body: self.body
}
if (opts.service) {
options.service = opts.service
}
var signRes = aws4.sign(options, {
accessKeyId: opts.key,
secretAccessKey: opts.secret,
......@@ -1372,18 +1390,19 @@ Request.prototype.aws = function (opts, now) {
if (signRes.headers['X-Amz-Security-Token']) {
self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
}
} else {
}
else {
// default: use aws-sign2
var date = new Date()
self.setHeader('date', date.toUTCString())
var auth = {
key: opts.key,
secret: opts.secret,
verb: self.method.toUpperCase(),
date: date,
contentType: self.getHeader('content-type') || '',
md5: self.getHeader('content-md5') || '',
amazonHeaders: aws2.canonicalizeHeaders(self.headers)
var auth =
{ key: opts.key
, secret: opts.secret
, verb: self.method.toUpperCase()
, date: date
, contentType: self.getHeader('content-type') || ''
, md5: self.getHeader('content-md5') || ''
, amazonHeaders: aws2.canonicalizeHeaders(self.headers)
}
var path = self.uri.path
if (opts.bucket && path) {
......@@ -1404,10 +1423,10 @@ Request.prototype.aws = function (opts, now) {
Request.prototype.httpSignature = function (opts) {
var self = this
httpSignature.signRequest({
getHeader: function (header) {
getHeader: function(header) {
return self.getHeader(header, self.headers)
},
setHeader: function (header, value) {
setHeader: function(header, value) {
self.setHeader(header, value)
},
method: self.method,
......@@ -1419,7 +1438,7 @@ Request.prototype.httpSignature = function (opts) {
}
Request.prototype.hawk = function (opts) {
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) {
var self = this
......@@ -1442,15 +1461,15 @@ Request.prototype.jar = function (jar) {
cookies = false
self._disableCookies = true
} else {
var targetCookieJar = jar.getCookieString ? jar : globalCookieJar
var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
var urihref = self.uri.href
// fetch cookie in the Specified host
//fetch cookie in the Specified host
if (targetCookieJar) {
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 (self.originalCookieHeader) {
// Don't overwrite existing Cookie header
......@@ -1463,6 +1482,7 @@ Request.prototype.jar = function (jar) {
return self
}
// Stream API
Request.prototype.pipe = function (dest, opts) {
var self = this
......@@ -1485,7 +1505,7 @@ Request.prototype.pipe = function (dest, opts) {
}
Request.prototype.write = function () {
var self = this
if (self._aborted) { return }
if (self._aborted) {return}
if (!self._started) {
self.start()
......@@ -1496,7 +1516,7 @@ Request.prototype.write = function () {
}
Request.prototype.end = function (chunk) {
var self = this
if (self._aborted) { return }
if (self._aborted) {return}
if (chunk) {
self.write(chunk)
......@@ -1526,7 +1546,6 @@ Request.prototype.resume = function () {
}
Request.prototype.destroy = function () {
var self = this
this.clearTimeout()
if (!self._ended) {
self.end()
} else if (self.response) {
......@@ -1534,13 +1553,6 @@ Request.prototype.destroy = function () {
}
}
Request.prototype.clearTimeout = function () {
if (this.timeoutTimer) {
clearTimeout(this.timeoutTimer)
this.timeoutTimer = null
}
}
Request.defaultProxyHeaderWhiteList =
Tunnel.defaultProxyHeaderWhiteList.slice()
......
......@@ -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.
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
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)`
......@@ -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 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)`
......@@ -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.
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.
......@@ -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.
### `.canonicalizedDomain()`
### `.canonicalizedDoman()`
### `.cdomain()`
......@@ -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.
### `.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
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
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))`
_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.
Pass an error if retrieval fails.
**Note**: not all Stores can implement this due to technical limitations, so it is optional.
## MemoryCookieStore
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
......@@ -493,7 +473,7 @@ These are some Store implementations authored and maintained by the community. T
# Copyright and License
BSD-3-Clause:
(tl;dr: BSD-3-Clause with some MPL/2.0)
```text
Copyright (c) 2015, Salesforce.com, Inc.
......@@ -525,3 +505,5 @@ BSD-3-Clause:
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
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 @@
'use strict';
var net = require('net');
var urlParse = require('url').parse;
var util = require('util');
var pubsuffix = require('./pubsuffix-psl');
var pubsuffix = require('./pubsuffix');
var Store = require('./store').Store;
var MemoryCookieStore = require('./memstore').MemoryCookieStore;
var pathMatch = require('./pathMatch').pathMatch;
var VERSION = require('./version');
var VERSION = require('../package.json').version;
var punycode;
try {
punycode = require('punycode');
} 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
......@@ -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() {
var obj = {};
......@@ -1371,6 +1364,7 @@ CookieJar.deserializeSync = function(strOrObj, store) {
};
CookieJar.fromJSON = CookieJar.deserializeSync;
CAN_BE_SYNC.push('clone');
CookieJar.prototype.clone = function(newStore, cb) {
if (arguments.length === 1) {
cb = newStore;
......@@ -1381,61 +1375,10 @@ CookieJar.prototype.clone = function(newStore, cb) {
if (err) {
return cb(err);
}
CookieJar.deserialize(serialized, newStore, 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.deserialize(newStore, serialized, cb);
});
};
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.
function syncWrap(method) {
return function() {
......@@ -1463,20 +1406,21 @@ CAN_BE_SYNC.forEach(function(method) {
CookieJar.prototype[method+'Sync'] = syncWrap(method);
});
exports.version = VERSION;
exports.CookieJar = CookieJar;
exports.Cookie = Cookie;
exports.Store = Store;
exports.MemoryCookieStore = MemoryCookieStore;
exports.parseDate = parseDate;
exports.formatDate = formatDate;
exports.parse = parse;
exports.fromJSON = fromJSON;
exports.domainMatch = domainMatch;
exports.defaultPath = defaultPath;
exports.pathMatch = pathMatch;
exports.getPublicSuffix = pubsuffix.getPublicSuffix;
exports.cookieCompare = cookieCompare;
exports.permuteDomain = require('./permuteDomain').permuteDomain;
exports.permutePath = permutePath;
exports.canonicalDomain = canonicalDomain;
module.exports = {
CookieJar: CookieJar,
Cookie: Cookie,
Store: Store,
MemoryCookieStore: MemoryCookieStore,
parseDate: parseDate,
formatDate: formatDate,
parse: parse,
fromJSON: fromJSON,
domainMatch: domainMatch,
defaultPath: defaultPath,
pathMatch: pathMatch,
getPublicSuffix: pubsuffix.getPublicSuffix,
cookieCompare: cookieCompare,
permuteDomain: require('./permuteDomain').permuteDomain,
permutePath: permutePath,
canonicalDomain: canonicalDomain
};
......@@ -50,12 +50,6 @@ MemoryCookieStore.prototype.inspect = function() {
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) {
if (!this.idx[domain]) {
return cb(null,undefined);
......@@ -149,11 +143,6 @@ MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) {
return cb(null);
};
MemoryCookieStore.prototype.removeAllCookies = function(cb) {
this.idx = {};
return cb(null);
}
MemoryCookieStore.prototype.getAllCookies = function(cb) {
var cookies = [];
var idx = this.idx;
......
......@@ -29,7 +29,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
var pubsuffix = require('./pubsuffix-psl');
var pubsuffix = require('./pubsuffix');
// Gives the permutation of all possible domainMatch()es of a given domain. The
// 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) {
throw new Error('removeCookies is not implemented');
};
Store.prototype.removeAllCookies = function(cb) {
throw new Error('removeAllCookies is not implemented');
}
Store.prototype.getAllCookies = function(cb) {
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",
"_id": "tough-cookie@2.5.0",
"_from": "tough-cookie@~2.3.0",
"_id": "tough-cookie@2.3.4",
"_inBundle": false,
"_integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==",
"_integrity": "sha512-TZ6TTfI5NtZnuyy/Kecv+CnoROnyXn2DN97LontgQpCwsX2XyLYCC0ENhYkehSOwAp8rTQKc/NUIF7BkQ5rKLA==",
"_location": "/tough-cookie",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "tough-cookie@~2.5.0",
"raw": "tough-cookie@~2.3.0",
"name": "tough-cookie",
"escapedName": "tough-cookie",
"rawSpec": "~2.5.0",
"rawSpec": "~2.3.0",
"saveSpec": null,
"fetchSpec": "~2.5.0"
"fetchSpec": "~2.3.0"
},
"_requiredBy": [
"/request"
],
"_resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",
"_shasum": "cd9fb2a0aa1d5a12b473bd9fb96fa3dcff65ade2",
"_spec": "tough-cookie@~2.5.0",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\TV3\\NewVersion01\\dev\\node_modules\\request",
"_resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.4.tgz",
"_shasum": "ec60cee38ac675063ffc97a5c18970578ee83655",
"_spec": "tough-cookie@~2.3.0",
"_where": "C:\\Work\\OneDrive - bwstaff\\M4_Lab\\Main\\02_Plattform_Main\\m4labplatform\\node_modules\\request",
"author": {
"name": "Jeremy Stashewsky",
"email": "jstash@gmail.com"
"email": "jstashewsky@salesforce.com"
},
"bugs": {
"url": "https://github.com/salesforce/tough-cookie/issues"
......@@ -51,17 +51,14 @@
}
],
"dependencies": {
"psl": "^1.1.28",
"punycode": "^2.1.1"
"punycode": "^1.4.1"
},
"deprecated": false,
"description": "RFC6265 Cookies and Cookie Jar for node.js",
"devDependencies": {
"async": "^1.4.2",
"genversion": "^2.1.0",
"nyc": "^11.6.0",
"string.prototype.repeat": "^0.2.0",
"vows": "^0.8.2"
"vows": "^0.8.1"
},
"engines": {
"node": ">=0.8"
......@@ -88,9 +85,8 @@
"url": "git://github.com/salesforce/tough-cookie.git"
},
"scripts": {
"cover": "nyc --reporter=lcov --reporter=html vows test/*_test.js",
"test": "vows test/*_test.js",
"version": "genversion lib/version.js && git add lib/version.js"
"suffixup": "curl -o public_suffix_list.dat https://publicsuffix.org/list/public_suffix_list.dat && ./generate-pubsuffix.js",
"test": "vows test/*_test.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