From 40c1a1d5ce694d7fba091e0be1f0841e355bb9e8 Mon Sep 17 00:00:00 2001 From: Titus Wormer Date: Wed, 16 Aug 2023 19:08:40 +0200 Subject: [PATCH] Add support for causes with causes --- lib/index.js | 24 ++++++++++++++++-------- test.js | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/lib/index.js b/lib/index.js index 6c4c2c5..1fc9a1f 100644 --- a/lib/index.js +++ b/lib/index.js @@ -241,20 +241,28 @@ function createByline(state, stats) { */ function createCauseLines(state, cause) { const lines = [' ' + state.bold + '[cause]' + state.normalIntensity + ':'] - /** @type {string | undefined} */ - let stackValue + let foundReasonableCause = false if (cause !== null && typeof cause === 'object') { - stackValue = + const stackValue = ('stack' in cause ? String(cause.stack) : undefined) || ('message' in cause ? String(cause.message) : undefined) + + if (typeof stackValue === 'string') { + foundReasonableCause = true + + const stackLines = stackValue.split(eol) + stackLines[0] = ' ' + stackLines[0] + + lines.push(...stackLines) + + if ('cause' in cause && cause.cause) { + lines.push(...createCauseLines(state, cause.cause)) + } + } } - if (typeof stackValue === 'string') { - const stackLines = stackValue.split(eol) - stackLines[0] = ' ' + stackLines[0] - lines.push(...stackLines) - } else { + if (!foundReasonableCause) { lines.push(' ' + cause) } diff --git a/test.js b/test.js index 25550e6..65fd57d 100644 --- a/test.js +++ b/test.js @@ -50,6 +50,10 @@ try { } /* eslint-enable no-undef */ +// @ts-expect-error: it’s assigned. +const causedCause = new Error('Boom!', {cause: exception}) +causedCause.stack = cleanStack(causedCause.stack, 3) + test('reporter', async function () { const mod = await import('./index.js') @@ -413,6 +417,30 @@ test('reporter', async function () { 'should support a `message.cause`' ) + file = new VFile() + + file.message('Something failed terribly', { + cause: causedCause + }) + + assert.equal( + strip(reporter(file)), + [ + ' warning Something failed terribly', + ' [cause]:', + ' Error: Boom!', + ' at test.js:1:1', + ' at ModuleJob.run (module_job:1:1)', + ' [cause]:', + ' ReferenceError: variable is not defined', + ' at test.js:1:1', + ' at ModuleJob.run (module_job:1:1)', + '', + '⚠ 1 warning' + ].join('\n'), + 'should support a `message.cause`, w/ another cause' + ) + file = new VFile() let message = file.message('Something failed terribly') message.cause = 'Boom!' @@ -442,7 +470,7 @@ test('reporter', async function () { '', '⚠ 1 warning' ].join('\n'), - 'should support a `message.cause` set to a n object w/o stack' + 'should support a `message.cause` set to an object w/o stack' ) file = new VFile() @@ -458,7 +486,7 @@ test('reporter', async function () { '', '⚠ 1 warning' ].join('\n'), - 'should support a `message.cause` set to a n object w/o stack or message' + 'should support a `message.cause` set to an object w/o stack or message' ) /** @type {Text} */