Merge pull request 'Fix assigning properties to non-writable error object (updated)' (#5) from ThePendulum/node-bhttp:readonly-error into master

Reviewed-on: #5
master
Sven Slootweg 3 years ago
commit 5539d06789

@ -43,9 +43,9 @@ You can donate using Bitcoin, PayPal, Gratipay, Flattr, cash-in-mail, SEPA trans
## Contributing
Pull requests welcome. Please make sure your modifications are in line with the overall code style, and ensure that you're editing the `.coffee` files, not the `.js` files.
Pull requests welcome. Please make sure your modifications are in line with the overall code style, and ensure that you're editing the `src/` files, not the `lib/` files.
Build tool of choice is `gulp`; simply run `gulp` while developing, and it will watch for changes.
Build tool of choice is `babel`; simply run `npm run build` while developing, and it will watch for changes.
Be aware that by making a pull request, you agree to release your modifications under the licenses stated above.

@ -4,13 +4,21 @@
// FIXME: Are arrays of streams in `data` correctly recognized as being streams?
// Core modules
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var urlUtil = require("url");
@ -127,40 +135,24 @@ function assign() {
var ofTypes = function ofTypes(obj, types) {
var match = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
var _iterator = _createForOfIteratorHelper(types),
_step;
try {
for (var _iterator = types[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var type = _step.value;
match = match || obj instanceof type;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
_iterator.e(err);
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
_iterator.f();
}
return match;
};
var addErrorData = function addErrorData(err, request, response, requestState) {
err.request = request;
err.response = response;
err.requestState = requestState;
return err;
};
var isStream = function isStream(obj) {
return obj != null && (ofTypes(obj, [stream.Readable, stream.Duplex, stream.Transform]) || obj.hasOwnProperty("_bhttpStreamWrapper"));
}; // Middleware
@ -299,11 +291,22 @@ var prepareOptions = function prepareOptions(request, response, requestState) {
return Promise.try(function () {
// Do some sanity checks - there are a number of options that cannot be used together
if ((request.options.formFields != null || request.options.files != null) && (request.options.inputStream != null || request.options.inputBuffer != null)) {
return Promise.reject(addErrorData(new bhttpErrors.ConflictingOptionsError("You cannot define both formFields/files and a raw inputStream or inputBuffer."), request, response, requestState));
return Promise.reject(new bhttpErrors.ConflictingOptionsError({
message: "You cannot define both formFields/files and a raw inputStream or inputBuffer.",
request: request,
response: response,
requestState: requestState
}));
}
if (request.options.encodeJSON && (request.options.inputStream != null || request.options.inputBuffer != null)) {
return Promise.reject(addErrorData(new bhttpErrors.ConflictingOptionsError("You cannot use both encodeJSON and a raw inputStream or inputBuffer.", undefined, "If you meant to JSON-encode the stream, you will currently have to do so manually."), request, response, requestState));
var _bhttpErrors$Conflict;
return Promise.reject(new bhttpErrors.ConflictingOptionsError((_bhttpErrors$Conflict = {
message: "You cannot use both encodeJSON and a raw inputStream or inputBuffer.",
response: "If you meant to JSON-encode the stream, you will currently have to do so manually.",
request: request
}, _defineProperty(_bhttpErrors$Conflict, "response", response), _defineProperty(_bhttpErrors$Conflict, "requestState", requestState), _bhttpErrors$Conflict)));
} // If the user plans on streaming the response, we need to disable the agent entirely - otherwise the streams will block the pool.
@ -372,12 +375,11 @@ var preparePayload = function preparePayload(request, response, requestState) {
fieldValue = [fieldValue];
}
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
var _iterator2 = _createForOfIteratorHelper(fieldValue),
_step2;
try {
for (var _iterator2 = fieldValue[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var valueElement = _step2.value;
var streamOptions;
@ -391,18 +393,9 @@ var preparePayload = function preparePayload(request, response, requestState) {
formDataObject.append(fieldName, valueElement, streamOptions);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
_iterator2.e(err);
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
_iterator2.f();
}
}
@ -411,7 +404,12 @@ var preparePayload = function preparePayload(request, response, requestState) {
return formDataObject.getHeaders();
}).then(function (headers) {
if (headers["content-transfer-encoding"] === "chunked" && !request.options.allowChunkedMultipart) {
return Promise.reject(addErrorData(new bhttpErrors.MultipartError("Most servers do not support chunked transfer encoding for multipart/form-data payloads, and we could not determine the length of all the input streams. See the documentation for more information."), request, response, requestState));
return Promise.reject(new bhttpErrors.MultipartError({
message: "Most servers do not support chunked transfer encoding for multipart/form-data payloads, and we could not determine the length of all the input streams. See the documentation for more information.",
request: request,
response: response,
requestState: requestState
}));
} else {
assign(request.options.headers, headers);
return Promise.resolve();
@ -517,7 +515,7 @@ var makeRequest = function makeRequest(request, response, requestState) {
var timeoutHandler = function timeoutHandler() {
debugRequest("a response timeout occurred!");
req.abort();
return reject(addErrorData(new bhttpErrors.ResponseTimeoutError("The response timed out.")));
return reject(new bhttpErrors.ResponseTimeoutError("The response timed out."));
};
timeoutTimer = setTimeout(timeoutHandler, request.responseOptions.responseTimeout);
@ -564,7 +562,7 @@ var makeRequest = function makeRequest(request, response, requestState) {
req.on("error", function (err) {
if (err.code === "ETIMEDOUT") {
debugRequest("a connection timeout occurred!");
return reject(addErrorData(new bhttpErrors.ConnectionTimeoutError("The connection timed out.")));
return reject(new bhttpErrors.ConnectionTimeoutError("The connection timed out."));
} else {
return reject(err);
}
@ -591,29 +589,20 @@ var processResponse = function processResponse(request, response, requestState)
if (request.cookieJar != null && response.headers["set-cookie"] != null) {
var promises = function () {
var result = [];
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
var _iterator3 = _createForOfIteratorHelper(response.headers["set-cookie"]),
_step3;
try {
for (var _iterator3 = response.headers["set-cookie"][Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var cookieHeader = _step3.value;
debugResponse("storing cookie: %s", cookieHeader);
result.push(request.cookieJar.set(cookieHeader, request.url));
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
_iterator3.e(err);
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
_iterator3.f();
}
return result;
@ -631,7 +620,7 @@ var processResponse = function processResponse(request, response, requestState)
if ([301, 302, 303, 307].includes(response.statusCode) && request.responseOptions.followRedirects) {
if (requestState.redirectHistory.length >= request.responseOptions.redirectLimit - 1) {
return Promise.reject(addErrorData(new bhttpErrors.RedirectError("The maximum amount of redirects ({request.responseOptions.redirectLimit}) was reached.")));
return Promise.reject(new bhttpErrors.RedirectError("The maximum amount of redirects ({request.responseOptions.redirectLimit}) was reached."));
} // 301: For GET and HEAD, redirect unchanged. For POST, PUT, PATCH, DELETE, "ask user" (in our case: throw an error.)
// 302: Redirect, change method to GET.
// 303: Redirect, change method to GET.
@ -649,10 +638,15 @@ var processResponse = function processResponse(request, response, requestState)
case "put":
case "patch":
case "delete":
return Promise.reject(addErrorData(new bhttpErrors.RedirectError("Encountered a 301 redirect for POST, PUT, PATCH or DELETE. RFC says we can't automatically continue."), request, response, requestState));
return Promise.reject(new bhttpErrors.RedirectError({
message: "Encountered a 301 redirect for POST, PUT, PATCH or DELETE. RFC says we can't automatically continue.",
request: request,
response: response,
requestState: requestState
}));
default:
return Promise.reject(addErrorData(new bhttpErrors.RedirectError("Encountered a 301 redirect, but not sure how to proceed for the ".concat(request.options.method.toUpperCase(), " method."))));
return Promise.reject(new bhttpErrors.RedirectError("Encountered a 301 redirect, but not sure how to proceed for the ".concat(request.options.method.toUpperCase(), " method.")));
}
case 302:
@ -661,7 +655,12 @@ var processResponse = function processResponse(request, response, requestState)
case 307:
if (request.containsStreams && !["get", "head"].includes(request.options.method)) {
return Promise.reject(addErrorData(new bhttpErrors.RedirectError("Encountered a 307 redirect for POST, PUT or DELETE, but your payload contained (single-use) streams. We therefore can't automatically follow the redirect."), request, response, requestState));
return Promise.reject(new bhttpErrors.RedirectError({
message: "Encountered a 307 redirect for POST, PUT or DELETE, but your payload contained (single-use) streams. We therefore can't automatically follow the redirect.",
request: request,
response: response,
requestState: requestState
}));
} else {
return redirectUnchanged(request, response, requestState);
}

@ -114,13 +114,6 @@ const ofTypes = function(obj, types) {
return match;
};
const addErrorData = function(err, request, response, requestState) {
err.request = request;
err.response = response;
err.requestState = requestState;
return err;
};
const isStream = obj => (obj != null) && (ofTypes(obj, [stream.Readable, stream.Duplex, stream.Transform]) || obj.hasOwnProperty("_bhttpStreamWrapper"));
// Middleware
@ -229,11 +222,17 @@ const prepareOptions = function(request, response, requestState) {
return Promise.try(function() {
// Do some sanity checks - there are a number of options that cannot be used together
if (((request.options.formFields != null) || (request.options.files != null)) && ((request.options.inputStream != null) || (request.options.inputBuffer != null))) {
return Promise.reject(addErrorData(new bhttpErrors.ConflictingOptionsError("You cannot define both formFields/files and a raw inputStream or inputBuffer."), request, response, requestState));
return Promise.reject(new bhttpErrors.ConflictingOptionsError({ message: "You cannot define both formFields/files and a raw inputStream or inputBuffer.", request, response, requestState }));
}
if (request.options.encodeJSON && ((request.options.inputStream != null) || (request.options.inputBuffer != null))) {
return Promise.reject(addErrorData(new bhttpErrors.ConflictingOptionsError("You cannot use both encodeJSON and a raw inputStream or inputBuffer.", undefined, "If you meant to JSON-encode the stream, you will currently have to do so manually."), request, response, requestState));
return Promise.reject(new bhttpErrors.ConflictingOptionsError({
message: "You cannot use both encodeJSON and a raw inputStream or inputBuffer.",
response: "If you meant to JSON-encode the stream, you will currently have to do so manually.",
request,
response,
requestState,
}));
}
// If the user plans on streaming the response, we need to disable the agent entirely - otherwise the streams will block the pool.
@ -316,7 +315,7 @@ const preparePayload = function(request, response, requestState) {
return Promise.try(() => formDataObject.getHeaders()).then(function(headers) {
if ((headers["content-transfer-encoding"] === "chunked") && !request.options.allowChunkedMultipart) {
return Promise.reject(addErrorData(new bhttpErrors.MultipartError("Most servers do not support chunked transfer encoding for multipart/form-data payloads, and we could not determine the length of all the input streams. See the documentation for more information."), request, response, requestState));
return Promise.reject(new bhttpErrors.MultipartError({ message: "Most servers do not support chunked transfer encoding for multipart/form-data payloads, and we could not determine the length of all the input streams. See the documentation for more information.", request, response, requestState }));
} else {
assign(request.options.headers, headers);
return Promise.resolve();
@ -425,7 +424,7 @@ const makeRequest = function(request, response, requestState) {
const timeoutHandler = function() {
debugRequest("a response timeout occurred!");
req.abort();
return reject(addErrorData(new bhttpErrors.ResponseTimeoutError("The response timed out.")));
return reject(new bhttpErrors.ResponseTimeoutError("The response timed out."));
};
timeoutTimer = setTimeout(timeoutHandler, request.responseOptions.responseTimeout);
@ -474,7 +473,7 @@ const makeRequest = function(request, response, requestState) {
req.on("error", function(err) {
if (err.code === "ETIMEDOUT") {
debugRequest("a connection timeout occurred!");
return reject(addErrorData(new bhttpErrors.ConnectionTimeoutError("The connection timed out.")));
return reject(new bhttpErrors.ConnectionTimeoutError("The connection timed out."));
} else {
return reject(err);
}
@ -517,7 +516,7 @@ const processResponse = function(request, response, requestState) {
if ([301, 302, 303, 307].includes(response.statusCode) && request.responseOptions.followRedirects) {
if (requestState.redirectHistory.length >= (request.responseOptions.redirectLimit - 1)) {
return Promise.reject(addErrorData(new bhttpErrors.RedirectError("The maximum amount of redirects ({request.responseOptions.redirectLimit}) was reached.")));
return Promise.reject(new bhttpErrors.RedirectError("The maximum amount of redirects ({request.responseOptions.redirectLimit}) was reached."));
}
// 301: For GET and HEAD, redirect unchanged. For POST, PUT, PATCH, DELETE, "ask user" (in our case: throw an error.)
@ -530,15 +529,15 @@ const processResponse = function(request, response, requestState) {
case "get": case "head":
return redirectUnchanged(request, response, requestState);
case "post": case "put": case "patch": case "delete":
return Promise.reject(addErrorData(new bhttpErrors.RedirectError("Encountered a 301 redirect for POST, PUT, PATCH or DELETE. RFC says we can't automatically continue."), request, response, requestState));
return Promise.reject(new bhttpErrors.RedirectError({ message: "Encountered a 301 redirect for POST, PUT, PATCH or DELETE. RFC says we can't automatically continue.", request, response, requestState }));
default:
return Promise.reject(addErrorData(new bhttpErrors.RedirectError(`Encountered a 301 redirect, but not sure how to proceed for the ${request.options.method.toUpperCase()} method.`)));
return Promise.reject(new bhttpErrors.RedirectError(`Encountered a 301 redirect, but not sure how to proceed for the ${request.options.method.toUpperCase()} method.`));
}
case 302: case 303:
return redirectGet(request, response, requestState);
case 307:
if (request.containsStreams && !["get", "head"].includes(request.options.method)) {
return Promise.reject(addErrorData(new bhttpErrors.RedirectError("Encountered a 307 redirect for POST, PUT or DELETE, but your payload contained (single-use) streams. We therefore can't automatically follow the redirect."), request, response, requestState));
return Promise.reject(new bhttpErrors.RedirectError({ message: "Encountered a 307 redirect for POST, PUT or DELETE, but your payload contained (single-use) streams. We therefore can't automatically follow the redirect.", request, response, requestState }));
} else {
return redirectUnchanged(request, response, requestState);
}

Loading…
Cancel
Save