Gathering detailed insights and metrics for youch
Gathering detailed insights and metrics for youch
Gathering detailed insights and metrics for youch
Gathering detailed insights and metrics for youch
npm install youch
Add toJSON method
Published on 23 Nov 2024
Add console printer and rename methods
Published on 22 Nov 2024
Add cheviron icon and support for CSP nonce
Published on 17 Nov 2024
Release 4.0.0-beta.0
Published on 16 Nov 2024
Add support for helpful links
Published on 29 Sept 2018
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
926 Stars
190 Commits
26 Forks
11 Watching
3 Branches
11 Contributors
Updated on 26 Nov 2024
TypeScript (74.14%)
CSS (23.16%)
JavaScript (2.71%)
Cumulative downloads
Total Downloads
Last day
7%
150,699
Compared to previous day
Last week
6.6%
816,496
Compared to previous week
Last month
11.5%
3,291,916
Compared to previous month
Last year
129.2%
30,340,593
Compared to previous year
3
Pretty print JavaScript errors on the Web and the Terminal
Table of Contents
Youch is an error-parsing library that pretty prints JavaScript errors on a web page or the terminal.
As you can see in the following screenshots, the error presented by Youch is a lot more readable and presentable in comparison to the unformatted stack trace.
Unformatted stack trace |
Youch output |
Install the package from the npm packages registry as follows.
1npm i youch@beta 2 3# Yarn 4yarn add youch@beta 5 6# Pnpm 7pnpm add youch@beta
You can render errors to HTML output using the youch.toHTML
method. The HTML output is self-contained and does not require separate CSS or JavaScript files.
In the following example, we use the hono
framework and pretty print all the errors in development using Youch. You can replace Hono with any other framework of your choice.
1import { Hono } from 'hono' 2import { Youch } from 'youch' 3 4const app = new Hono() 5const IN_DEV = process.env.NODE_ENV === 'development' 6 7app.onError(async (error, c) => { 8 if (IN_DEV) { 9 const youch = new Youch() 10 const html = await youch.toHTML(error) 11 return c.html(html) 12 } 13 return c.text(error.message) 14})
The youch.toHTML
method accepts the error as the first argument and the following options as the second argument.
1await youch.toHTML(error, {
2 title: 'An error occurred',
3 cspNonce: '',
4 offset: 0,
5 ide: 'vscode',
6})
Option | Description |
---|---|
title | Define the title for the error page. It defaults to "An error has occurred" |
cspNonce | If your application is using CSP protection, then you must provide the CSP-nonce for rendering inline style and script tags. |
offset | The offset can be used to skip displaying certain frames from the parsed error stack. |
ide | The ide option defines the code editor for opening the files when the filename anchor tag is clicked. Learn more about configuring code editors |
You can render an error to ANSI output (for terminal) using the youch.toANSI
method.
1try { 2 await performSomeAction() 3} catch (error) { 4 const youch = new Youch() 5 const ansiOutput = await youch.toANSI(error) 6 7 console.error(ansiOutput) 8}
The youch.toANSI
method accepts the error as the first argument and the following options as the second argument.
1await youch.toANSI(error, {
2 offset: 0,
3})
Option | Description |
---|---|
offset | The offset can be used to skip displaying certain frames from the parsed error stack. |
Let's deconstruct the error page and understand what each section of the output represents.
The top-most section displays the Error info, which includes:
options.title
property.The Stack trace section displays individual frames as accordion sections. Clicking on the section title reveals the frame source code. The source code is unavailable for native stack frames that are part of the Node.js, Deno, and Bun internals.
For the ANSI output, only the first frame from the application code is expanded to show the source code.
Clicking the Raw
button displays the Error object in its raw form, with all the error properties (not just the stack trace).
The raw output may be helpful for errors that contain additional properties. HTTP client libraries like Axios, Got, Undici, and others usually contain the HTTP response details within the error object.
In case of ANSI output, you can view the raw output using the YOUCH_RAW
environment variable. For example: YOUCH_RAW=true node your-script.js
.
Error cause is a standard way to bubble errors while wrapping them within a generic error. Youch displays the error cause as an interactive property within its own section.
For the ANSI output, the nested properties are shown upto the two levels deep. However, you can adjust the depth using the YOUCH_CAUSE
environment variable. For example: YOUCH_CAUSE=4 node your-script.js
.
Metadata refers to any additional data that you want to display on the error page. It could be the HTTP request headers, the logged-in user info, or the list of available application routes.
Metadata is structured as groups and sections. Each section contains an array of rows, and each row is composed of a key-value
pair.
In the following example, we display the request headers under the Request
group and the Headers
section.
1const youch = new Youch() 2 3youch.group('Request', { 4 headers: [ 5 { 6 key: 'cookie', 7 value: req.headers.cookie, 8 }, 9 { 10 key: 'host', 11 value: req.headers.host, 12 }, 13 ], 14})
Calling the youch.group
method multiple times with the same group name will merge the new sections with existing sections.
Youch reads the source code of files within the stack trace using the Node.js fs
module. However, you can override this default and provide a custom source loader using the youch.sourceLoader
method.
Note: The
sourceLoader
is called for every frame within the stack traces. Therefore, you must perform the necessary checks before attempting to read the source code of a file.For example, you must not attempt to read the source code for fileNames pointing to native code.
1import { Youch } from 'youch'
2const youch = new Youch(options)
3
4youch.sourceLoader(async (stackFrame) => {
5 if (stackFrame.type !== 'native') {
6 stackFrame.source = await getSourceForFile(stackFrame.fileName)
7 }
8})
You may inject custom CSS styles using the youch.injectStyles
method. The styles will be injected after the styles from the inbuilt templates.
1import { Youch } from 'youch'
2const youch = new Youch(options)
3
4youch.injectStyles(`
5 :root {
6 // Override variables for light mode
7 --surface-bg: #fff;
8 --surface-fg: #000;
9 --muted-fg: #999;
10 }
11
12 html.dark {
13 // Override variables for dark mode
14 }
15`)
Youch uses speed-highlight, a lightweight code highlighting library for JavaScript. To override the syntax highlighter, you can register a custom component for the errorStackSource
template.
In the following example, we use Shiki to perform syntax highlighting using a custom component.
1import { codeToHtml } from 'shiki' 2import { ErrorStackSourceProps } from 'youch/types' 3import { ErrorStackSource } from 'youch/templates/error_stack_source' 4 5/** 6 * A custom component that uses shiki to render the source 7 * code snippet for a stack frame 8 */ 9class CustomErrorStackSource<ErrorStackSourceProps> extends ErrorStackSource { 10 /** 11 * Return the styles you want to inject from this 12 * component 13 */ 14 async getStyles() { 15 return ` 16 html.dark .shiki { 17 background-color: var(--shiki-dark-bg) !important; 18 } 19 20 html.dark .shiki span { 21 color: var(--shiki-dark) !important; 22 font-weight: var(--shiki-dark-font-weight) !important; 23 text-decoration: var(--shiki-dark-text-decoration) !important; 24 } 25 26 pre.shiki { 27 padding: 16px 0; 28 } 29 30 code .line { 31 position: relative; 32 padding: 0 16px 0 48px; 33 height: 24px; 34 line-height: 24px; 35 width: 100%; 36 display: inline-block; 37 } 38 39 code .line:before { 40 position: absolute; 41 content: attr(data-line); 42 opacity: 0.5; 43 text-align: right; 44 margin-right: 5px; 45 left: 0; 46 width: 32px; 47 } 48 49 code .highlighted { 50 background-color: #ff000632; 51 } 52 53 html.dark code .highlighted { 54 background-color: #ff173f2d !important; 55 }` 56 } 57 58 async toHTML(props: ErrorStackSourceProps) { 59 if (props.frame.source) { 60 const code = props.frame.source.map(({ chunk }) => chunk).join('\n') 61 62 return codeToHtml(code, { 63 lang: 'typescript', 64 themes: { 65 light: 'min-light', 66 dark: 'vitesse-dark', 67 }, 68 transformers: [ 69 { 70 line(node, line) { 71 const lineNumber = props.frame.source![line - 1].lineNumber 72 node.properties['data-line'] = lineNumber 73 74 if (lineNumber === props.frame.lineNumber) { 75 this.addClassToHast(node, 'highlighted') 76 } 77 }, 78 }, 79 ], 80 }) 81 } 82 83 return '' 84 } 85} 86 87const youch = new Youch() 88 89/** 90 * Register the component 91 */ 92youch.templates.use('errorStackSource', new CustomErrorStackSource(false)) 93 94const html = await youch.toHTML(error)
When you click the filename anchor tag (displayed in the pretty error stack section), Youch will attempt to open the given file inside a pre-configured code editor (defaults to vscode
).
You can specify which code editor to use via the ide
option. Following is the list of support code editors.
If you prefer a different code editor, specify its URL via the ide
option. Make sure the URL contains the %f
placeholder for the filename and the %l
placeholder for the line number.
1await youch.toHTML(error, {
2 ide: 'mvim://open?url=file://%f&line=%l',
3})
Youch relies on the process.env.IDE
environment variable to detect the user's code editor and falls back to vscode
if the environment variable is not defined.
However, you can use any detection logic and specify the detected code editor via the ide
option. For example, In the case of AdonisJS, we configure the code editor within the .env
file using the ADONIS_IDE
environment variable.
One of the primary goals of Poppinss is to have a vibrant community of users and contributors who believe in the principles of the framework.
We encourage you to read the contribution guide before contributing to the framework.
In order to ensure that the Poppinss community is welcoming to all, please review and abide by the Code of Conduct.
Youch is open-sourced software licensed under the MIT license.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
25 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 2/30 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More