From c1e4425ad64b36cc0e78b5e02c383acc7c3458b3 Mon Sep 17 00:00:00 2001 From: Nicolas Morel Date: Wed, 8 Nov 2023 12:04:25 +0100 Subject: [PATCH 01/50] chore: change CI target for next --- .github/workflows/ci-module.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/ci-module.yml b/.github/workflows/ci-module.yml index 54426ca..23bc524 100644 --- a/.github/workflows/ci-module.yml +++ b/.github/workflows/ci-module.yml @@ -9,6 +9,4 @@ on: jobs: test: - uses: hapijs/.github/.github/workflows/ci-module.yml@master - with: - min-node-version: 14 + uses: hapijs/.github/.github/workflows/ci-module.yml@min-node-18-hapi-21 From faf4cf64a4258699cb98911ee73ae866b8d915fe Mon Sep 17 00:00:00 2001 From: Nicolas Morel Date: Wed, 8 Nov 2023 16:21:32 +0100 Subject: [PATCH 02/50] chore: add next branch to CI targets --- .github/workflows/ci-module.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci-module.yml b/.github/workflows/ci-module.yml index 23bc524..44369c8 100644 --- a/.github/workflows/ci-module.yml +++ b/.github/workflows/ci-module.yml @@ -4,6 +4,7 @@ on: push: branches: - master + - next pull_request: workflow_dispatch: From 5c6f895944273e3a3df23ef7dcab3423ad26c44a Mon Sep 17 00:00:00 2001 From: Nicolas Morel Date: Wed, 23 Oct 2024 16:38:51 +0200 Subject: [PATCH 03/50] chore: bump lab --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 3bae608..b1d938f 100644 --- a/package.json +++ b/package.json @@ -22,8 +22,8 @@ }, "devDependencies": { "@hapi/code": "9.x.x", - "@hapi/eslint-plugin": "*", - "@hapi/lab": "^25.1.0", + "@hapi/eslint-plugin": "^7.0.0", + "@hapi/lab": "^26.0.0", "@types/node": "^17.0.31", "typescript": "~4.6.4" }, From 87ad2988345ed3550225c94f3cad8339b1b0999e Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Fri, 1 Dec 2023 15:14:34 +0100 Subject: [PATCH 04/50] Rework to be a regular class instance --- API.md | 6 -- lib/index.js | 161 ++++++++++++++++++++++++-------------------------- test/index.js | 136 ++++++++++++++++++------------------------ 3 files changed, 132 insertions(+), 171 deletions(-) diff --git a/API.md b/API.md index 022e361..9bff592 100755 --- a/API.md +++ b/API.md @@ -27,12 +27,6 @@ Rebuilds `error.output` using the other object properties where: - `debug` - a Boolean that, when `true`, causes Internal Server Error messages to be left in tact. Defaults to `false`, meaning that Internal Server Error messages are redacted. -Note that `Boom` object will return `true` when used with `instanceof Boom`, but do not use the -`Boom` prototype (they are either plain `Error` or the error prototype passed in). This means -`Boom` objects should only be tested using `instanceof Boom` or `Boom.isBoom()` but not by looking -at the prototype or contructor information. This limitation is to avoid manipulating the prototype -chain which is very slow. - #### Helper Methods ##### `new Boom.Boom(message, [options])` diff --git a/lib/index.js b/lib/index.js index 709b754..b446322 100755 --- a/lib/index.js +++ b/lib/index.js @@ -68,25 +68,32 @@ const internals = { exports.Boom = class extends Error { + isBoom = true; + isServer; + data = null; + output; + constructor(messageOrError, options = {}) { + let cause; + if (messageOrError instanceof Error) { - return exports.boomify(Hoek.clone(messageOrError), options); + cause = messageOrError; + messageOrError = options.message; + options.message = null; + } + else if (typeof messageOrError !== 'string') { + messageOrError = options.message; + options.message = null; } - const { statusCode = 500, data = null, ctor = exports.Boom } = options; - const error = new Error(messageOrError ? messageOrError : undefined); // Avoids settings null message - Error.captureStackTrace(error, ctor); // Filter the stack to our external API - error.data = data; - const boom = internals.initialize(error, statusCode); - - Object.defineProperty(boom, 'typeof', { value: ctor }); + const { statusCode = 500, data, decorate, message, ctor = exports.Boom } = options; - if (options.decorate) { - Object.assign(boom, options.decorate); - } + super(messageOrError ?? internals.codes.get(statusCode) ?? 'Unknown', { cause }); + Error.captureStackTrace(this, ctor); // Filter the stack to our external API + this._apply(data, decorate, statusCode, message); - return boom; + Object.defineProperty(this, 'typeof', { value: ctor }); } static [Symbol.hasInstance](instance) { @@ -99,40 +106,79 @@ exports.Boom = class extends Error { return this.prototype.isPrototypeOf(instance); } -}; + reformat(debug = false) { -exports.isBoom = function (err, statusCode) { + this.output.payload.statusCode = this.output.statusCode; + this.output.payload.error = internals.codes.get(this.output.statusCode) ?? 'Unknown'; - return err instanceof Error && !!err.isBoom && (!statusCode || err.output.statusCode === statusCode); -}; + if (this.output.statusCode === 500 && debug !== true) { + this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user + } + else { + this.output.payload.message = this.message; + if (this.cause?.message) { + this.output.payload.message = (this.message === this.output.payload.error) ? this.cause.message : this.message + ': ' + this.cause.message; + } + } + } + + _apply(data, decorate, statusCode, message) { + + if (data !== undefined) { + this.data = data; + } + if (decorate) { + Object.assign(this, decorate); + } -exports.boomify = function (err, options) { + if (statusCode) { + const numberCode = parseInt(statusCode, 10); + Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'statusCode must be a number (400+):', statusCode); - Hoek.assert(err instanceof Error, 'Cannot wrap non-Error object'); + this.isServer = numberCode >= 500; - options = options || {}; + this.output = { + statusCode: numberCode, + payload: {}, + headers: {} + }; - if (options.data !== undefined) { - err.data = options.data; - } + if (message) { + this.message = `${message}: ${this.message}`; + } - if (options.decorate) { - Object.assign(err, options.decorate); + this.reformat(); + } } +}; + + +exports.isBoom = function (err, statusCode) { + + return err instanceof Error && !!err.isBoom && (!statusCode || err.output.statusCode === statusCode); +}; + + +exports.boomify = function (err, options = {}) { + + Hoek.assert(err instanceof Error, 'Cannot boomify non-Error object'); if (!err.isBoom) { - return internals.initialize(err, options.statusCode ?? 500, options.message); + return new exports.Boom(err, options); } - if (options.override === false || // Defaults to true - !options.statusCode && !options.message) { + const { override, data, decorate, statusCode, message } = options; - return err; + if (override === false) { // Defaults to true + err._apply(data, decorate); + } + else { + err._apply(data, decorate, statusCode ?? err.output.statusCode, message); } - return internals.initialize(err, options.statusCode ?? err.output.statusCode, options.message); + return err; }; @@ -397,67 +443,12 @@ exports.badImplementation = function (message, data) { return err; }; - -internals.initialize = function (err, statusCode, message) { - - const numberCode = parseInt(statusCode, 10); - Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'First argument must be a number (400+):', statusCode); - - err.isBoom = true; - err.isServer = numberCode >= 500; - - if (!err.hasOwnProperty('data')) { - err.data = null; - } - - err.output = { - statusCode: numberCode, - payload: {}, - headers: {} - }; - - Object.defineProperty(err, 'reformat', { value: internals.reformat, configurable: true }); - - if (!message && - !err.message) { - - err.reformat(); - message = err.output.payload.error; - } - - if (message) { - const props = Object.getOwnPropertyDescriptor(err, 'message') || Object.getOwnPropertyDescriptor(Object.getPrototypeOf(err), 'message'); - Hoek.assert(!props || props.configurable && !props.get, 'The error is not compatible with boom'); - - err.message = message + (err.message ? ': ' + err.message : ''); - err.output.payload.message = err.message; - } - - err.reformat(); - return err; -}; - - -internals.reformat = function (debug = false) { - - this.output.payload.statusCode = this.output.statusCode; - this.output.payload.error = internals.codes.get(this.output.statusCode) || 'Unknown'; - - if (this.output.statusCode === 500 && debug !== true) { - this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user - } - else if (this.message) { - this.output.payload.message = this.message; - } -}; - - internals.serverError = function (messageOrError, data, statusCode, ctor) { if (data instanceof Error && !data.isBoom) { - return exports.boomify(data, { statusCode, message: messageOrError }); + return new exports.Boom(data, { statusCode, message: messageOrError, ctor }); } return new exports.Boom(messageOrError, { statusCode, data, ctor }); diff --git a/test/index.js b/test/index.js index 8c7c5a7..d3cb7e9 100755 --- a/test/index.js +++ b/test/index.js @@ -20,17 +20,8 @@ describe('Boom', () => { expect(err.output.payload.message).to.equal('oops'); expect(err.output.statusCode).to.equal(400); - expect(Object.keys(err)).to.equal(['data', 'isBoom', 'isServer', 'output']); - expect(JSON.stringify(err)).to.equal('{"data":null,"isBoom":true,"isServer":false,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}'); - }); - - it('clones error object', () => { - - const oops = new Error('oops'); - const err = new Boom.Boom(oops, { statusCode: 400 }); - expect(err).to.not.shallow.equal(oops); - expect(err.output.payload.message).to.equal('oops'); - expect(err.output.statusCode).to.equal(400); + expect(Object.keys(err)).to.equal(['isBoom', 'isServer', 'data', 'output']); + expect(JSON.stringify(err)).to.equal('{"isBoom":true,"isServer":false,"data":null,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}'); }); it('decorates error', () => { @@ -43,22 +34,23 @@ describe('Boom', () => { it('handles missing message', () => { - const err = new Error(); - Boom.boomify(err); + const err = new Boom.Boom(new Error()); expect(Boom.isBoom(err)).to.be.true(); + expect(err.message).to.equal('Internal Server Error'); }); - it('handles missing message (class)', () => { + it('handles missing message with unknown statusCode', () => { - const Example = class extends Error { + const err = new Boom.Boom(new Error(), { statusCode: 999 }); - constructor(message) { + expect(Boom.isBoom(err)).to.be.true(); + expect(err.message).to.equal('Unknown'); + }); - super(message); - Boom.boomify(this); - } - }; + it('handles missing message (subclass)', () => { + + const Example = class extends Boom.Boom {}; const err = new Example(); expect(Boom.isBoom(err)).to.be.true(); @@ -69,10 +61,10 @@ describe('Boom', () => { expect(() => { new Boom.Boom('message', { statusCode: 'x' }); - }).to.throw('First argument must be a number (400+): x'); + }).to.throw('statusCode must be a number (400+): x'); }); - it('errors on incompatible message property (prototype)', () => { + it('handles readonly error message property', () => { const Err = class extends Error { @@ -82,18 +74,12 @@ describe('Boom', () => { } }; - const err = new Err(); - expect(() => Boom.boomify(err, { message: 'override' })).to.throw('The error is not compatible with boom'); - }); - - it('errors on incompatible message property (own)', () => { - - const err = new Error(); - Object.defineProperty(err, 'message', { get: function () { } }); - expect(() => Boom.boomify(err, { message: 'override' })).to.throw('The error is not compatible with boom'); + const err = new Boom.Boom(new Err(), { message: 'override' }); + expect(Boom.isBoom(err)).to.be.true(); + expect(err.message).to.equal('override'); }); - it('will cast a number-string to an integer', () => { + it('will cast a statusCode number-string to an integer', () => { const codes = [ { input: '404', result: 404 }, @@ -114,7 +100,7 @@ describe('Boom', () => { expect(() => { new Boom.Boom('', { statusCode: 1 / 0 }); - }).to.throw('First argument must be a number (400+): null'); + }).to.throw('statusCode must be a number (400+): null'); }); it('sets error code to unknown', () => { @@ -127,32 +113,29 @@ describe('Boom', () => { it('identifies a boom object', () => { - const BadaBoom = class extends Boom.Boom { }; + const BadaBoom = class extends Boom.Boom {}; expect(new Boom.Boom('oops')).to.be.instanceOf(Boom.Boom); expect(new BadaBoom('oops')).to.be.instanceOf(Boom.Boom); expect(Boom.badRequest('oops')).to.be.instanceOf(Boom.Boom); expect(new Error('oops')).to.not.be.instanceOf(Boom.Boom); - expect(Boom.boomify(new Error('oops'))).to.be.instanceOf(Boom.Boom); expect({ isBoom: true }).to.not.be.instanceOf(Boom.Boom); expect(null).to.not.be.instanceOf(Boom.Boom); }); - it('returns false when called on sub-class', () => { + it('can be called on a sub-class', () => { const BadaBoom = class extends Boom.Boom {}; - expect(new Boom.Boom('oops')).to.not.be.instanceOf(BadaBoom); - expect(new BadaBoom('oops')).to.not.be.instanceOf(BadaBoom); - expect(Boom.badRequest('oops')).to.not.be.instanceOf(BadaBoom); - expect(Boom.boomify(new Error('oops'))).to.not.be.instanceOf(BadaBoom); - }); + // Success - it('handles actual sub-class instances when called on sub-class', () => { + expect(new BadaBoom('oops')).to.be.instanceOf(BadaBoom); + expect(Object.create(BadaBoom.prototype)).to.be.instanceOf(BadaBoom); - const BadaBoom = class extends Boom.Boom { }; + // Fail - expect(Object.create(BadaBoom.prototype)).to.be.instanceOf(BadaBoom); + expect(new Boom.Boom('oops')).to.not.be.instanceOf(BadaBoom); + expect(Boom.badRequest('oops')).to.not.be.instanceOf(BadaBoom); }); }); @@ -160,7 +143,12 @@ describe('Boom', () => { it('identifies a boom object', () => { + // Success + expect(Boom.isBoom(new Boom.Boom('oops'))).to.be.true(); + + // Fail + expect(Boom.isBoom(new Error('oops'))).to.be.false(); expect(Boom.isBoom({ isBoom: true })).to.be.false(); expect(Boom.isBoom(null)).to.be.false(); @@ -182,24 +170,22 @@ describe('Boom', () => { it('returns the same object when already boom', () => { const error = Boom.badRequest(); - expect(error).to.equal(Boom.boomify(error)); - expect(error).to.equal(Boom.boomify(error, { statusCode: 444 })); + expect(error).to.shallow.equal(Boom.boomify(error)); + expect(error).to.shallow.equal(Boom.boomify(error, { statusCode: 444 })); }); it('decorates error', () => { - const err = new Error('oops'); - Boom.boomify(err, { statusCode: 400, decorate: { x: 1 } }); + const error = new Error('oops'); + const err = Boom.boomify(error, { statusCode: 400, decorate: { x: 1 } }); expect(err.x).to.equal(1); }); it('returns an error with info when constructed using another error', () => { const error = new Error('ka-boom'); - error.xyz = 123; const err = Boom.boomify(error); - expect(err.xyz).to.equal(123); - expect(err.message).to.equal('ka-boom'); + expect(err.cause).to.shallow.equal(error); expect(err.output).to.equal({ statusCode: 500, payload: { @@ -212,14 +198,6 @@ describe('Boom', () => { expect(err.data).to.equal(null); }); - it('does not override data when constructed using another error', () => { - - const error = new Error('ka-boom'); - error.data = { useful: 'data' }; - const err = Boom.boomify(error); - expect(err.data).to.equal(error.data); - }); - it('sets new message when none exists', () => { const error = new Error(); @@ -243,9 +221,9 @@ describe('Boom', () => { const error = new Error('Missing data'); const boom = Boom.boomify(error); - expect(boom).to.shallow.equal(error); - expect(error.output.payload.message).to.equal('An internal server error occurred'); - expect(error.output.statusCode).to.equal(500); + expect(boom.cause).to.shallow.equal(error); + expect(boom.output.payload.message).to.equal('An internal server error occurred'); + expect(boom.output.statusCode).to.equal(500); }); it('overrides message and statusCode', () => { @@ -297,9 +275,9 @@ describe('Boom', () => { const error = new Error('Missing data'); const boom = Boom.boomify(error, { message: 'Override message', statusCode: 599, override: false }); - expect(boom).to.shallow.equal(error); - expect(error.output.payload.message).to.equal('Override message: Missing data'); - expect(error.output.statusCode).to.equal(599); + expect(boom.cause).to.shallow.equal(error); + expect(boom.output.payload.message).to.equal('Override message: Missing data'); + expect(boom.output.statusCode).to.equal(599); }); }); @@ -325,21 +303,16 @@ describe('Boom', () => { it('does not sets null message', () => { const err = new Error('some error message'); - const boom = Boom.boomify(err, { statusCode: 400, message: 'modified error message' }); + const boom = new Boom.Boom(err, { statusCode: 400, message: 'modified error message' }); expect(boom.output.payload.message).to.equal('modified error message: some error message'); }); }); - describe('isBoom()', () => { - - it('returns true for Boom object', () => { - - expect(Boom.badRequest().isBoom).to.equal(true); - }); + describe('isBoom', () => { - it('returns false for Error object', () => { + it('is true for Boom object', () => { - expect((new Error()).isBoom).to.not.exist(); + expect(Boom.badRequest().isBoom).to.be.true(); }); }); @@ -834,8 +807,11 @@ describe('Boom', () => { x.foo(); } catch (err) { - const boom = Boom.internal('Someting bad', err); - expect(boom.message).to.equal('Someting bad: x.foo is not a function'); + const boom = Boom.internal('Something bad', err); + boom.reformat(true); + expect(boom.message).to.equal('Something bad'); + expect(boom.cause).to.be.an.error(TypeError, 'x.foo is not a function'); + expect(boom.output.payload.message).to.equal('Something bad: x.foo is not a function'); expect(boom.isServer).to.be.true(); } }); @@ -980,13 +956,13 @@ describe('Boom', () => { 'badImplementation' ].forEach((name) => { - it(`should allow \`Boom${name}(err)\` and preserve the error`, () => { + it(`should allow \`Boom.${name}(err)\` and preserve the error`, () => { const error = new Error('An example mongoose validation error'); error.name = 'ValidationError'; const err = Boom[name](error); - expect(err.name).to.equal('ValidationError'); - expect(err.message).to.equal('An example mongoose validation error'); + expect(err.cause.name).to.equal('ValidationError'); + expect(err.cause.message).to.equal('An example mongoose validation error'); }); // exclude unauthorized @@ -1057,7 +1033,7 @@ describe('Boom', () => { it('displays internal server error messages in debug mode', () => { const error = new Error('ka-boom'); - const err = Boom.boomify(error, { statusCode: 500 }); + const err = new Boom.Boom(error, { statusCode: 500 }); err.reformat(false); expect(err.output).to.equal({ From 0f2eafdb1ec71917ee1d425d62bccf9a06accbda Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 4 Dec 2023 11:34:23 +0100 Subject: [PATCH 05/50] Tighten input types and make cause option explicit --- lib/index.js | 133 +++++++++++++++++++++++--------------------------- test/index.js | 49 +++++-------------- 2 files changed, 72 insertions(+), 110 deletions(-) diff --git a/lib/index.js b/lib/index.js index b446322..56af936 100755 --- a/lib/index.js +++ b/lib/index.js @@ -73,25 +73,14 @@ exports.Boom = class extends Error { data = null; output; - constructor(messageOrError, options = {}) { + constructor(message, options = {}) { - let cause; + const { statusCode = 500, data, decorate, ctor = exports.Boom } = options; - if (messageOrError instanceof Error) { - cause = messageOrError; - messageOrError = options.message; - options.message = null; - } - else if (typeof messageOrError !== 'string') { - messageOrError = options.message; - options.message = null; - } - - const { statusCode = 500, data, decorate, message, ctor = exports.Boom } = options; - - super(messageOrError ?? internals.codes.get(statusCode) ?? 'Unknown', { cause }); + super(message ?? internals.codes.get(statusCode) ?? 'Unknown', options); Error.captureStackTrace(this, ctor); // Filter the stack to our external API - this._apply(data, decorate, statusCode, message); + + this._apply(data, decorate, statusCode); Object.defineProperty(this, 'typeof', { value: ctor }); } @@ -165,12 +154,12 @@ exports.boomify = function (err, options = {}) { Hoek.assert(err instanceof Error, 'Cannot boomify non-Error object'); + const { override, data, decorate, statusCode, message } = options; + if (!err.isBoom) { - return new exports.Boom(err, options); + return new exports.Boom(message, { statusCode, cause: err, data, decorate }); } - const { override, data, decorate, statusCode, message } = options; - if (override === false) { // Defaults to true err._apply(data, decorate); } @@ -184,9 +173,9 @@ exports.boomify = function (err, options = {}) { // 4xx Client Errors -exports.badRequest = function (messageOrError, data) { +exports.badRequest = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 400, data, ctor: exports.badRequest }); + return new exports.Boom(message, { statusCode: 400, data, ctor: exports.badRequest }); }; @@ -251,27 +240,27 @@ exports.unauthorized = function (message, scheme, attributes) { // Or ( }; -exports.paymentRequired = function (messageOrError, data) { +exports.paymentRequired = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 402, data, ctor: exports.paymentRequired }); + return new exports.Boom(message, { statusCode: 402, data, ctor: exports.paymentRequired }); }; -exports.forbidden = function (messageOrError, data) { +exports.forbidden = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 403, data, ctor: exports.forbidden }); + return new exports.Boom(message, { statusCode: 403, data, ctor: exports.forbidden }); }; -exports.notFound = function (messageOrError, data) { +exports.notFound = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 404, data, ctor: exports.notFound }); + return new exports.Boom(message, { statusCode: 404, data, ctor: exports.notFound }); }; -exports.methodNotAllowed = function (messageOrError, data, allow) { +exports.methodNotAllowed = function (message, data, allow) { - const err = new exports.Boom(messageOrError, { statusCode: 405, data, ctor: exports.methodNotAllowed }); + const err = new exports.Boom(message, { statusCode: 405, data, ctor: exports.methodNotAllowed }); if (typeof allow === 'string') { allow = [allow]; @@ -285,122 +274,122 @@ exports.methodNotAllowed = function (messageOrError, data, allow) { }; -exports.notAcceptable = function (messageOrError, data) { +exports.notAcceptable = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 406, data, ctor: exports.notAcceptable }); + return new exports.Boom(message, { statusCode: 406, data, ctor: exports.notAcceptable }); }; -exports.proxyAuthRequired = function (messageOrError, data) { +exports.proxyAuthRequired = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 407, data, ctor: exports.proxyAuthRequired }); + return new exports.Boom(message, { statusCode: 407, data, ctor: exports.proxyAuthRequired }); }; -exports.clientTimeout = function (messageOrError, data) { +exports.clientTimeout = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 408, data, ctor: exports.clientTimeout }); + return new exports.Boom(message, { statusCode: 408, data, ctor: exports.clientTimeout }); }; -exports.conflict = function (messageOrError, data) { +exports.conflict = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 409, data, ctor: exports.conflict }); + return new exports.Boom(message, { statusCode: 409, data, ctor: exports.conflict }); }; -exports.resourceGone = function (messageOrError, data) { +exports.resourceGone = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 410, data, ctor: exports.resourceGone }); + return new exports.Boom(message, { statusCode: 410, data, ctor: exports.resourceGone }); }; -exports.lengthRequired = function (messageOrError, data) { +exports.lengthRequired = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 411, data, ctor: exports.lengthRequired }); + return new exports.Boom(message, { statusCode: 411, data, ctor: exports.lengthRequired }); }; -exports.preconditionFailed = function (messageOrError, data) { +exports.preconditionFailed = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 412, data, ctor: exports.preconditionFailed }); + return new exports.Boom(message, { statusCode: 412, data, ctor: exports.preconditionFailed }); }; -exports.entityTooLarge = function (messageOrError, data) { +exports.entityTooLarge = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 413, data, ctor: exports.entityTooLarge }); + return new exports.Boom(message, { statusCode: 413, data, ctor: exports.entityTooLarge }); }; -exports.uriTooLong = function (messageOrError, data) { +exports.uriTooLong = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 414, data, ctor: exports.uriTooLong }); + return new exports.Boom(message, { statusCode: 414, data, ctor: exports.uriTooLong }); }; -exports.unsupportedMediaType = function (messageOrError, data) { +exports.unsupportedMediaType = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 415, data, ctor: exports.unsupportedMediaType }); + return new exports.Boom(message, { statusCode: 415, data, ctor: exports.unsupportedMediaType }); }; -exports.rangeNotSatisfiable = function (messageOrError, data) { +exports.rangeNotSatisfiable = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 416, data, ctor: exports.rangeNotSatisfiable }); + return new exports.Boom(message, { statusCode: 416, data, ctor: exports.rangeNotSatisfiable }); }; -exports.expectationFailed = function (messageOrError, data) { +exports.expectationFailed = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 417, data, ctor: exports.expectationFailed }); + return new exports.Boom(message, { statusCode: 417, data, ctor: exports.expectationFailed }); }; -exports.teapot = function (messageOrError, data) { +exports.teapot = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 418, data, ctor: exports.teapot }); + return new exports.Boom(message, { statusCode: 418, data, ctor: exports.teapot }); }; -exports.badData = function (messageOrError, data) { +exports.badData = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 422, data, ctor: exports.badData }); + return new exports.Boom(message, { statusCode: 422, data, ctor: exports.badData }); }; -exports.locked = function (messageOrError, data) { +exports.locked = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 423, data, ctor: exports.locked }); + return new exports.Boom(message, { statusCode: 423, data, ctor: exports.locked }); }; -exports.failedDependency = function (messageOrError, data) { +exports.failedDependency = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 424, data, ctor: exports.failedDependency }); + return new exports.Boom(message, { statusCode: 424, data, ctor: exports.failedDependency }); }; -exports.tooEarly = function (messageOrError, data) { +exports.tooEarly = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 425, data, ctor: exports.tooEarly }); + return new exports.Boom(message, { statusCode: 425, data, ctor: exports.tooEarly }); }; -exports.preconditionRequired = function (messageOrError, data) { +exports.preconditionRequired = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 428, data, ctor: exports.preconditionRequired }); + return new exports.Boom(message, { statusCode: 428, data, ctor: exports.preconditionRequired }); }; -exports.tooManyRequests = function (messageOrError, data) { +exports.tooManyRequests = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 429, data, ctor: exports.tooManyRequests }); + return new exports.Boom(message, { statusCode: 429, data, ctor: exports.tooManyRequests }); }; -exports.illegal = function (messageOrError, data) { +exports.illegal = function (message, data) { - return new exports.Boom(messageOrError, { statusCode: 451, data, ctor: exports.illegal }); + return new exports.Boom(message, { statusCode: 451, data, ctor: exports.illegal }); }; @@ -443,13 +432,13 @@ exports.badImplementation = function (message, data) { return err; }; -internals.serverError = function (messageOrError, data, statusCode, ctor) { +internals.serverError = function (message, data, statusCode, ctor) { if (data instanceof Error && !data.isBoom) { - return new exports.Boom(data, { statusCode, message: messageOrError, ctor }); + return new exports.Boom(message, { statusCode, cause: data, ctor }); } - return new exports.Boom(messageOrError, { statusCode, data, ctor }); + return new exports.Boom(message, { statusCode, data, ctor }); }; diff --git a/test/index.js b/test/index.js index d3cb7e9..917ff08 100755 --- a/test/index.js +++ b/test/index.js @@ -34,7 +34,7 @@ describe('Boom', () => { it('handles missing message', () => { - const err = new Boom.Boom(new Error()); + const err = new Boom.Boom(); expect(Boom.isBoom(err)).to.be.true(); expect(err.message).to.equal('Internal Server Error'); @@ -42,7 +42,7 @@ describe('Boom', () => { it('handles missing message with unknown statusCode', () => { - const err = new Boom.Boom(new Error(), { statusCode: 999 }); + const err = new Boom.Boom(null, { statusCode: 999 }); expect(Boom.isBoom(err)).to.be.true(); expect(err.message).to.equal('Unknown'); @@ -64,21 +64,6 @@ describe('Boom', () => { }).to.throw('statusCode must be a number (400+): x'); }); - it('handles readonly error message property', () => { - - const Err = class extends Error { - - get message() { - - return 'x'; - } - }; - - const err = new Boom.Boom(new Err(), { message: 'override' }); - expect(Boom.isBoom(err)).to.be.true(); - expect(err.message).to.equal('override'); - }); - it('will cast a statusCode number-string to an integer', () => { const codes = [ @@ -283,7 +268,7 @@ describe('Boom', () => { describe('create()', () => { - it('does not sets null message', () => { + it('does not set null message', () => { const error = Boom.unauthorized(null); expect(error.output.payload.message).to.equal('Unauthorized'); @@ -300,11 +285,11 @@ describe('Boom', () => { describe('initialize()', () => { - it('does not sets null message', () => { + it('does not set null message', () => { - const err = new Error('some error message'); - const boom = new Boom.Boom(err, { statusCode: 400, message: 'modified error message' }); - expect(boom.output.payload.message).to.equal('modified error message: some error message'); + const err = new Error('some error'); + const boom = new Boom.Boom('prepended error message', { statusCode: 400, cause: err }); + expect(boom.output.payload.message).to.equal('prepended error message: some error'); }); }); @@ -956,26 +941,14 @@ describe('Boom', () => { 'badImplementation' ].forEach((name) => { - it(`should allow \`Boom.${name}(err)\` and preserve the error`, () => { + it(`uses stringified error as message`, () => { const error = new Error('An example mongoose validation error'); error.name = 'ValidationError'; const err = Boom[name](error); - expect(err.cause.name).to.equal('ValidationError'); - expect(err.cause.message).to.equal('An example mongoose validation error'); + expect(err.cause).to.not.exist(); + expect(err.message).to.equal(error.toString()); }); - - // exclude unauthorized - - if (name !== 'unauthorized') { - - it(`should allow \`Boom.${name}(err, data)\` and preserve the data`, () => { - - const error = new Error(); - const err = Boom[name](error, { foo: 'bar' }); - expect(err.data).to.equal({ foo: 'bar' }); - }); - } }); }); @@ -1033,7 +1006,7 @@ describe('Boom', () => { it('displays internal server error messages in debug mode', () => { const error = new Error('ka-boom'); - const err = new Boom.Boom(error, { statusCode: 500 }); + const err = new Boom.Boom(null, { statusCode: 500, cause: error }); err.reformat(false); expect(err.output).to.equal({ From ebfd06baf64a0be55b445ce0797aba4e97c54ec3 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 4 Dec 2023 11:45:16 +0100 Subject: [PATCH 06/50] Remove decorate option --- lib/index.js | 18 +++++++----------- test/index.js | 15 --------------- 2 files changed, 7 insertions(+), 26 deletions(-) diff --git a/lib/index.js b/lib/index.js index 56af936..ccd9655 100755 --- a/lib/index.js +++ b/lib/index.js @@ -75,12 +75,12 @@ exports.Boom = class extends Error { constructor(message, options = {}) { - const { statusCode = 500, data, decorate, ctor = exports.Boom } = options; + const { statusCode = 500, data, ctor = exports.Boom } = options; super(message ?? internals.codes.get(statusCode) ?? 'Unknown', options); Error.captureStackTrace(this, ctor); // Filter the stack to our external API - this._apply(data, decorate, statusCode); + this._apply(data, statusCode); Object.defineProperty(this, 'typeof', { value: ctor }); } @@ -112,16 +112,12 @@ exports.Boom = class extends Error { } } - _apply(data, decorate, statusCode, message) { + _apply(data, statusCode, message) { if (data !== undefined) { this.data = data; } - if (decorate) { - Object.assign(this, decorate); - } - if (statusCode) { const numberCode = parseInt(statusCode, 10); Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'statusCode must be a number (400+):', statusCode); @@ -154,17 +150,17 @@ exports.boomify = function (err, options = {}) { Hoek.assert(err instanceof Error, 'Cannot boomify non-Error object'); - const { override, data, decorate, statusCode, message } = options; + const { override, data, statusCode, message } = options; if (!err.isBoom) { - return new exports.Boom(message, { statusCode, cause: err, data, decorate }); + return new exports.Boom(message, { statusCode, cause: err, data }); } if (override === false) { // Defaults to true - err._apply(data, decorate); + err._apply(data); } else { - err._apply(data, decorate, statusCode ?? err.output.statusCode, message); + err._apply(data, statusCode ?? err.output.statusCode, message); } return err; diff --git a/test/index.js b/test/index.js index 917ff08..ee5490c 100755 --- a/test/index.js +++ b/test/index.js @@ -24,14 +24,6 @@ describe('Boom', () => { expect(JSON.stringify(err)).to.equal('{"isBoom":true,"isServer":false,"data":null,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}'); }); - it('decorates error', () => { - - const err = new Boom.Boom('oops', { statusCode: 400, decorate: { x: 1 } }); - expect(err.output.payload.message).to.equal('oops'); - expect(err.output.statusCode).to.equal(400); - expect(err.x).to.equal(1); - }); - it('handles missing message', () => { const err = new Boom.Boom(); @@ -159,13 +151,6 @@ describe('Boom', () => { expect(error).to.shallow.equal(Boom.boomify(error, { statusCode: 444 })); }); - it('decorates error', () => { - - const error = new Error('oops'); - const err = Boom.boomify(error, { statusCode: 400, decorate: { x: 1 } }); - expect(err.x).to.equal(1); - }); - it('returns an error with info when constructed using another error', () => { const error = new Error('ka-boom'); From cf9964aac00fbdddd48f21121607b4e9a281cd32 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 4 Dec 2023 11:57:04 +0100 Subject: [PATCH 07/50] Allow to boomify non-Error errors --- lib/index.js | 9 ++++----- test/index.js | 9 +++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/lib/index.js b/lib/index.js index ccd9655..0a8fcef 100755 --- a/lib/index.js +++ b/lib/index.js @@ -106,8 +106,9 @@ exports.Boom = class extends Error { } else { this.output.payload.message = this.message; - if (this.cause?.message) { - this.output.payload.message = (this.message === this.output.payload.error) ? this.cause.message : this.message + ': ' + this.cause.message; + if (this.cause) { + const message = this.cause.message ?? this.cause; + this.output.payload.message = (this.message === this.output.payload.error) ? message : this.message + ': ' + message; } } } @@ -148,11 +149,9 @@ exports.isBoom = function (err, statusCode) { exports.boomify = function (err, options = {}) { - Hoek.assert(err instanceof Error, 'Cannot boomify non-Error object'); - const { override, data, statusCode, message } = options; - if (!err.isBoom) { + if (!err?.isBoom) { return new exports.Boom(message, { statusCode, cause: err, data }); } diff --git a/test/index.js b/test/index.js index ee5490c..cafce8f 100755 --- a/test/index.js +++ b/test/index.js @@ -249,6 +249,15 @@ describe('Boom', () => { expect(boom.output.payload.message).to.equal('Override message: Missing data'); expect(boom.output.statusCode).to.equal(599); }); + + it('handles non-Error errors', () => { + + const boom = Boom.boomify(123, { message: 'Hello', statusCode: 400 }); + + expect(boom.cause).to.equal(123); + expect(boom.output.payload.message).to.equal('Hello: 123'); + expect(boom.output.statusCode).to.equal(400); + }); }); describe('create()', () => { From 49b4cc8e8b2f03354d5b3df6559a4e9fb3ea3f5d Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 4 Dec 2023 14:34:44 +0100 Subject: [PATCH 08/50] Make _apply internal --- lib/index.js | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/lib/index.js b/lib/index.js index 0a8fcef..d7779a9 100755 --- a/lib/index.js +++ b/lib/index.js @@ -80,7 +80,7 @@ exports.Boom = class extends Error { super(message ?? internals.codes.get(statusCode) ?? 'Unknown', options); Error.captureStackTrace(this, ctor); // Filter the stack to our external API - this._apply(data, statusCode); + this.#apply(data, statusCode); Object.defineProperty(this, 'typeof', { value: ctor }); } @@ -113,7 +113,7 @@ exports.Boom = class extends Error { } } - _apply(data, statusCode, message) { + #apply(data, statusCode, message) { if (data !== undefined) { this.data = data; @@ -138,31 +138,31 @@ exports.Boom = class extends Error { this.reformat(); } } -}; - -exports.isBoom = function (err, statusCode) { + static { + exports.isBoom = function (err, statusCode) { - return err instanceof Error && !!err.isBoom && (!statusCode || err.output.statusCode === statusCode); -}; + return err instanceof Error && !!err.isBoom && (!statusCode || err.output.statusCode === statusCode); + }; + exports.boomify = function (err, options = {}) { -exports.boomify = function (err, options = {}) { + const { override, data, statusCode, message } = options; - const { override, data, statusCode, message } = options; + if (!err?.isBoom) { + return new exports.Boom(message, { statusCode, cause: err, data }); + } - if (!err?.isBoom) { - return new exports.Boom(message, { statusCode, cause: err, data }); - } + if (override === false) { // Defaults to true + err.#apply(data); + } + else { + err.#apply(data, statusCode ?? err.output.statusCode, message); + } - if (override === false) { // Defaults to true - err._apply(data); - } - else { - err._apply(data, statusCode ?? err.output.statusCode, message); + return err; + }; } - - return err; }; From 936187a2f952326c4eaae8260bc23299b35a24e4 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 4 Dec 2023 14:51:39 +0100 Subject: [PATCH 09/50] Make isBoom a prototype property --- lib/index.js | 8 +++++--- test/index.js | 5 +++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/index.js b/lib/index.js index d7779a9..f85d999 100755 --- a/lib/index.js +++ b/lib/index.js @@ -66,9 +66,8 @@ const internals = { }; -exports.Boom = class extends Error { +exports.Boom = class Boom extends Error { - isBoom = true; isServer; data = null; output; @@ -140,6 +139,9 @@ exports.Boom = class extends Error { } static { + Object.defineProperty(this.prototype, 'name', { value: 'Boom', writable: true, configurable: true }); + Object.defineProperty(this.prototype, 'isBoom', { value: true, configurable: true }); + exports.isBoom = function (err, statusCode) { return err instanceof Error && !!err.isBoom && (!statusCode || err.output.statusCode === statusCode); @@ -430,7 +432,7 @@ exports.badImplementation = function (message, data) { internals.serverError = function (message, data, statusCode, ctor) { if (data instanceof Error && - !data.isBoom) { + !exports.isBoom(data)) { return new exports.Boom(message, { statusCode, cause: data, ctor }); } diff --git a/test/index.js b/test/index.js index cafce8f..b85bdd5 100755 --- a/test/index.js +++ b/test/index.js @@ -20,8 +20,9 @@ describe('Boom', () => { expect(err.output.payload.message).to.equal('oops'); expect(err.output.statusCode).to.equal(400); - expect(Object.keys(err)).to.equal(['isBoom', 'isServer', 'data', 'output']); - expect(JSON.stringify(err)).to.equal('{"isBoom":true,"isServer":false,"data":null,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}'); + expect(err.name).to.equal('Boom'); + expect(Object.keys(err)).to.equal(['isServer', 'data', 'output']); + expect(JSON.stringify(err)).to.equal('{"isServer":false,"data":null,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}'); }); it('handles missing message', () => { From 3ea340be1ecdbca96a8674154d891a7cb9d4c2f0 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 4 Dec 2023 14:53:17 +0100 Subject: [PATCH 10/50] Make isServer property computed --- lib/index.js | 8 +++++--- test/index.js | 4 ++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/index.js b/lib/index.js index f85d999..4f7ef44 100755 --- a/lib/index.js +++ b/lib/index.js @@ -68,10 +68,14 @@ const internals = { exports.Boom = class Boom extends Error { - isServer; data = null; output; + get isServer() { + + return this.output.statusCode >= 500; + } + constructor(message, options = {}) { const { statusCode = 500, data, ctor = exports.Boom } = options; @@ -122,8 +126,6 @@ exports.Boom = class Boom extends Error { const numberCode = parseInt(statusCode, 10); Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'statusCode must be a number (400+):', statusCode); - this.isServer = numberCode >= 500; - this.output = { statusCode: numberCode, payload: {}, diff --git a/test/index.js b/test/index.js index b85bdd5..82cd978 100755 --- a/test/index.js +++ b/test/index.js @@ -21,8 +21,8 @@ describe('Boom', () => { expect(err.output.statusCode).to.equal(400); expect(err.name).to.equal('Boom'); - expect(Object.keys(err)).to.equal(['isServer', 'data', 'output']); - expect(JSON.stringify(err)).to.equal('{"isServer":false,"data":null,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}'); + expect(Object.keys(err)).to.equal(['data', 'output']); + expect(JSON.stringify(err)).to.equal('{"data":null,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}'); }); it('handles missing message', () => { From 8629a76fe66b13782bf580788ce5639f8c9ae5d9 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Tue, 5 Dec 2023 08:03:35 +0100 Subject: [PATCH 11/50] Refactor output and payload to classes --- lib/index.js | 62 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 42 insertions(+), 20 deletions(-) diff --git a/lib/index.js b/lib/index.js index 4f7ef44..0cc1a54 100755 --- a/lib/index.js +++ b/lib/index.js @@ -101,19 +101,7 @@ exports.Boom = class Boom extends Error { reformat(debug = false) { - this.output.payload.statusCode = this.output.statusCode; - this.output.payload.error = internals.codes.get(this.output.statusCode) ?? 'Unknown'; - - if (this.output.statusCode === 500 && debug !== true) { - this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user - } - else { - this.output.payload.message = this.message; - if (this.cause) { - const message = this.cause.message ?? this.cause; - this.output.payload.message = (this.message === this.output.payload.error) ? message : this.message + ': ' + message; - } - } + this.output.payload = new internals.PayloadObject(this, this.output.statusCode, debug); } #apply(data, statusCode, message) { @@ -126,17 +114,12 @@ exports.Boom = class Boom extends Error { const numberCode = parseInt(statusCode, 10); Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'statusCode must be a number (400+):', statusCode); - this.output = { - statusCode: numberCode, - payload: {}, - headers: {} - }; - if (message) { this.message = `${message}: ${this.message}`; } - this.reformat(); + const payload = new internals.PayloadObject(this, numberCode, false); + this.output = new internals.BoomOutput(numberCode, payload); } } @@ -170,6 +153,45 @@ exports.Boom = class Boom extends Error { }; +internals.PayloadObject = class { + + statusCode; + error; + message; + + constructor(error, statusCode, debug) { + + this.statusCode = statusCode; + this.error = internals.codes.get(statusCode) ?? 'Unknown'; + + if (statusCode === 500 && debug !== true) { + this.message = 'An internal server error occurred'; // Hide actual error from user + } + else { + this.message = error.message; + if (error.cause) { + const message = error.cause.message ?? error.cause; + this.message = (error.message === this.error) ? message : error.message + ': ' + message; + } + } + } +}; + + +internals.BoomOutput = class { + + statusCode; + payload; + headers = {}; + + constructor(statusCode, payload) { + + this.statusCode = statusCode; + this.payload = payload; + } +}; + + // 4xx Client Errors exports.badRequest = function (message, data) { From be75eacbfe7b83b80cffe1a96468d81f6e936d9d Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Tue, 5 Dec 2023 08:42:46 +0100 Subject: [PATCH 12/50] Remove unauthorized payload.attributes --- API.md | 19 +++++-------------- lib/index.js | 9 --------- test/index.js | 2 -- 3 files changed, 5 insertions(+), 25 deletions(-) diff --git a/API.md b/API.md index 9bff592..800309a 100755 --- a/API.md +++ b/API.md @@ -102,7 +102,8 @@ Returns a 401 Unauthorized error where: - an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header. - `attributes` - an object of values to use while setting the 'WWW-Authenticate' header. This value is only used when `scheme` is a string, otherwise it is ignored. Every key/value pair will be included in the - 'WWW-Authenticate' in the format of 'key="value"' as well as in the response payload under the `attributes` key. Alternatively value can be a string which is use to set the value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. + 'WWW-Authenticate' in the format of 'key="value"'. Alternatively value can be a string which is used to set the + value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. `null` and `undefined` will be replaced with an empty string. If `attributes` is set, `message` will be used as the 'error' segment of the 'WWW-Authenticate' header. If `message` is unset, the 'error' segment of the header will not be present and `isMissing` will be true on the error object. @@ -135,10 +136,7 @@ Generates the following response: "payload": { "statusCode": 401, "error": "Unauthorized", - "message": "invalid password", - "attributes": { - "error": "invalid password" - } + "message": "invalid password" }, "headers": { "WWW-Authenticate": "sample error=\"invalid password\"" @@ -154,8 +152,7 @@ Generates the following response: ```json "payload": { "statusCode": 401, - "error": "Unauthorized", - "attributes": "VGhpcyBpcyBhIHRlc3QgdG9rZW4=" + "error": "Unauthorized" }, "headers": { "WWW-Authenticate": "Negotiate VGhpcyBpcyBhIHRlc3QgdG9rZW4=" @@ -172,13 +169,7 @@ Generates the following response: "payload": { "statusCode": 401, "error": "Unauthorized", - "message": "invalid password", - "attributes": { - "error": "invalid password", - "ttl": 0, - "cache": "", - "foo": "bar" - } + "message": "invalid password" }, "headers": { "WWW-Authenticate": "sample ttl=\"0\", cache=\"\", foo=\"bar\", error=\"invalid password\"" diff --git a/lib/index.js b/lib/index.js index 0cc1a54..ceba6a7 100755 --- a/lib/index.js +++ b/lib/index.js @@ -221,23 +221,15 @@ exports.unauthorized = function (message, scheme, attributes) { // Or ( let wwwAuthenticate = `${scheme}`; - if (attributes || - message) { - - err.output.payload.attributes = {}; - } - if (attributes) { if (typeof attributes === 'string') { wwwAuthenticate += ' ' + Hoek.escapeHeaderAttribute(attributes); - err.output.payload.attributes = attributes; } else { wwwAuthenticate += ' ' + Object.keys(attributes).map((name) => { const value = attributes[name] ?? ''; - err.output.payload.attributes[name] = value; return `${name}="${Hoek.escapeHeaderAttribute(value.toString())}"`; }) .join(', '); @@ -250,7 +242,6 @@ exports.unauthorized = function (message, scheme, attributes) { // Or ( } wwwAuthenticate += ` error="${Hoek.escapeHeaderAttribute(message)}"`; - err.output.payload.attributes.error = message; } else { err.isMissing = true; diff --git a/test/index.js b/test/index.js index 82cd978..b1c30db 100755 --- a/test/index.js +++ b/test/index.js @@ -357,7 +357,6 @@ describe('Boom', () => { const err = Boom.unauthorized('boom', 'Test', { a: 1, b: 'something', c: null, d: 0 }); expect(err.output.statusCode).to.equal(401); expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0", error="boom"'); - expect(err.output.payload.attributes).to.equal({ a: 1, b: 'something', c: '', d: 0, error: 'boom' }); }); it('returns a WWW-Authenticate header from string input instead of object', () => { @@ -365,7 +364,6 @@ describe('Boom', () => { const err = Boom.unauthorized(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4='); expect(err.output.statusCode).to.equal(401); expect(err.output.headers['WWW-Authenticate']).to.equal('Negotiate VGhpcyBpcyBhIHRlc3QgdG9rZW4='); - expect(err.output.payload.attributes).to.equal('VGhpcyBpcyBhIHRlc3QgdG9rZW4='); }); it('returns a WWW-Authenticate header when passed attributes, missing error', () => { From 5854e212bf16fe556eb6c2014c0f5c8f0df0468a Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Tue, 5 Dec 2023 09:22:56 +0100 Subject: [PATCH 13/50] Fix WWW-Authenticate header when empty attributes --- lib/index.js | 14 +++++++------- test/index.js | 7 +++++++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/lib/index.js b/lib/index.js index ceba6a7..4ffc5f4 100755 --- a/lib/index.js +++ b/lib/index.js @@ -219,14 +219,14 @@ exports.unauthorized = function (message, scheme, attributes) { // Or ( // function (message, scheme, attributes) - let wwwAuthenticate = `${scheme}`; + let stringified = ''; if (attributes) { if (typeof attributes === 'string') { - wwwAuthenticate += ' ' + Hoek.escapeHeaderAttribute(attributes); + stringified += Hoek.escapeHeaderAttribute(attributes); } else { - wwwAuthenticate += ' ' + Object.keys(attributes).map((name) => { + stringified += Object.keys(attributes).map((name) => { const value = attributes[name] ?? ''; @@ -237,17 +237,17 @@ exports.unauthorized = function (message, scheme, attributes) { // Or ( } if (message) { - if (attributes) { - wwwAuthenticate += ','; + if (stringified) { + stringified += ', '; } - wwwAuthenticate += ` error="${Hoek.escapeHeaderAttribute(message)}"`; + stringified += `error="${Hoek.escapeHeaderAttribute(message)}"`; } else { err.isMissing = true; } - err.output.headers['WWW-Authenticate'] = wwwAuthenticate; + err.output.headers['WWW-Authenticate'] = stringified ? `${scheme} ${stringified}` : `${scheme}`; return err; }; diff --git a/test/index.js b/test/index.js index b1c30db..a8b5a18 100755 --- a/test/index.js +++ b/test/index.js @@ -359,6 +359,13 @@ describe('Boom', () => { expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0", error="boom"'); }); + it('returns a WWW-Authenticate header when passed a scheme and empty attributes', () => { + + const err = Boom.unauthorized('boom', 'Test', {}); + expect(err.output.statusCode).to.equal(401); + expect(err.output.headers['WWW-Authenticate']).to.equal('Test error="boom"'); + }); + it('returns a WWW-Authenticate header from string input instead of object', () => { const err = Boom.unauthorized(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4='); From 15f95dff404a4f12b7b33c27c20569394a89cb5a Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Tue, 5 Dec 2023 10:24:30 +0100 Subject: [PATCH 14/50] Refactor implementation to use helpers --- lib/index.js | 154 +++++++++++++++----------------------------------- test/index.js | 4 +- 2 files changed, 46 insertions(+), 112 deletions(-) diff --git a/lib/index.js b/lib/index.js index 4ffc5f4..8278a02 100755 --- a/lib/index.js +++ b/lib/index.js @@ -192,14 +192,27 @@ internals.BoomOutput = class { }; -// 4xx Client Errors +internals.statusError = function (statusCode, isServer) { + + const method = isServer ? + function (message, data) { -exports.badRequest = function (message, data) { + return internals.serverError(message, data, statusCode, method); + } : + function (message, data) { + + return new exports.Boom(message, { statusCode, data, ctor: method }); + }; - return new exports.Boom(message, { statusCode: 400, data, ctor: exports.badRequest }); + return method; }; +// 4xx Client Errors + +exports.badRequest = internals.statusError(400); + + exports.unauthorized = function (message, scheme, attributes) { // Or (message, wwwAuthenticate[]) const err = new exports.Boom(message, { statusCode: 401, ctor: exports.unauthorized }); @@ -252,22 +265,13 @@ exports.unauthorized = function (message, scheme, attributes) { // Or ( }; -exports.paymentRequired = function (message, data) { +exports.paymentRequired = internals.statusError(402); - return new exports.Boom(message, { statusCode: 402, data, ctor: exports.paymentRequired }); -}; - - -exports.forbidden = function (message, data) { - - return new exports.Boom(message, { statusCode: 403, data, ctor: exports.forbidden }); -}; +exports.forbidden = internals.statusError(403); -exports.notFound = function (message, data) { - return new exports.Boom(message, { statusCode: 404, data, ctor: exports.notFound }); -}; +exports.notFound = internals.statusError(404); exports.methodNotAllowed = function (message, data, allow) { @@ -286,123 +290,64 @@ exports.methodNotAllowed = function (message, data, allow) { }; -exports.notAcceptable = function (message, data) { - - return new exports.Boom(message, { statusCode: 406, data, ctor: exports.notAcceptable }); -}; - - -exports.proxyAuthRequired = function (message, data) { - - return new exports.Boom(message, { statusCode: 407, data, ctor: exports.proxyAuthRequired }); -}; - - -exports.clientTimeout = function (message, data) { - - return new exports.Boom(message, { statusCode: 408, data, ctor: exports.clientTimeout }); -}; - - -exports.conflict = function (message, data) { - - return new exports.Boom(message, { statusCode: 409, data, ctor: exports.conflict }); -}; - - -exports.resourceGone = function (message, data) { - - return new exports.Boom(message, { statusCode: 410, data, ctor: exports.resourceGone }); -}; - - -exports.lengthRequired = function (message, data) { +exports.notAcceptable = internals.statusError(406); - return new exports.Boom(message, { statusCode: 411, data, ctor: exports.lengthRequired }); -}; +exports.proxyAuthRequired = internals.statusError(407); -exports.preconditionFailed = function (message, data) { - return new exports.Boom(message, { statusCode: 412, data, ctor: exports.preconditionFailed }); -}; +exports.clientTimeout = internals.statusError(408); -exports.entityTooLarge = function (message, data) { +exports.conflict = internals.statusError(409); - return new exports.Boom(message, { statusCode: 413, data, ctor: exports.entityTooLarge }); -}; +exports.resourceGone = internals.statusError(410); -exports.uriTooLong = function (message, data) { - return new exports.Boom(message, { statusCode: 414, data, ctor: exports.uriTooLong }); -}; +exports.lengthRequired = internals.statusError(411); -exports.unsupportedMediaType = function (message, data) { +exports.preconditionFailed = internals.statusError(412); - return new exports.Boom(message, { statusCode: 415, data, ctor: exports.unsupportedMediaType }); -}; +exports.entityTooLarge = internals.statusError(413); -exports.rangeNotSatisfiable = function (message, data) { - return new exports.Boom(message, { statusCode: 416, data, ctor: exports.rangeNotSatisfiable }); -}; +exports.uriTooLong = internals.statusError(414); -exports.expectationFailed = function (message, data) { +exports.unsupportedMediaType = internals.statusError(415); - return new exports.Boom(message, { statusCode: 417, data, ctor: exports.expectationFailed }); -}; +exports.rangeNotSatisfiable = internals.statusError(416); -exports.teapot = function (message, data) { - return new exports.Boom(message, { statusCode: 418, data, ctor: exports.teapot }); -}; +exports.expectationFailed = internals.statusError(417); -exports.badData = function (message, data) { +exports.teapot = internals.statusError(418); - return new exports.Boom(message, { statusCode: 422, data, ctor: exports.badData }); -}; +exports.badData = internals.statusError(422); -exports.locked = function (message, data) { - return new exports.Boom(message, { statusCode: 423, data, ctor: exports.locked }); -}; +exports.locked = internals.statusError(423); -exports.failedDependency = function (message, data) { +exports.failedDependency = internals.statusError(424); - return new exports.Boom(message, { statusCode: 424, data, ctor: exports.failedDependency }); -}; -exports.tooEarly = function (message, data) { +exports.tooEarly = internals.statusError(425); - return new exports.Boom(message, { statusCode: 425, data, ctor: exports.tooEarly }); -}; +exports.preconditionRequired = internals.statusError(428); -exports.preconditionRequired = function (message, data) { - return new exports.Boom(message, { statusCode: 428, data, ctor: exports.preconditionRequired }); -}; +exports.tooManyRequests = internals.statusError(429); -exports.tooManyRequests = function (message, data) { - - return new exports.Boom(message, { statusCode: 429, data, ctor: exports.tooManyRequests }); -}; - - -exports.illegal = function (message, data) { - - return new exports.Boom(message, { statusCode: 451, data, ctor: exports.illegal }); -}; +exports.illegal = internals.statusError(451); // 5xx Server Errors @@ -413,28 +358,16 @@ exports.internal = function (message, data, statusCode = 500) { }; -exports.notImplemented = function (message, data) { +exports.notImplemented = internals.statusError(501, true); - return internals.serverError(message, data, 501, exports.notImplemented); -}; +exports.badGateway = internals.statusError(502, true); -exports.badGateway = function (message, data) { - return internals.serverError(message, data, 502, exports.badGateway); -}; +exports.serverUnavailable = internals.statusError(503, true); -exports.serverUnavailable = function (message, data) { - - return internals.serverError(message, data, 503, exports.serverUnavailable); -}; - - -exports.gatewayTimeout = function (message, data) { - - return internals.serverError(message, data, 504, exports.gatewayTimeout); -}; +exports.gatewayTimeout = internals.statusError(504, true); exports.badImplementation = function (message, data) { @@ -444,6 +377,7 @@ exports.badImplementation = function (message, data) { return err; }; + internals.serverError = function (message, data, statusCode, ctor) { if (data instanceof Error && diff --git a/test/index.js b/test/index.js index a8b5a18..fd2de4a 100755 --- a/test/index.js +++ b/test/index.js @@ -991,10 +991,10 @@ describe('Boom', () => { types.forEach((type) => { if (type === name) { - expect(error.typeof).to.equal(Boom[name]); + expect(error.typeof).to.shallow.equal(Boom[name]); } else { - expect(error.typeof).to.not.equal(Boom[type]); + expect(error.typeof).to.not.shallow.equal(Boom[type]); } }); }); From c3ca934737f93e71e1f476839463669af3b4b896 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Tue, 5 Dec 2023 11:14:30 +0100 Subject: [PATCH 15/50] Add and use a Boom "headers" option --- lib/index.js | 40 +++++++++++++++++++--------------------- test/index.js | 8 ++++++++ 2 files changed, 27 insertions(+), 21 deletions(-) diff --git a/lib/index.js b/lib/index.js index 8278a02..4790e77 100755 --- a/lib/index.js +++ b/lib/index.js @@ -78,12 +78,12 @@ exports.Boom = class Boom extends Error { constructor(message, options = {}) { - const { statusCode = 500, data, ctor = exports.Boom } = options; + const { statusCode = 500, data, headers, ctor = exports.Boom } = options; super(message ?? internals.codes.get(statusCode) ?? 'Unknown', options); Error.captureStackTrace(this, ctor); // Filter the stack to our external API - this.#apply(data, statusCode); + this.#apply(data, statusCode, headers); Object.defineProperty(this, 'typeof', { value: ctor }); } @@ -104,7 +104,7 @@ exports.Boom = class Boom extends Error { this.output.payload = new internals.PayloadObject(this, this.output.statusCode, debug); } - #apply(data, statusCode, message) { + #apply(data, statusCode, headers, message) { if (data !== undefined) { this.data = data; @@ -119,7 +119,7 @@ exports.Boom = class Boom extends Error { } const payload = new internals.PayloadObject(this, numberCode, false); - this.output = new internals.BoomOutput(numberCode, payload); + this.output = new internals.BoomOutput(numberCode, payload, headers); } } @@ -144,7 +144,7 @@ exports.Boom = class Boom extends Error { err.#apply(data); } else { - err.#apply(data, statusCode ?? err.output.statusCode, message); + err.#apply(data, statusCode ?? err.output.statusCode, {}, message); } return err; @@ -182,12 +182,13 @@ internals.BoomOutput = class { statusCode; payload; - headers = {}; + headers; - constructor(statusCode, payload) { + constructor(statusCode, payload, headers) { this.statusCode = statusCode; this.payload = payload; + this.headers = headers ?? {}; } }; @@ -215,23 +216,22 @@ exports.badRequest = internals.statusError(400); exports.unauthorized = function (message, scheme, attributes) { // Or (message, wwwAuthenticate[]) - const err = new exports.Boom(message, { statusCode: 401, ctor: exports.unauthorized }); - // function (message) if (!scheme) { - return err; + return new exports.Boom(message, { statusCode: 401, ctor: exports.unauthorized }); } // function (message, wwwAuthenticate[]) if (typeof scheme !== 'string') { - err.output.headers['WWW-Authenticate'] = scheme.join(', '); - return err; + const headers = { 'WWW-Authenticate': scheme.join(', ') }; + return new exports.Boom(message, { statusCode: 401, headers, ctor: exports.unauthorized }); } // function (message, scheme, attributes) + const decorate = {}; let stringified = ''; if (attributes) { @@ -257,11 +257,11 @@ exports.unauthorized = function (message, scheme, attributes) { // Or ( stringified += `error="${Hoek.escapeHeaderAttribute(message)}"`; } else { - err.isMissing = true; + decorate.isMissing = true; } - err.output.headers['WWW-Authenticate'] = stringified ? `${scheme} ${stringified}` : `${scheme}`; - return err; + const headers = { 'WWW-Authenticate': stringified ? `${scheme} ${stringified}` : `${scheme}` }; + return Object.assign(new exports.Boom(message, { statusCode: 401, headers, ctor: exports.unauthorized }), decorate); }; @@ -276,17 +276,15 @@ exports.notFound = internals.statusError(404); exports.methodNotAllowed = function (message, data, allow) { - const err = new exports.Boom(message, { statusCode: 405, data, ctor: exports.methodNotAllowed }); - if (typeof allow === 'string') { allow = [allow]; } - if (Array.isArray(allow)) { - err.output.headers.Allow = allow.join(', '); - } + const headers = Array.isArray(allow) ? { + Allow: allow.join(', ') + } : null; - return err; + return new exports.Boom(message, { statusCode: 405, data, headers, ctor: exports.methodNotAllowed }); }; diff --git a/test/index.js b/test/index.js index fd2de4a..dba0027 100755 --- a/test/index.js +++ b/test/index.js @@ -49,6 +49,14 @@ describe('Boom', () => { expect(Boom.isBoom(err)).to.be.true(); }); + it('handles headers option', () => { + + const err = new Boom.Boom('fail', { statusCode: 400, headers: { custom: 'yes' } }); + expect(err.output.payload.message).to.equal('fail'); + expect(err.output.statusCode).to.equal(400); + expect(err.output.headers).to.equal({ custom: 'yes' }); + }); + it('throws when statusCode is not a number', () => { expect(() => { From 642f4d54c06db3116c7ab7badfb8bac3093af342 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Tue, 5 Dec 2023 12:22:51 +0100 Subject: [PATCH 16/50] Use statusError for all helpers --- lib/index.js | 62 ++++++++++++++++++++++++++------------------------- test/index.js | 7 ++++++ 2 files changed, 39 insertions(+), 30 deletions(-) diff --git a/lib/index.js b/lib/index.js index 4790e77..8c67ea5 100755 --- a/lib/index.js +++ b/lib/index.js @@ -193,12 +193,13 @@ internals.BoomOutput = class { }; -internals.statusError = function (statusCode, isServer) { +internals.statusError = function (statusCode, massage) { - const method = isServer ? - function (message, data) { + const method = massage ? + function (...args) { - return internals.serverError(message, data, statusCode, method); + const [message, options, decorate] = massage(...args); + return Object.assign(new exports.Boom(message, { statusCode, ctor: method, ...options }), decorate); } : function (message, data) { @@ -214,19 +215,19 @@ internals.statusError = function (statusCode, isServer) { exports.badRequest = internals.statusError(400); -exports.unauthorized = function (message, scheme, attributes) { // Or (message, wwwAuthenticate[]) +exports.unauthorized = internals.statusError(401, (message, scheme, attributes) => { // Or (message, wwwAuthenticate[]) // function (message) if (!scheme) { - return new exports.Boom(message, { statusCode: 401, ctor: exports.unauthorized }); + return [message]; } // function (message, wwwAuthenticate[]) if (typeof scheme !== 'string') { const headers = { 'WWW-Authenticate': scheme.join(', ') }; - return new exports.Boom(message, { statusCode: 401, headers, ctor: exports.unauthorized }); + return [message, { headers }]; } // function (message, scheme, attributes) @@ -261,8 +262,8 @@ exports.unauthorized = function (message, scheme, attributes) { // Or ( } const headers = { 'WWW-Authenticate': stringified ? `${scheme} ${stringified}` : `${scheme}` }; - return Object.assign(new exports.Boom(message, { statusCode: 401, headers, ctor: exports.unauthorized }), decorate); -}; + return [message, { headers }, decorate]; +}); exports.paymentRequired = internals.statusError(402); @@ -274,7 +275,7 @@ exports.forbidden = internals.statusError(403); exports.notFound = internals.statusError(404); -exports.methodNotAllowed = function (message, data, allow) { +exports.methodNotAllowed = internals.statusError(405, (message, data, allow) => { if (typeof allow === 'string') { allow = [allow]; @@ -284,8 +285,8 @@ exports.methodNotAllowed = function (message, data, allow) { Allow: allow.join(', ') } : null; - return new exports.Boom(message, { statusCode: 405, data, headers, ctor: exports.methodNotAllowed }); -}; + return [message, { data, headers }]; +}); exports.notAcceptable = internals.statusError(406); @@ -350,39 +351,40 @@ exports.illegal = internals.statusError(451); // 5xx Server Errors -exports.internal = function (message, data, statusCode = 500) { +exports.internal = internals.statusError(500, (message, data, statusCode = 500) => { - return internals.serverError(message, data, statusCode, exports.internal); -}; + const res = internals.serverError(message, data); + if (statusCode !== 500) { + res[1].statusCode = statusCode; + } + return res; +}); -exports.notImplemented = internals.statusError(501, true); +exports.notImplemented = internals.statusError(501, internals.serverError); -exports.badGateway = internals.statusError(502, true); +exports.badGateway = internals.statusError(502, internals.serverError); -exports.serverUnavailable = internals.statusError(503, true); +exports.serverUnavailable = internals.statusError(503, internals.serverError); -exports.gatewayTimeout = internals.statusError(504, true); +exports.gatewayTimeout = internals.statusError(504, internals.serverError); -exports.badImplementation = function (message, data) { - const err = internals.serverError(message, data, 500, exports.badImplementation); - err.isDeveloperError = true; - return err; -}; +exports.badImplementation = internals.statusError(500, (message, data) => { + const res = internals.serverError(message, data); + res.push({ isDeveloperError: true }); + return res; +}); -internals.serverError = function (message, data, statusCode, ctor) { - if (data instanceof Error && - !exports.isBoom(data)) { +internals.serverError = function (message, data) { - return new exports.Boom(message, { statusCode, cause: data, ctor }); - } + const isDataNonBoomError = data instanceof Error && !exports.isBoom(data); - return new exports.Boom(message, { statusCode, data, ctor }); + return [message, isDataNonBoomError ? { cause: data } : { data }]; }; diff --git a/test/index.js b/test/index.js index dba0027..a3c5669 100755 --- a/test/index.js +++ b/test/index.js @@ -779,6 +779,13 @@ describe('Boom', () => { expect(Boom.internal().output.statusCode).to.equal(500); }); + it('handles a custom error statusCode', () => { + + const err = Boom.internal(null, null, 507); + expect(err.output.statusCode).to.equal(507); + expect(err.message).to.equal('Insufficient Storage'); + }); + it('sets the message with the passed in message', () => { const err = Boom.internal('my message'); From a3404afb74ff4f4b01200e3eba94789130f3ed6a Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Tue, 5 Dec 2023 12:30:33 +0100 Subject: [PATCH 17/50] Throw TypeError instead of Hoek assertion --- lib/index.js | 4 +++- test/index.js | 11 ++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/lib/index.js b/lib/index.js index 8c67ea5..00d4454 100755 --- a/lib/index.js +++ b/lib/index.js @@ -112,7 +112,9 @@ exports.Boom = class Boom extends Error { if (statusCode) { const numberCode = parseInt(statusCode, 10); - Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'statusCode must be a number (400+):', statusCode); + if (isNaN(numberCode) || numberCode < 400) { + throw new TypeError(`statusCode must be a number (400+): ${statusCode}`); + } if (message) { this.message = `${message}: ${this.message}`; diff --git a/test/index.js b/test/index.js index a3c5669..3d68284 100755 --- a/test/index.js +++ b/test/index.js @@ -57,12 +57,17 @@ describe('Boom', () => { expect(err.output.headers).to.equal({ custom: 'yes' }); }); - it('throws when statusCode is not a number', () => { + it('throws when statusCode is invalid', () => { expect(() => { new Boom.Boom('message', { statusCode: 'x' }); }).to.throw('statusCode must be a number (400+): x'); + + expect(() => { + + new Boom.Boom('message', { statusCode: '200' }); + }).to.throw('statusCode must be a number (400+): 200'); }); it('will cast a statusCode number-string to an integer', () => { @@ -81,12 +86,12 @@ describe('Boom', () => { } }); - it('throws when statusCode is not finite', () => { + it('throws TypeError when statusCode is not finite', () => { expect(() => { new Boom.Boom('', { statusCode: 1 / 0 }); - }).to.throw('statusCode must be a number (400+): null'); + }).to.throw(TypeError, 'statusCode must be a number (400+): Infinity'); }); it('sets error code to unknown', () => { From 8a3397dcf591dad50cfb19109bc3a08484117dab Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Tue, 5 Dec 2023 12:32:48 +0100 Subject: [PATCH 18/50] Remove typeof property --- lib/index.js | 2 -- test/index.js | 49 ------------------------------------------------- 2 files changed, 51 deletions(-) diff --git a/lib/index.js b/lib/index.js index 00d4454..15897b2 100755 --- a/lib/index.js +++ b/lib/index.js @@ -84,8 +84,6 @@ exports.Boom = class Boom extends Error { Error.captureStackTrace(this, ctor); // Filter the stack to our external API this.#apply(data, statusCode, headers); - - Object.defineProperty(this, 'typeof', { value: ctor }); } static [Symbol.hasInstance](instance) { diff --git a/test/index.js b/test/index.js index 3d68284..34152a5 100755 --- a/test/index.js +++ b/test/index.js @@ -972,55 +972,6 @@ describe('Boom', () => { }); }); - describe('error.typeof', () => { - - const types = [ - 'badRequest', - 'unauthorized', - 'forbidden', - 'notFound', - 'methodNotAllowed', - 'notAcceptable', - 'proxyAuthRequired', - 'clientTimeout', - 'conflict', - 'resourceGone', - 'lengthRequired', - 'preconditionFailed', - 'entityTooLarge', - 'uriTooLong', - 'unsupportedMediaType', - 'rangeNotSatisfiable', - 'expectationFailed', - 'badData', - 'preconditionRequired', - 'tooManyRequests', - 'internal', - 'notImplemented', - 'badGateway', - 'serverUnavailable', - 'gatewayTimeout', - 'badImplementation' - ]; - - types.forEach((name) => { - - it(`matches typeof Boom.${name}`, () => { - - const error = Boom[name](); - types.forEach((type) => { - - if (type === name) { - expect(error.typeof).to.shallow.equal(Boom[name]); - } - else { - expect(error.typeof).to.not.shallow.equal(Boom[type]); - } - }); - }); - }); - }); - describe('reformat()', () => { it('displays internal server error messages in debug mode', () => { From bc538a4358b78f5d61b503c1abfac15ef13bdfb1 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Wed, 6 Dec 2023 20:31:13 +0100 Subject: [PATCH 19/50] Fix legacy boom object support --- lib/index.js | 77 ++++++++++++++++++++++++++++----------------------- package.json | 5 ++-- test/index.js | 36 +++++++++++++++++++++++- 3 files changed, 80 insertions(+), 38 deletions(-) diff --git a/lib/index.js b/lib/index.js index 15897b2..5feef73 100755 --- a/lib/index.js +++ b/lib/index.js @@ -76,6 +76,8 @@ exports.Boom = class Boom extends Error { return this.output.statusCode >= 500; } + set isServer(value) {} // Allow for compatiblity with legacy boom + constructor(message, options = {}) { const { statusCode = 500, data, headers, ctor = exports.Boom } = options; @@ -83,7 +85,7 @@ exports.Boom = class Boom extends Error { super(message ?? internals.codes.get(statusCode) ?? 'Unknown', options); Error.captureStackTrace(this, ctor); // Filter the stack to our external API - this.#apply(data, statusCode, headers); + internals.apply(this, data, statusCode, headers); } static [Symbol.hasInstance](instance) { @@ -102,53 +104,58 @@ exports.Boom = class Boom extends Error { this.output.payload = new internals.PayloadObject(this, this.output.statusCode, debug); } - #apply(data, statusCode, headers, message) { + static { + Object.defineProperty(this.prototype, 'name', { value: 'Boom', writable: true, configurable: true }); + Object.defineProperty(this.prototype, 'isBoom', { value: true, writable: true, configurable: true }); + } +}; - if (data !== undefined) { - this.data = data; - } - if (statusCode) { - const numberCode = parseInt(statusCode, 10); - if (isNaN(numberCode) || numberCode < 400) { - throw new TypeError(`statusCode must be a number (400+): ${statusCode}`); - } +exports.isBoom = function (err, statusCode) { - if (message) { - this.message = `${message}: ${this.message}`; - } + return err instanceof Error && !!err.isBoom && (!statusCode || err.output.statusCode === statusCode); +}; - const payload = new internals.PayloadObject(this, numberCode, false); - this.output = new internals.BoomOutput(numberCode, payload, headers); - } + +exports.boomify = function (err, options = {}) { + + const { override, data, statusCode, message } = options; + + if (!err?.isBoom) { + return new exports.Boom(message, { statusCode, cause: err, data }); } - static { - Object.defineProperty(this.prototype, 'name', { value: 'Boom', writable: true, configurable: true }); - Object.defineProperty(this.prototype, 'isBoom', { value: true, configurable: true }); + if (override === false) { // Defaults to true + internals.apply(err, data); + } + else { + internals.apply(err, data, statusCode ?? err.output.statusCode, {}, message); + } - exports.isBoom = function (err, statusCode) { + err.isServer = err.output.statusCode >= 500; // Assign, in case it is a legacy boom object - return err instanceof Error && !!err.isBoom && (!statusCode || err.output.statusCode === statusCode); - }; + return err; +}; - exports.boomify = function (err, options = {}) { - const { override, data, statusCode, message } = options; +internals.apply = function (boom, data, statusCode, headers, message) { - if (!err?.isBoom) { - return new exports.Boom(message, { statusCode, cause: err, data }); - } + if (data !== undefined) { + boom.data = data; + } - if (override === false) { // Defaults to true - err.#apply(data); - } - else { - err.#apply(data, statusCode ?? err.output.statusCode, {}, message); - } + if (statusCode) { + const numberCode = parseInt(statusCode, 10); + if (isNaN(numberCode) || numberCode < 400) { + throw new TypeError(`statusCode must be a number (400+): ${statusCode}`); + } - return err; - }; + if (message) { + boom.message = `${message}: ${boom.message}`; + } + + const payload = new internals.PayloadObject(boom, numberCode, false); + boom.output = new internals.BoomOutput(numberCode, payload, headers); } }; diff --git a/package.json b/package.json index b1d938f..29277e0 100644 --- a/package.json +++ b/package.json @@ -25,10 +25,11 @@ "@hapi/eslint-plugin": "^7.0.0", "@hapi/lab": "^26.0.0", "@types/node": "^17.0.31", - "typescript": "~4.6.4" + "typescript": "~4.6.4", + "@hapi/boom10": "npm:@hapi/boom@^10.0.1" }, "scripts": { - "test": "lab -a @hapi/code -t 100 -L -Y", + "test": "lab -a @hapi/code -t 100 -L", "test-cov-html": "lab -a @hapi/code -t 100 -L -r html -o coverage.html" }, "license": "BSD-3-Clause" diff --git a/test/index.js b/test/index.js index 34152a5..ee4bc60 100755 --- a/test/index.js +++ b/test/index.js @@ -1,6 +1,7 @@ 'use strict'; const Boom = require('..'); +const Boom10 = require('@hapi/boom10'); const Code = require('@hapi/code'); const Lab = require('@hapi/lab'); @@ -107,6 +108,7 @@ describe('Boom', () => { const BadaBoom = class extends Boom.Boom {}; expect(new Boom.Boom('oops')).to.be.instanceOf(Boom.Boom); + expect(new Boom10.Boom('oops')).to.be.instanceOf(Boom.Boom); expect(new BadaBoom('oops')).to.be.instanceOf(Boom.Boom); expect(Boom.badRequest('oops')).to.be.instanceOf(Boom.Boom); expect(new Error('oops')).to.not.be.instanceOf(Boom.Boom); @@ -128,6 +130,12 @@ describe('Boom', () => { expect(new Boom.Boom('oops')).to.not.be.instanceOf(BadaBoom); expect(Boom.badRequest('oops')).to.not.be.instanceOf(BadaBoom); }); + + it('works from legacy boom', () => { + + expect(new Boom.Boom('oops')).to.be.instanceOf(Boom10.Boom); + expect(new Boom10.Boom('oops')).to.be.instanceOf(Boom10.Boom); + }); }); describe('isBoom()', () => { @@ -137,6 +145,7 @@ describe('Boom', () => { // Success expect(Boom.isBoom(new Boom.Boom('oops'))).to.be.true(); + expect(Boom.isBoom(new Boom10.Boom('oops'))).to.be.true(); // Fail @@ -148,11 +157,19 @@ describe('Boom', () => { it('returns true for valid boom object and valid status code', () => { expect(Boom.isBoom(Boom.notFound(),404)).to.be.true(); + expect(Boom.isBoom(Boom10.notFound(), 404)).to.be.true(); }); it('returns false for valid boom object and wrong status code', () => { - expect(Boom.isBoom(Boom.notFound(),503)).to.be.false(); + expect(Boom.isBoom(Boom.notFound(), 503)).to.be.false(); + expect(Boom.isBoom(Boom10.notFound(), 503)).to.be.false(); + }); + + it('works from legacy boom', () => { + + expect(Boom10.isBoom(new Boom.Boom('oops'))).to.be.true(); + expect(Boom10.isBoom(new Boom10.Boom('oops'))).to.be.true(); }); }); @@ -272,6 +289,23 @@ describe('Boom', () => { expect(boom.output.payload.message).to.equal('Hello: 123'); expect(boom.output.statusCode).to.equal(400); }); + + it('works with legacy boom', () => { + + const boom = Boom.boomify(new Boom10.Boom(null, { statusCode: 404 }), { statusCode: 501, message: 'Override' }); + + expect(boom.cause).to.be.undefined(); + expect(boom.message).to.equal('Override: Not Found'); + expect(boom.isServer).to.be.true(); + expect(boom.output.statusCode).to.equal(501); + + const boom10 = Boom10.boomify(new Boom.Boom(null, { statusCode: 404 }), { statusCode: 501, message: 'Override' }); + + expect(boom10.cause).to.be.undefined(); + expect(boom10.message).to.equal('Override: Not Found'); + expect(boom10.isServer).to.be.true(); + expect(boom10.output.statusCode).to.equal(501); + }); }); describe('create()', () => { From 7734f55685f47b73116b562359dd730318731d10 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 10:12:57 +0100 Subject: [PATCH 20/50] Add tests for "name" property --- test/index.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test/index.js b/test/index.js index ee4bc60..e122020 100755 --- a/test/index.js +++ b/test/index.js @@ -26,6 +26,27 @@ describe('Boom', () => { expect(JSON.stringify(err)).to.equal('{"data":null,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}'); }); + it('instances has .name "Boom"', () => { + + class SubBoom extends Boom.Boom {} + + expect(new Boom.Boom().name).to.equal('Boom'); + expect(new SubBoom().name).to.equal('Boom'); + }); + + it('instances .name can be changed', () => { + + class SubBoom extends Boom.Boom { + name = 'BadaBoom'; + } + + const err = new Boom.Boom(); + err.name = 'MyBoom'; + + expect(err.name).to.equal('MyBoom'); + expect(new SubBoom().name).to.equal('BadaBoom'); + }); + it('handles missing message', () => { const err = new Boom.Boom(); From bf96fd99b2efd4fb8fa9f4d0cf04046dd6d0e4e2 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 11:08:54 +0100 Subject: [PATCH 21/50] Explicit cause in super() call Co-authored-by: Matthieu Sieben --- lib/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/index.js b/lib/index.js index 5feef73..22a4925 100755 --- a/lib/index.js +++ b/lib/index.js @@ -80,9 +80,9 @@ exports.Boom = class Boom extends Error { constructor(message, options = {}) { - const { statusCode = 500, data, headers, ctor = exports.Boom } = options; + const { statusCode = 500, data, headers, ctor = exports.Boom, cause } = options; - super(message ?? internals.codes.get(statusCode) ?? 'Unknown', options); + super(message ?? internals.codes.get(statusCode) ?? 'Unknown', { cause }); Error.captureStackTrace(this, ctor); // Filter the stack to our external API internals.apply(this, data, statusCode, headers); From ab72170e299fd8a4c7cc83ecbd31c029f72a553b Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 11:36:27 +0100 Subject: [PATCH 22/50] Assign .cause if not handled by super() call --- lib/index.js | 4 ++++ test/index.js | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/index.js b/lib/index.js index 22a4925..314f7c2 100755 --- a/lib/index.js +++ b/lib/index.js @@ -85,6 +85,10 @@ exports.Boom = class Boom extends Error { super(message ?? internals.codes.get(statusCode) ?? 'Unknown', { cause }); Error.captureStackTrace(this, ctor); // Filter the stack to our external API + if (cause !== undefined) { + this.cause ??= cause; // Explicitly assign cause to work with old runtimes + } + internals.apply(this, data, statusCode, headers); } diff --git a/test/index.js b/test/index.js index e122020..dd63d65 100755 --- a/test/index.js +++ b/test/index.js @@ -122,6 +122,27 @@ describe('Boom', () => { expect(err.output.payload.error).to.equal('Unknown'); }); + it('assigns a .cause property if Error does not support it', (flags) => { + + const proto = Object.getPrototypeOf(Boom.Boom); + Object.setPrototypeOf(Boom.Boom, class extends Error { + + constructor(message, _options) { + + super(message); + } + }); + + flags.onCleanup = () => { + + Object.setPrototypeOf(Boom.Boom, proto); + }; + + const err = new Boom.Boom('fail', { cause: 0 }); + expect(err.cause).to.exist(); + expect(err.cause).to.equal(0); + }); + describe('instanceof', () => { it('identifies a boom object', () => { From c7edc9e94f4ca3882677ad368ac3fc4b9ae41845 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 14:11:20 +0100 Subject: [PATCH 23/50] Fix and update typings --- lib/index.d.ts | 216 ++++++++++++++++++++++++------------------------- package.json | 8 +- test/index.ts | 171 +++++++++++++++++++-------------------- 3 files changed, 194 insertions(+), 201 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index 34132bb..ff3a5df 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -6,22 +6,27 @@ export class Boom extends Error { /** * Creates a new Boom object using the provided message or Error */ - constructor(message?: string | Error, options?: Options); + constructor(message?: string, options?: Options); + + /** + * Underlying cause for the Boom error + */ + cause?: unknown; /** * Custom error data with additional information specific to the error type */ - data?: Data; + data: Data; /** - * isBoom - if true, indicates this is a Boom object instance. + * isBoom - true, indicates this is a Boom object instance. */ - isBoom: boolean; + readonly isBoom: boolean; /** * Convenience boolean indicating status code >= 500 */ - isServer: boolean; + readonly isServer: boolean; /** * The error message @@ -33,17 +38,12 @@ export class Boom extends Error { */ output: Output; - /** - * The constructor used to create the error - */ - typeof: Function; - /** * Specifies if an error object is a valid boom object * * @param debug - A boolean that, when true, does not hide the original 500 error message. Defaults to false. */ - reformat(debug?: boolean): string; + reformat(debug?: boolean): void; } @@ -53,40 +53,44 @@ export interface Options { * * @default 500 */ - statusCode?: number; + readonly statusCode?: number; /** * Additional error information */ - data?: Data; + readonly data?: Data; + + /** + * An object containing any HTTP headers where each key is a header name and value is the header content + */ + readonly headers?: { [header: string]: string | string[] | number }; /** * Constructor reference used to crop the exception call stack output */ - ctor?: Function; + readonly ctor?: Function; + + /** + * An underlying cause for the Boom error + */ + readonly cause?: Error | unknown; +} + +export interface BoomifyOptions extends Options { /** * Error message string * * @default none */ - message?: string; + readonly message?: string; /** * If false, the err provided is a Boom object, and a statusCode or message are provided, the values are ignored * * @default true */ - override?: boolean; -} - - -export interface Decorate { - - /** - * An option with extra properties to set on the error object - */ - decorate?: Decoration; + readonly override?: boolean; } @@ -94,22 +98,17 @@ export interface Payload { /** * The HTTP status code derived from error.output.statusCode */ - statusCode: number; + readonly statusCode: number; /** * The HTTP status message derived from statusCode */ - error: string; + readonly error: string; /** * The error message derived from error.message */ - message: string; - - /** - * Custom properties - */ - [key: string]: unknown; + readonly message: string; } @@ -117,17 +116,17 @@ export interface Output { /** * The HTTP status code */ - statusCode: number; + readonly statusCode: number; /** * An object containing any HTTP headers where each key is a header name and value is the header content */ - headers: { [header: string]: string | string[] | number | undefined }; + readonly headers: { [header: string]: string | string[] | number | undefined }; /** * The formatted object used as the response payload (stringified) */ - payload: Payload; + readonly payload: Payload; } @@ -143,14 +142,15 @@ export function isBoom(obj: unknown, statusCode?: number): obj is Boom; /** -* Specifies if an error object is a valid boom object +* Applies options to an existing boom object, or creates a new boom object with the error as `cause` * -* @param err - The error object to decorate +* @param err - The target object * @param options - Options object * -* @returns A decorated boom object +* @returns A boom object */ -export function boomify(err: Error, options?: Options & Decorate): Boom & Decoration; +export function boomify(err: Boom, options?: BoomifyOptions): Boom; +export function boomify(err: unknown, options?: BoomifyOptions): Boom; // 4xx Errors @@ -158,22 +158,22 @@ export function boomify(err: Error, options?: Options & /** * Returns a 400 Bad Request error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 400 bad request error */ -export function badRequest(messageOrError?: string | Error, data?: Data): Boom; +export function badRequest(message?: string, data?: Data): Boom; /** * Returns a 401 Unauthorized error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * * @returns A 401 Unauthorized error */ -export function unauthorized(messageOrError?: string | Error | null): Boom; +export function unauthorized(message?: string): Boom; /** @@ -185,8 +185,8 @@ export function unauthorized(messageOrError?: string | Error | null): Boom * * @returns A 401 Unauthorized error */ -export function unauthorized(message: '' | null, scheme: string, attributes?: string | unauthorized.Attributes): Boom & unauthorized.MissingAuth; -export function unauthorized(message: string | null, scheme: string, attributes?: string | unauthorized.Attributes): Boom; +export function unauthorized(message: '' | null | undefined, scheme: string, attributes?: string | unauthorized.Attributes): Boom & unauthorized.MissingAuth; +export function unauthorized(message: string, scheme: string, attributes?: string | unauthorized.Attributes): Boom; export namespace unauthorized { @@ -200,7 +200,7 @@ export namespace unauthorized { /** * Indicate whether the 401 unauthorized error is due to missing credentials (vs. invalid) */ - isMissing: boolean; + isMissing: true; } } @@ -213,271 +213,271 @@ export namespace unauthorized { * * @returns A 401 Unauthorized error */ -export function unauthorized(message: string | null, wwwAuthenticate: string[]): Boom; +export function unauthorized(message: string | null | undefined, wwwAuthenticate: string[]): Boom; /** * Returns a 402 Payment Required error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 402 Payment Required error */ -export function paymentRequired(messageOrError?: string | Error, data?: Data): Boom; +export function paymentRequired(message?: string, data?: Data): Boom; /** * Returns a 403 Forbidden error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 403 Forbidden error */ -export function forbidden(messageOrError?: string | Error, data?: Data): Boom; +export function forbidden(message?: string, data?: Data): Boom; /** * Returns a 404 Not Found error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 404 Not Found error */ -export function notFound(messageOrError?: string | Error, data?: Data): Boom; +export function notFound(message?: string, data?: Data): Boom; /** * Returns a 405 Method Not Allowed error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * @param allow - Optional string or array of strings which is used to set the 'Allow' header * * @returns A 405 Method Not Allowed error */ -export function methodNotAllowed(messageOrError?: string | Error, data?: Data, allow?: string | string[]): Boom; +export function methodNotAllowed(message?: string, data?: Data, allow?: string | string[]): Boom; /** * Returns a 406 Not Acceptable error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 406 Not Acceptable error */ -export function notAcceptable(messageOrError?: string | Error, data?: Data): Boom; +export function notAcceptable(message?: string, data?: Data): Boom; /** * Returns a 407 Proxy Authentication error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 407 Proxy Authentication error */ -export function proxyAuthRequired(messageOrError?: string | Error, data?: Data): Boom; +export function proxyAuthRequired(message?: string, data?: Data): Boom; /** * Returns a 408 Request Time-out error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 408 Request Time-out error */ -export function clientTimeout(messageOrError?: string | Error, data?: Data): Boom; +export function clientTimeout(message?: string, data?: Data): Boom; /** * Returns a 409 Conflict error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 409 Conflict error */ -export function conflict(messageOrError?: string | Error, data?: Data): Boom; +export function conflict(message?: string, data?: Data): Boom; /** * Returns a 410 Gone error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 410 gone error */ -export function resourceGone(messageOrError?: string | Error, data?: Data): Boom; +export function resourceGone(message?: string, data?: Data): Boom; /** * Returns a 411 Length Required error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 411 Length Required error */ -export function lengthRequired(messageOrError?: string | Error, data?: Data): Boom; +export function lengthRequired(message?: string, data?: Data): Boom; /** * Returns a 412 Precondition Failed error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 412 Precondition Failed error */ -export function preconditionFailed(messageOrError?: string | Error, data?: Data): Boom; +export function preconditionFailed(message?: string, data?: Data): Boom; /** * Returns a 413 Request Entity Too Large error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 413 Request Entity Too Large error */ -export function entityTooLarge(messageOrError?: string | Error, data?: Data): Boom; +export function entityTooLarge(message?: string, data?: Data): Boom; /** * Returns a 414 Request-URI Too Large error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 414 Request-URI Too Large error */ -export function uriTooLong(messageOrError?: string | Error, data?: Data): Boom; +export function uriTooLong(message?: string, data?: Data): Boom; /** * Returns a 415 Unsupported Media Type error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 415 Unsupported Media Type error */ -export function unsupportedMediaType(messageOrError?: string | Error, data?: Data): Boom; +export function unsupportedMediaType(message?: string, data?: Data): Boom; /** * Returns a 416 Request Range Not Satisfiable error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 416 Request Range Not Satisfiable error */ -export function rangeNotSatisfiable(messageOrError?: string | Error, data?: Data): Boom; +export function rangeNotSatisfiable(message?: string, data?: Data): Boom; /** * Returns a 417 Expectation Failed error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 417 Expectation Failed error */ -export function expectationFailed(messageOrError?: string | Error, data?: Data): Boom; +export function expectationFailed(message?: string, data?: Data): Boom; /** * Returns a 418 I'm a Teapot error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 418 I'm a Teapot error */ -export function teapot(messageOrError?: string | Error, data?: Data): Boom; +export function teapot(message?: string, data?: Data): Boom; /** * Returns a 422 Unprocessable Entity error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 422 Unprocessable Entity error */ -export function badData(messageOrError?: string | Error, data?: Data): Boom; +export function badData(message?: string, data?: Data): Boom; /** * Returns a 423 Locked error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 423 Locked error */ -export function locked(messageOrError?: string | Error, data?: Data): Boom; +export function locked(message?: string, data?: Data): Boom; /** * Returns a 424 Failed Dependency error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 424 Failed Dependency error */ -export function failedDependency(messageOrError?: string | Error, data?: Data): Boom; +export function failedDependency(message?: string, data?: Data): Boom; /** * Returns a 425 Too Early error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 425 Too Early error */ -export function tooEarly(messageOrError?: string | Error, data?: Data): Boom; +export function tooEarly(message?: string, data?: Data): Boom; /** * Returns a 428 Precondition Required error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 428 Precondition Required error */ -export function preconditionRequired(messageOrError?: string | Error, data?: Data): Boom; +export function preconditionRequired(message?: string, data?: Data): Boom; /** * Returns a 429 Too Many Requests error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 429 Too Many Requests error */ -export function tooManyRequests(messageOrError?: string | Error, data?: Data): Boom; +export function tooManyRequests(message?: string, data?: Data): Boom; /** * Returns a 451 Unavailable For Legal Reasons error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 451 Unavailable for Legal Reasons error */ -export function illegal(messageOrError?: string | Error, data?: Data): Boom; +export function illegal(message?: string, data?: Data): Boom; // 5xx Errors @@ -485,65 +485,65 @@ export function illegal(messageOrError?: string | Error, data?: Data): Boo /** * Returns a internal error (defaults to 500) * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * @param statusCode - Optional status code override. Defaults to 500. * * @returns A 500 Internal Server error */ -export function internal(messageOrError?: string | Error, data?: Data, statusCode?: number): Boom; +export function internal(message?: string, data?: Data | Error, statusCode?: number): Boom; /** * Returns a 500 Internal Server Error error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 500 Internal Server error */ -export function badImplementation(messageOrError?: string | Error, data?: Data): Boom; +export function badImplementation(message?: string, data?: Data | Error): Boom; /** * Returns a 501 Not Implemented error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 501 Not Implemented error */ -export function notImplemented(messageOrError?: string | Error, data?: Data): Boom; +export function notImplemented(message?: string, data?: Data | Error): Boom; /** * Returns a 502 Bad Gateway error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 502 Bad Gateway error */ -export function badGateway(messageOrError?: string | Error, data?: Data): Boom; +export function badGateway(message?: string, data?: Data | Error): Boom; /** * Returns a 503 Service Unavailable error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 503 Service Unavailable error */ -export function serverUnavailable(messageOrError?: string | Error, data?: Data): Boom; +export function serverUnavailable(message?: string, data?: Data | Error): Boom; /** * Returns a 504 Gateway Time-out error * -* @param messageOrError - Optional message or Error +* @param message - Optional message * @param data - Optional additional error data * * @returns A 504 Gateway Time-out error */ -export function gatewayTimeout(messageOrError?: string | Error, data?: Data): Boom; +export function gatewayTimeout(message?: string, data?: Data | Error): Boom; diff --git a/package.json b/package.json index 29277e0..67d04ec 100644 --- a/package.json +++ b/package.json @@ -21,15 +21,15 @@ "@hapi/hoek": "^11.0.2" }, "devDependencies": { + "@hapi/boom10": "npm:@hapi/boom@^10.0.1", "@hapi/code": "9.x.x", "@hapi/eslint-plugin": "^7.0.0", "@hapi/lab": "^26.0.0", - "@types/node": "^17.0.31", - "typescript": "~4.6.4", - "@hapi/boom10": "npm:@hapi/boom@^10.0.1" + "@types/node": "^18.19.3", + "typescript": "~5.3.3" }, "scripts": { - "test": "lab -a @hapi/code -t 100 -L", + "test": "lab -a @hapi/code -t 100 -L -Y", "test-cov-html": "lab -a @hapi/code -t 100 -L -r html -o coverage.html" }, "license": "BSD-3-Clause" diff --git a/test/index.ts b/test/index.ts index 046b37d..88fa5fb 100755 --- a/test/index.ts +++ b/test/index.ts @@ -14,8 +14,6 @@ class X { } }; -const decorate = new X(1); - // new Boom.Boom() @@ -23,7 +21,8 @@ expect.type(new Boom.Boom()); expect.type(new Boom.Boom()); expect.type(new Boom.Boom('error')); -expect.error(new Boom.Boom('error', { decorate })); // No support for decoration on constructor +expect.error(null); +expect.error(new Boom.Boom(new Error('error'))); class CustomError extends Boom.Boom {} @@ -32,11 +31,6 @@ expect.type(new CustomError('Some error')); const boom = new Boom.Boom('some error'); expect.type(boom.output); -boom.output.payload.custom_null = null; -boom.output.payload.custom_number = 42; -boom.output.payload.custom_string = 'foo'; -boom.output.payload.custom_boolean = true; -boom.output.payload.custom_object = { bar: 42 }; boom.output.headers['header1'] = 'foo'; boom.output.headers['header2'] = ['foo', 'bar']; boom.output.headers['header3'] = 42; @@ -51,14 +45,13 @@ const error = new Error('Unexpected input'); expect.type(Boom.boomify(error, { statusCode: 400 })); expect.type(Boom.boomify(error, { statusCode: 400, message: 'Unexpected Input', override: false })); -expect.type(Boom.boomify(error, { decorate }).x); +expect.type(Boom.boomify('error')); +expect.type>(Boom.boomify(new Boom.Boom<{ foo: 'bar' }>())); expect.error(Boom.boomify(error, { statusCode: '400' })); -expect.error(Boom.boomify('error')); expect.error(Boom.boomify(error, { statusCode: 400, message: true })); expect.error(Boom.boomify(error, { statusCode: 400, override: 'false' })); expect.error(Boom.boomify()); -expect.error(Boom.boomify(error, { decorate }).y); // isBoom @@ -82,40 +75,40 @@ expect.error(Boom.isBoom()); // badRequest() -expect.type(Boom.badRequest('invalid query', 'some data')); -expect.type(Boom.badRequest('invalid query', { foo: 'bar' })); +expect.type>(Boom.badRequest('invalid query', 'some data')); +expect.type>(Boom.badRequest('invalid query', { foo: 'bar' })); expect.type(Boom.badRequest('invalid query')); expect.type(Boom.badRequest()); expect.error(Boom.badRequest(400)); expect.error(Boom.badRequest({ foo: 'bar' })); +expect.error(Boom.badRequest(new Error())); // unauthorized() -expect.type(Boom.unauthorized('invalid password')); -expect.type(Boom.unauthorized('invalid password', 'simple')); -expect.type(Boom.unauthorized(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4=')); -expect.type(Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' })); -expect.type(Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' } as Boom.unauthorized.Attributes)); -expect.type(Boom.unauthorized()); -expect.type(Boom.unauthorized('basic', ['a', 'b', 'c'])); -expect.type(Boom.unauthorized('', 'basic')); -expect.type(Boom.unauthorized(null, 'basic')); -expect.type(Boom.unauthorized('', 'basic').isMissing); -expect.type(Boom.unauthorized(null, 'basic').isMissing); - -expect.error(Boom.unauthorized(401)) -expect.error(Boom.unauthorized('invalid password', 500)) -expect.error(Boom.unauthorized('invalid password', 'sample', 500)) +expect.type>(Boom.unauthorized('invalid password')); +expect.type>(Boom.unauthorized('invalid password', 'simple')); +expect.type>(Boom.unauthorized(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4=')); +expect.type>(Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' })); +expect.type>(Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' } as Boom.unauthorized.Attributes)); +expect.type>(Boom.unauthorized()); +expect.type>(Boom.unauthorized('basic', ['a', 'b', 'c'])); +expect.type & Boom.unauthorized.MissingAuth>(Boom.unauthorized('', 'basic')); +expect.type & Boom.unauthorized.MissingAuth>(Boom.unauthorized(null, 'basic')); +expect.type(Boom.unauthorized('', 'basic').isMissing); +expect.type(Boom.unauthorized(null, 'basic').isMissing); + +expect.error(Boom.unauthorized(401)); +expect.error(Boom.unauthorized('invalid password', 500)); +expect.error(Boom.unauthorized('invalid password', 'sample', 500)); expect.error(Boom.unauthorized('basic', ['a', 'b', 'c'], 'test')); expect.error(Boom.unauthorized('message', 'basic').isMissing); - // paymentRequired() -expect.type(Boom.paymentRequired('bandwidth used', 'some data')); -expect.type(Boom.paymentRequired('bandwidth used', { foo: 'bar' })); +expect.type>(Boom.paymentRequired('bandwidth used', 'some data')); +expect.type>(Boom.paymentRequired('bandwidth used', { foo: 'bar' })); expect.type(Boom.paymentRequired('bandwidth used')); expect.type(Boom.paymentRequired()); @@ -125,8 +118,8 @@ expect.error(Boom.paymentRequired({ foo: 'bar' })); // forbidden() -expect.type(Boom.forbidden('try again some time', 'some data')); -expect.type(Boom.forbidden('try again some time', { foo: 'bar' })); +expect.type>(Boom.forbidden('try again some time', 'some data')); +expect.type>(Boom.forbidden('try again some time', { foo: 'bar' })); expect.type(Boom.forbidden('try again some time')); expect.type(Boom.forbidden()); @@ -136,8 +129,8 @@ expect.error(Boom.forbidden({ foo: 'bar' })); // notFound() -expect.type(Boom.notFound('missing', 'some data')); -expect.type(Boom.notFound('missing', { foo: 'bar' })); +expect.type>(Boom.notFound('missing', 'some data')); +expect.type>(Boom.notFound('missing', { foo: 'bar' })); expect.type(Boom.notFound('missing')); expect.type(Boom.notFound()); @@ -147,8 +140,8 @@ expect.error(Boom.notFound({ foo: 'bar' })); // methodNotAllowed() -expect.type(Boom.methodNotAllowed('this method is not allowed', 'some data')); -expect.type(Boom.methodNotAllowed('this method is not allowed', { foo: 'bar' })); +expect.type>(Boom.methodNotAllowed('this method is not allowed', 'some data')); +expect.type>(Boom.methodNotAllowed('this method is not allowed', { foo: 'bar' })); expect.type(Boom.methodNotAllowed('this method is not allowed')); expect.type(Boom.methodNotAllowed()); @@ -158,8 +151,8 @@ expect.error(Boom.methodNotAllowed({ foo: 'bar' })); // notAcceptable() -expect.type(Boom.notAcceptable('unacceptable', 'some data')); -expect.type(Boom.notAcceptable('unacceptable', { foo: 'bar' })); +expect.type>(Boom.notAcceptable('unacceptable', 'some data')); +expect.type>(Boom.notAcceptable('unacceptable', { foo: 'bar' })); expect.type(Boom.notAcceptable('unacceptable')); expect.type(Boom.notAcceptable()); @@ -169,8 +162,8 @@ expect.error(Boom.notAcceptable({ foo: 'bar' })); // proxyAuthRequired() -expect.type(Boom.proxyAuthRequired('auth missing', 'some data')); -expect.type(Boom.proxyAuthRequired('auth missing', { foo: 'bar' })); +expect.type>(Boom.proxyAuthRequired('auth missing', 'some data')); +expect.type>(Boom.proxyAuthRequired('auth missing', { foo: 'bar' })); expect.type(Boom.proxyAuthRequired('auth missing')); expect.type(Boom.proxyAuthRequired()); @@ -180,8 +173,8 @@ expect.error(Boom.proxyAuthRequired({ foo: 'bar' })); // clientTimeout() -expect.type(Boom.clientTimeout('timed out', 'some data')); -expect.type(Boom.clientTimeout('timed out', { foo: 'bar' })); +expect.type>(Boom.clientTimeout('timed out', 'some data')); +expect.type>(Boom.clientTimeout('timed out', { foo: 'bar' })); expect.type(Boom.clientTimeout('timed out')); expect.type(Boom.clientTimeout()); @@ -191,8 +184,8 @@ expect.error(Boom.clientTimeout({ foo: 'bar' })); // conflict() -expect.type(Boom.conflict('there was a conflict', 'some data')); -expect.type(Boom.conflict('there was a conflict', { foo: 'bar' })); +expect.type>(Boom.conflict('there was a conflict', 'some data')); +expect.type>(Boom.conflict('there was a conflict', { foo: 'bar' })); expect.type(Boom.conflict('there was a conflict')); expect.type(Boom.conflict()); @@ -202,8 +195,8 @@ expect.error(Boom.conflict({ foo: 'bar' })); // resourceGone() -expect.type(Boom.resourceGone('it is gone', 'some data')); -expect.type(Boom.resourceGone('it is gone', { foo: 'bar' })); +expect.type>(Boom.resourceGone('it is gone', 'some data')); +expect.type>(Boom.resourceGone('it is gone', { foo: 'bar' })); expect.type(Boom.resourceGone('it is gone')); expect.type(Boom.resourceGone()); @@ -213,8 +206,8 @@ expect.error(Boom.resourceGone({ foo: 'bar' })); // lengthRequired() -expect.type(Boom.lengthRequired('length needed', 'some data')); -expect.type(Boom.lengthRequired('length needed', { foo: 'bar' })); +expect.type>(Boom.lengthRequired('length needed', 'some data')); +expect.type>(Boom.lengthRequired('length needed', { foo: 'bar' })); expect.type(Boom.lengthRequired('length needed')); expect.type(Boom.lengthRequired()); @@ -224,8 +217,8 @@ expect.error(Boom.lengthRequired({ foo: 'bar' })); // preconditionFailed() -expect.type(Boom.preconditionFailed('failed', 'some data')); -expect.type(Boom.preconditionFailed('failed', { foo: 'bar' })); +expect.type>(Boom.preconditionFailed('failed', 'some data')); +expect.type>(Boom.preconditionFailed('failed', { foo: 'bar' })); expect.type(Boom.preconditionFailed('failed')); expect.type(Boom.preconditionFailed()); @@ -235,8 +228,8 @@ expect.error(Boom.preconditionFailed({ foo: 'bar' })); // entityTooLarge() -expect.type(Boom.entityTooLarge('too big', 'some data')); -expect.type(Boom.entityTooLarge('too big', { foo: 'bar' })); +expect.type>(Boom.entityTooLarge('too big', 'some data')); +expect.type>(Boom.entityTooLarge('too big', { foo: 'bar' })); expect.type(Boom.entityTooLarge('too big')); expect.type(Boom.entityTooLarge()); @@ -246,8 +239,8 @@ expect.error(Boom.entityTooLarge({ foo: 'bar' })); // uriTooLong() -expect.type(Boom.uriTooLong('uri is too long', 'some data')); -expect.type(Boom.uriTooLong('uri is too long', { foo: 'bar' })); +expect.type>(Boom.uriTooLong('uri is too long', 'some data')); +expect.type>(Boom.uriTooLong('uri is too long', { foo: 'bar' })); expect.type(Boom.uriTooLong('uri is too long')); expect.type(Boom.uriTooLong()); @@ -257,8 +250,8 @@ expect.error(Boom.uriTooLong({ foo: 'bar' })); // unsupportedMediaType() -expect.type(Boom.unsupportedMediaType('that media is not supported', 'some data')); -expect.type(Boom.unsupportedMediaType('that media is not supported', { foo: 'bar' })); +expect.type>(Boom.unsupportedMediaType('that media is not supported', 'some data')); +expect.type>(Boom.unsupportedMediaType('that media is not supported', { foo: 'bar' })); expect.type(Boom.unsupportedMediaType('that media is not supported')); expect.type(Boom.unsupportedMediaType()); @@ -268,8 +261,8 @@ expect.error(Boom.unsupportedMediaType({ foo: 'bar' })); // rangeNotSatisfiable() -expect.type(Boom.rangeNotSatisfiable('range not satisfiable', 'some data')); -expect.type(Boom.rangeNotSatisfiable('range not satisfiable', { foo: 'bar' })); +expect.type>(Boom.rangeNotSatisfiable('range not satisfiable', 'some data')); +expect.type>(Boom.rangeNotSatisfiable('range not satisfiable', { foo: 'bar' })); expect.type(Boom.rangeNotSatisfiable('range not satisfiable')); expect.type(Boom.rangeNotSatisfiable()); @@ -279,8 +272,8 @@ expect.error(Boom.rangeNotSatisfiable({ foo: 'bar' })); // expectationFailed() -expect.type(Boom.expectationFailed('expected this to work', 'some data')); -expect.type(Boom.expectationFailed('expected this to work', { foo: 'bar' })); +expect.type>(Boom.expectationFailed('expected this to work', 'some data')); +expect.type>(Boom.expectationFailed('expected this to work', { foo: 'bar' })); expect.type(Boom.expectationFailed('expected this to work')); expect.type(Boom.expectationFailed()); @@ -290,8 +283,8 @@ expect.error(Boom.expectationFailed({ foo: 'bar' })); // teapot() -expect.type(Boom.teapot('sorry, no coffee...', 'some data')); -expect.type(Boom.teapot('sorry, no coffee...', { foo: 'bar' })); +expect.type>(Boom.teapot('sorry, no coffee...', 'some data')); +expect.type>(Boom.teapot('sorry, no coffee...', { foo: 'bar' })); expect.type(Boom.teapot('sorry, no coffee...')); expect.type(Boom.teapot()); @@ -301,8 +294,8 @@ expect.error(Boom.teapot({ foo: 'bar' })); // badData() -expect.type(Boom.badData('your data is bad and you should feel bad', 'some data')); -expect.type(Boom.badData('your data is bad and you should feel bad', { foo: 'bar' })); +expect.type>(Boom.badData('your data is bad and you should feel bad', 'some data')); +expect.type>(Boom.badData('your data is bad and you should feel bad', { foo: 'bar' })); expect.type(Boom.badData('your data is bad and you should feel bad')); expect.type(Boom.badData()); @@ -312,8 +305,8 @@ expect.error(Boom.badData({ foo: 'bar' })); // locked() -expect.type(Boom.locked('this resource has been locked', 'some data')); -expect.type(Boom.locked('this resource has been locked', { foo: 'bar' })); +expect.type>(Boom.locked('this resource has been locked', 'some data')); +expect.type>(Boom.locked('this resource has been locked', { foo: 'bar' })); expect.type(Boom.locked('this resource has been locked')); expect.type(Boom.locked()); @@ -323,8 +316,8 @@ expect.error(Boom.locked({ foo: 'bar' })); // failedDependency() -expect.type(Boom.failedDependency('an external resource failed', 'some data')); -expect.type(Boom.failedDependency('an external resource failed', { foo: 'bar' })); +expect.type>(Boom.failedDependency('an external resource failed', 'some data')); +expect.type>(Boom.failedDependency('an external resource failed', { foo: 'bar' })); expect.type(Boom.failedDependency('an external resource failed')); expect.type(Boom.failedDependency()); @@ -333,8 +326,8 @@ expect.error(Boom.failedDependency({ foo: 'bar' })); // tooEarly() -expect.type(Boom.tooEarly('won\'t process your request', 'some data')); -expect.type(Boom.tooEarly('won\'t process your request', { foo: 'bar' })); +expect.type>(Boom.tooEarly('won\'t process your request', 'some data')); +expect.type>(Boom.tooEarly('won\'t process your request', { foo: 'bar' })); expect.type(Boom.tooEarly('won\'t process your request')); expect.type(Boom.tooEarly()); @@ -343,8 +336,8 @@ expect.error(Boom.tooEarly({ foo: 'bar' })); // preconditionRequired() -expect.type(Boom.preconditionRequired('you must supple an If-Match header', 'some data')); -expect.type(Boom.preconditionRequired('you must supple an If-Match header', { foo: 'bar' })); +expect.type>(Boom.preconditionRequired('you must supple an If-Match header', 'some data')); +expect.type>(Boom.preconditionRequired('you must supple an If-Match header', { foo: 'bar' })); expect.type(Boom.preconditionRequired('you must supple an If-Match header')); expect.type(Boom.preconditionRequired()); @@ -354,8 +347,8 @@ expect.error(Boom.preconditionRequired({ foo: 'bar' })); // tooManyRequests() -expect.type(Boom.tooManyRequests('you have exceeded your request limit', 'some data')); -expect.type(Boom.tooManyRequests('you have exceeded your request limit', { foo: 'bar' })); +expect.type>(Boom.tooManyRequests('you have exceeded your request limit', 'some data')); +expect.type>(Boom.tooManyRequests('you have exceeded your request limit', { foo: 'bar' })); expect.type(Boom.tooManyRequests('you have exceeded your request limit')); expect.type(Boom.tooManyRequests()); @@ -365,8 +358,8 @@ expect.error(Boom.tooManyRequests({ foo: 'bar' })); // illegal() -expect.type(Boom.illegal('you are not permitted to view this resource for legal reasons', 'some data')); -expect.type(Boom.illegal('you are not permitted to view this resource for legal reasons', { foo: 'bar' })); +expect.type>(Boom.illegal('you are not permitted to view this resource for legal reasons', 'some data')); +expect.type>(Boom.illegal('you are not permitted to view this resource for legal reasons', { foo: 'bar' })); expect.type(Boom.illegal('you are not permitted to view this resource for legal reasons')); expect.type(Boom.illegal()); @@ -378,8 +371,8 @@ expect.error(Boom.illegal({ foo: 'bar' })); // internal() -expect.type(Boom.internal('terrible implementation', 'some data', 599)); -expect.type(Boom.internal('terrible implementation', { foo: 'bar' })); +expect.type>(Boom.internal('terrible implementation', 'some data', 599)); +expect.type>(Boom.internal('terrible implementation', { foo: 'bar' })); expect.type(Boom.internal('terrible implementation')); expect.type(Boom.internal()); @@ -389,8 +382,8 @@ expect.error(Boom.internal({ foo: 'bar' })); // badImplementation() -expect.type(Boom.badImplementation('terrible implementation', 'some data')); -expect.type(Boom.badImplementation('terrible implementation', { foo: 'bar' })); +expect.type>(Boom.badImplementation('terrible implementation', 'some data')); +expect.type>(Boom.badImplementation('terrible implementation', { foo: 'bar' })); expect.type(Boom.badImplementation('terrible implementation')); expect.type(Boom.badImplementation()); @@ -400,8 +393,8 @@ expect.error(Boom.badImplementation({ foo: 'bar' })); // notImplemented() -expect.type(Boom.notImplemented('method not implemented', 'some data')); -expect.type(Boom.notImplemented('method not implemented', { foo: 'bar' })); +expect.type>(Boom.notImplemented('method not implemented', 'some data')); +expect.type>(Boom.notImplemented('method not implemented', { foo: 'bar' })); expect.type(Boom.notImplemented('method not implemented')); expect.type(Boom.notImplemented()); @@ -411,8 +404,8 @@ expect.error(Boom.notImplemented({ foo: 'bar' })); // badGateway() -expect.type(Boom.badGateway('this is a bad gateway', 'some data')); -expect.type(Boom.badGateway('this is a bad gateway', { foo: 'bar' })); +expect.type>(Boom.badGateway('this is a bad gateway', 'some data')); +expect.type>(Boom.badGateway('this is a bad gateway', { foo: 'bar' })); expect.type(Boom.badGateway('this is a bad gateway')); expect.type(Boom.badGateway()); @@ -422,8 +415,8 @@ expect.error(Boom.badGateway({ foo: 'bar' })); // serverUnavailable() -expect.type(Boom.serverUnavailable('unavailable', 'some data')); -expect.type(Boom.serverUnavailable('unavailable', { foo: 'bar' })); +expect.type>(Boom.serverUnavailable('unavailable', 'some data')); +expect.type>(Boom.serverUnavailable('unavailable', { foo: 'bar' })); expect.type(Boom.serverUnavailable('unavailable')); expect.type(Boom.serverUnavailable()); @@ -433,8 +426,8 @@ expect.error(Boom.serverUnavailable({ foo: 'bar' })); // gatewayTimeout() -expect.type(Boom.gatewayTimeout('gateway timeout', 'some data')); -expect.type(Boom.gatewayTimeout('gateway timeout', { foo: 'bar' })); +expect.type>(Boom.gatewayTimeout('gateway timeout', 'some data')); +expect.type>(Boom.gatewayTimeout('gateway timeout', { foo: 'bar' })); expect.type(Boom.gatewayTimeout('gateway timeout')); expect.type(Boom.gatewayTimeout()); From 4159ddebda55e537d520b4f64da7bb4431e498fb Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 14:33:50 +0100 Subject: [PATCH 24/50] Clone incoming headers --- lib/index.js | 2 +- test/index.js | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/index.js b/lib/index.js index 314f7c2..3a853a7 100755 --- a/lib/index.js +++ b/lib/index.js @@ -199,7 +199,7 @@ internals.BoomOutput = class { this.statusCode = statusCode; this.payload = payload; - this.headers = headers ?? {}; + this.headers = headers ? Hoek.clone(headers, { prototype: false, symbols: false }) : {}; } }; diff --git a/test/index.js b/test/index.js index dd63d65..546f3a3 100755 --- a/test/index.js +++ b/test/index.js @@ -79,6 +79,17 @@ describe('Boom', () => { expect(err.output.headers).to.equal({ custom: 'yes' }); }); + it('clones headers object', () => { + + const headers = { custom: ['yes'] }; + const err = new Boom.Boom('fail', { statusCode: 400, headers }); + err.output.headers.custom.push('more'); + err.output.headers.extra = 'added'; + + expect(err.output.headers).to.equal({ custom: ['yes', 'more'], extra: 'added' }); + expect(headers).to.equal({ custom: ['yes'] }); + }); + it('throws when statusCode is invalid', () => { expect(() => { From 7c10de206f9a64b0b09ac997554b9f7cce76505d Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 14:54:19 +0100 Subject: [PATCH 25/50] Cleanup typings --- lib/index.d.ts | 12 ++++++------ test/index.ts | 5 +++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index ff3a5df..5608c08 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -63,7 +63,7 @@ export interface Options { /** * An object containing any HTTP headers where each key is a header name and value is the header content */ - readonly headers?: { [header: string]: string | string[] | number }; + readonly headers?: { [header: string]: string | readonly string[] | number }; /** * Constructor reference used to crop the exception call stack output @@ -116,17 +116,17 @@ export interface Output { /** * The HTTP status code */ - readonly statusCode: number; + statusCode: number; /** * An object containing any HTTP headers where each key is a header name and value is the header content */ - readonly headers: { [header: string]: string | string[] | number | undefined }; + headers: { [header: string]: string | string[] | number | undefined }; /** * The formatted object used as the response payload (stringified) */ - readonly payload: Payload; + payload: Payload & { [key: string]: unknown }; } @@ -213,7 +213,7 @@ export namespace unauthorized { * * @returns A 401 Unauthorized error */ -export function unauthorized(message: string | null | undefined, wwwAuthenticate: string[]): Boom; +export function unauthorized(message: string | null | undefined, wwwAuthenticate: readonly string[]): Boom; /** @@ -258,7 +258,7 @@ export function notFound(message?: string, data?: Data): Boom; * * @returns A 405 Method Not Allowed error */ -export function methodNotAllowed(message?: string, data?: Data, allow?: string | string[]): Boom; +export function methodNotAllowed(message?: string, data?: Data, allow?: string | readonly string[]): Boom; /** diff --git a/test/index.ts b/test/index.ts index 88fa5fb..82b69f0 100755 --- a/test/index.ts +++ b/test/index.ts @@ -31,6 +31,11 @@ expect.type(new CustomError('Some error')); const boom = new Boom.Boom('some error'); expect.type(boom.output); +boom.output.payload.custom_null = null; +boom.output.payload.custom_number = 42; +boom.output.payload.custom_string = 'foo'; +boom.output.payload.custom_boolean = true; +boom.output.payload.custom_object = { bar: 42 }; boom.output.headers['header1'] = 'foo'; boom.output.headers['header2'] = ['foo', 'bar']; boom.output.headers['header3'] = 42; From 7dd941e03e6b07c64f59ffd5b208b28b7523d12d Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 11 Dec 2023 11:02:12 +0100 Subject: [PATCH 26/50] Narrow typings Co-authored-by: Matthieu Sieben --- lib/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index 5608c08..fa777b9 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -63,7 +63,7 @@ export interface Options { /** * An object containing any HTTP headers where each key is a header name and value is the header content */ - readonly headers?: { [header: string]: string | readonly string[] | number }; + readonly headers?: { readonly [header: string]: string | readonly string[] | number }; /** * Constructor reference used to crop the exception call stack output From 6c15e5b4fa6c865266de17e9bbcd3ded2becfabe Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 17:18:53 +0100 Subject: [PATCH 27/50] Revert "Remove decorate option" This reverts commit 19e5e2a0ad42d6fcd97c87d3c62535f1f1cd8065. # Conflicts: # lib/index.js --- lib/index.js | 18 +++++++++++------- test/index.js | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/lib/index.js b/lib/index.js index 3a853a7..c246734 100755 --- a/lib/index.js +++ b/lib/index.js @@ -80,7 +80,7 @@ exports.Boom = class Boom extends Error { constructor(message, options = {}) { - const { statusCode = 500, data, headers, ctor = exports.Boom, cause } = options; + const { statusCode = 500, data, headers, decorate, ctor = exports.Boom, cause } = options; super(message ?? internals.codes.get(statusCode) ?? 'Unknown', { cause }); Error.captureStackTrace(this, ctor); // Filter the stack to our external API @@ -89,7 +89,7 @@ exports.Boom = class Boom extends Error { this.cause ??= cause; // Explicitly assign cause to work with old runtimes } - internals.apply(this, data, statusCode, headers); + internals.apply(this, data, decorate, statusCode, headers); } static [Symbol.hasInstance](instance) { @@ -123,17 +123,17 @@ exports.isBoom = function (err, statusCode) { exports.boomify = function (err, options = {}) { - const { override, data, statusCode, message } = options; + const { override, data, decorate, statusCode, message } = options; if (!err?.isBoom) { - return new exports.Boom(message, { statusCode, cause: err, data }); + return new exports.Boom(message, { statusCode, cause: err, data, decorate }); } if (override === false) { // Defaults to true - internals.apply(err, data); + internals.apply(err, data, decorate); } else { - internals.apply(err, data, statusCode ?? err.output.statusCode, {}, message); + internals.apply(err, data, decorate, statusCode ?? err.output.statusCode, {}, message); } err.isServer = err.output.statusCode >= 500; // Assign, in case it is a legacy boom object @@ -142,7 +142,11 @@ exports.boomify = function (err, options = {}) { }; -internals.apply = function (boom, data, statusCode, headers, message) { +internals.apply = function (boom, data, decorate, statusCode, headers, message) { + + if (decorate) { + Object.assign(boom, decorate); + } if (data !== undefined) { boom.data = data; diff --git a/test/index.js b/test/index.js index 546f3a3..1adb817 100755 --- a/test/index.js +++ b/test/index.js @@ -47,6 +47,14 @@ describe('Boom', () => { expect(new SubBoom().name).to.equal('BadaBoom'); }); + it('decorates error', () => { + + const err = new Boom.Boom('oops', { statusCode: 400, decorate: { x: 1 } }); + expect(err.output.payload.message).to.equal('oops'); + expect(err.output.statusCode).to.equal(400); + expect(err.x).to.equal(1); + }); + it('handles missing message', () => { const err = new Boom.Boom(); @@ -235,6 +243,13 @@ describe('Boom', () => { expect(error).to.shallow.equal(Boom.boomify(error, { statusCode: 444 })); }); + it('decorates error', () => { + + const error = new Error('oops'); + const err = Boom.boomify(error, { statusCode: 400, decorate: { x: 1 } }); + expect(err.x).to.equal(1); + }); + it('returns an error with info when constructed using another error', () => { const error = new Error('ka-boom'); From 56f68c60c3b51abba9a9d5589cfcc9b53ab9aecb Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 17:22:43 +0100 Subject: [PATCH 28/50] Use decorate option internally --- lib/index.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/index.js b/lib/index.js index c246734..44afb7b 100755 --- a/lib/index.js +++ b/lib/index.js @@ -213,8 +213,8 @@ internals.statusError = function (statusCode, massage) { const method = massage ? function (...args) { - const [message, options, decorate] = massage(...args); - return Object.assign(new exports.Boom(message, { statusCode, ctor: method, ...options }), decorate); + const [message, options] = massage(...args); + return new exports.Boom(message, { statusCode, ctor: method, ...options }); } : function (message, data) { @@ -277,7 +277,7 @@ exports.unauthorized = internals.statusError(401, (message, scheme, attributes) } const headers = { 'WWW-Authenticate': stringified ? `${scheme} ${stringified}` : `${scheme}` }; - return [message, { headers }, decorate]; + return [message, { headers, decorate }]; }); @@ -392,7 +392,7 @@ exports.gatewayTimeout = internals.statusError(504, internals.serverError); exports.badImplementation = internals.statusError(500, (message, data) => { const res = internals.serverError(message, data); - res.push({ isDeveloperError: true }); + res[1].decorate = { isDeveloperError: true }; return res; }); From e0283660468bd8381e0b3658a9ba5808da6762c8 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 24 Oct 2024 14:03:51 +0200 Subject: [PATCH 29/50] Allow usage on runtimes with no Error.captureStackTrace() --- lib/index.js | 4 +++- test/index.js | 42 ++++++++++++++++++++++++++++++------------ 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/lib/index.js b/lib/index.js index 44afb7b..aedd94b 100755 --- a/lib/index.js +++ b/lib/index.js @@ -83,7 +83,9 @@ exports.Boom = class Boom extends Error { const { statusCode = 500, data, headers, decorate, ctor = exports.Boom, cause } = options; super(message ?? internals.codes.get(statusCode) ?? 'Unknown', { cause }); - Error.captureStackTrace(this, ctor); // Filter the stack to our external API + if (typeof Error.captureStackTrace === 'function') { // Only use when available + Error.captureStackTrace(this, ctor); // Filter the stack to our external API + } if (cause !== undefined) { this.cause ??= cause; // Explicitly assign cause to work with old runtimes diff --git a/test/index.js b/test/index.js index 1adb817..d9e9415 100755 --- a/test/index.js +++ b/test/index.js @@ -1013,22 +1013,40 @@ describe('Boom', () => { describe('stack trace', () => { + const helpers = ['badRequest', 'unauthorized', 'forbidden', 'notFound', 'methodNotAllowed', + 'notAcceptable', 'proxyAuthRequired', 'clientTimeout', 'conflict', + 'resourceGone', 'lengthRequired', 'preconditionFailed', 'entityTooLarge', + 'uriTooLong', 'unsupportedMediaType', 'rangeNotSatisfiable', 'expectationFailed', + 'badData', 'preconditionRequired', 'tooManyRequests', + + // 500s + 'internal', 'notImplemented', 'badGateway', 'serverUnavailable', + 'gatewayTimeout', 'badImplementation' + ]; + it('should omit lib', () => { - ['badRequest', 'unauthorized', 'forbidden', 'notFound', 'methodNotAllowed', - 'notAcceptable', 'proxyAuthRequired', 'clientTimeout', 'conflict', - 'resourceGone', 'lengthRequired', 'preconditionFailed', 'entityTooLarge', - 'uriTooLong', 'unsupportedMediaType', 'rangeNotSatisfiable', 'expectationFailed', - 'badData', 'preconditionRequired', 'tooManyRequests', + for (const helper of helpers) { + const err = Boom[helper](); + expect(err.stack).to.not.match(/\/lib\/index\.js/); + } + }); - // 500s - 'internal', 'notImplemented', 'badGateway', 'serverUnavailable', - 'gatewayTimeout', 'badImplementation' - ].forEach((name) => { + it('should not crash when Error.captureStackTrace is missing', (flags) => { - const err = Boom[name](); - expect(err.stack).to.not.match(/\/lib\/index\.js/); - }); + const captureStackTrace = Error.captureStackTrace; + + for (const helper of helpers) { + try { + Error.captureStackTrace = undefined; + var err = Boom[helper](); + } + finally { + Error.captureStackTrace = captureStackTrace; + } + + expect(err.stack).to.match(/\/lib\/index\.js/); + } }); }); From 7cdb489da518f167af1bdb2639077f5719e0a320 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 24 Oct 2024 14:39:37 +0200 Subject: [PATCH 30/50] Update docs --- API.md | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/API.md b/API.md index 800309a..beb2fdf 100755 --- a/API.md +++ b/API.md @@ -31,34 +31,33 @@ Rebuilds `error.output` using the other object properties where: ##### `new Boom.Boom(message, [options])` -Creates a new `Boom` object using the provided `message` and then calling -[`boomify()`](#boomifyerr-options) to decorate the error with the `Boom` properties, where: -- `message` - the error message. If `message` is an error, it is the same as calling - [`boomify()`](#boomifyerr-options) directly. +Creates a new `Boom` object, where: +- `message` - the error message. - `options` - and optional object where: - - `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set. + - `statusCode` - the HTTP status code. Defaults to `500`. + - `cause` - The error that caused the boom error. - `data` - additional error information (assigned to `error.data`). - `decorate` - an option with extra properties to set on the error object. - `ctor` - constructor reference used to crop the exception call stack output. - - if `message` is an error object, also supports the other [`boomify()`](#boomifyerr-options) - options. ##### `boomify(err, [options])` -Decorates an error with the `Boom` properties where: +This works as [`new Boom.Boom()`](#new-boomboommessage-options), except when the `err` argument is a boom error. +In that case, it will apply the options to the existing error, instead of wrapping it in a new boom error. +Decorates a boom object with the `Boom` properties where: - `err` - the `Error` object to decorate. - `options` - optional object with the following optional settings: - `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set and `err` is not a `Boom` object. - `message` - error message string. If the error already has a message, the provided `message` is added as a prefix. - Defaults to no message. - `decorate` - an option with extra properties to set on the error object. - `override` - if `false`, the `err` provided is a `Boom` object, and a `statusCode` or `message` are provided, the values are ignored. Defaults to `true` (apply the provided `statusCode` and `message` options to the error regardless of its type, `Error` or `Boom` object). +- it returns the boomified error ```js -var error = new Error('Unexpected input'); -Boom.boomify(error, { statusCode: 400 }); +const error = new Error('Unexpected input'); +const boomified = Boom.boomify(error, { statusCode: 400 }); ``` ##### `isBoom(err, [statusCode])` From 65f4dc564291d3d538cbd244db4f431e0115a39e Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 24 Oct 2024 14:40:01 +0200 Subject: [PATCH 31/50] Restore decorate option to typings --- lib/index.d.ts | 10 ++++++++-- test/index.ts | 11 ++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index fa777b9..f8f26db 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -60,6 +60,11 @@ export interface Options { */ readonly data?: Data; + /** + * An object with extra properties to set on the error object + */ + readonly decorate?: { [key: string]: any }; + /** * An object containing any HTTP headers where each key is a header name and value is the header content */ @@ -149,10 +154,11 @@ export function isBoom(obj: unknown, statusCode?: number): obj is Boom; * * @returns A boom object */ -export function boomify(err: Boom, options?: BoomifyOptions): Boom; +export function boomify(err: Boom, options?: BoomifyOptions & { decorate: Decoration }): Boom & Decoration; +export function boomify(err: unknown, options?: BoomifyOptions & { decorate: Decoration }): Boom & Decoration; +export function boomify(err: Boom, options?: BoomifyOptions): Boom; export function boomify(err: unknown, options?: BoomifyOptions): Boom; - // 4xx Errors /** diff --git a/test/index.ts b/test/index.ts index 82b69f0..387e0d9 100755 --- a/test/index.ts +++ b/test/index.ts @@ -15,14 +15,17 @@ class X { }; +const decorate = new X(1); + // new Boom.Boom() expect.type(new Boom.Boom()); expect.type(new Boom.Boom()); expect.type(new Boom.Boom('error')); +expect.type(new Boom.Boom('error', { decorate })); -expect.error(null); -expect.error(new Boom.Boom(new Error('error'))); +expect.error(new Boom.Boom(null)); +expect.error(new Boom.Boom(new Error('error'))); class CustomError extends Boom.Boom {} @@ -50,6 +53,7 @@ const error = new Error('Unexpected input'); expect.type(Boom.boomify(error, { statusCode: 400 })); expect.type(Boom.boomify(error, { statusCode: 400, message: 'Unexpected Input', override: false })); +expect.type(Boom.boomify(error, { decorate }).x); expect.type(Boom.boomify('error')); expect.type>(Boom.boomify(new Boom.Boom<{ foo: 'bar' }>())); @@ -57,7 +61,8 @@ expect.error(Boom.boomify(error, { statusCode: '400' })); expect.error(Boom.boomify(error, { statusCode: 400, message: true })); expect.error(Boom.boomify(error, { statusCode: 400, override: 'false' })); expect.error(Boom.boomify()); - +expect.error(Boom.boomify(error, { decorate: true })); +expect.error(Boom.boomify(error, { decorate }).y); // isBoom From 5f95c1b6f8d0569e896b0d8345e757ccd266d5fd Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 17:13:17 +0100 Subject: [PATCH 32/50] Make reformat() apply to initial payload --- lib/index.js | 9 ++++----- test/index.js | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/lib/index.js b/lib/index.js index aedd94b..aa7baa4 100755 --- a/lib/index.js +++ b/lib/index.js @@ -164,8 +164,8 @@ internals.apply = function (boom, data, decorate, statusCode, headers, message) boom.message = `${message}: ${boom.message}`; } - const payload = new internals.PayloadObject(boom, numberCode, false); - boom.output = new internals.BoomOutput(numberCode, payload, headers); + boom.output = new internals.BoomOutput(numberCode, headers); + boom.reformat(); } }; @@ -198,13 +198,12 @@ internals.PayloadObject = class { internals.BoomOutput = class { statusCode; - payload; + payload = {}; headers; - constructor(statusCode, payload, headers) { + constructor(statusCode, headers) { this.statusCode = statusCode; - this.payload = payload; this.headers = headers ? Hoek.clone(headers, { prototype: false, symbols: false }) : {}; } }; diff --git a/test/index.js b/test/index.js index d9e9415..74e314c 100755 --- a/test/index.js +++ b/test/index.js @@ -1126,5 +1126,45 @@ describe('Boom', () => { Object.defineProperty(new Boom.Boom('oops'), 'reformat', { value: true }); }); + + it('can be implemented by subclasses to apply custom formatting', () => { + + class MyBoom extends Boom.Boom { + + reformat(...args) { + + super.reformat(...args); + + this.output.payload.custom = true; + } + } + + const err = new MyBoom('boom', { statusCode: 400 }); + expect(err.output.statusCode).to.equal(400); + expect(err.output.payload.message).to.equal('boom'); + expect(err.output.payload.custom).to.be.true(); + + err.output.statusCode = 500; + err.reformat(); + expect(err.output.statusCode).to.equal(500); + expect(err.output.payload.message).to.equal('An internal server error occurred'); + expect(err.output.payload.custom).to.be.true(); + }); + + it('prototype can be changed to always debug', (flags) => { + + const proto = Boom.Boom.prototype.reformat; + flags.onCleanup = () => { + + Boom.Boom.prototype.reformat = proto; + }; + + Boom.Boom.prototype.reformat = function () { + + return proto.call(this, true); + }; + + expect(Boom.internal('DEBUG').output.payload.message).to.equal('DEBUG'); + }); }); }); From e412efb4a04a91bffa865cf40a0e304d37250888 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 24 Oct 2024 14:47:54 +0200 Subject: [PATCH 33/50] Update typescript --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 67d04ec..099707c 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "@hapi/eslint-plugin": "^7.0.0", "@hapi/lab": "^26.0.0", "@types/node": "^18.19.3", - "typescript": "~5.3.3" + "typescript": "~5.6.3" }, "scripts": { "test": "lab -a @hapi/code -t 100 -L -Y", From c04639ec76344a94da9703049e6bf697fefee486 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 24 Oct 2024 14:51:04 +0200 Subject: [PATCH 34/50] Fix tests on windows filesystem --- test/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/index.js b/test/index.js index 74e314c..d74f6e3 100755 --- a/test/index.js +++ b/test/index.js @@ -1028,7 +1028,7 @@ describe('Boom', () => { for (const helper of helpers) { const err = Boom[helper](); - expect(err.stack).to.not.match(/\/lib\/index\.js/); + expect(err.stack).to.not.match(/(\/|\\)lib(\/|\\)index\.js/); } }); @@ -1045,7 +1045,7 @@ describe('Boom', () => { Error.captureStackTrace = captureStackTrace; } - expect(err.stack).to.match(/\/lib\/index\.js/); + expect(err.stack).to.match(/(\/|\\)lib(\/|\\)index\.js/); } }); }); From 01643e9645192ec4a5ba354f315520a89343ea78 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Sat, 26 Oct 2024 12:39:59 +0200 Subject: [PATCH 35/50] Don't set cause when not in the options --- lib/index.d.ts | 2 +- lib/index.js | 9 +++++---- test/index.js | 11 +++++++++++ 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index f8f26db..18fe68c 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -78,7 +78,7 @@ export interface Options { /** * An underlying cause for the Boom error */ - readonly cause?: Error | unknown; + readonly cause?: Error | unknown | undefined; } diff --git a/lib/index.js b/lib/index.js index aa7baa4..d71429c 100755 --- a/lib/index.js +++ b/lib/index.js @@ -80,15 +80,16 @@ exports.Boom = class Boom extends Error { constructor(message, options = {}) { - const { statusCode = 500, data, headers, decorate, ctor = exports.Boom, cause } = options; + const { statusCode = 500, data, headers, decorate, ctor = exports.Boom } = options; + const causeOption = 'cause' in options ? { cause: options.cause } : undefined; - super(message ?? internals.codes.get(statusCode) ?? 'Unknown', { cause }); + super(message ?? internals.codes.get(statusCode) ?? 'Unknown', causeOption); if (typeof Error.captureStackTrace === 'function') { // Only use when available Error.captureStackTrace(this, ctor); // Filter the stack to our external API } - if (cause !== undefined) { - this.cause ??= cause; // Explicitly assign cause to work with old runtimes + if (causeOption) { + this.cause ??= causeOption.cause; // Explicitly assign cause to work with old runtimes } internals.apply(this, data, decorate, statusCode, headers); diff --git a/test/index.js b/test/index.js index d74f6e3..35cb321 100755 --- a/test/index.js +++ b/test/index.js @@ -141,6 +141,17 @@ describe('Boom', () => { expect(err.output.payload.error).to.equal('Unknown'); }); + it('only sets cause when part of options', () => { + + const err1 = new Boom.Boom('fail', { cause: undefined }); + expect(err1).to.include('cause'); + expect(err1.cause).to.equal(undefined); + + const err2 = new Boom.Boom('fail', {}); + expect(err2).to.not.include('cause'); + expect(err2.cause).to.equal(undefined); + }); + it('assigns a .cause property if Error does not support it', (flags) => { const proto = Object.getPrototypeOf(Boom.Boom); From 413224dc42cfb4b18c9c1bb141c1b01635054808 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Sat, 26 Oct 2024 13:16:09 +0200 Subject: [PATCH 36/50] Allow isServer to be written to --- lib/index.js | 15 ++++++++++++--- test/index.js | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/lib/index.js b/lib/index.js index d71429c..9d0f4ce 100755 --- a/lib/index.js +++ b/lib/index.js @@ -76,7 +76,14 @@ exports.Boom = class Boom extends Error { return this.output.statusCode >= 500; } - set isServer(value) {} // Allow for compatiblity with legacy boom + set isServer(value) { // Allow for compatiblity with legacy boom + + Object.defineProperty(this, 'isServer', { + value, + writable: true, + configurable: true + }); + } constructor(message, options = {}) { @@ -128,7 +135,7 @@ exports.boomify = function (err, options = {}) { const { override, data, decorate, statusCode, message } = options; - if (!err?.isBoom) { + if (!err?.isBoom === true) { return new exports.Boom(message, { statusCode, cause: err, data, decorate }); } @@ -139,7 +146,9 @@ exports.boomify = function (err, options = {}) { internals.apply(err, data, decorate, statusCode ?? err.output.statusCode, {}, message); } - err.isServer = err.output.statusCode >= 500; // Assign, in case it is a legacy boom object + if (err.hasOwnProperty('isServer')) { + err.isServer = err.output.statusCode >= 500; // Assign, in case it is a legacy boom object + } return err; }; diff --git a/test/index.js b/test/index.js index 35cb321..36e988a 100755 --- a/test/index.js +++ b/test/index.js @@ -369,6 +369,22 @@ describe('Boom', () => { expect(boom.output.statusCode).to.equal(400); }); + it('only sets isServer when it is an own property', () => { + + const boom = Boom.boomify(new Boom.Boom()); + expect(boom.isServer).to.be.true(); + expect(boom.hasOwnProperty('isServer')).to.be.false(); + + const Boom2 = class extends Boom.Boom { + + isServer = undefined; + }; + + const boom2 = Boom.boomify(new Boom2()); + expect(boom2.isServer).to.be.true(); + expect(boom2.hasOwnProperty('isServer')).to.be.true(); + }); + it('works with legacy boom', () => { const boom = Boom.boomify(new Boom10.Boom(null, { statusCode: 404 }), { statusCode: 501, message: 'Override' }); @@ -376,6 +392,7 @@ describe('Boom', () => { expect(boom.cause).to.be.undefined(); expect(boom.message).to.equal('Override: Not Found'); expect(boom.isServer).to.be.true(); + expect(boom.hasOwnProperty('isServer')).to.be.true(); expect(boom.output.statusCode).to.equal(501); const boom10 = Boom10.boomify(new Boom.Boom(null, { statusCode: 404 }), { statusCode: 501, message: 'Override' }); @@ -383,6 +400,7 @@ describe('Boom', () => { expect(boom10.cause).to.be.undefined(); expect(boom10.message).to.equal('Override: Not Found'); expect(boom10.isServer).to.be.true(); + expect(boom10.hasOwnProperty('isServer')).to.be.true(); expect(boom10.output.statusCode).to.equal(501); }); }); From af7b957addc4cf62de14d2a65ee18759ac792d5a Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Sat, 26 Oct 2024 13:31:33 +0200 Subject: [PATCH 37/50] Fix boomify option typings --- lib/index.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index 18fe68c..1947522 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -46,8 +46,7 @@ export class Boom extends Error { reformat(debug?: boolean): void; } - -export interface Options { +export interface BaseOptions { /** * The HTTP status code * @@ -64,7 +63,10 @@ export interface Options { * An object with extra properties to set on the error object */ readonly decorate?: { [key: string]: any }; +} + +export interface Options extends BaseOptions { /** * An object containing any HTTP headers where each key is a header name and value is the header content */ @@ -82,7 +84,7 @@ export interface Options { } -export interface BoomifyOptions extends Options { +export interface BoomifyOptions extends BaseOptions { /** * Error message string * From 46fe6b0b43a6eb8b369b0a22a6a83aeec4cd9945 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Sat, 26 Oct 2024 14:25:40 +0200 Subject: [PATCH 38/50] Improve boomify typings --- lib/index.d.ts | 7 +++---- test/index.ts | 5 +++++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index 1947522..3ed9367 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -156,10 +156,9 @@ export function isBoom(obj: unknown, statusCode?: number): obj is Boom; * * @returns A boom object */ -export function boomify(err: Boom, options?: BoomifyOptions & { decorate: Decoration }): Boom & Decoration; -export function boomify(err: unknown, options?: BoomifyOptions & { decorate: Decoration }): Boom & Decoration; -export function boomify(err: Boom, options?: BoomifyOptions): Boom; -export function boomify(err: unknown, options?: BoomifyOptions): Boom; +export function boomify(err: Terr, options: BoomifyOptions & { decorate: Decoration, data: Data }): (Terr extends Boom ? Terr : Boom) & Omit; +export function boomify(err: Terr, options: BoomifyOptions & { decorate: Decoration }): (Terr extends Boom ? Terr : Boom) & Decoration; +export function boomify(err: Terr, options?: BoomifyOptions): Terr extends Boom ? Terr : Boom; // 4xx Errors diff --git a/test/index.ts b/test/index.ts index 387e0d9..b4cbd48 100755 --- a/test/index.ts +++ b/test/index.ts @@ -50,12 +50,17 @@ expect.type(boom.output.headers); // boomify() const error = new Error('Unexpected input'); +class BadaBoom extends Boom.Boom {} expect.type(Boom.boomify(error, { statusCode: 400 })); expect.type(Boom.boomify(error, { statusCode: 400, message: 'Unexpected Input', override: false })); expect.type(Boom.boomify(error, { decorate }).x); expect.type(Boom.boomify('error')); expect.type>(Boom.boomify(new Boom.Boom<{ foo: 'bar' }>())); +expect.type(Boom.boomify(error, { decorate: { data: 1 } }).data); +expect.type(Boom.boomify(error, { decorate: { data: 1 }, data: 'bla' }).data); +expect.type(Boom.boomify(error, { data: 'bla' }).data); +expect.type(Boom.boomify(new BadaBoom(), { statusCode: 400 })); expect.error(Boom.boomify(error, { statusCode: '400' })); expect.error(Boom.boomify(error, { statusCode: 400, message: true })); From c748aae930e6739d43882843337d0160406aa328 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Sat, 26 Oct 2024 17:02:11 +0200 Subject: [PATCH 39/50] Document headers option --- API.md | 1 + 1 file changed, 1 insertion(+) diff --git a/API.md b/API.md index beb2fdf..4c732b7 100755 --- a/API.md +++ b/API.md @@ -38,6 +38,7 @@ Creates a new `Boom` object, where: - `cause` - The error that caused the boom error. - `data` - additional error information (assigned to `error.data`). - `decorate` - an option with extra properties to set on the error object. + - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content. - `ctor` - constructor reference used to crop the exception call stack output. ##### `boomify(err, [options])` From aea4536a257f7dd0e4772aa7b4c6143fe4cacfcf Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Wed, 30 Oct 2024 20:38:46 +0100 Subject: [PATCH 40/50] Require data option when Data generic is not unknown --- lib/index.d.ts | 11 +++++++++-- test/index.ts | 11 +++++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index 3ed9367..d8872e1 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -1,12 +1,19 @@ +type NotUnknown = string | number | boolean | bigint | symbol | null | object; + +declare namespace Boom { + type CtorArgs = [message?: string, options?: Options]; + type WithDataArgs = [message: string, options: Options & { data: Data }]; +} + /** * An Error object used to return an HTTP response error (4xx, 5xx) */ -export class Boom extends Error { +export class Boom extends Error { /** * Creates a new Boom object using the provided message or Error */ - constructor(message?: string, options?: Options); + constructor(...args: Data extends NotUnknown ? Boom.WithDataArgs : Boom.CtorArgs); /** * Underlying cause for the Boom error diff --git a/test/index.ts b/test/index.ts index b4cbd48..9e126fa 100755 --- a/test/index.ts +++ b/test/index.ts @@ -19,13 +19,16 @@ const decorate = new X(1); // new Boom.Boom() -expect.type(new Boom.Boom()); expect.type(new Boom.Boom()); -expect.type(new Boom.Boom('error')); -expect.type(new Boom.Boom('error', { decorate })); +expect.type>(new Boom.Boom('error')); +expect.type>(new Boom.Boom('error', { data: true })); +expect.type>(new Boom.Boom('error')); +expect.type>(new Boom.Boom('error', { data: true })); expect.error(new Boom.Boom(null)); expect.error(new Boom.Boom(new Error('error'))); +expect.error(new Boom.Boom('error')); +expect.error(new Boom.Boom('error', { data: true })); class CustomError extends Boom.Boom {} @@ -56,7 +59,7 @@ expect.type(Boom.boomify(error, { statusCode: 400 })); expect.type(Boom.boomify(error, { statusCode: 400, message: 'Unexpected Input', override: false })); expect.type(Boom.boomify(error, { decorate }).x); expect.type(Boom.boomify('error')); -expect.type>(Boom.boomify(new Boom.Boom<{ foo: 'bar' }>())); +expect.type>(Boom.boomify(new Boom.Boom<{ foo: 'bar' }>('error', { data: { foo: 'bar' }}))); expect.type(Boom.boomify(error, { decorate: { data: 1 } }).data); expect.type(Boom.boomify(error, { decorate: { data: 1 }, data: 'bla' }).data); expect.type(Boom.boomify(error, { data: 'bla' }).data); From 72219158b7f8f7c96258535981b81bfe99b4f389 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Wed, 30 Oct 2024 20:44:34 +0100 Subject: [PATCH 41/50] Remove decorate option --- API.md | 7 ++----- lib/index.d.ts | 7 ------- lib/index.js | 26 +++++++++++--------------- test/index.js | 15 --------------- test/index.ts | 19 +------------------ 5 files changed, 14 insertions(+), 60 deletions(-) diff --git a/API.md b/API.md index 4c732b7..ccb9edf 100755 --- a/API.md +++ b/API.md @@ -37,20 +37,17 @@ Creates a new `Boom` object, where: - `statusCode` - the HTTP status code. Defaults to `500`. - `cause` - The error that caused the boom error. - `data` - additional error information (assigned to `error.data`). - - `decorate` - an option with extra properties to set on the error object. - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content. - `ctor` - constructor reference used to crop the exception call stack output. ##### `boomify(err, [options])` This works as [`new Boom.Boom()`](#new-boomboommessage-options), except when the `err` argument is a boom error. -In that case, it will apply the options to the existing error, instead of wrapping it in a new boom error. -Decorates a boom object with the `Boom` properties where: -- `err` - the `Error` object to decorate. +In that case, it will apply the options to the existing error, instead of wrapping it in a new boom error, where: +- `err` - the object to boomify. - `options` - optional object with the following optional settings: - `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set and `err` is not a `Boom` object. - `message` - error message string. If the error already has a message, the provided `message` is added as a prefix. - - `decorate` - an option with extra properties to set on the error object. - `override` - if `false`, the `err` provided is a `Boom` object, and a `statusCode` or `message` are provided, the values are ignored. Defaults to `true` (apply the provided `statusCode` and `message` options to the error regardless of its type, `Error` or `Boom` object). diff --git a/lib/index.d.ts b/lib/index.d.ts index d8872e1..6efa7fb 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -65,11 +65,6 @@ export interface BaseOptions { * Additional error information */ readonly data?: Data; - - /** - * An object with extra properties to set on the error object - */ - readonly decorate?: { [key: string]: any }; } @@ -163,8 +158,6 @@ export function isBoom(obj: unknown, statusCode?: number): obj is Boom; * * @returns A boom object */ -export function boomify(err: Terr, options: BoomifyOptions & { decorate: Decoration, data: Data }): (Terr extends Boom ? Terr : Boom) & Omit; -export function boomify(err: Terr, options: BoomifyOptions & { decorate: Decoration }): (Terr extends Boom ? Terr : Boom) & Decoration; export function boomify(err: Terr, options?: BoomifyOptions): Terr extends Boom ? Terr : Boom; // 4xx Errors diff --git a/lib/index.js b/lib/index.js index 9d0f4ce..af04dd1 100755 --- a/lib/index.js +++ b/lib/index.js @@ -87,7 +87,7 @@ exports.Boom = class Boom extends Error { constructor(message, options = {}) { - const { statusCode = 500, data, headers, decorate, ctor = exports.Boom } = options; + const { statusCode = 500, data, headers, ctor = exports.Boom } = options; const causeOption = 'cause' in options ? { cause: options.cause } : undefined; super(message ?? internals.codes.get(statusCode) ?? 'Unknown', causeOption); @@ -99,7 +99,7 @@ exports.Boom = class Boom extends Error { this.cause ??= causeOption.cause; // Explicitly assign cause to work with old runtimes } - internals.apply(this, data, decorate, statusCode, headers); + internals.apply(this, data, statusCode, headers); } static [Symbol.hasInstance](instance) { @@ -133,17 +133,17 @@ exports.isBoom = function (err, statusCode) { exports.boomify = function (err, options = {}) { - const { override, data, decorate, statusCode, message } = options; + const { override, data, statusCode, message } = options; if (!err?.isBoom === true) { - return new exports.Boom(message, { statusCode, cause: err, data, decorate }); + return new exports.Boom(message, { statusCode, cause: err, data }); } if (override === false) { // Defaults to true - internals.apply(err, data, decorate); + internals.apply(err, data); } else { - internals.apply(err, data, decorate, statusCode ?? err.output.statusCode, {}, message); + internals.apply(err, data, statusCode ?? err.output.statusCode, {}, message); } if (err.hasOwnProperty('isServer')) { @@ -154,11 +154,7 @@ exports.boomify = function (err, options = {}) { }; -internals.apply = function (boom, data, decorate, statusCode, headers, message) { - - if (decorate) { - Object.assign(boom, decorate); - } +internals.apply = function (boom, data, statusCode, headers, message) { if (data !== undefined) { boom.data = data; @@ -224,8 +220,8 @@ internals.statusError = function (statusCode, massage) { const method = massage ? function (...args) { - const [message, options] = massage(...args); - return new exports.Boom(message, { statusCode, ctor: method, ...options }); + const [message, options, decorate] = massage(...args); + return Object.assign(new exports.Boom(message, { statusCode, ctor: method, ...options }), decorate); } : function (message, data) { @@ -288,7 +284,7 @@ exports.unauthorized = internals.statusError(401, (message, scheme, attributes) } const headers = { 'WWW-Authenticate': stringified ? `${scheme} ${stringified}` : `${scheme}` }; - return [message, { headers, decorate }]; + return [message, { headers }, decorate]; }); @@ -403,7 +399,7 @@ exports.gatewayTimeout = internals.statusError(504, internals.serverError); exports.badImplementation = internals.statusError(500, (message, data) => { const res = internals.serverError(message, data); - res[1].decorate = { isDeveloperError: true }; + res.push({ isDeveloperError: true }); return res; }); diff --git a/test/index.js b/test/index.js index 36e988a..369fb91 100755 --- a/test/index.js +++ b/test/index.js @@ -47,14 +47,6 @@ describe('Boom', () => { expect(new SubBoom().name).to.equal('BadaBoom'); }); - it('decorates error', () => { - - const err = new Boom.Boom('oops', { statusCode: 400, decorate: { x: 1 } }); - expect(err.output.payload.message).to.equal('oops'); - expect(err.output.statusCode).to.equal(400); - expect(err.x).to.equal(1); - }); - it('handles missing message', () => { const err = new Boom.Boom(); @@ -254,13 +246,6 @@ describe('Boom', () => { expect(error).to.shallow.equal(Boom.boomify(error, { statusCode: 444 })); }); - it('decorates error', () => { - - const error = new Error('oops'); - const err = Boom.boomify(error, { statusCode: 400, decorate: { x: 1 } }); - expect(err.x).to.equal(1); - }); - it('returns an error with info when constructed using another error', () => { const error = new Error('ka-boom'); diff --git a/test/index.ts b/test/index.ts index 9e126fa..e045c2c 100755 --- a/test/index.ts +++ b/test/index.ts @@ -4,19 +4,6 @@ import * as Lab from '@hapi/lab'; const { expect } = Lab.types; -class X { - - x: number; - - constructor(value: number) { - - this.x = value; - } -}; - - -const decorate = new X(1); - // new Boom.Boom() expect.type(new Boom.Boom()); @@ -57,11 +44,8 @@ class BadaBoom extends Boom.Boom {} expect.type(Boom.boomify(error, { statusCode: 400 })); expect.type(Boom.boomify(error, { statusCode: 400, message: 'Unexpected Input', override: false })); -expect.type(Boom.boomify(error, { decorate }).x); expect.type(Boom.boomify('error')); expect.type>(Boom.boomify(new Boom.Boom<{ foo: 'bar' }>('error', { data: { foo: 'bar' }}))); -expect.type(Boom.boomify(error, { decorate: { data: 1 } }).data); -expect.type(Boom.boomify(error, { decorate: { data: 1 }, data: 'bla' }).data); expect.type(Boom.boomify(error, { data: 'bla' }).data); expect.type(Boom.boomify(new BadaBoom(), { statusCode: 400 })); @@ -69,8 +53,7 @@ expect.error(Boom.boomify(error, { statusCode: '400' })); expect.error(Boom.boomify(error, { statusCode: 400, message: true })); expect.error(Boom.boomify(error, { statusCode: 400, override: 'false' })); expect.error(Boom.boomify()); -expect.error(Boom.boomify(error, { decorate: true })); -expect.error(Boom.boomify(error, { decorate }).y); +expect.error(Boom.boomify(error, { decorate: { x: 'y' } })); // isBoom From 26462c17c22dc592022c1993368515fcd99ea463 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 31 Oct 2024 11:34:21 +0100 Subject: [PATCH 42/50] Improve boomify data type support --- lib/index.d.ts | 7 +++++-- test/index.ts | 17 ++++++++++++++--- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index 6efa7fb..d02d491 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -86,7 +86,7 @@ export interface Options extends BaseOptions { } -export interface BoomifyOptions extends BaseOptions { +export interface BoomifyOptions extends BaseOptions { /** * Error message string * @@ -158,7 +158,10 @@ export function isBoom(obj: unknown, statusCode?: number): obj is Boom; * * @returns A boom object */ -export function boomify(err: Terr, options?: BoomifyOptions): Terr extends Boom ? Terr : Boom; +export function boomify & Pick, 'data'>, Terr extends Omit = Boom, Data = unknown>(err: Terr, options: BoomifyOptions & { data: Tres extends Boom ? Data : Data }): Tres; +export function boomify, Terr = any, Data = unknown>(err: Terr, options: BoomifyOptions & { data: Tres extends Boom ? Data : Data }): Tres; +export function boomify = Tres>(err: Terr, options?: BoomifyOptions): Tres; +export function boomify, Terr = any>(err: Terr, options?: BoomifyOptions): Tres; // 4xx Errors diff --git a/test/index.ts b/test/index.ts index e045c2c..fdeac2c 100755 --- a/test/index.ts +++ b/test/index.ts @@ -40,20 +40,31 @@ expect.type(boom.output.headers); // boomify() const error = new Error('Unexpected input'); -class BadaBoom extends Boom.Boom {} +class BadaBoom extends Boom.Boom { + constructor() { super('boom', { data: 1 }) } +} +expect.type(Boom.boomify(error)); expect.type(Boom.boomify(error, { statusCode: 400 })); expect.type(Boom.boomify(error, { statusCode: 400, message: 'Unexpected Input', override: false })); expect.type(Boom.boomify('error')); expect.type>(Boom.boomify(new Boom.Boom<{ foo: 'bar' }>('error', { data: { foo: 'bar' }}))); -expect.type(Boom.boomify(error, { data: 'bla' }).data); +expect.type>(Boom.boomify(error, { data: 'bla' })); +expect.type>(Boom.boomify>(error, { data: 'bla' })); expect.type(Boom.boomify(new BadaBoom(), { statusCode: 400 })); +expect.type>(Boom.boomify(new BadaBoom(), { statusCode: 400 })); +expect.type(Boom.boomify(new BadaBoom(), { data: 'bla' }).data); +expect.type>(Boom.boomify(new Boom.Boom('error', { data: 'ok' }))); +expect.type>(Boom.boomify(new Boom.Boom('error', { data: 'ok' }), { data: 1 })); +expect.type>(Boom.boomify>(new Boom.Boom('error', { data: 'ok' }), { data: 1 })); + +expect.error(Boom.boomify()); expect.error(Boom.boomify(error, { statusCode: '400' })); expect.error(Boom.boomify(error, { statusCode: 400, message: true })); expect.error(Boom.boomify(error, { statusCode: 400, override: 'false' })); -expect.error(Boom.boomify()); expect.error(Boom.boomify(error, { decorate: { x: 'y' } })); +//expect.error(Boom.boomify>(new Boom.Boom('error', { data: 'ok' }))); // Cannot work without partial type inference (https://github.com/microsoft/TypeScript/issues/26242) // isBoom From c10512e68890cb48c21dd835cfa8f943ff117327 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 31 Oct 2024 11:35:17 +0100 Subject: [PATCH 43/50] Improve docs --- API.md | 65 ++++++++++++++++++++++++++++++++++------------------------ 1 file changed, 38 insertions(+), 27 deletions(-) diff --git a/API.md b/API.md index ccb9edf..ab6953b 100755 --- a/API.md +++ b/API.md @@ -1,57 +1,64 @@ **boom** provides a set of utilities for returning HTTP errors. Each utility returns a `Boom` error response object which includes the following properties: -- `isBoom` - if `true`, indicates this is a `Boom` object instance. Note that this boolean should - only be used if the error is an instance of `Error`. If it is not certain, use `Boom.isBoom()` - instead. -- `isServer` - convenience bool indicating status code >= 500. - `message` - the error message. -- `typeof` - the constructor used to create the error (e.g. `Boom.badRequest`). - `output` - the formatted response. Can be directly manipulated after object construction to return a custom error response. Allowed root keys: - `statusCode` - the HTTP status code (typically 4xx or 5xx). - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content. - - `payload` - the formatted object used as the response payload (stringified). Can be directly manipulated but any - changes will be lost - if `reformat()` is called. Any content allowed and by default includes the following content: + - `payload` - the formatted object used as the response payload. + Can be directly manipulated but any changes will be lost if `reformat()` is called. + Any content allowed and by default includes the following content: - `statusCode` - the HTTP status code, derived from `error.output.statusCode`. - `error` - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from `statusCode`. - `message` - the error message derived from `error.message`. -- inherited `Error` properties. +- `stack` - string with stack trace from where error was created. +- optional `cause` - the error cause, as set by constructor. -The `Boom` object also supports the following method: +The object has additional properties from the `Boom` prototype: +- `name` - string with error name. Set to `'Boom'`. +- `isBoom` - set to `true`, indicating this is a `Boom` object instance. Note that this boolean should + only be tested if the error is an instance of `Error`. If it is not certain, use [`Boom.isBoom()`](#isboomerr-statuscode) instead. +- `isServer` - convenience boolean indicating status code >= 500. + +The object also supports the following method: #### `reformat(debug)` Rebuilds `error.output` using the other object properties where: -- `debug` - a Boolean that, when `true`, causes Internal Server Error messages to be left in tact. Defaults to `false`, meaning that Internal Server Error messages are redacted. +- `debug` - a Boolean that, when `true`, causes Internal Server Error messages to be left intact. + Defaults to `false`, meaning that Internal Server Error messages are redacted. -#### Helper Methods +#### Base Constructor -##### `new Boom.Boom(message, [options])` +##### `new Boom([message], [options])` -Creates a new `Boom` object, where: +Creates a new `Boom` sub-classed `Error` object, where: - `message` - the error message. - `options` - and optional object where: - `statusCode` - the HTTP status code. Defaults to `500`. - `cause` - The error that caused the boom error. - - `data` - additional error information (assigned to `error.data`). + - `data` - additional error information, assigned to `this.data`. - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content. - `ctor` - constructor reference used to crop the exception call stack output. +#### Helper Methods + ##### `boomify(err, [options])` -This works as [`new Boom.Boom()`](#new-boomboommessage-options), except when the `err` argument is a boom error. -In that case, it will apply the options to the existing error, instead of wrapping it in a new boom error, where: -- `err` - the object to boomify. +Creates a `Boom` object similar to [`new Boom()`](#new-boommessage-options), except it +applies the `options` to the existing error when it is a `Boom` object, where: +- `err` - the object to boomify, set as `cause` when `err` is not a `Boom` object. - `options` - optional object with the following optional settings: - `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set and `err` is not a `Boom` object. - `message` - error message string. If the error already has a message, the provided `message` is added as a prefix. - `override` - if `false`, the `err` provided is a `Boom` object, and a `statusCode` or `message` are provided, the values are ignored. Defaults to `true` (apply the provided `statusCode` and `message` options to the error - regardless of its type, `Error` or `Boom` object). -- it returns the boomified error + regardless of its type). +- it returns a `Boom` object with the boomified error + +Note that [`new Boom()`](#new-boommessage-options) should generally be preferred in cases where the error can come from awaited logic, or has been passed around. ```js const error = new Error('Unexpected input'); @@ -60,7 +67,7 @@ const boomified = Boom.boomify(error, { statusCode: 400 }); ##### `isBoom(err, [statusCode])` -Identifies whether an error is a `Boom` object. Same as calling `instanceof Boom.Boom`. +Identifies whether an error is a `Boom` object. Same as calling `err instanceof Boom.Boom`. - `err` - Error object. - `statusCode` - optional status code. @@ -68,6 +75,7 @@ Identifies whether an error is a `Boom` object. Same as calling `instanceof Boom Boom.isBoom(Boom.badRequest()); // true Boom.isBoom(Boom.badRequest(), 400); // true ``` + #### HTTP 4xx Errors ##### `Boom.badRequest([message], [data])` @@ -660,7 +668,7 @@ All 500 errors hide your message from the end user. Returns a 500 Internal Server Error error where: - `message` - optional message. -- `data` - optional additional error data. +- `data` - optional additional error data. Used as `cause` when when an `Error`. ```js Boom.badImplementation('terrible implementation'); @@ -680,7 +688,7 @@ Generates the following response payload: Returns a 501 Not Implemented error where: - `message` - optional message. -- `data` - optional additional error data. +- `data` - optional additional error data. Used as `cause` when when an `Error`. ```js Boom.notImplemented('method not implemented'); @@ -700,7 +708,7 @@ Generates the following response payload: Returns a 502 Bad Gateway error where: - `message` - optional message. -- `data` - optional additional error data. +- `data` - optional additional error data. Used as `cause` when when an `Error`. ```js Boom.badGateway('that is a bad gateway'); @@ -720,7 +728,7 @@ Generates the following response payload: Returns a 503 Service Unavailable error where: - `message` - optional message. -- `data` - optional additional error data. +- `data` - optional additional error data. Used as `cause` when when an `Error`. ```js Boom.serverUnavailable('unavailable'); @@ -740,7 +748,7 @@ Generates the following response payload: Returns a 504 Gateway Time-out error where: - `message` - optional message. -- `data` - optional additional error data. +- `data` - optional additional error data. Used as `cause` when when an `Error`. ```js Boom.gatewayTimeout(); @@ -759,4 +767,7 @@ Generates the following response payload: **Q** How do I include extra information in my responses? `output.payload` is missing `data`, what gives? -**A** There is a reason the values passed back in the response payloads are pretty locked down. It's mostly for security and to not leak any important information back to the client. This means you will need to put in a little more effort to include extra information about your custom error. Check out the ["Error transformation"](https://github.com/hapijs/hapi/blob/master/API.md#error-transformation) section in the hapi documentation. +**A** There is a reason the values passed back in the response payloads are pretty locked down. +It's mostly for security and to not leak any important information back to the client. +This means you will need to put in a little more effort to include extra information about your custom error. +Check out the ["Error transformation"](https://github.com/hapijs/hapi/blob/master/API.md#error-transformation) section in the hapi documentation. From 46b4234608427c4afff31031e4e3a5b58ad69b69 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 31 Oct 2024 11:53:38 +0100 Subject: [PATCH 44/50] Fix notImplemented and more setting Error cause --- lib/index.js | 19 ++++++++++--------- test/index.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/lib/index.js b/lib/index.js index af04dd1..83fa569 100755 --- a/lib/index.js +++ b/lib/index.js @@ -373,11 +373,20 @@ exports.illegal = internals.statusError(451); // 5xx Server Errors +internals.serverError = function (message, data) { + + const isDataNonBoomError = data instanceof Error && !exports.isBoom(data); + + return [message, isDataNonBoomError ? { cause: data } : { data }]; +}; + + exports.internal = internals.statusError(500, (message, data, statusCode = 500) => { const res = internals.serverError(message, data); if (statusCode !== 500) { - res[1].statusCode = statusCode; + const [, options] = res; + options.statusCode = statusCode; } return res; @@ -402,11 +411,3 @@ exports.badImplementation = internals.statusError(500, (message, data) => { res.push({ isDeveloperError: true }); return res; }); - - -internals.serverError = function (message, data) { - - const isDataNonBoomError = data instanceof Error && !exports.isBoom(data); - - return [message, isDataNonBoomError ? { cause: data } : { data }]; -}; diff --git a/test/index.js b/test/index.js index 369fb91..809f311 100755 --- a/test/index.js +++ b/test/index.js @@ -920,6 +920,14 @@ describe('Boom', () => { expect(Boom.internal('my message', { my: 'data' }).data.my).to.equal('data'); }); + it('uses data with Error as cause', () => { + + const insideErr = new Error('inside'); + const err = Boom.internal('my message', insideErr); + expect(err.data).to.not.exist(); + expect(err.cause).to.shallow.equal(insideErr); + }); + it('returns an error with composite message', () => { const x = {}; @@ -949,6 +957,14 @@ describe('Boom', () => { expect(Boom.notImplemented('my message').message).to.equal('my message'); }); + + it('uses data with Error as cause', () => { + + const insideErr = new Error('inside'); + const err = Boom.notImplemented('my message', insideErr); + expect(err.data).to.not.exist(); + expect(err.cause).to.shallow.equal(insideErr); + }); }); describe('badGateway()', () => { @@ -970,6 +986,14 @@ describe('Boom', () => { expect(boom.output.statusCode).to.equal(502); expect(boom.data).to.equal(upstream); }); + + it('uses data with Error as cause', () => { + + const insideErr = new Error('inside'); + const err = Boom.badGateway('my message', insideErr); + expect(err.data).to.not.exist(); + expect(err.cause).to.shallow.equal(insideErr); + }); }); describe('gatewayTimeout()', () => { @@ -983,6 +1007,14 @@ describe('Boom', () => { expect(Boom.gatewayTimeout('my message').message).to.equal('my message'); }); + + it('uses data with Error as cause', () => { + + const insideErr = new Error('inside'); + const err = Boom.gatewayTimeout('my message', insideErr); + expect(err.data).to.not.exist(); + expect(err.cause).to.shallow.equal(insideErr); + }); }); describe('badImplementation()', () => { From e9080664a3d335abafc75f806a7a0c6cda98a349 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 31 Oct 2024 11:54:02 +0100 Subject: [PATCH 45/50] Cleanup --- API.md | 2 +- lib/index.js | 10 ++++---- test/index.js | 70 ++++++++++++++++++--------------------------------- 3 files changed, 31 insertions(+), 51 deletions(-) diff --git a/API.md b/API.md index ab6953b..b0c0917 100755 --- a/API.md +++ b/API.md @@ -38,7 +38,7 @@ Creates a new `Boom` sub-classed `Error` object, where: - `message` - the error message. - `options` - and optional object where: - `statusCode` - the HTTP status code. Defaults to `500`. - - `cause` - The error that caused the boom error. + - `cause` - the error that caused the boom error. - `data` - additional error information, assigned to `this.data`. - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content. - `ctor` - constructor reference used to crop the exception call stack output. diff --git a/lib/index.js b/lib/index.js index 83fa569..9bd1f94 100755 --- a/lib/index.js +++ b/lib/index.js @@ -119,8 +119,10 @@ exports.Boom = class Boom extends Error { } static { - Object.defineProperty(this.prototype, 'name', { value: 'Boom', writable: true, configurable: true }); - Object.defineProperty(this.prototype, 'isBoom', { value: true, writable: true, configurable: true }); + Object.defineProperties(this.prototype, { + name: { value: 'Boom', writable: true, configurable: true }, + isBoom: { value: true, writable: true, configurable: true } + }); } }; @@ -407,7 +409,5 @@ exports.gatewayTimeout = internals.statusError(504, internals.serverError); exports.badImplementation = internals.statusError(500, (message, data) => { - const res = internals.serverError(message, data); - res.push({ isDeveloperError: true }); - return res; + return [...internals.serverError(message, data), { isDeveloperError: true }]; }); diff --git a/test/index.js b/test/index.js index 809f311..832af91 100755 --- a/test/index.js +++ b/test/index.js @@ -425,6 +425,17 @@ describe('Boom', () => { }); }); + const utilities = ['badRequest', 'unauthorized', 'forbidden', 'notFound', 'methodNotAllowed', + 'notAcceptable', 'proxyAuthRequired', 'clientTimeout', 'conflict', + 'resourceGone', 'lengthRequired', 'preconditionFailed', 'entityTooLarge', + 'uriTooLong', 'unsupportedMediaType', 'rangeNotSatisfiable', 'expectationFailed', + 'badData', 'preconditionRequired', 'tooManyRequests', + + // 500s + 'internal', 'notImplemented', 'badGateway', 'serverUnavailable', + 'gatewayTimeout', 'badImplementation' + ]; + describe('badRequest()', () => { it('returns a 400 error statusCode', () => { @@ -1055,25 +1066,22 @@ describe('Boom', () => { } }); }); - }); - describe('stack trace', () => { + it('uses data with Error as cause', () => { - const helpers = ['badRequest', 'unauthorized', 'forbidden', 'notFound', 'methodNotAllowed', - 'notAcceptable', 'proxyAuthRequired', 'clientTimeout', 'conflict', - 'resourceGone', 'lengthRequired', 'preconditionFailed', 'entityTooLarge', - 'uriTooLong', 'unsupportedMediaType', 'rangeNotSatisfiable', 'expectationFailed', - 'badData', 'preconditionRequired', 'tooManyRequests', + const insideErr = new Error('inside'); + const err = Boom.badImplementation('my message', insideErr); + expect(err.data).to.not.exist(); + expect(err.cause).to.shallow.equal(insideErr); + }); + }); - // 500s - 'internal', 'notImplemented', 'badGateway', 'serverUnavailable', - 'gatewayTimeout', 'badImplementation' - ]; + describe('stack trace', () => { it('should omit lib', () => { - for (const helper of helpers) { - const err = Boom[helper](); + for (const name of utilities) { + const err = Boom[name](); expect(err.stack).to.not.match(/(\/|\\)lib(\/|\\)index\.js/); } }); @@ -1082,10 +1090,10 @@ describe('Boom', () => { const captureStackTrace = Error.captureStackTrace; - for (const helper of helpers) { + for (const name of utilities) { try { Error.captureStackTrace = undefined; - var err = Boom[helper](); + var err = Boom[name](); } finally { Error.captureStackTrace = captureStackTrace; @@ -1098,35 +1106,7 @@ describe('Boom', () => { describe('method with error object instead of message', () => { - [ - 'badRequest', - 'unauthorized', - 'forbidden', - 'notFound', - 'methodNotAllowed', - 'notAcceptable', - 'proxyAuthRequired', - 'clientTimeout', - 'conflict', - 'resourceGone', - 'lengthRequired', - 'preconditionFailed', - 'entityTooLarge', - 'uriTooLong', - 'unsupportedMediaType', - 'rangeNotSatisfiable', - 'expectationFailed', - 'badData', - 'preconditionRequired', - 'tooManyRequests', - 'internal', - 'notImplemented', - 'badGateway', - 'serverUnavailable', - 'gatewayTimeout', - 'badImplementation' - ].forEach((name) => { - + for (const name of utilities) { it(`uses stringified error as message`, () => { const error = new Error('An example mongoose validation error'); @@ -1135,7 +1115,7 @@ describe('Boom', () => { expect(err.cause).to.not.exist(); expect(err.message).to.equal(error.toString()); }); - }); + } }); describe('reformat()', () => { From e76e128cd7bafec9a8be1010d2a9423cb7a3a55e Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Fri, 1 Nov 2024 10:29:58 +0100 Subject: [PATCH 46/50] Ignore all non-object headers option --- lib/index.js | 2 +- test/index.js | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/index.js b/lib/index.js index 9bd1f94..9fa9d4b 100755 --- a/lib/index.js +++ b/lib/index.js @@ -212,7 +212,7 @@ internals.BoomOutput = class { constructor(statusCode, headers) { this.statusCode = statusCode; - this.headers = headers ? Hoek.clone(headers, { prototype: false, symbols: false }) : {}; + this.headers = typeof headers === 'object' ? Hoek.clone(headers, { prototype: false, symbols: false }) : {}; } }; diff --git a/test/index.js b/test/index.js index 832af91..b1db734 100755 --- a/test/index.js +++ b/test/index.js @@ -90,6 +90,14 @@ describe('Boom', () => { expect(headers).to.equal({ custom: ['yes'] }); }); + it('ignores non-object headers option', () => { + + const err = new Boom.Boom('fail', { statusCode: 400, headers: true }); + expect(err.output.payload.message).to.equal('fail'); + expect(err.output.statusCode).to.equal(400); + expect(err.output.headers).to.equal({}); + }); + it('throws when statusCode is invalid', () => { expect(() => { From f235761092fd5b29ec45ef315a6cc757a9e6392e Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 4 Nov 2024 12:38:47 +0100 Subject: [PATCH 47/50] Shallow copy headers and throw when bad --- lib/index.d.ts | 2 +- lib/index.js | 18 ++++++++++++++++-- test/index.js | 15 ++++++++++----- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index d02d491..404529c 100755 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -72,7 +72,7 @@ export interface Options extends BaseOptions { /** * An object containing any HTTP headers where each key is a header name and value is the header content */ - readonly headers?: { readonly [header: string]: string | readonly string[] | number }; + readonly headers?: { readonly [header: string]: string | readonly string[] | number } | undefined; /** * Constructor reference used to crop the exception call stack output diff --git a/lib/index.js b/lib/index.js index 9fa9d4b..6d125ee 100755 --- a/lib/index.js +++ b/lib/index.js @@ -168,6 +168,12 @@ internals.apply = function (boom, data, statusCode, headers, message) { throw new TypeError(`statusCode must be a number (400+): ${statusCode}`); } + if (headers !== undefined && + (headers === null || typeof headers !== 'object')) { + + throw new TypeError('headers must be an object'); + } + if (message) { boom.message = `${message}: ${boom.message}`; } @@ -212,7 +218,15 @@ internals.BoomOutput = class { constructor(statusCode, headers) { this.statusCode = statusCode; - this.headers = typeof headers === 'object' ? Hoek.clone(headers, { prototype: false, symbols: false }) : {}; + + const copy = Object.assign(Object.create(null), headers); + for (const [key, value] of Object.entries(copy)) { + if (Array.isArray(value)) { + copy[key] = value.slice(); + } + } + + this.headers = copy; } }; @@ -307,7 +321,7 @@ exports.methodNotAllowed = internals.statusError(405, (message, data, allow) => const headers = Array.isArray(allow) ? { Allow: allow.join(', ') - } : null; + } : undefined; return [message, { data, headers }]; }); diff --git a/test/index.js b/test/index.js index b1db734..8c34257 100755 --- a/test/index.js +++ b/test/index.js @@ -90,12 +90,17 @@ describe('Boom', () => { expect(headers).to.equal({ custom: ['yes'] }); }); - it('ignores non-object headers option', () => { + it('throws TypeError on non-object headers option', () => { - const err = new Boom.Boom('fail', { statusCode: 400, headers: true }); - expect(err.output.payload.message).to.equal('fail'); - expect(err.output.statusCode).to.equal(400); - expect(err.output.headers).to.equal({}); + expect(() => { + + new Boom.Boom('fail', { statusCode: 400, headers: true }); + }).to.throw(TypeError); + + expect(() => { + + new Boom.Boom('fail', { statusCode: 400, headers: null }); + }).to.throw(TypeError); }); it('throws when statusCode is invalid', () => { From 9b51c19409e7f905bafb8ab4c456681160fc3fed Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Mon, 4 Nov 2024 12:39:37 +0100 Subject: [PATCH 48/50] Directly require escapeHeaderAttribute --- lib/index.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/index.js b/lib/index.js index 6d125ee..39627c1 100755 --- a/lib/index.js +++ b/lib/index.js @@ -1,6 +1,6 @@ 'use strict'; -const Hoek = require('@hapi/hoek'); +const EscapeHeaderAttribute = require('@hapi/hoek/escapeHeaderAttribute'); const internals = { @@ -275,14 +275,14 @@ exports.unauthorized = internals.statusError(401, (message, scheme, attributes) if (attributes) { if (typeof attributes === 'string') { - stringified += Hoek.escapeHeaderAttribute(attributes); + stringified += EscapeHeaderAttribute(attributes); } else { stringified += Object.keys(attributes).map((name) => { const value = attributes[name] ?? ''; - return `${name}="${Hoek.escapeHeaderAttribute(value.toString())}"`; + return `${name}="${EscapeHeaderAttribute(value.toString())}"`; }) .join(', '); } @@ -293,7 +293,7 @@ exports.unauthorized = internals.statusError(401, (message, scheme, attributes) stringified += ', '; } - stringified += `error="${Hoek.escapeHeaderAttribute(message)}"`; + stringified += `error="${EscapeHeaderAttribute(message)}"`; } else { decorate.isMissing = true; From d36c81285fac2e6035cc2d8aa3e3eb177efbecc5 Mon Sep 17 00:00:00 2001 From: Nicolas Morel Date: Sat, 1 Aug 2026 11:01:10 +0200 Subject: [PATCH 49/50] chore: convert module to ESM --- .github/workflows/ci-module.yml | 16 +- .gitignore | 2 +- API.md | 61 ++- lib/index.d.ts | 559 --------------------- lib/index.js | 427 ---------------- oxfmt.config.ts | 8 + oxlint.config.ts | 11 + package.json | 82 +-- src/index.d.ts | 459 +++++++++++++++++ src/index.js | 365 ++++++++++++++ test/index.js | 860 +++++++++++++------------------- test/index.ts | 447 ----------------- test/typings.ts | 709 ++++++++++++++++++++++++++ tsconfig.json | 25 + vitest.config.ts | 24 + 15 files changed, 2045 insertions(+), 2010 deletions(-) delete mode 100755 lib/index.d.ts delete mode 100755 lib/index.js create mode 100644 oxfmt.config.ts create mode 100644 oxlint.config.ts create mode 100755 src/index.d.ts create mode 100755 src/index.js delete mode 100755 test/index.ts create mode 100644 test/typings.ts create mode 100644 tsconfig.json create mode 100644 vitest.config.ts diff --git a/.github/workflows/ci-module.yml b/.github/workflows/ci-module.yml index 44369c8..49bcabb 100644 --- a/.github/workflows/ci-module.yml +++ b/.github/workflows/ci-module.yml @@ -1,13 +1,13 @@ name: ci on: - push: - branches: - - master - - next - pull_request: - workflow_dispatch: + push: + branches: + - master + - next + pull_request: + workflow_dispatch: jobs: - test: - uses: hapijs/.github/.github/workflows/ci-module.yml@min-node-18-hapi-21 + test: + uses: hapijs/.github/.github/workflows/ci-module.yml@min-node-22-hapi-21 diff --git a/.gitignore b/.gitignore index 8f679c9..af5a347 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ **/node_modules **/package-lock.json -coverage.* +coverage/ **/.DS_Store **/._* diff --git a/API.md b/API.md index b0c0917..419f5fb 100755 --- a/API.md +++ b/API.md @@ -1,6 +1,6 @@ - **boom** provides a set of utilities for returning HTTP errors. Each utility returns a `Boom` error response object which includes the following properties: + - `message` - the error message. - `output` - the formatted response. Can be directly manipulated after object construction to return a custom error response. Allowed root keys: @@ -16,9 +16,10 @@ error response object which includes the following properties: - optional `cause` - the error cause, as set by constructor. The object has additional properties from the `Boom` prototype: + - `name` - string with error name. Set to `'Boom'`. - `isBoom` - set to `true`, indicating this is a `Boom` object instance. Note that this boolean should - only be tested if the error is an instance of `Error`. If it is not certain, use [`Boom.isBoom()`](#isboomerr-statuscode) instead. + only be tested if the error is an instance of `Error`. If it is not certain, use [`Boom.isBoom()`](#isboomerr-statuscode) instead. - `isServer` - convenience boolean indicating status code >= 500. The object also supports the following method: @@ -35,10 +36,11 @@ Rebuilds `error.output` using the other object properties where: ##### `new Boom([message], [options])` Creates a new `Boom` sub-classed `Error` object, where: + - `message` - the error message. - `options` - and optional object where: - - `statusCode` - the HTTP status code. Defaults to `500`. - - `cause` - the error that caused the boom error. + - `statusCode` - the HTTP status code. Defaults to `500`. + - `cause` - the error that caused the boom error. - `data` - additional error information, assigned to `this.data`. - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content. - `ctor` - constructor reference used to crop the exception call stack output. @@ -49,13 +51,14 @@ Creates a new `Boom` sub-classed `Error` object, where: Creates a `Boom` object similar to [`new Boom()`](#new-boommessage-options), except it applies the `options` to the existing error when it is a `Boom` object, where: + - `err` - the object to boomify, set as `cause` when `err` is not a `Boom` object. - `options` - optional object with the following optional settings: - - `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set and `err` is not a `Boom` object. - - `message` - error message string. If the error already has a message, the provided `message` is added as a prefix. - - `override` - if `false`, the `err` provided is a `Boom` object, and a `statusCode` or `message` are provided, - the values are ignored. Defaults to `true` (apply the provided `statusCode` and `message` options to the error - regardless of its type). + - `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set and `err` is not a `Boom` object. + - `message` - error message string. If the error already has a message, the provided `message` is added as a prefix. + - `override` - if `false`, the `err` provided is a `Boom` object, and a `statusCode` or `message` are provided, + the values are ignored. Defaults to `true` (apply the provided `statusCode` and `message` options to the error + regardless of its type). - it returns a `Boom` object with the boomified error Note that [`new Boom()`](#new-boommessage-options) should generally be preferred in cases where the error can come from awaited logic, or has been passed around. @@ -68,6 +71,7 @@ const boomified = Boom.boomify(error, { statusCode: 400 }); ##### `isBoom(err, [statusCode])` Identifies whether an error is a `Boom` object. Same as calling `err instanceof Boom.Boom`. + - `err` - Error object. - `statusCode` - optional status code. @@ -81,6 +85,7 @@ Boom.isBoom(Boom.badRequest(), 400); // true ##### `Boom.badRequest([message], [data])` Returns a 400 Bad Request error where: + - `message` - optional message. - `data` - optional additional error data. @@ -101,14 +106,15 @@ Generates the following response payload: ##### `Boom.unauthorized([message], [scheme], [attributes])` Returns a 401 Unauthorized error where: + - `message` - optional message. - `scheme` can be one of the following: - - an authentication scheme name - - an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header. + - an authentication scheme name + - an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header. - `attributes` - an object of values to use while setting the 'WWW-Authenticate' header. This value is only used when `scheme` is a string, otherwise it is ignored. Every key/value pair will be included in the 'WWW-Authenticate' in the format of 'key="value"'. Alternatively value can be a string which is used to set the - value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. + value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. `null` and `undefined` will be replaced with an empty string. If `attributes` is set, `message` will be used as the 'error' segment of the 'WWW-Authenticate' header. If `message` is unset, the 'error' segment of the header will not be present and `isMissing` will be true on the error object. @@ -184,6 +190,7 @@ Generates the following response: ##### `Boom.paymentRequired([message], [data])` Returns a 402 Payment Required error where: + - `message` - optional message. - `data` - optional additional error data. @@ -204,6 +211,7 @@ Generates the following response payload: ##### `Boom.forbidden([message], [data])` Returns a 403 Forbidden error where: + - `message` - optional message. - `data` - optional additional error data. @@ -224,6 +232,7 @@ Generates the following response payload: ##### `Boom.notFound([message], [data])` Returns a 404 Not Found error where: + - `message` - optional message. - `data` - optional additional error data. @@ -244,6 +253,7 @@ Generates the following response payload: ##### `Boom.methodNotAllowed([message], [data], [allow])` Returns a 405 Method Not Allowed error where: + - `message` - optional message. - `data` - optional additional error data. - `allow` - optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header. @@ -265,6 +275,7 @@ Generates the following response payload: ##### `Boom.notAcceptable([message], [data])` Returns a 406 Not Acceptable error where: + - `message` - optional message. - `data` - optional additional error data. @@ -285,6 +296,7 @@ Generates the following response payload: ##### `Boom.proxyAuthRequired([message], [data])` Returns a 407 Proxy Authentication Required error where: + - `message` - optional message. - `data` - optional additional error data. @@ -305,6 +317,7 @@ Generates the following response payload: ##### `Boom.clientTimeout([message], [data])` Returns a 408 Request Time-out error where: + - `message` - optional message. - `data` - optional additional error data. @@ -325,6 +338,7 @@ Generates the following response payload: ##### `Boom.conflict([message], [data])` Returns a 409 Conflict error where: + - `message` - optional message. - `data` - optional additional error data. @@ -345,6 +359,7 @@ Generates the following response payload: ##### `Boom.resourceGone([message], [data])` Returns a 410 Gone error where: + - `message` - optional message. - `data` - optional additional error data. @@ -365,6 +380,7 @@ Generates the following response payload: ##### `Boom.lengthRequired([message], [data])` Returns a 411 Length Required error where: + - `message` - optional message. - `data` - optional additional error data. @@ -385,6 +401,7 @@ Generates the following response payload: ##### `Boom.preconditionFailed([message], [data])` Returns a 412 Precondition Failed error where: + - `message` - optional message. - `data` - optional additional error data. @@ -404,6 +421,7 @@ Generates the following response payload: ##### `Boom.entityTooLarge([message], [data])` Returns a 413 Request Entity Too Large error where: + - `message` - optional message. - `data` - optional additional error data. @@ -424,6 +442,7 @@ Generates the following response payload: ##### `Boom.uriTooLong([message], [data])` Returns a 414 Request-URI Too Large error where: + - `message` - optional message. - `data` - optional additional error data. @@ -444,6 +463,7 @@ Generates the following response payload: ##### `Boom.unsupportedMediaType([message], [data])` Returns a 415 Unsupported Media Type error where: + - `message` - optional message. - `data` - optional additional error data. @@ -464,6 +484,7 @@ Generates the following response payload: ##### `Boom.rangeNotSatisfiable([message], [data])` Returns a 416 Requested Range Not Satisfiable error where: + - `message` - optional message. - `data` - optional additional error data. @@ -483,6 +504,7 @@ Generates the following response payload: ##### `Boom.expectationFailed([message], [data])` Returns a 417 Expectation Failed error where: + - `message` - optional message. - `data` - optional additional error data. @@ -503,6 +525,7 @@ Generates the following response payload: ##### `Boom.teapot([message], [data])` Returns a 418 I'm a Teapot error where: + - `message` - optional message. - `data` - optional additional error data. @@ -523,6 +546,7 @@ Generates the following response payload: ##### `Boom.badData([message], [data])` Returns a 422 Unprocessable Entity error where: + - `message` - optional message. - `data` - optional additional error data. @@ -543,6 +567,7 @@ Generates the following response payload: ##### `Boom.locked([message], [data])` Returns a 423 Locked error where: + - `message` - optional message. - `data` - optional additional error data. @@ -563,6 +588,7 @@ Generates the following response payload: ##### `Boom.failedDependency([message], [data])` Returns a 424 Failed Dependency error where: + - `message` - optional message. - `data` - optional additional error data. @@ -583,6 +609,7 @@ Generates the following response payload: ##### `Boom.tooEarly([message], [data])` Returns a 425 Too Early error where: + - `message` - optional message. - `data` - optional additional error data. @@ -603,6 +630,7 @@ Generates the following response payload: ##### `Boom.preconditionRequired([message], [data])` Returns a 428 Precondition Required error where: + - `message` - optional message. - `data` - optional additional error data. @@ -623,6 +651,7 @@ Generates the following response payload: ##### `Boom.tooManyRequests([message], [data])` Returns a 429 Too Many Requests error where: + - `message` - optional message. - `data` - optional additional error data. @@ -643,6 +672,7 @@ Generates the following response payload: ##### `Boom.illegal([message], [data])` Returns a 451 Unavailable For Legal Reasons error where: + - `message` - optional message. - `data` - optional additional error data. @@ -664,9 +694,10 @@ Generates the following response payload: All 500 errors hide your message from the end user. -##### `Boom.badImplementation([message], [data])` - (*alias: `internal`*) +##### `Boom.badImplementation([message], [data])` - (_alias: `internal`_) Returns a 500 Internal Server Error error where: + - `message` - optional message. - `data` - optional additional error data. Used as `cause` when when an `Error`. @@ -687,6 +718,7 @@ Generates the following response payload: ##### `Boom.notImplemented([message], [data])` Returns a 501 Not Implemented error where: + - `message` - optional message. - `data` - optional additional error data. Used as `cause` when when an `Error`. @@ -707,6 +739,7 @@ Generates the following response payload: ##### `Boom.badGateway([message], [data])` Returns a 502 Bad Gateway error where: + - `message` - optional message. - `data` - optional additional error data. Used as `cause` when when an `Error`. @@ -727,6 +760,7 @@ Generates the following response payload: ##### `Boom.serverUnavailable([message], [data])` Returns a 503 Service Unavailable error where: + - `message` - optional message. - `data` - optional additional error data. Used as `cause` when when an `Error`. @@ -747,6 +781,7 @@ Generates the following response payload: ##### `Boom.gatewayTimeout([message], [data])` Returns a 504 Gateway Time-out error where: + - `message` - optional message. - `data` - optional additional error data. Used as `cause` when when an `Error`. diff --git a/lib/index.d.ts b/lib/index.d.ts deleted file mode 100755 index 404529c..0000000 --- a/lib/index.d.ts +++ /dev/null @@ -1,559 +0,0 @@ -type NotUnknown = string | number | boolean | bigint | symbol | null | object; - -declare namespace Boom { - type CtorArgs = [message?: string, options?: Options]; - type WithDataArgs = [message: string, options: Options & { data: Data }]; -} - -/** - * An Error object used to return an HTTP response error (4xx, 5xx) - */ -export class Boom extends Error { - - /** - * Creates a new Boom object using the provided message or Error - */ - constructor(...args: Data extends NotUnknown ? Boom.WithDataArgs : Boom.CtorArgs); - - /** - * Underlying cause for the Boom error - */ - cause?: unknown; - - /** - * Custom error data with additional information specific to the error type - */ - data: Data; - - /** - * isBoom - true, indicates this is a Boom object instance. - */ - readonly isBoom: boolean; - - /** - * Convenience boolean indicating status code >= 500 - */ - readonly isServer: boolean; - - /** - * The error message - */ - message: string; - - /** - * The formatted response - */ - output: Output; - - /** - * Specifies if an error object is a valid boom object - * - * @param debug - A boolean that, when true, does not hide the original 500 error message. Defaults to false. - */ - reformat(debug?: boolean): void; -} - -export interface BaseOptions { - /** - * The HTTP status code - * - * @default 500 - */ - readonly statusCode?: number; - - /** - * Additional error information - */ - readonly data?: Data; -} - - -export interface Options extends BaseOptions { - /** - * An object containing any HTTP headers where each key is a header name and value is the header content - */ - readonly headers?: { readonly [header: string]: string | readonly string[] | number } | undefined; - - /** - * Constructor reference used to crop the exception call stack output - */ - readonly ctor?: Function; - - /** - * An underlying cause for the Boom error - */ - readonly cause?: Error | unknown | undefined; -} - - -export interface BoomifyOptions extends BaseOptions { - /** - * Error message string - * - * @default none - */ - readonly message?: string; - - /** - * If false, the err provided is a Boom object, and a statusCode or message are provided, the values are ignored - * - * @default true - */ - readonly override?: boolean; -} - - -export interface Payload { - /** - * The HTTP status code derived from error.output.statusCode - */ - readonly statusCode: number; - - /** - * The HTTP status message derived from statusCode - */ - readonly error: string; - - /** - * The error message derived from error.message - */ - readonly message: string; -} - - -export interface Output { - /** - * The HTTP status code - */ - statusCode: number; - - /** - * An object containing any HTTP headers where each key is a header name and value is the header content - */ - headers: { [header: string]: string | string[] | number | undefined }; - - /** - * The formatted object used as the response payload (stringified) - */ - payload: Payload & { [key: string]: unknown }; -} - - -/** -* Specifies if an object is a valid boom object -* -* @param obj - The object to assess -* @param statusCode - Optional status code -* -* @returns Returns a boolean stating if the error object is a valid boom object and it has the provided statusCode (if present) -*/ -export function isBoom(obj: unknown, statusCode?: number): obj is Boom; - - -/** -* Applies options to an existing boom object, or creates a new boom object with the error as `cause` -* -* @param err - The target object -* @param options - Options object -* -* @returns A boom object -*/ -export function boomify & Pick, 'data'>, Terr extends Omit = Boom, Data = unknown>(err: Terr, options: BoomifyOptions & { data: Tres extends Boom ? Data : Data }): Tres; -export function boomify, Terr = any, Data = unknown>(err: Terr, options: BoomifyOptions & { data: Tres extends Boom ? Data : Data }): Tres; -export function boomify = Tres>(err: Terr, options?: BoomifyOptions): Tres; -export function boomify, Terr = any>(err: Terr, options?: BoomifyOptions): Tres; - -// 4xx Errors - -/** -* Returns a 400 Bad Request error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 400 bad request error -*/ -export function badRequest(message?: string, data?: Data): Boom; - - -/** -* Returns a 401 Unauthorized error -* -* @param message - Optional message -* -* @returns A 401 Unauthorized error -*/ -export function unauthorized(message?: string): Boom; - - -/** -* Returns a 401 Unauthorized error -* -* @param message - Optional message -* @param scheme - the authentication scheme name -* @param attributes - an object of values used to construct the 'WWW-Authenticate' header -* -* @returns A 401 Unauthorized error -*/ -export function unauthorized(message: '' | null | undefined, scheme: string, attributes?: string | unauthorized.Attributes): Boom & unauthorized.MissingAuth; -export function unauthorized(message: string, scheme: string, attributes?: string | unauthorized.Attributes): Boom; - - -export namespace unauthorized { - - interface Attributes { - [index: string]: number | string | null | undefined; - } - - interface MissingAuth { - - /** - * Indicate whether the 401 unauthorized error is due to missing credentials (vs. invalid) - */ - isMissing: true; - } -} - - -/** -* Returns a 401 Unauthorized error -* -* @param message - Optional message -* @param wwwAuthenticate - array of string values used to construct the wwwAuthenticate header -* -* @returns A 401 Unauthorized error -*/ -export function unauthorized(message: string | null | undefined, wwwAuthenticate: readonly string[]): Boom; - - -/** -* Returns a 402 Payment Required error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 402 Payment Required error -*/ -export function paymentRequired(message?: string, data?: Data): Boom; - - -/** -* Returns a 403 Forbidden error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 403 Forbidden error -*/ -export function forbidden(message?: string, data?: Data): Boom; - - -/** -* Returns a 404 Not Found error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 404 Not Found error -*/ -export function notFound(message?: string, data?: Data): Boom; - - -/** -* Returns a 405 Method Not Allowed error -* -* @param message - Optional message -* @param data - Optional additional error data -* @param allow - Optional string or array of strings which is used to set the 'Allow' header -* -* @returns A 405 Method Not Allowed error -*/ -export function methodNotAllowed(message?: string, data?: Data, allow?: string | readonly string[]): Boom; - - -/** -* Returns a 406 Not Acceptable error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 406 Not Acceptable error -*/ -export function notAcceptable(message?: string, data?: Data): Boom; - - -/** -* Returns a 407 Proxy Authentication error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 407 Proxy Authentication error -*/ -export function proxyAuthRequired(message?: string, data?: Data): Boom; - - -/** -* Returns a 408 Request Time-out error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 408 Request Time-out error -*/ -export function clientTimeout(message?: string, data?: Data): Boom; - - -/** -* Returns a 409 Conflict error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 409 Conflict error -*/ -export function conflict(message?: string, data?: Data): Boom; - - -/** -* Returns a 410 Gone error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 410 gone error -*/ -export function resourceGone(message?: string, data?: Data): Boom; - - -/** -* Returns a 411 Length Required error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 411 Length Required error -*/ -export function lengthRequired(message?: string, data?: Data): Boom; - - -/** -* Returns a 412 Precondition Failed error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 412 Precondition Failed error -*/ -export function preconditionFailed(message?: string, data?: Data): Boom; - - -/** -* Returns a 413 Request Entity Too Large error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 413 Request Entity Too Large error -*/ -export function entityTooLarge(message?: string, data?: Data): Boom; - - -/** -* Returns a 414 Request-URI Too Large error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 414 Request-URI Too Large error -*/ -export function uriTooLong(message?: string, data?: Data): Boom; - - -/** -* Returns a 415 Unsupported Media Type error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 415 Unsupported Media Type error -*/ -export function unsupportedMediaType(message?: string, data?: Data): Boom; - - -/** -* Returns a 416 Request Range Not Satisfiable error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 416 Request Range Not Satisfiable error -*/ -export function rangeNotSatisfiable(message?: string, data?: Data): Boom; - - -/** -* Returns a 417 Expectation Failed error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 417 Expectation Failed error -*/ -export function expectationFailed(message?: string, data?: Data): Boom; - - -/** -* Returns a 418 I'm a Teapot error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 418 I'm a Teapot error -*/ -export function teapot(message?: string, data?: Data): Boom; - - -/** -* Returns a 422 Unprocessable Entity error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 422 Unprocessable Entity error -*/ -export function badData(message?: string, data?: Data): Boom; - - -/** -* Returns a 423 Locked error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 423 Locked error -*/ -export function locked(message?: string, data?: Data): Boom; - - -/** -* Returns a 424 Failed Dependency error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 424 Failed Dependency error -*/ -export function failedDependency(message?: string, data?: Data): Boom; - -/** -* Returns a 425 Too Early error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 425 Too Early error -*/ -export function tooEarly(message?: string, data?: Data): Boom; - - -/** -* Returns a 428 Precondition Required error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 428 Precondition Required error -*/ -export function preconditionRequired(message?: string, data?: Data): Boom; - - -/** -* Returns a 429 Too Many Requests error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 429 Too Many Requests error -*/ -export function tooManyRequests(message?: string, data?: Data): Boom; - - -/** -* Returns a 451 Unavailable For Legal Reasons error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 451 Unavailable for Legal Reasons error -*/ -export function illegal(message?: string, data?: Data): Boom; - - -// 5xx Errors - -/** -* Returns a internal error (defaults to 500) -* -* @param message - Optional message -* @param data - Optional additional error data -* @param statusCode - Optional status code override. Defaults to 500. -* -* @returns A 500 Internal Server error -*/ -export function internal(message?: string, data?: Data | Error, statusCode?: number): Boom; - - -/** -* Returns a 500 Internal Server Error error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 500 Internal Server error -*/ -export function badImplementation(message?: string, data?: Data | Error): Boom; - - -/** -* Returns a 501 Not Implemented error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 501 Not Implemented error -*/ -export function notImplemented(message?: string, data?: Data | Error): Boom; - - -/** -* Returns a 502 Bad Gateway error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 502 Bad Gateway error -*/ -export function badGateway(message?: string, data?: Data | Error): Boom; - - -/** -* Returns a 503 Service Unavailable error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 503 Service Unavailable error -*/ -export function serverUnavailable(message?: string, data?: Data | Error): Boom; - - -/** -* Returns a 504 Gateway Time-out error -* -* @param message - Optional message -* @param data - Optional additional error data -* -* @returns A 504 Gateway Time-out error -*/ -export function gatewayTimeout(message?: string, data?: Data | Error): Boom; diff --git a/lib/index.js b/lib/index.js deleted file mode 100755 index 39627c1..0000000 --- a/lib/index.js +++ /dev/null @@ -1,427 +0,0 @@ -'use strict'; - -const EscapeHeaderAttribute = require('@hapi/hoek/escapeHeaderAttribute'); - - -const internals = { - codes: new Map([ - [100, 'Continue'], - [101, 'Switching Protocols'], - [102, 'Processing'], - [200, 'OK'], - [201, 'Created'], - [202, 'Accepted'], - [203, 'Non-Authoritative Information'], - [204, 'No Content'], - [205, 'Reset Content'], - [206, 'Partial Content'], - [207, 'Multi-Status'], - [300, 'Multiple Choices'], - [301, 'Moved Permanently'], - [302, 'Moved Temporarily'], - [303, 'See Other'], - [304, 'Not Modified'], - [305, 'Use Proxy'], - [307, 'Temporary Redirect'], - [400, 'Bad Request'], - [401, 'Unauthorized'], - [402, 'Payment Required'], - [403, 'Forbidden'], - [404, 'Not Found'], - [405, 'Method Not Allowed'], - [406, 'Not Acceptable'], - [407, 'Proxy Authentication Required'], - [408, 'Request Time-out'], - [409, 'Conflict'], - [410, 'Gone'], - [411, 'Length Required'], - [412, 'Precondition Failed'], - [413, 'Request Entity Too Large'], - [414, 'Request-URI Too Large'], - [415, 'Unsupported Media Type'], - [416, 'Requested Range Not Satisfiable'], - [417, 'Expectation Failed'], - [418, 'I\'m a teapot'], - [422, 'Unprocessable Entity'], - [423, 'Locked'], - [424, 'Failed Dependency'], - [425, 'Too Early'], - [426, 'Upgrade Required'], - [428, 'Precondition Required'], - [429, 'Too Many Requests'], - [431, 'Request Header Fields Too Large'], - [451, 'Unavailable For Legal Reasons'], - [500, 'Internal Server Error'], - [501, 'Not Implemented'], - [502, 'Bad Gateway'], - [503, 'Service Unavailable'], - [504, 'Gateway Time-out'], - [505, 'HTTP Version Not Supported'], - [506, 'Variant Also Negotiates'], - [507, 'Insufficient Storage'], - [509, 'Bandwidth Limit Exceeded'], - [510, 'Not Extended'], - [511, 'Network Authentication Required'] - ]) -}; - - -exports.Boom = class Boom extends Error { - - data = null; - output; - - get isServer() { - - return this.output.statusCode >= 500; - } - - set isServer(value) { // Allow for compatiblity with legacy boom - - Object.defineProperty(this, 'isServer', { - value, - writable: true, - configurable: true - }); - } - - constructor(message, options = {}) { - - const { statusCode = 500, data, headers, ctor = exports.Boom } = options; - const causeOption = 'cause' in options ? { cause: options.cause } : undefined; - - super(message ?? internals.codes.get(statusCode) ?? 'Unknown', causeOption); - if (typeof Error.captureStackTrace === 'function') { // Only use when available - Error.captureStackTrace(this, ctor); // Filter the stack to our external API - } - - if (causeOption) { - this.cause ??= causeOption.cause; // Explicitly assign cause to work with old runtimes - } - - internals.apply(this, data, statusCode, headers); - } - - static [Symbol.hasInstance](instance) { - - if (this === exports.Boom) { - return exports.isBoom(instance); - } - - // Cannot use 'instanceof' as it creates infinite recursion - - return this.prototype.isPrototypeOf(instance); - } - - reformat(debug = false) { - - this.output.payload = new internals.PayloadObject(this, this.output.statusCode, debug); - } - - static { - Object.defineProperties(this.prototype, { - name: { value: 'Boom', writable: true, configurable: true }, - isBoom: { value: true, writable: true, configurable: true } - }); - } -}; - - -exports.isBoom = function (err, statusCode) { - - return err instanceof Error && !!err.isBoom && (!statusCode || err.output.statusCode === statusCode); -}; - - -exports.boomify = function (err, options = {}) { - - const { override, data, statusCode, message } = options; - - if (!err?.isBoom === true) { - return new exports.Boom(message, { statusCode, cause: err, data }); - } - - if (override === false) { // Defaults to true - internals.apply(err, data); - } - else { - internals.apply(err, data, statusCode ?? err.output.statusCode, {}, message); - } - - if (err.hasOwnProperty('isServer')) { - err.isServer = err.output.statusCode >= 500; // Assign, in case it is a legacy boom object - } - - return err; -}; - - -internals.apply = function (boom, data, statusCode, headers, message) { - - if (data !== undefined) { - boom.data = data; - } - - if (statusCode) { - const numberCode = parseInt(statusCode, 10); - if (isNaN(numberCode) || numberCode < 400) { - throw new TypeError(`statusCode must be a number (400+): ${statusCode}`); - } - - if (headers !== undefined && - (headers === null || typeof headers !== 'object')) { - - throw new TypeError('headers must be an object'); - } - - if (message) { - boom.message = `${message}: ${boom.message}`; - } - - boom.output = new internals.BoomOutput(numberCode, headers); - boom.reformat(); - } -}; - - -internals.PayloadObject = class { - - statusCode; - error; - message; - - constructor(error, statusCode, debug) { - - this.statusCode = statusCode; - this.error = internals.codes.get(statusCode) ?? 'Unknown'; - - if (statusCode === 500 && debug !== true) { - this.message = 'An internal server error occurred'; // Hide actual error from user - } - else { - this.message = error.message; - if (error.cause) { - const message = error.cause.message ?? error.cause; - this.message = (error.message === this.error) ? message : error.message + ': ' + message; - } - } - } -}; - - -internals.BoomOutput = class { - - statusCode; - payload = {}; - headers; - - constructor(statusCode, headers) { - - this.statusCode = statusCode; - - const copy = Object.assign(Object.create(null), headers); - for (const [key, value] of Object.entries(copy)) { - if (Array.isArray(value)) { - copy[key] = value.slice(); - } - } - - this.headers = copy; - } -}; - - -internals.statusError = function (statusCode, massage) { - - const method = massage ? - function (...args) { - - const [message, options, decorate] = massage(...args); - return Object.assign(new exports.Boom(message, { statusCode, ctor: method, ...options }), decorate); - } : - function (message, data) { - - return new exports.Boom(message, { statusCode, data, ctor: method }); - }; - - return method; -}; - - -// 4xx Client Errors - -exports.badRequest = internals.statusError(400); - - -exports.unauthorized = internals.statusError(401, (message, scheme, attributes) => { // Or (message, wwwAuthenticate[]) - - // function (message) - - if (!scheme) { - return [message]; - } - - // function (message, wwwAuthenticate[]) - - if (typeof scheme !== 'string') { - const headers = { 'WWW-Authenticate': scheme.join(', ') }; - return [message, { headers }]; - } - - // function (message, scheme, attributes) - - const decorate = {}; - let stringified = ''; - - if (attributes) { - if (typeof attributes === 'string') { - stringified += EscapeHeaderAttribute(attributes); - } - else { - stringified += Object.keys(attributes).map((name) => { - - const value = attributes[name] ?? ''; - - return `${name}="${EscapeHeaderAttribute(value.toString())}"`; - }) - .join(', '); - } - } - - if (message) { - if (stringified) { - stringified += ', '; - } - - stringified += `error="${EscapeHeaderAttribute(message)}"`; - } - else { - decorate.isMissing = true; - } - - const headers = { 'WWW-Authenticate': stringified ? `${scheme} ${stringified}` : `${scheme}` }; - return [message, { headers }, decorate]; -}); - - -exports.paymentRequired = internals.statusError(402); - - -exports.forbidden = internals.statusError(403); - - -exports.notFound = internals.statusError(404); - - -exports.methodNotAllowed = internals.statusError(405, (message, data, allow) => { - - if (typeof allow === 'string') { - allow = [allow]; - } - - const headers = Array.isArray(allow) ? { - Allow: allow.join(', ') - } : undefined; - - return [message, { data, headers }]; -}); - - -exports.notAcceptable = internals.statusError(406); - - -exports.proxyAuthRequired = internals.statusError(407); - - -exports.clientTimeout = internals.statusError(408); - - -exports.conflict = internals.statusError(409); - - -exports.resourceGone = internals.statusError(410); - - -exports.lengthRequired = internals.statusError(411); - - -exports.preconditionFailed = internals.statusError(412); - - -exports.entityTooLarge = internals.statusError(413); - - -exports.uriTooLong = internals.statusError(414); - - -exports.unsupportedMediaType = internals.statusError(415); - - -exports.rangeNotSatisfiable = internals.statusError(416); - - -exports.expectationFailed = internals.statusError(417); - - -exports.teapot = internals.statusError(418); - - -exports.badData = internals.statusError(422); - - -exports.locked = internals.statusError(423); - - -exports.failedDependency = internals.statusError(424); - - -exports.tooEarly = internals.statusError(425); - - -exports.preconditionRequired = internals.statusError(428); - - -exports.tooManyRequests = internals.statusError(429); - - -exports.illegal = internals.statusError(451); - - -// 5xx Server Errors - -internals.serverError = function (message, data) { - - const isDataNonBoomError = data instanceof Error && !exports.isBoom(data); - - return [message, isDataNonBoomError ? { cause: data } : { data }]; -}; - - -exports.internal = internals.statusError(500, (message, data, statusCode = 500) => { - - const res = internals.serverError(message, data); - if (statusCode !== 500) { - const [, options] = res; - options.statusCode = statusCode; - } - - return res; -}); - - -exports.notImplemented = internals.statusError(501, internals.serverError); - - -exports.badGateway = internals.statusError(502, internals.serverError); - - -exports.serverUnavailable = internals.statusError(503, internals.serverError); - - -exports.gatewayTimeout = internals.statusError(504, internals.serverError); - - -exports.badImplementation = internals.statusError(500, (message, data) => { - - return [...internals.serverError(message, data), { isDeveloperError: true }]; -}); diff --git a/oxfmt.config.ts b/oxfmt.config.ts new file mode 100644 index 0000000..12e357b --- /dev/null +++ b/oxfmt.config.ts @@ -0,0 +1,8 @@ +import DefaultOxfmtConfig from '@hapi/oxc-plugin/oxfmt'; +import { defineConfig } from 'oxfmt'; + +import type { OxfmtConfig } from 'oxfmt'; + +export default defineConfig({ + ...DefaultOxfmtConfig, +}) as OxfmtConfig; diff --git a/oxlint.config.ts b/oxlint.config.ts new file mode 100644 index 0000000..fd4548e --- /dev/null +++ b/oxlint.config.ts @@ -0,0 +1,11 @@ +import HapiRecommended from '@hapi/oxc-plugin/oxlint'; +import { defineConfig } from 'oxlint'; + +import type { OxlintConfig } from 'oxlint'; + +export default defineConfig({ + extends: [HapiRecommended], + env: { + ...HapiRecommended.env, + }, +}) as OxlintConfig; diff --git a/package.json b/package.json index 099707c..48616ef 100644 --- a/package.json +++ b/package.json @@ -1,36 +1,50 @@ { - "name": "@hapi/boom", - "description": "HTTP-friendly error objects", - "version": "10.0.1", - "repository": "git://github.com/hapijs/boom", - "main": "lib/index.js", - "types": "lib/index.d.ts", - "keywords": [ - "error", - "http" - ], - "files": [ - "lib" - ], - "eslintConfig": { - "extends": [ - "plugin:@hapi/module" - ] - }, - "dependencies": { - "@hapi/hoek": "^11.0.2" - }, - "devDependencies": { - "@hapi/boom10": "npm:@hapi/boom@^10.0.1", - "@hapi/code": "9.x.x", - "@hapi/eslint-plugin": "^7.0.0", - "@hapi/lab": "^26.0.0", - "@types/node": "^18.19.3", - "typescript": "~5.6.3" - }, - "scripts": { - "test": "lab -a @hapi/code -t 100 -L -Y", - "test-cov-html": "lab -a @hapi/code -t 100 -L -r html -o coverage.html" - }, - "license": "BSD-3-Clause" + "name": "@hapi/boom", + "version": "10.0.1", + "description": "HTTP-friendly error objects", + "keywords": [ + "error", + "http" + ], + "license": "BSD-3-Clause", + "repository": { + "type": "git", + "url": "git://github.com/hapijs/boom.git" + }, + "files": [ + "src", + "API.md" + ], + "type": "module", + "types": "src/index.d.ts", + "exports": { + ".": { + "types": "./src/index.d.ts", + "default": "./src/index.js" + } + }, + "scripts": { + "test": "vitest run --coverage", + "typecheck": "tsc --noEmit", + "lint": "oxlint", + "lint:fix": "oxlint --fix", + "fmt": "oxfmt --check", + "fmt:fix": "oxfmt", + "check": "npm run lint && npm run fmt && npm run typecheck && npm test" + }, + "dependencies": { + "@hapi/hoek": "^12.0.0-rc.0" + }, + "devDependencies": { + "@hapi/boom10": "npm:@hapi/boom@^10.0.1", + "@hapi/oxc-plugin": "^1.0.4", + "@vitest/coverage-v8": "^4.1.10", + "oxfmt": "^0.61.0", + "oxlint": "^1.76.0", + "typescript": "^6.0.3", + "vitest": "^4.1.10" + }, + "engines": { + "node": ">=22" + } } diff --git a/src/index.d.ts b/src/index.d.ts new file mode 100755 index 0000000..8f3c752 --- /dev/null +++ b/src/index.d.ts @@ -0,0 +1,459 @@ +type NotUnknown = string | number | boolean | bigint | symbol | null | object; + +declare namespace Boom { + type CtorArgs = [message?: string, options?: Options]; + type WithDataArgs = [message: string, options: Options & { data: Data }]; +} + +/** An Error object used to return an HTTP response error (4xx, 5xx) */ +export class Boom extends Error { + /** Creates a new Boom object using the provided message or Error */ + constructor(...args: Data extends NotUnknown ? Boom.WithDataArgs : Boom.CtorArgs); + + /** Underlying cause for the Boom error */ + cause?: unknown; + + /** Custom error data with additional information specific to the error type */ + data: Data; + + /** IsBoom - true, indicates this is a Boom object instance. */ + readonly isBoom: boolean; + + /** Convenience boolean indicating status code >= 500 */ + readonly isServer: boolean; + + /** The error message */ + message: string; + + /** The formatted response */ + output: Output; + + /** + * Specifies if an error object is a valid boom object + * + * @param debug - A boolean that, when true, does not hide the original 500 error message. Defaults to false. + */ + reformat(debug?: boolean): void; +} + +export interface BaseOptions { + /** + * The HTTP status code + * + * @default 500 + */ + readonly statusCode?: number; + + /** Additional error information */ + readonly data?: Data; +} + +export interface Options extends BaseOptions { + /** An object containing any HTTP headers where each key is a header name and value is the header content */ + readonly headers?: { readonly [header: string]: string | readonly string[] | number } | undefined; + + /** Constructor reference used to crop the exception call stack output */ + readonly ctor?: Function; + + /** An underlying cause for the Boom error */ + readonly cause?: Error | unknown | undefined; +} + +export interface BoomifyOptions extends BaseOptions { + /** + * Error message string + * + * @default none + */ + readonly message?: string; + + /** + * If false, the err provided is a Boom object, and a statusCode or message are provided, the values are ignored + * + * @default true + */ + readonly override?: boolean; +} + +export interface Payload { + /** The HTTP status code derived from error.output.statusCode */ + readonly statusCode: number; + + /** The HTTP status message derived from statusCode */ + readonly error: string; + + /** The error message derived from error.message */ + readonly message: string; +} + +export interface Output { + /** The HTTP status code */ + statusCode: number; + + /** An object containing any HTTP headers where each key is a header name and value is the header content */ + headers: { [header: string]: string | string[] | number | undefined }; + + /** The formatted object used as the response payload (stringified) */ + payload: Payload & { [key: string]: unknown }; +} + +/** + * Specifies if an object is a valid boom object + * + * @param obj - The object to assess + * @param statusCode - Optional status code + * @returns Returns a boolean stating if the error object is a valid boom object and it has the provided statusCode (if + * present) + */ +export function isBoom(obj: unknown, statusCode?: number): obj is Boom; + +/** + * Applies options to an existing boom object, or creates a new boom object with the error as `cause` + * + * @param err - The target object + * @param options - Options object + * @returns A boom object + */ +export function boomify< + Tres extends Omit & Pick, 'data'>, + Terr extends Omit = Boom, + Data = unknown, +>(err: Terr, options: BoomifyOptions & { data: Tres extends Boom ? Data : Data }): Tres; +export function boomify, Terr = any, Data = unknown>( + err: Terr, + options: BoomifyOptions & { data: Tres extends Boom ? Data : Data }, +): Tres; +export function boomify = Tres>(err: Terr, options?: BoomifyOptions): Tres; +export function boomify, Terr = any>(err: Terr, options?: BoomifyOptions): Tres; + +// 4xx Errors + +/** + * Returns a 400 Bad Request error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 400 bad request error + */ +export function badRequest(message?: string, data?: Data): Boom; + +/** + * Returns a 401 Unauthorized error + * + * @param message - Optional message + * @returns A 401 Unauthorized error + */ +export function unauthorized(message?: string): Boom; + +/** + * Returns a 401 Unauthorized error + * + * @param message - Optional message + * @param scheme - The authentication scheme name + * @param attributes - An object of values used to construct the 'WWW-Authenticate' header + * @returns A 401 Unauthorized error + */ +export function unauthorized( + message: '' | null | undefined, + scheme: string, + attributes?: string | unauthorized.Attributes, +): Boom & unauthorized.MissingAuth; +export function unauthorized( + message: string, + scheme: string, + attributes?: string | unauthorized.Attributes, +): Boom; + +export namespace unauthorized { + interface Attributes { + [index: string]: number | string | null | undefined; + } + + interface MissingAuth { + /** Indicate whether the 401 unauthorized error is due to missing credentials (vs. invalid) */ + isMissing: true; + } +} + +/** + * Returns a 401 Unauthorized error + * + * @param message - Optional message + * @param wwwAuthenticate - Array of string values used to construct the wwwAuthenticate header + * @returns A 401 Unauthorized error + */ +export function unauthorized(message: string | null | undefined, wwwAuthenticate: readonly string[]): Boom; + +/** + * Returns a 402 Payment Required error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 402 Payment Required error + */ +export function paymentRequired(message?: string, data?: Data): Boom; + +/** + * Returns a 403 Forbidden error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 403 Forbidden error + */ +export function forbidden(message?: string, data?: Data): Boom; + +/** + * Returns a 404 Not Found error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 404 Not Found error + */ +export function notFound(message?: string, data?: Data): Boom; + +/** + * Returns a 405 Method Not Allowed error + * + * @param message - Optional message + * @param data - Optional additional error data + * @param allow - Optional string or array of strings which is used to set the 'Allow' header + * @returns A 405 Method Not Allowed error + */ +export function methodNotAllowed(message?: string, data?: Data, allow?: string | readonly string[]): Boom; + +/** + * Returns a 406 Not Acceptable error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 406 Not Acceptable error + */ +export function notAcceptable(message?: string, data?: Data): Boom; + +/** + * Returns a 407 Proxy Authentication error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 407 Proxy Authentication error + */ +export function proxyAuthRequired(message?: string, data?: Data): Boom; + +/** + * Returns a 408 Request Time-out error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 408 Request Time-out error + */ +export function clientTimeout(message?: string, data?: Data): Boom; + +/** + * Returns a 409 Conflict error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 409 Conflict error + */ +export function conflict(message?: string, data?: Data): Boom; + +/** + * Returns a 410 Gone error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 410 gone error + */ +export function resourceGone(message?: string, data?: Data): Boom; + +/** + * Returns a 411 Length Required error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 411 Length Required error + */ +export function lengthRequired(message?: string, data?: Data): Boom; + +/** + * Returns a 412 Precondition Failed error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 412 Precondition Failed error + */ +export function preconditionFailed(message?: string, data?: Data): Boom; + +/** + * Returns a 413 Request Entity Too Large error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 413 Request Entity Too Large error + */ +export function entityTooLarge(message?: string, data?: Data): Boom; + +/** + * Returns a 414 Request-URI Too Large error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 414 Request-URI Too Large error + */ +export function uriTooLong(message?: string, data?: Data): Boom; + +/** + * Returns a 415 Unsupported Media Type error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 415 Unsupported Media Type error + */ +export function unsupportedMediaType(message?: string, data?: Data): Boom; + +/** + * Returns a 416 Request Range Not Satisfiable error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 416 Request Range Not Satisfiable error + */ +export function rangeNotSatisfiable(message?: string, data?: Data): Boom; + +/** + * Returns a 417 Expectation Failed error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 417 Expectation Failed error + */ +export function expectationFailed(message?: string, data?: Data): Boom; + +/** + * Returns a 418 I'm a Teapot error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 418 I'm a Teapot error + */ +export function teapot(message?: string, data?: Data): Boom; + +/** + * Returns a 422 Unprocessable Entity error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 422 Unprocessable Entity error + */ +export function badData(message?: string, data?: Data): Boom; + +/** + * Returns a 423 Locked error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 423 Locked error + */ +export function locked(message?: string, data?: Data): Boom; + +/** + * Returns a 424 Failed Dependency error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 424 Failed Dependency error + */ +export function failedDependency(message?: string, data?: Data): Boom; + +/** + * Returns a 425 Too Early error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 425 Too Early error + */ +export function tooEarly(message?: string, data?: Data): Boom; + +/** + * Returns a 428 Precondition Required error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 428 Precondition Required error + */ +export function preconditionRequired(message?: string, data?: Data): Boom; + +/** + * Returns a 429 Too Many Requests error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 429 Too Many Requests error + */ +export function tooManyRequests(message?: string, data?: Data): Boom; + +/** + * Returns a 451 Unavailable For Legal Reasons error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 451 Unavailable for Legal Reasons error + */ +export function illegal(message?: string, data?: Data): Boom; + +// 5xx Errors + +/** + * Returns a internal error (defaults to 500) + * + * @param message - Optional message + * @param data - Optional additional error data + * @param statusCode - Optional status code override. Defaults to 500. + * @returns A 500 Internal Server error + */ +export function internal(message?: string, data?: Data | Error, statusCode?: number): Boom; + +/** + * Returns a 500 Internal Server Error error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 500 Internal Server error + */ +export function badImplementation(message?: string, data?: Data | Error): Boom; + +/** + * Returns a 501 Not Implemented error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 501 Not Implemented error + */ +export function notImplemented(message?: string, data?: Data | Error): Boom; + +/** + * Returns a 502 Bad Gateway error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 502 Bad Gateway error + */ +export function badGateway(message?: string, data?: Data | Error): Boom; + +/** + * Returns a 503 Service Unavailable error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 503 Service Unavailable error + */ +export function serverUnavailable(message?: string, data?: Data | Error): Boom; + +/** + * Returns a 504 Gateway Time-out error + * + * @param message - Optional message + * @param data - Optional additional error data + * @returns A 504 Gateway Time-out error + */ +export function gatewayTimeout(message?: string, data?: Data | Error): Boom; diff --git a/src/index.js b/src/index.js new file mode 100755 index 0000000..7b7934b --- /dev/null +++ b/src/index.js @@ -0,0 +1,365 @@ +import { escapeHeaderAttribute } from '@hapi/hoek'; + +const codes = new Map([ + [100, 'Continue'], + [101, 'Switching Protocols'], + [102, 'Processing'], + [200, 'OK'], + [201, 'Created'], + [202, 'Accepted'], + [203, 'Non-Authoritative Information'], + [204, 'No Content'], + [205, 'Reset Content'], + [206, 'Partial Content'], + [207, 'Multi-Status'], + [300, 'Multiple Choices'], + [301, 'Moved Permanently'], + [302, 'Moved Temporarily'], + [303, 'See Other'], + [304, 'Not Modified'], + [305, 'Use Proxy'], + [307, 'Temporary Redirect'], + [400, 'Bad Request'], + [401, 'Unauthorized'], + [402, 'Payment Required'], + [403, 'Forbidden'], + [404, 'Not Found'], + [405, 'Method Not Allowed'], + [406, 'Not Acceptable'], + [407, 'Proxy Authentication Required'], + [408, 'Request Time-out'], + [409, 'Conflict'], + [410, 'Gone'], + [411, 'Length Required'], + [412, 'Precondition Failed'], + [413, 'Request Entity Too Large'], + [414, 'Request-URI Too Large'], + [415, 'Unsupported Media Type'], + [416, 'Requested Range Not Satisfiable'], + [417, 'Expectation Failed'], + [418, "I'm a teapot"], + [422, 'Unprocessable Entity'], + [423, 'Locked'], + [424, 'Failed Dependency'], + [425, 'Too Early'], + [426, 'Upgrade Required'], + [428, 'Precondition Required'], + [429, 'Too Many Requests'], + [431, 'Request Header Fields Too Large'], + [451, 'Unavailable For Legal Reasons'], + [500, 'Internal Server Error'], + [501, 'Not Implemented'], + [502, 'Bad Gateway'], + [503, 'Service Unavailable'], + [504, 'Gateway Time-out'], + [505, 'HTTP Version Not Supported'], + [506, 'Variant Also Negotiates'], + [507, 'Insufficient Storage'], + [509, 'Bandwidth Limit Exceeded'], + [510, 'Not Extended'], + [511, 'Network Authentication Required'], +]); + +export class Boom extends Error { + data = null; + output; + + get isServer() { + return this.output.statusCode >= 500; + } + + // Allow for compatiblity with legacy boom + + set isServer(value) { + Object.defineProperty(this, 'isServer', { + value, + writable: true, + configurable: true, + }); + } + + constructor(message, options = {}) { + const { statusCode = 500, data, headers, ctor = Boom } = options; + const causeOption = 'cause' in options ? { cause: options.cause } : undefined; + + super(message ?? codes.get(statusCode) ?? 'Unknown', causeOption); + // Only use Error.captureStackTrace when available + + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, ctor); // Filter the stack to our external API + } + + if (causeOption) { + this.cause ??= causeOption.cause; // Explicitly assign cause to work with old runtimes + } + + apply(this, data, statusCode, headers); + } + + static [Symbol.hasInstance](instance) { + if (this === Boom) { + return isBoom(instance); + } + + // Cannot use 'instanceof' as it creates infinite recursion + + return this.prototype.isPrototypeOf(instance); + } + + reformat(debug = false) { + this.output.payload = new PayloadObject(this, this.output.statusCode, debug); + } + + static { + Object.defineProperties(this.prototype, { + name: { value: 'Boom', writable: true, configurable: true }, + isBoom: { value: true, writable: true, configurable: true }, + }); + } +} + +export function isBoom(err, statusCode) { + return err instanceof Error && !!err.isBoom && (!statusCode || err.output.statusCode === statusCode); +} + +export function boomify(err, options = {}) { + const { override, data, statusCode, message } = options; + + if (!err?.isBoom === true) { + return new Boom(message, { statusCode, cause: err, data }); + } + + // override defaults to true + + if (override === false) { + apply(err, data); + } else { + apply(err, data, statusCode ?? err.output.statusCode, {}, message); + } + + if (Object.hasOwn(err, 'isServer')) { + err.isServer = err.output.statusCode >= 500; // Assign, in case it is a legacy boom object + } + + return err; +} + +function apply(boom, data, statusCode, headers, message) { + if (data !== undefined) { + boom.data = data; + } + + if (statusCode) { + const numberCode = parseInt(statusCode, 10); + if (isNaN(numberCode) || numberCode < 400) { + throw new TypeError(`statusCode must be a number (400+): ${statusCode}`); + } + + if (headers !== undefined && (headers === null || typeof headers !== 'object')) { + throw new TypeError('headers must be an object'); + } + + if (message) { + boom.message = `${message}: ${boom.message}`; + } + + boom.output = new BoomOutput(numberCode, headers); + boom.reformat(); + } +} + +class PayloadObject { + statusCode; + error; + message; + + constructor(error, statusCode, debug) { + this.statusCode = statusCode; + this.error = codes.get(statusCode) ?? 'Unknown'; + + if (statusCode === 500 && debug !== true) { + this.message = 'An internal server error occurred'; // Hide actual error from user + } else { + this.message = error.message; + if (error.cause) { + const message = error.cause.message ?? error.cause; + this.message = error.message === this.error ? message : error.message + ': ' + message; + } + } + } +} + +class BoomOutput { + statusCode; + payload = {}; + headers; + + constructor(statusCode, headers) { + this.statusCode = statusCode; + + const copy = Object.assign(Object.create(null), headers); + for (const [key, value] of Object.entries(copy)) { + if (Array.isArray(value)) { + copy[key] = value.slice(); + } + } + + this.headers = copy; + } +} + +function statusError(statusCode, massage) { + const method = massage + ? function (...args) { + const [message, options, decorate] = massage(...args); + return Object.assign(new Boom(message, { statusCode, ctor: method, ...options }), decorate); + } + : function (message, data) { + return new Boom(message, { statusCode, data, ctor: method }); + }; + + return method; +} + +// 4xx Client Errors + +export const badRequest = statusError(400); + +// Or (message, wwwAuthenticate[]) + +export const unauthorized = statusError(401, (message, scheme, attributes) => { + // function (message) + + if (!scheme) { + return [message]; + } + + // function (message, wwwAuthenticate[]) + + if (typeof scheme !== 'string') { + const headers = { 'WWW-Authenticate': scheme.join(', ') }; + return [message, { headers }]; + } + + // function (message, scheme, attributes) + + const decorate = {}; + let stringified = ''; + + if (attributes) { + if (typeof attributes === 'string') { + stringified += escapeHeaderAttribute(attributes); + } else { + stringified += Object.keys(attributes) + .map((name) => { + const value = attributes[name] ?? ''; + + return `${name}="${escapeHeaderAttribute(value.toString())}"`; + }) + .join(', '); + } + } + + if (message) { + if (stringified) { + stringified += ', '; + } + + stringified += `error="${escapeHeaderAttribute(message)}"`; + } else { + decorate.isMissing = true; + } + + const headers = { 'WWW-Authenticate': stringified ? `${scheme} ${stringified}` : `${scheme}` }; + return [message, { headers }, decorate]; +}); + +export const paymentRequired = statusError(402); + +export const forbidden = statusError(403); + +export const notFound = statusError(404); + +export const methodNotAllowed = statusError(405, (message, data, allow) => { + if (typeof allow === 'string') { + allow = [allow]; + } + + const headers = Array.isArray(allow) + ? { + Allow: allow.join(', '), + } + : undefined; + + return [message, { data, headers }]; +}); + +export const notAcceptable = statusError(406); + +export const proxyAuthRequired = statusError(407); + +export const clientTimeout = statusError(408); + +export const conflict = statusError(409); + +export const resourceGone = statusError(410); + +export const lengthRequired = statusError(411); + +export const preconditionFailed = statusError(412); + +export const entityTooLarge = statusError(413); + +export const uriTooLong = statusError(414); + +export const unsupportedMediaType = statusError(415); + +export const rangeNotSatisfiable = statusError(416); + +export const expectationFailed = statusError(417); + +export const teapot = statusError(418); + +export const badData = statusError(422); + +export const locked = statusError(423); + +export const failedDependency = statusError(424); + +export const tooEarly = statusError(425); + +export const preconditionRequired = statusError(428); + +export const tooManyRequests = statusError(429); + +export const illegal = statusError(451); + +// 5xx Server Errors + +function serverError(message, data) { + const isDataNonBoomError = data instanceof Error && !isBoom(data); + + return [message, isDataNonBoomError ? { cause: data } : { data }]; +} + +export const internal = statusError(500, (message, data, statusCode = 500) => { + const res = serverError(message, data); + if (statusCode !== 500) { + const [, options] = res; + options.statusCode = statusCode; + } + + return res; +}); + +export const notImplemented = statusError(501, serverError); + +export const badGateway = statusError(502, serverError); + +export const serverUnavailable = statusError(503, serverError); + +export const gatewayTimeout = statusError(504, serverError); + +export const badImplementation = statusError(500, (message, data) => { + return [...serverError(message, data), { isDeveloperError: true }]; +}); diff --git a/test/index.js b/test/index.js index 8c34257..1c760ce 100755 --- a/test/index.js +++ b/test/index.js @@ -1,41 +1,29 @@ -'use strict'; - -const Boom = require('..'); -const Boom10 = require('@hapi/boom10'); -const Code = require('@hapi/code'); -const Lab = require('@hapi/lab'); - - -const internals = {}; - - -const { describe, it } = exports.lab = Lab.script(); -const expect = Code.expect; +import * as Boom10 from '@hapi/boom10'; +import { describe, expect, it, onTestFinished } from 'vitest'; +import * as Boom from '../src/index.js'; describe('Boom', () => { - it('constructs error object (new)', () => { - const err = new Boom.Boom('oops', { statusCode: 400 }); - expect(err.output.payload.message).to.equal('oops'); - expect(err.output.statusCode).to.equal(400); - - expect(err.name).to.equal('Boom'); - expect(Object.keys(err)).to.equal(['data', 'output']); - expect(JSON.stringify(err)).to.equal('{"data":null,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}'); + expect(err.output.payload.message).toBe('oops'); + expect(err.output.statusCode).toBe(400); + + expect(err.name).toBe('Boom'); + expect(Object.keys(err)).toEqual(['data', 'output']); + expect(JSON.stringify(err)).toBe( + '{"data":null,"output":{"statusCode":400,"payload":{"statusCode":400,"error":"Bad Request","message":"oops"},"headers":{}}}', + ); }); it('instances has .name "Boom"', () => { - class SubBoom extends Boom.Boom {} - expect(new Boom.Boom().name).to.equal('Boom'); - expect(new SubBoom().name).to.equal('Boom'); + expect(new Boom.Boom().name).toBe('Boom'); + expect(new SubBoom().name).toBe('Boom'); }); it('instances .name can be changed', () => { - class SubBoom extends Boom.Boom { name = 'BadaBoom'; } @@ -43,1135 +31,967 @@ describe('Boom', () => { const err = new Boom.Boom(); err.name = 'MyBoom'; - expect(err.name).to.equal('MyBoom'); - expect(new SubBoom().name).to.equal('BadaBoom'); + expect(err.name).toBe('MyBoom'); + expect(new SubBoom().name).toBe('BadaBoom'); }); it('handles missing message', () => { - const err = new Boom.Boom(); - expect(Boom.isBoom(err)).to.be.true(); - expect(err.message).to.equal('Internal Server Error'); + expect(Boom.isBoom(err)).toBe(true); + expect(err.message).toBe('Internal Server Error'); }); it('handles missing message with unknown statusCode', () => { - const err = new Boom.Boom(null, { statusCode: 999 }); - expect(Boom.isBoom(err)).to.be.true(); - expect(err.message).to.equal('Unknown'); + expect(Boom.isBoom(err)).toBe(true); + expect(err.message).toBe('Unknown'); }); it('handles missing message (subclass)', () => { - const Example = class extends Boom.Boom {}; const err = new Example(); - expect(Boom.isBoom(err)).to.be.true(); + expect(Boom.isBoom(err)).toBe(true); }); it('handles headers option', () => { - const err = new Boom.Boom('fail', { statusCode: 400, headers: { custom: 'yes' } }); - expect(err.output.payload.message).to.equal('fail'); - expect(err.output.statusCode).to.equal(400); - expect(err.output.headers).to.equal({ custom: 'yes' }); + expect(err.output.payload.message).toBe('fail'); + expect(err.output.statusCode).toBe(400); + expect(err.output.headers).toEqual({ custom: 'yes' }); }); it('clones headers object', () => { - const headers = { custom: ['yes'] }; const err = new Boom.Boom('fail', { statusCode: 400, headers }); err.output.headers.custom.push('more'); err.output.headers.extra = 'added'; - expect(err.output.headers).to.equal({ custom: ['yes', 'more'], extra: 'added' }); - expect(headers).to.equal({ custom: ['yes'] }); + expect(err.output.headers).toEqual({ custom: ['yes', 'more'], extra: 'added' }); + expect(headers).toEqual({ custom: ['yes'] }); }); it('throws TypeError on non-object headers option', () => { - - expect(() => { - - new Boom.Boom('fail', { statusCode: 400, headers: true }); - }).to.throw(TypeError); - - expect(() => { - - new Boom.Boom('fail', { statusCode: 400, headers: null }); - }).to.throw(TypeError); + expect(() => new Boom.Boom('fail', { statusCode: 400, headers: true })).toThrow(TypeError); + expect(() => new Boom.Boom('fail', { statusCode: 400, headers: null })).toThrow(TypeError); }); it('throws when statusCode is invalid', () => { + expect(() => new Boom.Boom('message', { statusCode: 'x' })).toThrow('statusCode must be a number (400+): x'); - expect(() => { - - new Boom.Boom('message', { statusCode: 'x' }); - }).to.throw('statusCode must be a number (400+): x'); - - expect(() => { - - new Boom.Boom('message', { statusCode: '200' }); - }).to.throw('statusCode must be a number (400+): 200'); + expect(() => new Boom.Boom('message', { statusCode: '200' })).toThrow( + 'statusCode must be a number (400+): 200', + ); }); it('will cast a statusCode number-string to an integer', () => { - const codes = [ { input: '404', result: 404 }, { input: '404.1', result: 404 }, { input: 400, result: 400 }, - { input: 400.123, result: 400 } + { input: 400.123, result: 400 }, ]; - for (let i = 0; i < codes.length; ++i) { - const code = codes[i]; + for (const code of codes) { const err = new Boom.Boom('', { statusCode: code.input }); - expect(err.output.statusCode).to.equal(code.result); + expect(err.output.statusCode).toBe(code.result); } }); it('throws TypeError when statusCode is not finite', () => { + const fn = () => new Boom.Boom('', { statusCode: 1 / 0 }); - expect(() => { - - new Boom.Boom('', { statusCode: 1 / 0 }); - }).to.throw(TypeError, 'statusCode must be a number (400+): Infinity'); + expect(fn).toThrow(TypeError); + expect(fn).toThrow('statusCode must be a number (400+): Infinity'); }); it('sets error code to unknown', () => { - const err = new Boom.Boom('', { statusCode: 999 }); - expect(err.output.payload.error).to.equal('Unknown'); + expect(err.output.payload.error).toBe('Unknown'); }); it('only sets cause when part of options', () => { - const err1 = new Boom.Boom('fail', { cause: undefined }); - expect(err1).to.include('cause'); - expect(err1.cause).to.equal(undefined); + expect(Object.hasOwn(err1, 'cause')).toBe(true); + expect(err1.cause).toBeUndefined(); const err2 = new Boom.Boom('fail', {}); - expect(err2).to.not.include('cause'); - expect(err2.cause).to.equal(undefined); + expect(Object.hasOwn(err2, 'cause')).toBe(false); + expect(err2.cause).toBeUndefined(); }); - it('assigns a .cause property if Error does not support it', (flags) => { - + it('assigns a .cause property if Error does not support it', () => { const proto = Object.getPrototypeOf(Boom.Boom); - Object.setPrototypeOf(Boom.Boom, class extends Error { - - constructor(message, _options) { - - super(message); - } - }); - - flags.onCleanup = () => { + Object.setPrototypeOf( + Boom.Boom, + class extends Error { + constructor(message) { + super(message); + } + }, + ); + onTestFinished(() => { Object.setPrototypeOf(Boom.Boom, proto); - }; + }); const err = new Boom.Boom('fail', { cause: 0 }); - expect(err.cause).to.exist(); - expect(err.cause).to.equal(0); + expect(err.cause).toBe(0); }); describe('instanceof', () => { - it('identifies a boom object', () => { - const BadaBoom = class extends Boom.Boom {}; - expect(new Boom.Boom('oops')).to.be.instanceOf(Boom.Boom); - expect(new Boom10.Boom('oops')).to.be.instanceOf(Boom.Boom); - expect(new BadaBoom('oops')).to.be.instanceOf(Boom.Boom); - expect(Boom.badRequest('oops')).to.be.instanceOf(Boom.Boom); - expect(new Error('oops')).to.not.be.instanceOf(Boom.Boom); - expect({ isBoom: true }).to.not.be.instanceOf(Boom.Boom); - expect(null).to.not.be.instanceOf(Boom.Boom); + expect(new Boom.Boom('oops')).toBeInstanceOf(Boom.Boom); + expect(new Boom10.Boom('oops')).toBeInstanceOf(Boom.Boom); + expect(new BadaBoom('oops')).toBeInstanceOf(Boom.Boom); + expect(Boom.badRequest('oops')).toBeInstanceOf(Boom.Boom); + expect(new Error('oops')).not.toBeInstanceOf(Boom.Boom); + expect({ isBoom: true }).not.toBeInstanceOf(Boom.Boom); + expect(null).not.toBeInstanceOf(Boom.Boom); }); it('can be called on a sub-class', () => { - const BadaBoom = class extends Boom.Boom {}; // Success - expect(new BadaBoom('oops')).to.be.instanceOf(BadaBoom); - expect(Object.create(BadaBoom.prototype)).to.be.instanceOf(BadaBoom); + expect(new BadaBoom('oops')).toBeInstanceOf(BadaBoom); + expect(Object.create(BadaBoom.prototype)).toBeInstanceOf(BadaBoom); // Fail - expect(new Boom.Boom('oops')).to.not.be.instanceOf(BadaBoom); - expect(Boom.badRequest('oops')).to.not.be.instanceOf(BadaBoom); + expect(new Boom.Boom('oops')).not.toBeInstanceOf(BadaBoom); + expect(Boom.badRequest('oops')).not.toBeInstanceOf(BadaBoom); }); it('works from legacy boom', () => { - - expect(new Boom.Boom('oops')).to.be.instanceOf(Boom10.Boom); - expect(new Boom10.Boom('oops')).to.be.instanceOf(Boom10.Boom); + expect(new Boom.Boom('oops')).toBeInstanceOf(Boom10.Boom); + expect(new Boom10.Boom('oops')).toBeInstanceOf(Boom10.Boom); }); }); describe('isBoom()', () => { - it('identifies a boom object', () => { - // Success - expect(Boom.isBoom(new Boom.Boom('oops'))).to.be.true(); - expect(Boom.isBoom(new Boom10.Boom('oops'))).to.be.true(); + expect(Boom.isBoom(new Boom.Boom('oops'))).toBe(true); + expect(Boom.isBoom(new Boom10.Boom('oops'))).toBe(true); // Fail - expect(Boom.isBoom(new Error('oops'))).to.be.false(); - expect(Boom.isBoom({ isBoom: true })).to.be.false(); - expect(Boom.isBoom(null)).to.be.false(); + expect(Boom.isBoom(new Error('oops'))).toBe(false); + expect(Boom.isBoom({ isBoom: true })).toBe(false); + expect(Boom.isBoom(null)).toBe(false); }); it('returns true for valid boom object and valid status code', () => { - - expect(Boom.isBoom(Boom.notFound(),404)).to.be.true(); - expect(Boom.isBoom(Boom10.notFound(), 404)).to.be.true(); + expect(Boom.isBoom(Boom.notFound(), 404)).toBe(true); + expect(Boom.isBoom(Boom10.notFound(), 404)).toBe(true); }); it('returns false for valid boom object and wrong status code', () => { - - expect(Boom.isBoom(Boom.notFound(), 503)).to.be.false(); - expect(Boom.isBoom(Boom10.notFound(), 503)).to.be.false(); + expect(Boom.isBoom(Boom.notFound(), 503)).toBe(false); + expect(Boom.isBoom(Boom10.notFound(), 503)).toBe(false); }); it('works from legacy boom', () => { - - expect(Boom10.isBoom(new Boom.Boom('oops'))).to.be.true(); - expect(Boom10.isBoom(new Boom10.Boom('oops'))).to.be.true(); + expect(Boom10.isBoom(new Boom.Boom('oops'))).toBe(true); + expect(Boom10.isBoom(new Boom10.Boom('oops'))).toBe(true); }); }); describe('boomify()', () => { - it('returns the same object when already boom', () => { - const error = Boom.badRequest(); - expect(error).to.shallow.equal(Boom.boomify(error)); - expect(error).to.shallow.equal(Boom.boomify(error, { statusCode: 444 })); + expect(Boom.boomify(error)).toBe(error); + expect(Boom.boomify(error, { statusCode: 444 })).toBe(error); }); it('returns an error with info when constructed using another error', () => { - const error = new Error('ka-boom'); const err = Boom.boomify(error); - expect(err.cause).to.shallow.equal(error); - expect(err.output).to.equal({ + expect(err.cause).toBe(error); + expect(err.output).toEqual({ statusCode: 500, payload: { statusCode: 500, error: 'Internal Server Error', - message: 'An internal server error occurred' + message: 'An internal server error occurred', }, - headers: {} + headers: {}, }); - expect(err.data).to.equal(null); + expect(err.data).toBeNull(); }); it('sets new message when none exists', () => { - const error = new Error(); const wrapped = Boom.boomify(error, { statusCode: 400, message: 'something bad' }); - expect(wrapped.message).to.equal('something bad'); + expect(wrapped.message).toBe('something bad'); }); it('returns boom error unchanged', () => { - const error = Boom.badRequest('Missing data', { type: 'user' }); const boom = Boom.boomify(error); - expect(boom).to.shallow.equal(error); - expect(error.data.type).to.equal('user'); - expect(error.output.payload.message).to.equal('Missing data'); - expect(error.output.statusCode).to.equal(400); + expect(boom).toBe(error); + expect(error.data.type).toBe('user'); + expect(error.output.payload.message).toBe('Missing data'); + expect(error.output.statusCode).toBe(400); }); it('defaults to 500', () => { - const error = new Error('Missing data'); const boom = Boom.boomify(error); - expect(boom.cause).to.shallow.equal(error); - expect(boom.output.payload.message).to.equal('An internal server error occurred'); - expect(boom.output.statusCode).to.equal(500); + expect(boom.cause).toBe(error); + expect(boom.output.payload.message).toBe('An internal server error occurred'); + expect(boom.output.statusCode).toBe(500); }); it('overrides message and statusCode', () => { - const error = Boom.badRequest('Missing data', { type: 'user' }); const boom = Boom.boomify(error, { message: 'Override message', statusCode: 599 }); - expect(boom).to.shallow.equal(error); - expect(error.data.type).to.equal('user'); - expect(error.output.payload.message).to.equal('Override message: Missing data'); - expect(error.output.statusCode).to.equal(599); + expect(boom).toBe(error); + expect(error.data.type).toBe('user'); + expect(error.output.payload.message).toBe('Override message: Missing data'); + expect(error.output.statusCode).toBe(599); }); it('overrides message', () => { - const error = Boom.badRequest('Missing data', { type: 'user' }); const boom = Boom.boomify(error, { message: 'Override message' }); - expect(boom).to.shallow.equal(error); - expect(error.data.type).to.equal('user'); - expect(error.output.payload.message).to.equal('Override message: Missing data'); - expect(error.output.statusCode).to.equal(400); + expect(boom).toBe(error); + expect(error.data.type).toBe('user'); + expect(error.output.payload.message).toBe('Override message: Missing data'); + expect(error.output.statusCode).toBe(400); }); it('overrides statusCode', () => { - const error = Boom.badRequest('Missing data', { type: 'user' }); const boom = Boom.boomify(error, { statusCode: 599 }); - expect(boom).to.shallow.equal(error); - expect(error.data.type).to.equal('user'); - expect(error.output.payload.message).to.equal('Missing data'); - expect(error.output.statusCode).to.equal(599); + expect(boom).toBe(error); + expect(error.data.type).toBe('user'); + expect(error.output.payload.message).toBe('Missing data'); + expect(error.output.statusCode).toBe(599); }); it('skips override', () => { - const error = Boom.badRequest('Missing data', { type: 'user' }); - const boom = Boom.boomify(error, { message: 'Override message', statusCode: 599, override: false }); + const boom = Boom.boomify(error, { + message: 'Override message', + statusCode: 599, + override: false, + }); - expect(boom).to.shallow.equal(error); - expect(error.data.type).to.equal('user'); - expect(error.output.payload.message).to.equal('Missing data'); - expect(error.output.statusCode).to.equal(400); + expect(boom).toBe(error); + expect(error.data.type).toBe('user'); + expect(error.output.payload.message).toBe('Missing data'); + expect(error.output.statusCode).toBe(400); }); it('initializes plain error', () => { - const error = new Error('Missing data'); - const boom = Boom.boomify(error, { message: 'Override message', statusCode: 599, override: false }); + const boom = Boom.boomify(error, { + message: 'Override message', + statusCode: 599, + override: false, + }); - expect(boom.cause).to.shallow.equal(error); - expect(boom.output.payload.message).to.equal('Override message: Missing data'); - expect(boom.output.statusCode).to.equal(599); + expect(boom.cause).toBe(error); + expect(boom.output.payload.message).toBe('Override message: Missing data'); + expect(boom.output.statusCode).toBe(599); }); it('handles non-Error errors', () => { - const boom = Boom.boomify(123, { message: 'Hello', statusCode: 400 }); - expect(boom.cause).to.equal(123); - expect(boom.output.payload.message).to.equal('Hello: 123'); - expect(boom.output.statusCode).to.equal(400); + expect(boom.cause).toBe(123); + expect(boom.output.payload.message).toBe('Hello: 123'); + expect(boom.output.statusCode).toBe(400); }); it('only sets isServer when it is an own property', () => { - const boom = Boom.boomify(new Boom.Boom()); - expect(boom.isServer).to.be.true(); - expect(boom.hasOwnProperty('isServer')).to.be.false(); + expect(boom.isServer).toBe(true); + expect(Object.hasOwn(boom, 'isServer')).toBe(false); const Boom2 = class extends Boom.Boom { - isServer = undefined; }; const boom2 = Boom.boomify(new Boom2()); - expect(boom2.isServer).to.be.true(); - expect(boom2.hasOwnProperty('isServer')).to.be.true(); + expect(boom2.isServer).toBe(true); + expect(Object.hasOwn(boom2, 'isServer')).toBe(true); }); it('works with legacy boom', () => { + const boom = Boom.boomify(new Boom10.Boom(null, { statusCode: 404 }), { + statusCode: 501, + message: 'Override', + }); - const boom = Boom.boomify(new Boom10.Boom(null, { statusCode: 404 }), { statusCode: 501, message: 'Override' }); - - expect(boom.cause).to.be.undefined(); - expect(boom.message).to.equal('Override: Not Found'); - expect(boom.isServer).to.be.true(); - expect(boom.hasOwnProperty('isServer')).to.be.true(); - expect(boom.output.statusCode).to.equal(501); + expect(boom.cause).toBeUndefined(); + expect(boom.message).toBe('Override: Not Found'); + expect(boom.isServer).toBe(true); + expect(Object.hasOwn(boom, 'isServer')).toBe(true); + expect(boom.output.statusCode).toBe(501); - const boom10 = Boom10.boomify(new Boom.Boom(null, { statusCode: 404 }), { statusCode: 501, message: 'Override' }); + const boom10 = Boom10.boomify(new Boom.Boom(null, { statusCode: 404 }), { + statusCode: 501, + message: 'Override', + }); - expect(boom10.cause).to.be.undefined(); - expect(boom10.message).to.equal('Override: Not Found'); - expect(boom10.isServer).to.be.true(); - expect(boom10.hasOwnProperty('isServer')).to.be.true(); - expect(boom10.output.statusCode).to.equal(501); + expect(boom10.cause).toBeUndefined(); + expect(boom10.message).toBe('Override: Not Found'); + expect(boom10.isServer).toBe(true); + expect(Object.hasOwn(boom10, 'isServer')).toBe(true); + expect(boom10.output.statusCode).toBe(501); }); }); describe('create()', () => { - it('does not set null message', () => { - const error = Boom.unauthorized(null); - expect(error.output.payload.message).to.equal('Unauthorized'); - expect(error.isServer).to.be.false(); + expect(error.output.payload.message).toBe('Unauthorized'); + expect(error.isServer).toBe(false); }); it('sets message and data', () => { - const error = Boom.badRequest('Missing data', { type: 'user' }); - expect(error.data.type).to.equal('user'); - expect(error.output.payload.message).to.equal('Missing data'); + expect(error.data.type).toBe('user'); + expect(error.output.payload.message).toBe('Missing data'); }); }); describe('initialize()', () => { - it('does not set null message', () => { - const err = new Error('some error'); const boom = new Boom.Boom('prepended error message', { statusCode: 400, cause: err }); - expect(boom.output.payload.message).to.equal('prepended error message: some error'); + expect(boom.output.payload.message).toBe('prepended error message: some error'); }); }); describe('isBoom', () => { - it('is true for Boom object', () => { - - expect(Boom.badRequest().isBoom).to.be.true(); + expect(Boom.badRequest().isBoom).toBe(true); }); }); - const utilities = ['badRequest', 'unauthorized', 'forbidden', 'notFound', 'methodNotAllowed', - 'notAcceptable', 'proxyAuthRequired', 'clientTimeout', 'conflict', - 'resourceGone', 'lengthRequired', 'preconditionFailed', 'entityTooLarge', - 'uriTooLong', 'unsupportedMediaType', 'rangeNotSatisfiable', 'expectationFailed', - 'badData', 'preconditionRequired', 'tooManyRequests', + const utilities = [ + 'badRequest', + 'unauthorized', + 'forbidden', + 'notFound', + 'methodNotAllowed', + 'notAcceptable', + 'proxyAuthRequired', + 'clientTimeout', + 'conflict', + 'resourceGone', + 'lengthRequired', + 'preconditionFailed', + 'entityTooLarge', + 'uriTooLong', + 'unsupportedMediaType', + 'rangeNotSatisfiable', + 'expectationFailed', + 'badData', + 'preconditionRequired', + 'tooManyRequests', // 500s - 'internal', 'notImplemented', 'badGateway', 'serverUnavailable', - 'gatewayTimeout', 'badImplementation' + 'internal', + 'notImplemented', + 'badGateway', + 'serverUnavailable', + 'gatewayTimeout', + 'badImplementation', ]; describe('badRequest()', () => { - it('returns a 400 error statusCode', () => { - const error = Boom.badRequest(); - expect(error.output.statusCode).to.equal(400); - expect(error.isServer).to.be.false(); + expect(error.output.statusCode).toBe(400); + expect(error.isServer).toBe(false); }); it('sets the message with the passed in message', () => { - - expect(Boom.badRequest('my message').message).to.equal('my message'); + expect(Boom.badRequest('my message').message).toBe('my message'); }); it('sets the message to HTTP status if none provided', () => { - - expect(Boom.badRequest().message).to.equal('Bad Request'); + expect(Boom.badRequest().message).toBe('Bad Request'); }); }); describe('unauthorized()', () => { - it('returns a 401 error statusCode', () => { - const err = Boom.unauthorized(); - expect(err.output.statusCode).to.equal(401); - expect(err.output.headers).to.equal({}); + expect(err.output.statusCode).toBe(401); + expect(err.output.headers).toEqual({}); }); it('sets the message with the passed in message', () => { - - expect(Boom.unauthorized('my message').message).to.equal('my message'); + expect(Boom.unauthorized('my message').message).toBe('my message'); }); it('returns a WWW-Authenticate header when passed a scheme', () => { - const err = Boom.unauthorized('boom', 'Test'); - expect(err.output.statusCode).to.equal(401); - expect(err.output.headers['WWW-Authenticate']).to.equal('Test error="boom"'); + expect(err.output.statusCode).toBe(401); + expect(err.output.headers['WWW-Authenticate']).toBe('Test error="boom"'); }); it('returns a WWW-Authenticate header when passed a scheme (no message)', () => { - const err = Boom.unauthorized(null, 'Test'); - expect(err.output.statusCode).to.equal(401); - expect(err.output.headers['WWW-Authenticate']).to.equal('Test'); + expect(err.output.statusCode).toBe(401); + expect(err.output.headers['WWW-Authenticate']).toBe('Test'); }); it('returns a WWW-Authenticate header set to the schema array value', () => { - const err = Boom.unauthorized(null, ['Test', 'one', 'two']); - expect(err.output.statusCode).to.equal(401); - expect(err.output.headers['WWW-Authenticate']).to.equal('Test, one, two'); + expect(err.output.statusCode).toBe(401); + expect(err.output.headers['WWW-Authenticate']).toBe('Test, one, two'); }); it('returns a WWW-Authenticate header when passed a scheme and attributes', () => { - const err = Boom.unauthorized('boom', 'Test', { a: 1, b: 'something', c: null, d: 0 }); - expect(err.output.statusCode).to.equal(401); - expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0", error="boom"'); + expect(err.output.statusCode).toBe(401); + expect(err.output.headers['WWW-Authenticate']).toBe('Test a="1", b="something", c="", d="0", error="boom"'); }); it('returns a WWW-Authenticate header when passed a scheme and empty attributes', () => { - const err = Boom.unauthorized('boom', 'Test', {}); - expect(err.output.statusCode).to.equal(401); - expect(err.output.headers['WWW-Authenticate']).to.equal('Test error="boom"'); + expect(err.output.statusCode).toBe(401); + expect(err.output.headers['WWW-Authenticate']).toBe('Test error="boom"'); }); it('returns a WWW-Authenticate header from string input instead of object', () => { - const err = Boom.unauthorized(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4='); - expect(err.output.statusCode).to.equal(401); - expect(err.output.headers['WWW-Authenticate']).to.equal('Negotiate VGhpcyBpcyBhIHRlc3QgdG9rZW4='); + expect(err.output.statusCode).toBe(401); + expect(err.output.headers['WWW-Authenticate']).toBe('Negotiate VGhpcyBpcyBhIHRlc3QgdG9rZW4='); }); it('returns a WWW-Authenticate header when passed attributes, missing error', () => { - - const err = Boom.unauthorized(null, 'Test', { a: 1, b: 'something', c: null, d: 0, e: undefined }); - expect(err.output.statusCode).to.equal(401); - expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0", e=""'); - expect(err.isMissing).to.equal(true); + const err = Boom.unauthorized(null, 'Test', { + a: 1, + b: 'something', + c: null, + d: 0, + e: undefined, + }); + expect(err.output.statusCode).toBe(401); + expect(err.output.headers['WWW-Authenticate']).toBe('Test a="1", b="something", c="", d="0", e=""'); + expect(err.isMissing).toBe(true); }); it('sets the isMissing flag when error message is empty', () => { - const err = Boom.unauthorized('', 'Basic'); - expect(err.isMissing).to.equal(true); + expect(err.isMissing).toBe(true); }); it('does not set the isMissing flag when error message is not empty', () => { - const err = Boom.unauthorized('message', 'Basic'); - expect(err.isMissing).to.equal(undefined); + expect(err.isMissing).toBeUndefined(); }); it('sets a WWW-Authenticate when passed as an array', () => { - const err = Boom.unauthorized('message', ['Basic', 'Example e="1"', 'Another x="3", y="4"']); - expect(err.output.headers['WWW-Authenticate']).to.equal('Basic, Example e="1", Another x="3", y="4"'); + expect(err.output.headers['WWW-Authenticate']).toBe('Basic, Example e="1", Another x="3", y="4"'); }); }); - describe('paymentRequired()', () => { - it('returns a 402 error statusCode', () => { - - expect(Boom.paymentRequired().output.statusCode).to.equal(402); + expect(Boom.paymentRequired().output.statusCode).toBe(402); }); it('sets the message with the passed in message', () => { - - expect(Boom.paymentRequired('my message').message).to.equal('my message'); + expect(Boom.paymentRequired('my message').message).toBe('my message'); }); it('sets the message to HTTP status if none provided', () => { - - expect(Boom.paymentRequired().message).to.equal('Payment Required'); + expect(Boom.paymentRequired().message).toBe('Payment Required'); }); }); - describe('methodNotAllowed()', () => { - it('returns a 405 error statusCode', () => { - - expect(Boom.methodNotAllowed().output.statusCode).to.equal(405); + expect(Boom.methodNotAllowed().output.statusCode).toBe(405); }); it('sets the message with the passed in message', () => { - - expect(Boom.methodNotAllowed('my message').message).to.equal('my message'); + expect(Boom.methodNotAllowed('my message').message).toBe('my message'); }); it('returns an Allow header when passed a string', () => { - const err = Boom.methodNotAllowed('my message', null, 'GET'); - expect(err.output.statusCode).to.equal(405); - expect(err.output.headers.Allow).to.equal('GET'); + expect(err.output.statusCode).toBe(405); + expect(err.output.headers.Allow).toBe('GET'); }); it('returns an Allow header when passed an array', () => { - const err = Boom.methodNotAllowed('my message', null, ['GET', 'POST']); - expect(err.output.statusCode).to.equal(405); - expect(err.output.headers.Allow).to.equal('GET, POST'); + expect(err.output.statusCode).toBe(405); + expect(err.output.headers.Allow).toBe('GET, POST'); }); }); - describe('notAcceptable()', () => { - it('returns a 406 error statusCode', () => { - - expect(Boom.notAcceptable().output.statusCode).to.equal(406); + expect(Boom.notAcceptable().output.statusCode).toBe(406); }); it('sets the message with the passed in message', () => { - - expect(Boom.notAcceptable('my message').message).to.equal('my message'); + expect(Boom.notAcceptable('my message').message).toBe('my message'); }); }); - describe('proxyAuthRequired()', () => { - it('returns a 407 error statusCode', () => { - - expect(Boom.proxyAuthRequired().output.statusCode).to.equal(407); + expect(Boom.proxyAuthRequired().output.statusCode).toBe(407); }); it('sets the message with the passed in message', () => { - - expect(Boom.proxyAuthRequired('my message').message).to.equal('my message'); + expect(Boom.proxyAuthRequired('my message').message).toBe('my message'); }); }); - describe('clientTimeout()', () => { - it('returns a 408 error statusCode', () => { - - expect(Boom.clientTimeout().output.statusCode).to.equal(408); + expect(Boom.clientTimeout().output.statusCode).toBe(408); }); it('sets the message with the passed in message', () => { - - expect(Boom.clientTimeout('my message').message).to.equal('my message'); + expect(Boom.clientTimeout('my message').message).toBe('my message'); }); }); - describe('conflict()', () => { - it('returns a 409 error statusCode', () => { - - expect(Boom.conflict().output.statusCode).to.equal(409); + expect(Boom.conflict().output.statusCode).toBe(409); }); it('sets the message with the passed in message', () => { - - expect(Boom.conflict('my message').message).to.equal('my message'); + expect(Boom.conflict('my message').message).toBe('my message'); }); }); - describe('resourceGone()', () => { - it('returns a 410 error statusCode', () => { - - expect(Boom.resourceGone().output.statusCode).to.equal(410); + expect(Boom.resourceGone().output.statusCode).toBe(410); }); it('sets the message with the passed in message', () => { - - expect(Boom.resourceGone('my message').message).to.equal('my message'); + expect(Boom.resourceGone('my message').message).toBe('my message'); }); }); - describe('lengthRequired()', () => { - it('returns a 411 error statusCode', () => { - - expect(Boom.lengthRequired().output.statusCode).to.equal(411); + expect(Boom.lengthRequired().output.statusCode).toBe(411); }); it('sets the message with the passed in message', () => { - - expect(Boom.lengthRequired('my message').message).to.equal('my message'); + expect(Boom.lengthRequired('my message').message).toBe('my message'); }); }); - describe('preconditionFailed()', () => { - it('returns a 412 error statusCode', () => { - - expect(Boom.preconditionFailed().output.statusCode).to.equal(412); + expect(Boom.preconditionFailed().output.statusCode).toBe(412); }); it('sets the message with the passed in message', () => { - - expect(Boom.preconditionFailed('my message').message).to.equal('my message'); + expect(Boom.preconditionFailed('my message').message).toBe('my message'); }); }); - describe('entityTooLarge()', () => { - it('returns a 413 error statusCode', () => { - - expect(Boom.entityTooLarge().output.statusCode).to.equal(413); + expect(Boom.entityTooLarge().output.statusCode).toBe(413); }); it('sets the message with the passed in message', () => { - - expect(Boom.entityTooLarge('my message').message).to.equal('my message'); + expect(Boom.entityTooLarge('my message').message).toBe('my message'); }); }); - describe('uriTooLong()', () => { - it('returns a 414 error statusCode', () => { - - expect(Boom.uriTooLong().output.statusCode).to.equal(414); + expect(Boom.uriTooLong().output.statusCode).toBe(414); }); it('sets the message with the passed in message', () => { - - expect(Boom.uriTooLong('my message').message).to.equal('my message'); + expect(Boom.uriTooLong('my message').message).toBe('my message'); }); }); - describe('unsupportedMediaType()', () => { - it('returns a 415 error statusCode', () => { - - expect(Boom.unsupportedMediaType().output.statusCode).to.equal(415); + expect(Boom.unsupportedMediaType().output.statusCode).toBe(415); }); it('sets the message with the passed in message', () => { - - expect(Boom.unsupportedMediaType('my message').message).to.equal('my message'); + expect(Boom.unsupportedMediaType('my message').message).toBe('my message'); }); }); - describe('rangeNotSatisfiable()', () => { - it('returns a 416 error statusCode', () => { - - expect(Boom.rangeNotSatisfiable().output.statusCode).to.equal(416); + expect(Boom.rangeNotSatisfiable().output.statusCode).toBe(416); }); it('sets the message with the passed in message', () => { - - expect(Boom.rangeNotSatisfiable('my message').message).to.equal('my message'); + expect(Boom.rangeNotSatisfiable('my message').message).toBe('my message'); }); }); - describe('expectationFailed()', () => { - it('returns a 417 error statusCode', () => { - - expect(Boom.expectationFailed().output.statusCode).to.equal(417); + expect(Boom.expectationFailed().output.statusCode).toBe(417); }); it('sets the message with the passed in message', () => { - - expect(Boom.expectationFailed('my message').message).to.equal('my message'); + expect(Boom.expectationFailed('my message').message).toBe('my message'); }); }); - describe('teapot()', () => { - it('returns a 418 error statusCode', () => { - - expect(Boom.teapot().output.statusCode).to.equal(418); + expect(Boom.teapot().output.statusCode).toBe(418); }); it('sets the message with the passed in message', () => { - - expect(Boom.teapot('Sorry, no coffee...').message).to.equal('Sorry, no coffee...'); + expect(Boom.teapot('Sorry, no coffee...').message).toBe('Sorry, no coffee...'); }); }); - describe('badData()', () => { - it('returns a 422 error statusCode', () => { - - expect(Boom.badData().output.statusCode).to.equal(422); + expect(Boom.badData().output.statusCode).toBe(422); }); it('sets the message with the passed in message', () => { - - expect(Boom.badData('my message').message).to.equal('my message'); + expect(Boom.badData('my message').message).toBe('my message'); }); }); - describe('locked()', () => { - it('returns a 423 error statusCode', () => { - - expect(Boom.locked().output.statusCode).to.equal(423); + expect(Boom.locked().output.statusCode).toBe(423); }); it('sets the message with the passed in message', () => { - - expect(Boom.locked('my message').message).to.equal('my message'); + expect(Boom.locked('my message').message).toBe('my message'); }); }); describe('failedDependency()', () => { - it('returns a 424 error statusCode', () => { - - expect(Boom.failedDependency().output.statusCode).to.equal(424); + expect(Boom.failedDependency().output.statusCode).toBe(424); }); it('sets the message with the passed in message', () => { - - expect(Boom.failedDependency('my message').message).to.equal('my message'); + expect(Boom.failedDependency('my message').message).toBe('my message'); }); }); describe('tooEarly()', () => { - it('returns a 425 error statusCode', () => { - - expect(Boom.tooEarly().output.statusCode).to.equal(425); + expect(Boom.tooEarly().output.statusCode).toBe(425); }); it('sets the message with the passed in message', () => { - - expect(Boom.tooEarly('my message').message).to.equal('my message'); + expect(Boom.tooEarly('my message').message).toBe('my message'); }); }); - describe('preconditionRequired()', () => { - it('returns a 428 error statusCode', () => { - - expect(Boom.preconditionRequired().output.statusCode).to.equal(428); + expect(Boom.preconditionRequired().output.statusCode).toBe(428); }); it('sets the message with the passed in message', () => { - - expect(Boom.preconditionRequired('my message').message).to.equal('my message'); + expect(Boom.preconditionRequired('my message').message).toBe('my message'); }); }); - describe('tooManyRequests()', () => { - it('returns a 429 error statusCode', () => { - - expect(Boom.tooManyRequests().output.statusCode).to.equal(429); + expect(Boom.tooManyRequests().output.statusCode).toBe(429); }); it('sets the message with the passed-in message', () => { - - expect(Boom.tooManyRequests('my message').message).to.equal('my message'); + expect(Boom.tooManyRequests('my message').message).toBe('my message'); }); }); - describe('illegal()', () => { - it('returns a 451 error statusCode', () => { - - expect(Boom.illegal().output.statusCode).to.equal(451); + expect(Boom.illegal().output.statusCode).toBe(451); }); it('sets the message with the passed-in message', () => { - - expect(Boom.illegal('my message').message).to.equal('my message'); + expect(Boom.illegal('my message').message).toBe('my message'); }); }); describe('serverUnavailable()', () => { - it('returns a 503 error statusCode', () => { - - expect(Boom.serverUnavailable().output.statusCode).to.equal(503); + expect(Boom.serverUnavailable().output.statusCode).toBe(503); }); it('sets the message with the passed in message', () => { - - expect(Boom.serverUnavailable('my message').message).to.equal('my message'); + expect(Boom.serverUnavailable('my message').message).toBe('my message'); }); }); describe('forbidden()', () => { - it('returns a 403 error statusCode', () => { - - expect(Boom.forbidden().output.statusCode).to.equal(403); + expect(Boom.forbidden().output.statusCode).toBe(403); }); it('sets the message with the passed in message', () => { - - expect(Boom.forbidden('my message').message).to.equal('my message'); + expect(Boom.forbidden('my message').message).toBe('my message'); }); }); describe('notFound()', () => { - it('returns a 404 error statusCode', () => { - - expect(Boom.notFound().output.statusCode).to.equal(404); + expect(Boom.notFound().output.statusCode).toBe(404); }); it('sets the message with the passed in message', () => { - - expect(Boom.notFound('my message').message).to.equal('my message'); + expect(Boom.notFound('my message').message).toBe('my message'); }); }); describe('internal()', () => { - it('returns a 500 error statusCode', () => { - - expect(Boom.internal().output.statusCode).to.equal(500); + expect(Boom.internal().output.statusCode).toBe(500); }); it('handles a custom error statusCode', () => { - const err = Boom.internal(null, null, 507); - expect(err.output.statusCode).to.equal(507); - expect(err.message).to.equal('Insufficient Storage'); + expect(err.output.statusCode).toBe(507); + expect(err.message).toBe('Insufficient Storage'); }); it('sets the message with the passed in message', () => { - const err = Boom.internal('my message'); - expect(err.message).to.equal('my message'); - expect(err.isServer).to.true(); - expect(err.output.payload.message).to.equal('An internal server error occurred'); + expect(err.message).toBe('my message'); + expect(err.isServer).toBe(true); + expect(err.output.payload.message).toBe('An internal server error occurred'); }); it('passes data on the callback if its passed in', () => { - - expect(Boom.internal('my message', { my: 'data' }).data.my).to.equal('data'); + expect(Boom.internal('my message', { my: 'data' }).data.my).toBe('data'); }); it('uses data with Error as cause', () => { - const insideErr = new Error('inside'); const err = Boom.internal('my message', insideErr); - expect(err.data).to.not.exist(); - expect(err.cause).to.shallow.equal(insideErr); + expect(err.data).toBeNull(); + expect(err.cause).toBe(insideErr); }); it('returns an error with composite message', () => { - const x = {}; try { x.foo(); - } - catch (err) { + } catch (err) { const boom = Boom.internal('Something bad', err); boom.reformat(true); - expect(boom.message).to.equal('Something bad'); - expect(boom.cause).to.be.an.error(TypeError, 'x.foo is not a function'); - expect(boom.output.payload.message).to.equal('Something bad: x.foo is not a function'); - expect(boom.isServer).to.be.true(); + expect(boom.message).toBe('Something bad'); + expect(boom.cause).toBeInstanceOf(TypeError); + expect(boom.cause.message).toBe('x.foo is not a function'); + expect(boom.output.payload.message).toBe('Something bad: x.foo is not a function'); + expect(boom.isServer).toBe(true); } }); }); describe('notImplemented()', () => { - it('returns a 501 error statusCode', () => { - - expect(Boom.notImplemented().output.statusCode).to.equal(501); + expect(Boom.notImplemented().output.statusCode).toBe(501); }); it('sets the message with the passed in message', () => { - - expect(Boom.notImplemented('my message').message).to.equal('my message'); + expect(Boom.notImplemented('my message').message).toBe('my message'); }); it('uses data with Error as cause', () => { - const insideErr = new Error('inside'); const err = Boom.notImplemented('my message', insideErr); - expect(err.data).to.not.exist(); - expect(err.cause).to.shallow.equal(insideErr); + expect(err.data).toBeNull(); + expect(err.cause).toBe(insideErr); }); }); describe('badGateway()', () => { - it('returns a 502 error statusCode', () => { - - expect(Boom.badGateway().output.statusCode).to.equal(502); + expect(Boom.badGateway().output.statusCode).toBe(502); }); it('sets the message with the passed in message', () => { - - expect(Boom.badGateway('my message').message).to.equal('my message'); + expect(Boom.badGateway('my message').message).toBe('my message'); }); it('retains source boom error as data when wrapped', () => { - const upstream = Boom.serverUnavailable(); const boom = Boom.badGateway('Upstream error', upstream); - expect(boom.output.statusCode).to.equal(502); - expect(boom.data).to.equal(upstream); + expect(boom.output.statusCode).toBe(502); + expect(boom.data).toBe(upstream); }); it('uses data with Error as cause', () => { - const insideErr = new Error('inside'); const err = Boom.badGateway('my message', insideErr); - expect(err.data).to.not.exist(); - expect(err.cause).to.shallow.equal(insideErr); + expect(err.data).toBeNull(); + expect(err.cause).toBe(insideErr); }); }); describe('gatewayTimeout()', () => { - it('returns a 504 error statusCode', () => { - - expect(Boom.gatewayTimeout().output.statusCode).to.equal(504); + expect(Boom.gatewayTimeout().output.statusCode).toBe(504); }); it('sets the message with the passed in message', () => { - - expect(Boom.gatewayTimeout('my message').message).to.equal('my message'); + expect(Boom.gatewayTimeout('my message').message).toBe('my message'); }); it('uses data with Error as cause', () => { - const insideErr = new Error('inside'); const err = Boom.gatewayTimeout('my message', insideErr); - expect(err.data).to.not.exist(); - expect(err.cause).to.shallow.equal(insideErr); + expect(err.data).toBeNull(); + expect(err.cause).toBe(insideErr); }); }); describe('badImplementation()', () => { - it('returns a 500 error statusCode', () => { - const err = Boom.badImplementation(); - expect(err.output.statusCode).to.equal(500); - expect(err.isDeveloperError).to.equal(true); - expect(err.isServer).to.be.true(); + expect(err.output.statusCode).toBe(500); + expect(err.isDeveloperError).toBe(true); + expect(err.isServer).toBe(true); }); it('hides error from user when error data is included', () => { - const err = Boom.badImplementation('Invalid', new Error('kaboom')); - expect(err.output).to.equal({ + expect(err.output).toEqual({ headers: {}, statusCode: 500, payload: { error: 'Internal Server Error', message: 'An internal server error occurred', - statusCode: 500 - } + statusCode: 500, + }, }); }); it('hides error from user when error data is included (boom)', () => { - const err = Boom.badImplementation('Invalid', Boom.badRequest('kaboom')); - expect(err.isDeveloperError).to.equal(true); - expect(err.output).to.equal({ + expect(err.isDeveloperError).toBe(true); + expect(err.output).toEqual({ headers: {}, statusCode: 500, payload: { error: 'Internal Server Error', message: 'An internal server error occurred', - statusCode: 500 - } + statusCode: 500, + }, }); }); it('uses data with Error as cause', () => { - const insideErr = new Error('inside'); const err = Boom.badImplementation('my message', insideErr); - expect(err.data).to.not.exist(); - expect(err.cause).to.shallow.equal(insideErr); + expect(err.data).toBeNull(); + expect(err.cause).toBe(insideErr); }); }); describe('stack trace', () => { - - it('should omit lib', () => { - + it('should omit src', () => { for (const name of utilities) { const err = Boom[name](); - expect(err.stack).to.not.match(/(\/|\\)lib(\/|\\)index\.js/); + expect(err.stack).not.toMatch(/(\/|\\)src(\/|\\)index\.js/); } }); - it('should not crash when Error.captureStackTrace is missing', (flags) => { - + it('should not crash when Error.captureStackTrace is missing', () => { const captureStackTrace = Error.captureStackTrace; for (const name of utilities) { + let err; + try { Error.captureStackTrace = undefined; - var err = Boom[name](); - } - finally { + err = Boom[name](); + } finally { Error.captureStackTrace = captureStackTrace; } - expect(err.stack).to.match(/(\/|\\)lib(\/|\\)index\.js/); + expect(err.stack).toMatch(/(\/|\\)src(\/|\\)index\.js/); } }); }); describe('method with error object instead of message', () => { - - for (const name of utilities) { - it(`uses stringified error as message`, () => { - - const error = new Error('An example mongoose validation error'); - error.name = 'ValidationError'; - const err = Boom[name](error); - expect(err.cause).to.not.exist(); - expect(err.message).to.equal(error.toString()); - }); - } + it.each(utilities)('%s uses stringified error as message', (name) => { + const error = new Error('An example mongoose validation error'); + error.name = 'ValidationError'; + const err = Boom[name](error); + expect(err.cause).toBeUndefined(); + expect(err.message).toBe(error.toString()); + }); }); describe('reformat()', () => { - it('displays internal server error messages in debug mode', () => { - const error = new Error('ka-boom'); const err = new Boom.Boom(null, { statusCode: 500, cause: error }); err.reformat(false); - expect(err.output).to.equal({ + expect(err.output).toEqual({ statusCode: 500, payload: { statusCode: 500, error: 'Internal Server Error', - message: 'An internal server error occurred' + message: 'An internal server error occurred', }, - headers: {} + headers: {}, }); err.reformat(true); - expect(err.output).to.equal({ + expect(err.output).toEqual({ statusCode: 500, payload: { statusCode: 500, error: 'Internal Server Error', - message: 'ka-boom' + message: 'ka-boom', }, - headers: {} + headers: {}, }); }); it('is redefinable', () => { - Object.defineProperty(new Boom.Boom('oops'), 'reformat', { value: true }); }); it('can be implemented by subclasses to apply custom formatting', () => { - class MyBoom extends Boom.Boom { - reformat(...args) { - super.reformat(...args); this.output.payload.custom = true; @@ -1179,31 +999,29 @@ describe('Boom', () => { } const err = new MyBoom('boom', { statusCode: 400 }); - expect(err.output.statusCode).to.equal(400); - expect(err.output.payload.message).to.equal('boom'); - expect(err.output.payload.custom).to.be.true(); + expect(err.output.statusCode).toBe(400); + expect(err.output.payload.message).toBe('boom'); + expect(err.output.payload.custom).toBe(true); err.output.statusCode = 500; err.reformat(); - expect(err.output.statusCode).to.equal(500); - expect(err.output.payload.message).to.equal('An internal server error occurred'); - expect(err.output.payload.custom).to.be.true(); + expect(err.output.statusCode).toBe(500); + expect(err.output.payload.message).toBe('An internal server error occurred'); + expect(err.output.payload.custom).toBe(true); }); - it('prototype can be changed to always debug', (flags) => { - + it('prototype can be changed to always debug', () => { const proto = Boom.Boom.prototype.reformat; - flags.onCleanup = () => { + onTestFinished(() => { Boom.Boom.prototype.reformat = proto; - }; + }); Boom.Boom.prototype.reformat = function () { - return proto.call(this, true); }; - expect(Boom.internal('DEBUG').output.payload.message).to.equal('DEBUG'); + expect(Boom.internal('DEBUG').output.payload.message).toBe('DEBUG'); }); }); }); diff --git a/test/index.ts b/test/index.ts deleted file mode 100755 index fdeac2c..0000000 --- a/test/index.ts +++ /dev/null @@ -1,447 +0,0 @@ -import * as Boom from '..'; -import * as Lab from '@hapi/lab'; - -const { expect } = Lab.types; - - -// new Boom.Boom() - -expect.type(new Boom.Boom()); -expect.type>(new Boom.Boom('error')); -expect.type>(new Boom.Boom('error', { data: true })); -expect.type>(new Boom.Boom('error')); -expect.type>(new Boom.Boom('error', { data: true })); - -expect.error(new Boom.Boom(null)); -expect.error(new Boom.Boom(new Error('error'))); -expect.error(new Boom.Boom('error')); -expect.error(new Boom.Boom('error', { data: true })); - - -class CustomError extends Boom.Boom {} -expect.type(new CustomError('Some error')); - - -const boom = new Boom.Boom('some error'); -expect.type(boom.output); -boom.output.payload.custom_null = null; -boom.output.payload.custom_number = 42; -boom.output.payload.custom_string = 'foo'; -boom.output.payload.custom_boolean = true; -boom.output.payload.custom_object = { bar: 42 }; -boom.output.headers['header1'] = 'foo'; -boom.output.headers['header2'] = ['foo', 'bar']; -boom.output.headers['header3'] = 42; -boom.output.headers['header4'] = undefined; -expect.type(boom.output.payload); -expect.type(boom.output.headers); - - -// boomify() - -const error = new Error('Unexpected input'); -class BadaBoom extends Boom.Boom { - constructor() { super('boom', { data: 1 }) } -} - -expect.type(Boom.boomify(error)); -expect.type(Boom.boomify(error, { statusCode: 400 })); -expect.type(Boom.boomify(error, { statusCode: 400, message: 'Unexpected Input', override: false })); -expect.type(Boom.boomify('error')); -expect.type>(Boom.boomify(new Boom.Boom<{ foo: 'bar' }>('error', { data: { foo: 'bar' }}))); -expect.type>(Boom.boomify(error, { data: 'bla' })); -expect.type>(Boom.boomify>(error, { data: 'bla' })); -expect.type(Boom.boomify(new BadaBoom(), { statusCode: 400 })); -expect.type>(Boom.boomify(new BadaBoom(), { statusCode: 400 })); -expect.type(Boom.boomify(new BadaBoom(), { data: 'bla' }).data); - -expect.type>(Boom.boomify(new Boom.Boom('error', { data: 'ok' }))); -expect.type>(Boom.boomify(new Boom.Boom('error', { data: 'ok' }), { data: 1 })); -expect.type>(Boom.boomify>(new Boom.Boom('error', { data: 'ok' }), { data: 1 })); - -expect.error(Boom.boomify()); -expect.error(Boom.boomify(error, { statusCode: '400' })); -expect.error(Boom.boomify(error, { statusCode: 400, message: true })); -expect.error(Boom.boomify(error, { statusCode: 400, override: 'false' })); -expect.error(Boom.boomify(error, { decorate: { x: 'y' } })); -//expect.error(Boom.boomify>(new Boom.Boom('error', { data: 'ok' }))); // Cannot work without partial type inference (https://github.com/microsoft/TypeScript/issues/26242) - -// isBoom - -expect.type(Boom.boomify(error).isBoom); - -// isBoom() - -expect.type(Boom.isBoom(error)); -expect.type(Boom.isBoom(error, 404)); -expect.type(Boom.isBoom(Boom.boomify(error))); -expect.type(Boom.isBoom('error')); -expect.type(Boom.isBoom({ foo: 'bar' })); -expect.type(Boom.isBoom({ error: true })); - -expect.error(Boom.isBoom(error, 'test')); -expect.error(Boom.isBoom()); - - -// 4xx Errors - -// badRequest() - -expect.type>(Boom.badRequest('invalid query', 'some data')); -expect.type>(Boom.badRequest('invalid query', { foo: 'bar' })); -expect.type(Boom.badRequest('invalid query')); -expect.type(Boom.badRequest()); - -expect.error(Boom.badRequest(400)); -expect.error(Boom.badRequest({ foo: 'bar' })); -expect.error(Boom.badRequest(new Error())); - - -// unauthorized() - -expect.type>(Boom.unauthorized('invalid password')); -expect.type>(Boom.unauthorized('invalid password', 'simple')); -expect.type>(Boom.unauthorized(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4=')); -expect.type>(Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' })); -expect.type>(Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' } as Boom.unauthorized.Attributes)); -expect.type>(Boom.unauthorized()); -expect.type>(Boom.unauthorized('basic', ['a', 'b', 'c'])); -expect.type & Boom.unauthorized.MissingAuth>(Boom.unauthorized('', 'basic')); -expect.type & Boom.unauthorized.MissingAuth>(Boom.unauthorized(null, 'basic')); -expect.type(Boom.unauthorized('', 'basic').isMissing); -expect.type(Boom.unauthorized(null, 'basic').isMissing); - -expect.error(Boom.unauthorized(401)); -expect.error(Boom.unauthorized('invalid password', 500)); -expect.error(Boom.unauthorized('invalid password', 'sample', 500)); -expect.error(Boom.unauthorized('basic', ['a', 'b', 'c'], 'test')); -expect.error(Boom.unauthorized('message', 'basic').isMissing); - -// paymentRequired() - -expect.type>(Boom.paymentRequired('bandwidth used', 'some data')); -expect.type>(Boom.paymentRequired('bandwidth used', { foo: 'bar' })); -expect.type(Boom.paymentRequired('bandwidth used')); -expect.type(Boom.paymentRequired()); - -expect.error(Boom.paymentRequired(402)); -expect.error(Boom.paymentRequired({ foo: 'bar' })); - - -// forbidden() - -expect.type>(Boom.forbidden('try again some time', 'some data')); -expect.type>(Boom.forbidden('try again some time', { foo: 'bar' })); -expect.type(Boom.forbidden('try again some time')); -expect.type(Boom.forbidden()); - -expect.error(Boom.forbidden(403)); -expect.error(Boom.forbidden({ foo: 'bar' })); - - -// notFound() - -expect.type>(Boom.notFound('missing', 'some data')); -expect.type>(Boom.notFound('missing', { foo: 'bar' })); -expect.type(Boom.notFound('missing')); -expect.type(Boom.notFound()); - -expect.error(Boom.notFound(404)); -expect.error(Boom.notFound({ foo: 'bar' })); - - -// methodNotAllowed() - -expect.type>(Boom.methodNotAllowed('this method is not allowed', 'some data')); -expect.type>(Boom.methodNotAllowed('this method is not allowed', { foo: 'bar' })); -expect.type(Boom.methodNotAllowed('this method is not allowed')); -expect.type(Boom.methodNotAllowed()); - -expect.error(Boom.methodNotAllowed(405)); -expect.error(Boom.methodNotAllowed({ foo: 'bar' })); - - -// notAcceptable() - -expect.type>(Boom.notAcceptable('unacceptable', 'some data')); -expect.type>(Boom.notAcceptable('unacceptable', { foo: 'bar' })); -expect.type(Boom.notAcceptable('unacceptable')); -expect.type(Boom.notAcceptable()); - -expect.error(Boom.notAcceptable(406)); -expect.error(Boom.notAcceptable({ foo: 'bar' })); - - -// proxyAuthRequired() - -expect.type>(Boom.proxyAuthRequired('auth missing', 'some data')); -expect.type>(Boom.proxyAuthRequired('auth missing', { foo: 'bar' })); -expect.type(Boom.proxyAuthRequired('auth missing')); -expect.type(Boom.proxyAuthRequired()); - -expect.error(Boom.proxyAuthRequired(407)); -expect.error(Boom.proxyAuthRequired({ foo: 'bar' })); - - -// clientTimeout() - -expect.type>(Boom.clientTimeout('timed out', 'some data')); -expect.type>(Boom.clientTimeout('timed out', { foo: 'bar' })); -expect.type(Boom.clientTimeout('timed out')); -expect.type(Boom.clientTimeout()); - -expect.error(Boom.clientTimeout(408)); -expect.error(Boom.clientTimeout({ foo: 'bar' })); - - -// conflict() - -expect.type>(Boom.conflict('there was a conflict', 'some data')); -expect.type>(Boom.conflict('there was a conflict', { foo: 'bar' })); -expect.type(Boom.conflict('there was a conflict')); -expect.type(Boom.conflict()); - -expect.error(Boom.conflict(409)); -expect.error(Boom.conflict({ foo: 'bar' })); - - -// resourceGone() - -expect.type>(Boom.resourceGone('it is gone', 'some data')); -expect.type>(Boom.resourceGone('it is gone', { foo: 'bar' })); -expect.type(Boom.resourceGone('it is gone')); -expect.type(Boom.resourceGone()); - -expect.error(Boom.resourceGone(410)); -expect.error(Boom.resourceGone({ foo: 'bar' })); - - -// lengthRequired() - -expect.type>(Boom.lengthRequired('length needed', 'some data')); -expect.type>(Boom.lengthRequired('length needed', { foo: 'bar' })); -expect.type(Boom.lengthRequired('length needed')); -expect.type(Boom.lengthRequired()); - -expect.error(Boom.lengthRequired(411)); -expect.error(Boom.lengthRequired({ foo: 'bar' })); - - -// preconditionFailed() - -expect.type>(Boom.preconditionFailed('failed', 'some data')); -expect.type>(Boom.preconditionFailed('failed', { foo: 'bar' })); -expect.type(Boom.preconditionFailed('failed')); -expect.type(Boom.preconditionFailed()); - -expect.error(Boom.preconditionFailed(412)); -expect.error(Boom.preconditionFailed({ foo: 'bar' })); - - -// entityTooLarge() - -expect.type>(Boom.entityTooLarge('too big', 'some data')); -expect.type>(Boom.entityTooLarge('too big', { foo: 'bar' })); -expect.type(Boom.entityTooLarge('too big')); -expect.type(Boom.entityTooLarge()); - -expect.error(Boom.entityTooLarge(413)); -expect.error(Boom.entityTooLarge({ foo: 'bar' })); - - -// uriTooLong() - -expect.type>(Boom.uriTooLong('uri is too long', 'some data')); -expect.type>(Boom.uriTooLong('uri is too long', { foo: 'bar' })); -expect.type(Boom.uriTooLong('uri is too long')); -expect.type(Boom.uriTooLong()); - -expect.error(Boom.uriTooLong(414)); -expect.error(Boom.uriTooLong({ foo: 'bar' })); - - -// unsupportedMediaType() - -expect.type>(Boom.unsupportedMediaType('that media is not supported', 'some data')); -expect.type>(Boom.unsupportedMediaType('that media is not supported', { foo: 'bar' })); -expect.type(Boom.unsupportedMediaType('that media is not supported')); -expect.type(Boom.unsupportedMediaType()); - -expect.error(Boom.unsupportedMediaType(415)); -expect.error(Boom.unsupportedMediaType({ foo: 'bar' })); - - -// rangeNotSatisfiable() - -expect.type>(Boom.rangeNotSatisfiable('range not satisfiable', 'some data')); -expect.type>(Boom.rangeNotSatisfiable('range not satisfiable', { foo: 'bar' })); -expect.type(Boom.rangeNotSatisfiable('range not satisfiable')); -expect.type(Boom.rangeNotSatisfiable()); - -expect.error(Boom.rangeNotSatisfiable(416)); -expect.error(Boom.rangeNotSatisfiable({ foo: 'bar' })); - - -// expectationFailed() - -expect.type>(Boom.expectationFailed('expected this to work', 'some data')); -expect.type>(Boom.expectationFailed('expected this to work', { foo: 'bar' })); -expect.type(Boom.expectationFailed('expected this to work')); -expect.type(Boom.expectationFailed()); - -expect.error(Boom.expectationFailed(417)); -expect.error(Boom.expectationFailed({ foo: 'bar' })); - - -// teapot() - -expect.type>(Boom.teapot('sorry, no coffee...', 'some data')); -expect.type>(Boom.teapot('sorry, no coffee...', { foo: 'bar' })); -expect.type(Boom.teapot('sorry, no coffee...')); -expect.type(Boom.teapot()); - -expect.error(Boom.teapot(418)); -expect.error(Boom.teapot({ foo: 'bar' })); - - -// badData() - -expect.type>(Boom.badData('your data is bad and you should feel bad', 'some data')); -expect.type>(Boom.badData('your data is bad and you should feel bad', { foo: 'bar' })); -expect.type(Boom.badData('your data is bad and you should feel bad')); -expect.type(Boom.badData()); - -expect.error(Boom.badData(422)); -expect.error(Boom.badData({ foo: 'bar' })); - - -// locked() - -expect.type>(Boom.locked('this resource has been locked', 'some data')); -expect.type>(Boom.locked('this resource has been locked', { foo: 'bar' })); -expect.type(Boom.locked('this resource has been locked')); -expect.type(Boom.locked()); - -expect.error(Boom.locked(423)); -expect.error(Boom.locked({ foo: 'bar' })); - - -// failedDependency() - -expect.type>(Boom.failedDependency('an external resource failed', 'some data')); -expect.type>(Boom.failedDependency('an external resource failed', { foo: 'bar' })); -expect.type(Boom.failedDependency('an external resource failed')); -expect.type(Boom.failedDependency()); - -expect.error(Boom.failedDependency(424)); -expect.error(Boom.failedDependency({ foo: 'bar' })); - -// tooEarly() - -expect.type>(Boom.tooEarly('won\'t process your request', 'some data')); -expect.type>(Boom.tooEarly('won\'t process your request', { foo: 'bar' })); -expect.type(Boom.tooEarly('won\'t process your request')); -expect.type(Boom.tooEarly()); - -expect.error(Boom.tooEarly(425)); -expect.error(Boom.tooEarly({ foo: 'bar' })); - -// preconditionRequired() - -expect.type>(Boom.preconditionRequired('you must supple an If-Match header', 'some data')); -expect.type>(Boom.preconditionRequired('you must supple an If-Match header', { foo: 'bar' })); -expect.type(Boom.preconditionRequired('you must supple an If-Match header')); -expect.type(Boom.preconditionRequired()); - -expect.error(Boom.preconditionRequired(428)); -expect.error(Boom.preconditionRequired({ foo: 'bar' })); - - -// tooManyRequests() - -expect.type>(Boom.tooManyRequests('you have exceeded your request limit', 'some data')); -expect.type>(Boom.tooManyRequests('you have exceeded your request limit', { foo: 'bar' })); -expect.type(Boom.tooManyRequests('you have exceeded your request limit')); -expect.type(Boom.tooManyRequests()); - -expect.error(Boom.tooManyRequests(414)); -expect.error(Boom.tooManyRequests({ foo: 'bar' })); - - -// illegal() - -expect.type>(Boom.illegal('you are not permitted to view this resource for legal reasons', 'some data')); -expect.type>(Boom.illegal('you are not permitted to view this resource for legal reasons', { foo: 'bar' })); -expect.type(Boom.illegal('you are not permitted to view this resource for legal reasons')); -expect.type(Boom.illegal()); - -expect.error(Boom.illegal(451)); -expect.error(Boom.illegal({ foo: 'bar' })); - - -// 5xx Errors - -// internal() - -expect.type>(Boom.internal('terrible implementation', 'some data', 599)); -expect.type>(Boom.internal('terrible implementation', { foo: 'bar' })); -expect.type(Boom.internal('terrible implementation')); -expect.type(Boom.internal()); - -expect.error(Boom.internal(500)); -expect.error(Boom.internal({ foo: 'bar' })); - - -// badImplementation() - -expect.type>(Boom.badImplementation('terrible implementation', 'some data')); -expect.type>(Boom.badImplementation('terrible implementation', { foo: 'bar' })); -expect.type(Boom.badImplementation('terrible implementation')); -expect.type(Boom.badImplementation()); - -expect.error(Boom.badImplementation(500)); -expect.error(Boom.badImplementation({ foo: 'bar' })); - - -// notImplemented() - -expect.type>(Boom.notImplemented('method not implemented', 'some data')); -expect.type>(Boom.notImplemented('method not implemented', { foo: 'bar' })); -expect.type(Boom.notImplemented('method not implemented')); -expect.type(Boom.notImplemented()); - -expect.error(Boom.notImplemented(501)); -expect.error(Boom.notImplemented({ foo: 'bar' })); - - -// badGateway() - -expect.type>(Boom.badGateway('this is a bad gateway', 'some data')); -expect.type>(Boom.badGateway('this is a bad gateway', { foo: 'bar' })); -expect.type(Boom.badGateway('this is a bad gateway')); -expect.type(Boom.badGateway()); - -expect.error(Boom.badGateway(502)); -expect.error(Boom.badGateway({ foo: 'bar' })); - - -// serverUnavailable() - -expect.type>(Boom.serverUnavailable('unavailable', 'some data')); -expect.type>(Boom.serverUnavailable('unavailable', { foo: 'bar' })); -expect.type(Boom.serverUnavailable('unavailable')); -expect.type(Boom.serverUnavailable()); - -expect.error(Boom.serverUnavailable(503)); -expect.error(Boom.serverUnavailable({ foo: 'bar' })); - - -// gatewayTimeout() - -expect.type>(Boom.gatewayTimeout('gateway timeout', 'some data')); -expect.type>(Boom.gatewayTimeout('gateway timeout', { foo: 'bar' })); -expect.type(Boom.gatewayTimeout('gateway timeout')); -expect.type(Boom.gatewayTimeout()); - -expect.error(Boom.gatewayTimeout(504)); -expect.error(Boom.gatewayTimeout({ foo: 'bar' })); diff --git a/test/typings.ts b/test/typings.ts new file mode 100644 index 0000000..9a1ecc9 --- /dev/null +++ b/test/typings.ts @@ -0,0 +1,709 @@ +import { describe, expectTypeOf, it } from 'vitest'; + +import * as Boom from '../src/index.js'; + +describe('typings', () => { + describe('Boom', () => { + it('accepts valid calls', () => { + expectTypeOf(new Boom.Boom()).toExtend(); + expectTypeOf(new Boom.Boom('error')).toExtend>(); + expectTypeOf(new Boom.Boom('error', { data: true })).toExtend>(); + expectTypeOf(new Boom.Boom('error')).toExtend>(); + expectTypeOf(new Boom.Boom('error', { data: true })).toExtend>(); + + class CustomError extends Boom.Boom {} + expectTypeOf(new CustomError('Some error')).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + new Boom.Boom(null); + // @ts-expect-error message must be a string + new Boom.Boom(new Error('error')); + // @ts-expect-error data is required when Data is set + new Boom.Boom('error'); + // @ts-expect-error data must match Data + new Boom.Boom('error', { data: true }); + }); + + it('exposes a writable output', () => { + const boom = new Boom.Boom('some error'); + expectTypeOf(boom.output).toEqualTypeOf(); + + boom.output.payload.custom_null = null; + boom.output.payload.custom_number = 42; + boom.output.payload.custom_string = 'foo'; + boom.output.payload.custom_boolean = true; + boom.output.payload.custom_object = { bar: 42 }; + boom.output.headers['header1'] = 'foo'; + boom.output.headers['header2'] = ['foo', 'bar']; + boom.output.headers['header3'] = 42; + boom.output.headers['header4'] = undefined; + + expectTypeOf(boom.output.payload).toExtend(); + expectTypeOf(boom.output.headers).toEqualTypeOf(); + }); + }); + + describe('boomify()', () => { + const error = new Error('Unexpected input'); + + class BadaBoom extends Boom.Boom { + constructor() { + super('boom', { data: 1 }); + } + } + + it('accepts valid calls', () => { + expectTypeOf(Boom.boomify(error)).toExtend(); + expectTypeOf(Boom.boomify(error, { statusCode: 400 })).toExtend(); + expectTypeOf( + Boom.boomify(error, { statusCode: 400, message: 'Unexpected Input', override: false }), + ).toExtend(); + expectTypeOf(Boom.boomify('error')).toExtend(); + expectTypeOf(Boom.boomify(new Boom.Boom<{ foo: 'bar' }>('error', { data: { foo: 'bar' } }))).toExtend< + Boom.Boom<{ foo: 'bar' }> + >(); + expectTypeOf(Boom.boomify(error, { data: 'bla' })).toExtend>(); + expectTypeOf(Boom.boomify>(error, { data: 'bla' })).toExtend>(); + expectTypeOf(Boom.boomify(new BadaBoom(), { statusCode: 400 })).toExtend(); + expectTypeOf(Boom.boomify(new BadaBoom(), { statusCode: 400 })).toExtend>(); + expectTypeOf(Boom.boomify(new BadaBoom(), { data: 'bla' }).data).toEqualTypeOf(); + + expectTypeOf(Boom.boomify(new Boom.Boom('error', { data: 'ok' }))).toExtend>(); + expectTypeOf(Boom.boomify(new Boom.Boom('error', { data: 'ok' }), { data: 1 })).toExtend< + Boom.Boom + >(); + expectTypeOf( + Boom.boomify>(new Boom.Boom('error', { data: 'ok' }), { data: 1 }), + ).toExtend>(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error requires an error + Boom.boomify(); + // @ts-expect-error statusCode must be a number + Boom.boomify(error, { statusCode: '400' }); + // @ts-expect-error message must be a string + Boom.boomify(error, { statusCode: 400, message: true }); + // @ts-expect-error override must be a boolean + Boom.boomify(error, { statusCode: 400, override: 'false' }); + // @ts-expect-error unknown option + Boom.boomify(error, { decorate: { x: 'y' } }); + + // Cannot work without partial type inference (https://github.com/microsoft/TypeScript/issues/26242) + // Boom.boomify>(new Boom.Boom('error', { data: 'ok' })); + }); + }); + + describe('isBoom()', () => { + const error = new Error('Unexpected input'); + + it('accepts valid calls', () => { + expectTypeOf(Boom.boomify(error).isBoom).toEqualTypeOf(); + + expectTypeOf(Boom.isBoom(error)).toBeBoolean(); + expectTypeOf(Boom.isBoom(error, 404)).toBeBoolean(); + expectTypeOf(Boom.isBoom(Boom.boomify(error))).toBeBoolean(); + expectTypeOf(Boom.isBoom('error')).toBeBoolean(); + expectTypeOf(Boom.isBoom({ foo: 'bar' })).toBeBoolean(); + expectTypeOf(Boom.isBoom({ error: true })).toBeBoolean(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error statusCode must be a number + Boom.isBoom(error, 'test'); + // @ts-expect-error requires an object + Boom.isBoom(); + }); + }); + + // 4xx Errors + + describe('badRequest()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.badRequest('invalid query', 'some data')).toExtend>(); + expectTypeOf(Boom.badRequest('invalid query', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.badRequest('invalid query')).toExtend(); + expectTypeOf(Boom.badRequest()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.badRequest(400); + // @ts-expect-error message must be a string + Boom.badRequest({ foo: 'bar' }); + // @ts-expect-error message must be a string + Boom.badRequest(new Error()); + }); + }); + + describe('unauthorized()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.unauthorized('invalid password')).toExtend>(); + expectTypeOf(Boom.unauthorized('invalid password', 'simple')).toExtend>(); + expectTypeOf(Boom.unauthorized(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4=')).toExtend< + Boom.Boom + >(); + expectTypeOf(Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' })).toExtend< + Boom.Boom + >(); + expectTypeOf( + Boom.unauthorized('invalid password', 'sample', { + ttl: 0, + cache: null, + foo: 'bar', + } as Boom.unauthorized.Attributes), + ).toExtend>(); + expectTypeOf(Boom.unauthorized()).toExtend>(); + expectTypeOf(Boom.unauthorized('basic', ['a', 'b', 'c'])).toExtend>(); + expectTypeOf(Boom.unauthorized('', 'basic')).toExtend & Boom.unauthorized.MissingAuth>(); + expectTypeOf(Boom.unauthorized(null, 'basic')).toExtend & Boom.unauthorized.MissingAuth>(); + expectTypeOf(Boom.unauthorized('', 'basic').isMissing).toEqualTypeOf(); + expectTypeOf(Boom.unauthorized(null, 'basic').isMissing).toEqualTypeOf(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.unauthorized(401); + try { + // @ts-expect-error scheme must be a string or an array + Boom.unauthorized('invalid password', 500); + } catch {} + // @ts-expect-error attributes must be a string or an object + Boom.unauthorized('invalid password', 'sample', 500); + // @ts-expect-error attributes are not supported with an array of schemes + Boom.unauthorized('basic', ['a', 'b', 'c'], 'test'); + // @ts-expect-error isMissing is only set when the message is empty + Boom.unauthorized('message', 'basic').isMissing; + }); + }); + + describe('paymentRequired()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.paymentRequired('bandwidth used', 'some data')).toExtend>(); + expectTypeOf(Boom.paymentRequired('bandwidth used', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.paymentRequired('bandwidth used')).toExtend(); + expectTypeOf(Boom.paymentRequired()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.paymentRequired(402); + // @ts-expect-error message must be a string + Boom.paymentRequired({ foo: 'bar' }); + }); + }); + + describe('forbidden()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.forbidden('try again some time', 'some data')).toExtend>(); + expectTypeOf(Boom.forbidden('try again some time', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.forbidden('try again some time')).toExtend(); + expectTypeOf(Boom.forbidden()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.forbidden(403); + // @ts-expect-error message must be a string + Boom.forbidden({ foo: 'bar' }); + }); + }); + + describe('notFound()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.notFound('missing', 'some data')).toExtend>(); + expectTypeOf(Boom.notFound('missing', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.notFound('missing')).toExtend(); + expectTypeOf(Boom.notFound()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.notFound(404); + // @ts-expect-error message must be a string + Boom.notFound({ foo: 'bar' }); + }); + }); + + describe('methodNotAllowed()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.methodNotAllowed('this method is not allowed', 'some data')).toExtend< + Boom.Boom + >(); + expectTypeOf(Boom.methodNotAllowed('this method is not allowed', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.methodNotAllowed('this method is not allowed')).toExtend(); + expectTypeOf(Boom.methodNotAllowed()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.methodNotAllowed(405); + // @ts-expect-error message must be a string + Boom.methodNotAllowed({ foo: 'bar' }); + }); + }); + + describe('notAcceptable()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.notAcceptable('unacceptable', 'some data')).toExtend>(); + expectTypeOf(Boom.notAcceptable('unacceptable', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.notAcceptable('unacceptable')).toExtend(); + expectTypeOf(Boom.notAcceptable()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.notAcceptable(406); + // @ts-expect-error message must be a string + Boom.notAcceptable({ foo: 'bar' }); + }); + }); + + describe('proxyAuthRequired()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.proxyAuthRequired('auth missing', 'some data')).toExtend>(); + expectTypeOf(Boom.proxyAuthRequired('auth missing', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.proxyAuthRequired('auth missing')).toExtend(); + expectTypeOf(Boom.proxyAuthRequired()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.proxyAuthRequired(407); + // @ts-expect-error message must be a string + Boom.proxyAuthRequired({ foo: 'bar' }); + }); + }); + + describe('clientTimeout()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.clientTimeout('timed out', 'some data')).toExtend>(); + expectTypeOf(Boom.clientTimeout('timed out', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.clientTimeout('timed out')).toExtend(); + expectTypeOf(Boom.clientTimeout()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.clientTimeout(408); + // @ts-expect-error message must be a string + Boom.clientTimeout({ foo: 'bar' }); + }); + }); + + describe('conflict()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.conflict('there was a conflict', 'some data')).toExtend>(); + expectTypeOf(Boom.conflict('there was a conflict', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.conflict('there was a conflict')).toExtend(); + expectTypeOf(Boom.conflict()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.conflict(409); + // @ts-expect-error message must be a string + Boom.conflict({ foo: 'bar' }); + }); + }); + + describe('resourceGone()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.resourceGone('it is gone', 'some data')).toExtend>(); + expectTypeOf(Boom.resourceGone('it is gone', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.resourceGone('it is gone')).toExtend(); + expectTypeOf(Boom.resourceGone()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.resourceGone(410); + // @ts-expect-error message must be a string + Boom.resourceGone({ foo: 'bar' }); + }); + }); + + describe('lengthRequired()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.lengthRequired('length needed', 'some data')).toExtend>(); + expectTypeOf(Boom.lengthRequired('length needed', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.lengthRequired('length needed')).toExtend(); + expectTypeOf(Boom.lengthRequired()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.lengthRequired(411); + // @ts-expect-error message must be a string + Boom.lengthRequired({ foo: 'bar' }); + }); + }); + + describe('preconditionFailed()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.preconditionFailed('failed', 'some data')).toExtend>(); + expectTypeOf(Boom.preconditionFailed('failed', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.preconditionFailed('failed')).toExtend(); + expectTypeOf(Boom.preconditionFailed()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.preconditionFailed(412); + // @ts-expect-error message must be a string + Boom.preconditionFailed({ foo: 'bar' }); + }); + }); + + describe('entityTooLarge()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.entityTooLarge('too big', 'some data')).toExtend>(); + expectTypeOf(Boom.entityTooLarge('too big', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.entityTooLarge('too big')).toExtend(); + expectTypeOf(Boom.entityTooLarge()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.entityTooLarge(413); + // @ts-expect-error message must be a string + Boom.entityTooLarge({ foo: 'bar' }); + }); + }); + + describe('uriTooLong()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.uriTooLong('uri is too long', 'some data')).toExtend>(); + expectTypeOf(Boom.uriTooLong('uri is too long', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.uriTooLong('uri is too long')).toExtend(); + expectTypeOf(Boom.uriTooLong()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.uriTooLong(414); + // @ts-expect-error message must be a string + Boom.uriTooLong({ foo: 'bar' }); + }); + }); + + describe('unsupportedMediaType()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.unsupportedMediaType('that media is not supported', 'some data')).toExtend< + Boom.Boom + >(); + expectTypeOf(Boom.unsupportedMediaType('that media is not supported', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.unsupportedMediaType('that media is not supported')).toExtend(); + expectTypeOf(Boom.unsupportedMediaType()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.unsupportedMediaType(415); + // @ts-expect-error message must be a string + Boom.unsupportedMediaType({ foo: 'bar' }); + }); + }); + + describe('rangeNotSatisfiable()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.rangeNotSatisfiable('range not satisfiable', 'some data')).toExtend>(); + expectTypeOf(Boom.rangeNotSatisfiable('range not satisfiable', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.rangeNotSatisfiable('range not satisfiable')).toExtend(); + expectTypeOf(Boom.rangeNotSatisfiable()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.rangeNotSatisfiable(416); + // @ts-expect-error message must be a string + Boom.rangeNotSatisfiable({ foo: 'bar' }); + }); + }); + + describe('expectationFailed()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.expectationFailed('expected this to work', 'some data')).toExtend>(); + expectTypeOf(Boom.expectationFailed('expected this to work', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.expectationFailed('expected this to work')).toExtend(); + expectTypeOf(Boom.expectationFailed()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.expectationFailed(417); + // @ts-expect-error message must be a string + Boom.expectationFailed({ foo: 'bar' }); + }); + }); + + describe('teapot()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.teapot('sorry, no coffee...', 'some data')).toExtend>(); + expectTypeOf(Boom.teapot('sorry, no coffee...', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.teapot('sorry, no coffee...')).toExtend(); + expectTypeOf(Boom.teapot()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.teapot(418); + // @ts-expect-error message must be a string + Boom.teapot({ foo: 'bar' }); + }); + }); + + describe('badData()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.badData('your data is bad and you should feel bad', 'some data')).toExtend< + Boom.Boom + >(); + expectTypeOf(Boom.badData('your data is bad and you should feel bad', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.badData('your data is bad and you should feel bad')).toExtend(); + expectTypeOf(Boom.badData()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.badData(422); + // @ts-expect-error message must be a string + Boom.badData({ foo: 'bar' }); + }); + }); + + describe('locked()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.locked('this resource has been locked', 'some data')).toExtend>(); + expectTypeOf(Boom.locked('this resource has been locked', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.locked('this resource has been locked')).toExtend(); + expectTypeOf(Boom.locked()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.locked(423); + // @ts-expect-error message must be a string + Boom.locked({ foo: 'bar' }); + }); + }); + + describe('failedDependency()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.failedDependency('an external resource failed', 'some data')).toExtend< + Boom.Boom + >(); + expectTypeOf(Boom.failedDependency('an external resource failed', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.failedDependency('an external resource failed')).toExtend(); + expectTypeOf(Boom.failedDependency()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.failedDependency(424); + // @ts-expect-error message must be a string + Boom.failedDependency({ foo: 'bar' }); + }); + }); + + describe('tooEarly()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.tooEarly("won't process your request", 'some data')).toExtend>(); + expectTypeOf(Boom.tooEarly("won't process your request", { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.tooEarly("won't process your request")).toExtend(); + expectTypeOf(Boom.tooEarly()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.tooEarly(425); + // @ts-expect-error message must be a string + Boom.tooEarly({ foo: 'bar' }); + }); + }); + + describe('preconditionRequired()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.preconditionRequired('you must supple an If-Match header', 'some data')).toExtend< + Boom.Boom + >(); + expectTypeOf(Boom.preconditionRequired('you must supple an If-Match header', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.preconditionRequired('you must supple an If-Match header')).toExtend(); + expectTypeOf(Boom.preconditionRequired()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.preconditionRequired(428); + // @ts-expect-error message must be a string + Boom.preconditionRequired({ foo: 'bar' }); + }); + }); + + describe('tooManyRequests()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.tooManyRequests('you have exceeded your request limit', 'some data')).toExtend< + Boom.Boom + >(); + expectTypeOf(Boom.tooManyRequests('you have exceeded your request limit', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.tooManyRequests('you have exceeded your request limit')).toExtend(); + expectTypeOf(Boom.tooManyRequests()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.tooManyRequests(414); + // @ts-expect-error message must be a string + Boom.tooManyRequests({ foo: 'bar' }); + }); + }); + + describe('illegal()', () => { + it('accepts valid calls', () => { + expectTypeOf( + Boom.illegal('you are not permitted to view this resource for legal reasons', 'some data'), + ).toExtend>(); + expectTypeOf( + Boom.illegal('you are not permitted to view this resource for legal reasons', { foo: 'bar' }), + ).toExtend>(); + expectTypeOf( + Boom.illegal('you are not permitted to view this resource for legal reasons'), + ).toExtend(); + expectTypeOf(Boom.illegal()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.illegal(451); + // @ts-expect-error message must be a string + Boom.illegal({ foo: 'bar' }); + }); + }); + + // 5xx Errors + + describe('internal()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.internal('terrible implementation', 'some data', 599)).toExtend>(); + expectTypeOf(Boom.internal('terrible implementation', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.internal('terrible implementation')).toExtend(); + expectTypeOf(Boom.internal()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.internal(500); + // @ts-expect-error message must be a string + Boom.internal({ foo: 'bar' }); + }); + }); + + describe('badImplementation()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.badImplementation('terrible implementation', 'some data')).toExtend>(); + expectTypeOf(Boom.badImplementation('terrible implementation', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.badImplementation('terrible implementation')).toExtend(); + expectTypeOf(Boom.badImplementation()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.badImplementation(500); + // @ts-expect-error message must be a string + Boom.badImplementation({ foo: 'bar' }); + }); + }); + + describe('notImplemented()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.notImplemented('method not implemented', 'some data')).toExtend>(); + expectTypeOf(Boom.notImplemented('method not implemented', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.notImplemented('method not implemented')).toExtend(); + expectTypeOf(Boom.notImplemented()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.notImplemented(501); + // @ts-expect-error message must be a string + Boom.notImplemented({ foo: 'bar' }); + }); + }); + + describe('badGateway()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.badGateway('this is a bad gateway', 'some data')).toExtend>(); + expectTypeOf(Boom.badGateway('this is a bad gateway', { foo: 'bar' })).toExtend< + Boom.Boom<{ foo: string }> + >(); + expectTypeOf(Boom.badGateway('this is a bad gateway')).toExtend(); + expectTypeOf(Boom.badGateway()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.badGateway(502); + // @ts-expect-error message must be a string + Boom.badGateway({ foo: 'bar' }); + }); + }); + + describe('serverUnavailable()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.serverUnavailable('unavailable', 'some data')).toExtend>(); + expectTypeOf(Boom.serverUnavailable('unavailable', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.serverUnavailable('unavailable')).toExtend(); + expectTypeOf(Boom.serverUnavailable()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.serverUnavailable(503); + // @ts-expect-error message must be a string + Boom.serverUnavailable({ foo: 'bar' }); + }); + }); + + describe('gatewayTimeout()', () => { + it('accepts valid calls', () => { + expectTypeOf(Boom.gatewayTimeout('gateway timeout', 'some data')).toExtend>(); + expectTypeOf(Boom.gatewayTimeout('gateway timeout', { foo: 'bar' })).toExtend>(); + expectTypeOf(Boom.gatewayTimeout('gateway timeout')).toExtend(); + expectTypeOf(Boom.gatewayTimeout()).toExtend(); + }); + + it('rejects invalid calls', () => { + // @ts-expect-error message must be a string + Boom.gatewayTimeout(504); + // @ts-expect-error message must be a string + Boom.gatewayTimeout({ foo: 'bar' }); + }); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..849762f --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "exactOptionalPropertyTypes": true, + "forceConsistentCasingInFileNames": true, + "inlineSources": true, + "isolatedDeclarations": true, + "isolatedModules": true, + "module": "NodeNext", + "moduleResolution": "NodeNext", + "noEmit": true, + "noFallthroughCasesInSwitch": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noUncheckedIndexedAccess": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "skipDefaultLibCheck": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "target": "ESNext" + } +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..20fc611 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,24 @@ +import Oxc from '@hapi/oxc-plugin/vitest'; +import { defineConfig } from 'vitest/config'; + +import type { ViteUserConfig } from 'vitest/config'; + +export default defineConfig({ + plugins: [Oxc()], + test: { + environment: 'node', + include: ['test/**/*.{js,ts}'], + typecheck: { + enabled: true, + include: ['test/**/*.{js,ts}'], + }, + coverage: { + provider: 'v8', + include: ['src/**'], + exclude: ['**/*.d.ts'], + thresholds: { + 100: true, + }, + }, + }, +}) as ViteUserConfig; From edfc9968914c8d29c76e52b44ef041b00f694399 Mon Sep 17 00:00:00 2001 From: Nicolas Morel Date: Sun, 2 Aug 2026 13:41:20 +0200 Subject: [PATCH 50/50] chore: add regression tests based on #307 --- test/index.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/index.js b/test/index.js index 1c760ce..171c0e0 100755 --- a/test/index.js +++ b/test/index.js @@ -227,6 +227,14 @@ describe('Boom', () => { expect(err.data).toBeNull(); }); + it('wraps a DOMException without touching its getters', () => { + const error = new DOMException('kaboom', 'AbortError'); + const err = Boom.boomify(error, { statusCode: 400 }); + + expect(err.cause).toBe(error); + expect(err.output.payload.message).toBe('kaboom'); + }); + it('sets new message when none exists', () => { const error = new Error(); const wrapped = Boom.boomify(error, { statusCode: 400, message: 'something bad' });