This commit is contained in:
2026-07-08 18:29:36 +08:00
parent ad51ced86c
commit 3af8ff9b80
1613 changed files with 701644 additions and 2 deletions
+69
View File
@@ -0,0 +1,69 @@
import {
colors,
wordWrap
} from "./chunk-4L7RY2JA.js";
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/error_info/main.ts
var ERROR_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="24" height="24" fill="none"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 7v6m0 4.01.01-.011M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10Z"/></svg>`;
var HINT_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="24" height="24" fill="none"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m21 2-1 1M3 2l1 1m17 13-1-1M3 16l1-1m5 3h6m-5 3h4M12 3C8 3 5.952 4.95 6 8c.023 1.487.5 2.5 1.5 3.5S9 13 9 15h6c0-2 .5-2.5 1.5-3.5h0c1-1 1.477-2.013 1.5-3.5.048-3.05-2-5-6-5Z"/></svg>`;
var ErrorInfo = class extends BaseComponent {
cssFile = new URL("./error_info/style.css", publicDirURL);
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
return `<section>
<h4 id="error-name">${props.error.name}</h4>
<h1 id="error-title">${props.title}</h1>
</section>
<section>
<div class="card">
<div class="card-body">
<h2 id="error-message">
<span>${ERROR_ICON_SVG}</span>
<span>${props.error.message}</span>
</h2>
${props.error.hint ? `<div id="error-hint">
<span>${HINT_ICON_SVG}</span>
<span>${props.error.hint}</span>
</div>` : ""}
</div>
</div>
</section>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI(props) {
const errorMessage = colors.red(
`\u2139 ${wordWrap(`${props.error.name}: ${props.error.message}`, {
width: process.stdout.columns,
indent: " ",
newLine: "\n",
escape: (value) => value
})}`
);
const hint = props.error.hint ? `
${colors.blue("\u25C9")} ${colors.dim().italic(
wordWrap(props.error.hint.replace(/(<([^>]+)>)/gi, ""), {
width: process.stdout.columns,
indent: " ",
newLine: "\n",
escape: (value) => value
})
)}` : "";
return `${errorMessage}${hint}`;
}
};
export {
ErrorInfo
};
+42
View File
@@ -0,0 +1,42 @@
// src/helpers.ts
import useColors from "@poppinss/colors";
var ANSI_REGEX = new RegExp(
[
`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
].join("|"),
"g"
);
function htmlEscape(value) {
return value.replace(/&/g, "&amp;").replace(/\\"/g, "&bsol;&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
function wordWrap(value, options) {
const width = options.width;
const indent = options.indent;
const newLine = `${options.newLine}${indent}`;
if (!width) {
return options.escape ? options.escape(value) : htmlEscape(value);
}
let regexString = ".{1," + width + "}";
regexString += "([\\s\u200B]+|$)|[^\\s\u200B]+?([\\s\u200B]+|$)";
const re = new RegExp(regexString, "g");
const lines = value.match(re) || [];
const result = lines.map(function(line) {
if (line.slice(-1) === "\n") {
line = line.slice(0, line.length - 1);
}
return options.escape ? options.escape(line) : htmlEscape(line);
}).join(newLine);
return result;
}
function stripAnsi(value) {
return value.replace(ANSI_REGEX, "");
}
var colors = useColors.ansi();
export {
htmlEscape,
wordWrap,
stripAnsi,
colors
};
+85
View File
@@ -0,0 +1,85 @@
import {
colors,
stripAnsi
} from "./chunk-4L7RY2JA.js";
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/error_stack_source/main.ts
import { extname } from "path";
import { highlightText } from "@speed-highlight/core";
import { highlightText as cliHighlightText } from "@speed-highlight/core/terminal";
var GUTTER = "\u2503";
var POINTER = "\u276F";
var LANGS_MAP = {
".tsx": "ts",
".jsx": "js",
".js": "js",
".ts": "ts",
".css": "css",
".json": "json",
".html": "html",
".astro": "ts",
".vue": "ts"
};
var ErrorStackSource = class extends BaseComponent {
cssFile = new URL("./error_stack_source/style.css", publicDirURL);
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
const frame = props.frame;
if (frame.type === "native" || !frame.source || !frame.fileName) {
return "";
}
const language = LANGS_MAP[extname(frame.fileName)] ?? "plain";
const highlightMarginTop = `${frame.source.findIndex((chunk) => {
return chunk.lineNumber === frame.lineNumber;
}) * 24}px`;
const highlight = `<div class="line-highlight" style="margin-top: ${highlightMarginTop}"></div>`;
let code = await highlightText(
frame.source.map((chunk) => chunk.chunk).join("\n"),
language,
true
);
code = code.replace(
'<div class="shj-numbers">',
`<div class="shj-numbers" style="counter-set: line ${frame.source[0].lineNumber - 1}">`
);
return `<pre><code class="shj-lang-js">${highlight}${code}</code></pre>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI(props) {
const frame = props.frame;
if (frame.type === "native" || !frame.source || !frame.fileName) {
return "";
}
const language = LANGS_MAP[extname(frame.fileName)] ?? "plain";
const largestLineNumber = Math.max(...frame.source.map(({ lineNumber }) => lineNumber));
const lineNumberCols = String(largestLineNumber).length;
const code = frame.source.map(({ chunk }) => chunk).join("\n");
const highlighted = await cliHighlightText(code, language);
return `
${highlighted.split("\n").map((line, index) => {
const lineNumber = frame.source[index].lineNumber;
const alignedLineNumber = String(lineNumber).padStart(lineNumberCols, " ");
if (lineNumber === props.frame.lineNumber) {
return ` ${colors.bgRed(`${POINTER} ${alignedLineNumber} ${GUTTER} ${stripAnsi(line)}`)}`;
}
return ` ${colors.dim(alignedLineNumber)} ${colors.dim(GUTTER)} ${line}`;
}).join("\n")}
`;
}
};
export {
ErrorStackSource
};
+61
View File
@@ -0,0 +1,61 @@
// src/component.ts
import { readFile } from "fs/promises";
var BaseComponent = class {
#cachedStyles;
#cachedScript;
/**
* A flag to know if we are in dev mode or not. In dev mode,
* the styles and scripts are refetched from the disk.
* Otherwise they are cached.
*/
#inDevMode;
/**
* Absolute path to the frontend JavaScript that should be
* injected within the HTML head. The JavaScript does not
* get transpiled, hence it should work cross browser by
* default.
*/
scriptFile;
/**
* Absolute path to the CSS file that should be injected
* within the HTML head.
*/
cssFile;
constructor(devMode) {
this.#inDevMode = devMode;
}
/**
* Returns the styles for the component. The null value
* is not returned if no styles are associated with
* the component
*/
async getStyles() {
if (!this.cssFile) {
return null;
}
if (this.#inDevMode) {
return await readFile(this.cssFile, "utf-8");
}
this.#cachedStyles = this.#cachedStyles ?? await readFile(this.cssFile, "utf-8");
return this.#cachedStyles;
}
/**
* Returns the frontend script for the component. The null
* value is not returned if no styles are associated
* with the component
*/
async getScript() {
if (!this.scriptFile) {
return null;
}
if (this.#inDevMode) {
return await readFile(this.scriptFile, "utf-8");
}
this.#cachedScript = this.#cachedScript ?? await readFile(this.scriptFile, "utf-8");
return this.#cachedScript;
}
};
export {
BaseComponent
};
+85
View File
@@ -0,0 +1,85 @@
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/error_metadata/main.ts
import { dump, themes } from "@poppinss/dumper/html";
var ErrorMetadata = class extends BaseComponent {
#primitives = ["string", "boolean", "number", "undefined"];
/**
* Formats the error row value
*/
#formatRowValue(value, dumpValue, cspNonce) {
if (dumpValue === true) {
return dump(value, { styles: themes.cssVariables, cspNonce });
}
if (this.#primitives.includes(typeof value) || value === null) {
return value;
}
return dump(value, { styles: themes.cssVariables, cspNonce });
}
/**
* Returns HTML fragment with HTML table containing rows
* metadata section rows
*/
#renderRows(rows, cspNonce) {
return `<table class="card-table">
<tbody>
${rows.map((row) => {
return `<tr>
<td class="table-key">${row.key}</td>
<td class="table-value">
${this.#formatRowValue(row.value, row.dump, cspNonce)}
</td>
</tr>`;
}).join("\n")}
</tbody>
</table>`;
}
/**
* Renders each section with its rows inside a table
*/
#renderSection(section, rows, cspNonce) {
return `<div>
<h4 class="card-subtitle">${section}</h4>
${Array.isArray(rows) ? this.#renderRows(rows, cspNonce) : `<span>${this.#formatRowValue(rows.value, rows.dump, cspNonce)}</span>`}
</div>`;
}
/**
* Renders each group as a card
*/
#renderGroup(group, sections, cspNonce) {
return `<section>
<div class="card">
<div class="card-heading">
<h3 class="card-title">${group}</h3>
</div>
<div class="card-body">
${Object.keys(sections).map((section) => this.#renderSection(section, sections[section], cspNonce)).join("\n")}
</div>
</div>
</section>`;
}
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
const groups = props.metadata.toJSON();
const groupsNames = Object.keys(groups);
if (!groupsNames.length) {
return "";
}
return groupsNames.map((group) => this.#renderGroup(group, groups[group], props.cspNonce)).join("\n");
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI() {
return "";
}
};
export {
ErrorMetadata
};
+222
View File
@@ -0,0 +1,222 @@
import {
colors,
htmlEscape
} from "./chunk-4L7RY2JA.js";
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/error_stack/main.ts
import { dump, themes } from "@poppinss/dumper/html";
import { dump as dumpCli } from "@poppinss/dumper/console";
var CHEVIRON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" width="24" height="24" stroke-width="2">
<path d="M6 9l6 6l6 -6"></path>
</svg>`;
var EDITORS = {
textmate: "txmt://open?url=file://%f&line=%l",
macvim: "mvim://open?url=file://%f&line=%l",
emacs: "emacs://open?url=file://%f&line=%l",
sublime: "subl://open?url=file://%f&line=%l",
phpstorm: "phpstorm://open?file=%f&line=%l",
atom: "atom://core/open/file?filename=%f&line=%l",
vscode: "vscode://file/%f:%l"
};
var ErrorStack = class extends BaseComponent {
cssFile = new URL("./error_stack/style.css", publicDirURL);
scriptFile = new URL("./error_stack/script.js", publicDirURL);
/**
* Returns the file's relative name from the CWD
*/
#getRelativeFileName(filePath) {
return filePath.replace(`${process.cwd()}/`, "");
}
/**
* Returns the index of the frame that should be expanded by
* default
*/
#getFirstExpandedFrameIndex(frames) {
let expandAtIndex = frames.findIndex((frame) => frame.type === "app");
if (expandAtIndex === -1) {
expandAtIndex = frames.findIndex((frame) => frame.type === "module");
}
return expandAtIndex;
}
/**
* Returns the link to open the file within known code
* editors
*/
#getEditorLink(ide, frame) {
const editorURL = EDITORS[ide] || ide;
if (!editorURL || frame.type === "native") {
return {
text: this.#getRelativeFileName(frame.fileName)
};
}
return {
href: editorURL.replace("%f", frame.fileName).replace("%l", String(frame.lineNumber)),
text: this.#getRelativeFileName(frame.fileName)
};
}
/**
* Returns the HTML fragment for the frame location
*/
#renderFrameLocation(frame, ide) {
const { text, href } = this.#getEditorLink(ide, frame);
const fileName = `<a${href ? ` href="${href}"` : ""} class="stack-frame-filepath" title="${text}">
${htmlEscape(text)}
</a>`;
const functionName = frame.functionName ? `<span>in <code title="${frame.functionName}">
${htmlEscape(frame.functionName)}
</code></span>` : "";
const loc = `<span>at line <code>${frame.lineNumber}:${frame.columnNumber}</code></span>`;
if (frame.type !== "native" && frame.source) {
return `<button class="stack-frame-location">
${fileName} ${functionName} ${loc}
</button>`;
}
return `<div class="stack-frame-location">
${fileName} ${functionName} ${loc}
</div>`;
}
/**
* Returns HTML fragment for the stack frame
*/
async #renderStackFrame(frame, index, expandAtIndex, props) {
const label = frame.type === "app" ? '<span class="frame-label">In App</span>' : "";
const expandedClass = expandAtIndex === index ? " expanded" : "";
const toggleButton = frame.type !== "native" && frame.source ? `<button class="stack-frame-toggle-indicator">${CHEVIRON}</button>` : "";
return `<li class="stack-frame stack-frame-${frame.type}${expandedClass}">
<div class="stack-frame-contents">
${this.#renderFrameLocation(frame, props.ide)}
<div class="stack-frame-extras">
${label}
${toggleButton}
</div>
</div>
<div class="stack-frame-source">
${await props.sourceCodeRenderer(props.error, frame)}
</div>
</li>`;
}
/**
* Returns the ANSI output to print the stack frame on the
* terminal
*/
async #printStackFrame(frame, index, expandAtIndex, props) {
const fileName = this.#getRelativeFileName(frame.fileName);
const loc = `${fileName}:${frame.lineNumber}:${frame.columnNumber}`;
if (index === expandAtIndex) {
const functionName2 = frame.functionName ? `at ${frame.functionName} ` : "";
const codeSnippet = await props.sourceCodeRenderer(props.error, frame);
return ` \u2043 ${functionName2}${colors.yellow(`(${loc})`)}${codeSnippet}`;
}
if (frame.type === "native") {
const functionName2 = frame.functionName ? `at ${colors.italic(frame.functionName)} ` : "";
return colors.dim(` \u2043 ${functionName2}(${colors.italic(loc)})`);
}
const functionName = frame.functionName ? `at ${frame.functionName} ` : "";
return ` \u2043 ${functionName}${colors.yellow(`(${loc})`)}`;
}
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
const frames = await Promise.all(
props.error.frames.map((frame, index) => {
return this.#renderStackFrame(
frame,
index,
this.#getFirstExpandedFrameIndex(props.error.frames),
props
);
})
);
return `<section>
<div class="card">
<div class="card-heading">
<div>
<h3 class="card-title">
Stack Trace
</h3>
</div>
</div>
<div class="card-body">
<div id="stack-frames-wrapper">
<div id="stack-frames-header">
<div id="all-frames-toggle-wrapper">
<label id="all-frames-toggle">
<input type="checkbox" />
<span> View All Frames </span>
</label>
</div>
<div>
<div class="toggle-switch">
<button id="formatted-frames-toggle" class="active"> Pretty </button>
<button id="raw-frames-toggle"> Raw </button>
</div>
</div>
</div>
<div id="stack-frames-body">
<div id="stack-frames-formatted" class="visible">
<ul id="stack-frames">
${frames.join("\n")}
</ul>
</div>
<div id="stack-frames-raw">
${dump(props.error.raw, {
styles: themes.cssVariables,
expand: true,
cspNonce: props.cspNonce,
inspectObjectPrototype: false,
inspectStaticMembers: false,
inspectArrayPrototype: false
})}
</div>
</div>
<div>
</div>
</div>
</section>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI(props) {
const displayRaw = process.env.YOUCH_RAW;
if (displayRaw) {
const depth = Number.isNaN(Number(displayRaw)) ? 2 : Number(displayRaw);
return `
${colors.red("[RAW]")}
${dumpCli(props.error.raw, {
depth,
inspectObjectPrototype: false,
inspectStaticMembers: false,
inspectArrayPrototype: false
})}`;
}
const frames = await Promise.all(
props.error.frames.map((frame, index) => {
return this.#printStackFrame(
frame,
index,
this.#getFirstExpandedFrameIndex(props.error.frames),
props
);
})
);
return `
${frames.join("\n")}`;
}
};
export {
ErrorStack
};
+6
View File
@@ -0,0 +1,6 @@
// src/public_dir.ts
var publicDirURL = new URL("./public/", import.meta.url);
export {
publicDirURL
};
+72
View File
@@ -0,0 +1,72 @@
import {
colors
} from "./chunk-4L7RY2JA.js";
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/error_cause/main.ts
import { dump, themes } from "@poppinss/dumper/html";
import { dump as dumpCli } from "@poppinss/dumper/console";
var ErrorCause = class extends BaseComponent {
cssFile = new URL("./error_cause/style.css", publicDirURL);
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
if (!props.error.cause) {
return "";
}
return `<section>
<div class="card">
<div class="card-heading">
<div>
<h3 class="card-title">
Error Cause
</h3>
</div>
</div>
<div class="card-body">
<div id="error-cause">
${dump(props.error.cause, {
cspNonce: props.cspNonce,
styles: themes.cssVariables,
inspectObjectPrototype: false,
inspectStaticMembers: false,
inspectArrayPrototype: false
})}
</div>
</div>
</div>
</section>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI(props) {
if (!props.error.cause) {
return "";
}
let depth = process.env.YOUCH_CAUSE ? Number(process.env.YOUCH_CAUSE) : 2;
if (Number.isNaN(depth)) {
depth = 2;
}
return `
${colors.red("[CAUSE]")}
${dumpCli(props.error.cause, {
depth,
inspectObjectPrototype: false,
inspectStaticMembers: false,
inspectArrayPrototype: false
})}`;
}
};
export {
ErrorCause
};
+41
View File
@@ -0,0 +1,41 @@
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/header/main.ts
var DARK_MODE_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M0 0h24v24H0z" stroke="none"/><path d="M12 3h.393a7.5 7.5 0 0 0 7.92 12.446A9 9 0 1 1 12 2.992z"/></svg>`;
var LIGHT_MODE_SVG = `<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M0 0h24v24H0z" stroke="none"/><circle cx="12" cy="12" r="4"/><path d="M3 12h1m8-9v1m8 8h1m-9 8v1M5.6 5.6l.7.7m12.1-.7-.7.7m0 11.4.7.7m-12.1-.7-.7.7"/></svg>`;
var Header = class extends BaseComponent {
cssFile = new URL("./header/style.css", publicDirURL);
scriptFile = new URL("./header/script.js", publicDirURL);
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML() {
return `<header id="header">
<div id="header-actions">
<div id="toggle-theme-container">
<input type="checkbox" id="toggle-theme-checkbox" />
<label id="toggle-theme-label" for="toggle-theme-checkbox">
<span id="light-theme-indicator" title="Light mode">${LIGHT_MODE_SVG}</span>
<span id="dark-theme-indicator" title="Dark mode">${DARK_MODE_SVG}</span>
</label>
</div>
</div>
</header>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI() {
return "";
}
};
export {
Header
};
+45
View File
@@ -0,0 +1,45 @@
import {
publicDirURL
} from "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/templates/layout/main.ts
var Layout = class extends BaseComponent {
cssFile = new URL("./layout/style.css", publicDirURL);
scriptFile = new URL("./layout/script.js", publicDirURL);
/**
* The toHTML method is used to output the HTML for the
* web view
*/
async toHTML(props) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${props.title}</title>
<!-- STYLES -->
<!-- SCRIPTS -->
</head>
<body>
<div id="layout">
${await props.children()}
</div>
</body>
</html>`;
}
/**
* The toANSI method is used to output the text for the console
*/
async toANSI(props) {
return `
${await props.children()}
`;
}
};
export {
Layout
};
+3
View File
@@ -0,0 +1,3 @@
export { Youch } from './src/youch.js';
export { Metadata } from './src/metadata.js';
export { BaseComponent } from './src/component.js';
+352
View File
@@ -0,0 +1,352 @@
import {
Layout
} from "./chunk-VE4LENUR.js";
import {
ErrorInfo
} from "./chunk-3X66E37A.js";
import {
ErrorCause
} from "./chunk-PINJDICN.js";
import {
ErrorMetadata
} from "./chunk-HFSXRSKS.js";
import {
ErrorStack
} from "./chunk-JAN2TFI2.js";
import {
ErrorStackSource
} from "./chunk-4XB2BYKC.js";
import "./chunk-4L7RY2JA.js";
import {
Header
} from "./chunk-PUHGL6HA.js";
import "./chunk-OSUFJZHZ.js";
import {
BaseComponent
} from "./chunk-4YEN7HVQ.js";
// src/youch.ts
import cookie from "cookie";
import { ErrorParser } from "youch-core";
// src/metadata.ts
var Metadata = class {
#groups = {};
/**
* Converts value to an array (if not an array already)
*/
#toArray(value) {
return Array.isArray(value) ? value : [value];
}
/**
* Define a group, its sections and their rows. In case of
* existing groups/sections, the new data will be merged
* with the existing data
*/
group(name, sections) {
this.#groups[name] = this.#groups[name] ?? {};
Object.keys(sections).forEach((section) => {
if (!this.#groups[name][section]) {
this.#groups[name][section] = sections[section];
} else {
this.#groups[name][section] = this.#toArray(this.#groups[name][section]);
this.#groups[name][section].push(...this.#toArray(sections[section]));
}
});
return this;
}
/**
* Returns the existing metadata groups, sections and
* rows.
*/
toJSON() {
return this.#groups;
}
};
// src/templates.ts
import { createScript, createStyleSheet } from "@poppinss/dumper/html";
var Templates = class {
constructor(devMode) {
this.devMode = devMode;
this.#knownTemplates = {
layout: new Layout(devMode),
header: new Header(devMode),
errorInfo: new ErrorInfo(devMode),
errorStack: new ErrorStack(devMode),
errorStackSource: new ErrorStackSource(devMode),
errorCause: new ErrorCause(devMode),
errorMetadata: new ErrorMetadata(devMode)
};
}
#knownTemplates;
#styles = /* @__PURE__ */ new Map([["global", createStyleSheet()]]);
#scripts = /* @__PURE__ */ new Map([["global", createScript()]]);
/**
* Returns a collection of style and script tags to dump
* inside the document HEAD.
*/
#getStylesAndScripts(cspNonce) {
let customInjectedStyles = "";
const styles = [];
const scripts = [];
const cspNonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
this.#styles.forEach((bucket, name) => {
if (name === "injected") {
customInjectedStyles = `<style id="${name}-styles"${cspNonceAttr}>${bucket}</style>`;
} else {
styles.push(`<style id="${name}-styles"${cspNonceAttr}>${bucket}</style>`);
}
});
this.#scripts.forEach((bucket, name) => {
scripts.push(`<script id="${name}-script"${cspNonceAttr}>${bucket}</script>`);
});
return { styles: `${styles.join("\n")}
${customInjectedStyles}`, scripts: scripts.join("\n") };
}
/**
* Collects styles and scripts for components as we render
* them.
*/
async #collectStylesAndScripts(templateName) {
if (!this.#styles.has(templateName)) {
const styles = await this.#knownTemplates[templateName].getStyles();
if (styles) {
this.#styles.set(templateName, styles);
}
}
if (!this.#scripts.has(templateName)) {
const script = await this.#knownTemplates[templateName].getScript();
if (script) {
this.#scripts.set(templateName, script);
}
}
}
/**
* Returns the HTML for a given template
*/
async #tmplToHTML(templateName, props) {
const component = this.#knownTemplates[templateName];
if (!component) {
throw new Error(`Invalid template "${templateName}"`);
}
await this.#collectStylesAndScripts(templateName);
return component.toHTML(props);
}
/**
* Returns the ANSI output for a given template
*/
async #tmplToANSI(templateName, props) {
const component = this.#knownTemplates[templateName];
if (!component) {
throw new Error(`Invalid template "${templateName}"`);
}
return component.toANSI(props);
}
/**
* Define a custom component to be used in place of the default component.
* Overriding components allows you control the HTML layout, styles and
* the frontend scripts of an HTML fragment.
*/
use(templateName, component) {
this.#knownTemplates[templateName] = component;
return this;
}
/**
* Inject custom styles to the document. Injected styles are
* always placed after the global and the components style
* tags.
*/
injectStyles(cssFragment) {
let injectedStyles = this.#styles.get("injected") ?? "";
injectedStyles += `
${cssFragment}`;
this.#styles.set("injected", injectedStyles);
return this;
}
/**
* Returns the HTML output for the given parsed error
*/
async toHTML(props) {
const html = await this.#tmplToHTML("layout", {
title: props.title,
ide: props.ide,
cspNonce: props.cspNonce,
children: async () => {
const header = await this.#tmplToHTML("header", props);
const info = await this.#tmplToHTML("errorInfo", props);
const stackTrace = await this.#tmplToHTML("errorStack", {
ide: process.env.EDITOR ?? "vscode",
sourceCodeRenderer: (error, frame) => {
return this.#tmplToHTML("errorStackSource", {
error,
frame,
ide: props.ide,
cspNonce: props.cspNonce
});
},
...props
});
const cause = await this.#tmplToHTML("errorCause", props);
const metadata = await this.#tmplToHTML("errorMetadata", props);
return `${header}${info}${stackTrace}${cause}${metadata}`;
}
});
const { scripts, styles } = this.#getStylesAndScripts(props.cspNonce);
return html.replace("<!-- STYLES -->", styles).replace("<!-- SCRIPTS -->", scripts);
}
/**
* Returns the ANSI output to be printed on the terminal
*/
async toANSI(props) {
const ansiOutput = await this.#tmplToANSI("layout", {
title: props.title,
children: async () => {
const header = await this.#tmplToANSI("header", {});
const info = await this.#tmplToANSI("errorInfo", props);
const stackTrace = await this.#tmplToANSI("errorStack", {
ide: process.env.EDITOR ?? "vscode",
sourceCodeRenderer: (error, frame) => {
return this.#tmplToANSI("errorStackSource", {
error,
frame
});
},
...props
});
const cause = await this.#tmplToANSI("errorCause", props);
const metadata = await this.#tmplToANSI("errorMetadata", props);
return `${header}${info}${stackTrace}${cause}${metadata}`;
}
});
return ansiOutput;
}
};
// src/youch.ts
var Youch = class {
/**
* Properties to be shared with the Error parser
*/
#sourceLoader;
#parsers = [];
#transformers = [];
/**
* Manage templates used for converting error to the HTML
* output
*/
templates = new Templates(false);
/**
* Define metadata to be displayed alongside the error output
*/
metadata = new Metadata();
/**
* Creates an instance of the ErrorParser and applies the
* source loader, parsers and transformers on it
*/
#createErrorParser(options) {
const errorParser = new ErrorParser(options);
if (this.#sourceLoader) {
errorParser.defineSourceLoader(this.#sourceLoader);
}
this.#parsers.forEach((parser) => errorParser.useParser(parser));
this.#transformers.forEach((transformer) => errorParser.useTransformer(transformer));
return errorParser;
}
/**
* Defines the request properties as a metadata group
*/
#defineRequestMetadataGroup(request) {
if (!request || Object.keys(request).length === 0) {
return;
}
this.metadata.group("Request", {
...request.url ? {
url: {
key: "URL",
value: request.url
}
} : {},
...request.method ? {
method: {
key: "Method",
value: request.method
}
} : {},
...request.headers ? {
headers: Object.keys(request.headers).map((key) => {
const value = request.headers[key];
return {
key,
value: key === "cookie" ? { ...cookie.parse(value) } : value
};
})
} : {}
});
}
/**
* Define custom implementation for loading the source code
* of a stack frame.
*/
defineSourceLoader(loader) {
this.#sourceLoader = loader;
return this;
}
/**
* Define a custom parser. Parsers are executed before the
* error gets parsed and provides you with an option to
* modify the error
*/
useParser(parser) {
this.#parsers.push(parser);
return this;
}
/**
* Define a custom transformer. Transformers are executed
* after the error has been parsed and can mutate the
* properties of the parsed error.
*/
useTransformer(transformer) {
this.#transformers.push(transformer);
return this;
}
/**
* Parses error to JSON
*/
async toJSON(error, options) {
options = { ...options };
return this.#createErrorParser({ offset: options.offset }).parse(error);
}
/**
* Render error to HTML
*/
async toHTML(error, options) {
options = { ...options };
this.#defineRequestMetadataGroup(options.request);
const parsedError = await this.#createErrorParser({ offset: options.offset }).parse(error);
return this.templates.toHTML({
title: options.title ?? "An error has occurred",
ide: options.ide ?? process.env.IDE ?? "vscode",
cspNonce: options.cspNonce,
error: parsedError,
metadata: this.metadata
});
}
/**
* Render error to ANSI output
*/
async toANSI(error, options) {
options = { ...options };
const parsedError = await this.#createErrorParser({ offset: options.offset }).parse(error);
return this.templates.toANSI({
title: "",
error: parsedError,
metadata: this.metadata
});
}
};
export {
BaseComponent,
Metadata,
Youch
};
+42
View File
@@ -0,0 +1,42 @@
/**
* BaseComponent that must be used to create custom components.
* It has support for loading CSS files and frontend scripts.
*/
export declare abstract class BaseComponent<Props = undefined> {
#private;
$props: Props;
/**
* Absolute path to the frontend JavaScript that should be
* injected within the HTML head. The JavaScript does not
* get transpiled, hence it should work cross browser by
* default.
*/
scriptFile?: string | URL;
/**
* Absolute path to the CSS file that should be injected
* within the HTML head.
*/
cssFile?: string | URL;
constructor(devMode: boolean);
/**
* Returns the styles for the component. The null value
* is not returned if no styles are associated with
* the component
*/
getStyles(): Promise<string | null>;
/**
* Returns the frontend script for the component. The null
* value is not returned if no styles are associated
* with the component
*/
getScript(): Promise<string | null>;
/**
* The toHTML method is used to output the HTML for the
* web view
*/
abstract toHTML(props: Props): Promise<string>;
/**
* The toANSI method is used to output the text for the console
*/
abstract toANSI(props: Props): Promise<string>;
}
+24
View File
@@ -0,0 +1,24 @@
import { type Colors } from '@poppinss/colors/types';
/**
* HTML escape string values so that they can be nested
* inside the pre-tags.
*/
export declare function htmlEscape(value: string): string;
/**
* Wraps a string value to be on multiple lines after
* a certain characters limit has been hit.
*/
export declare function wordWrap(value: string, options: {
width: number;
indent: string;
newLine: string;
escape?: (value: string) => string;
}): string;
/**
* Strips ANSI sequences from the string
*/
export declare function stripAnsi(value: string): string;
/**
* ANSI coloring library
*/
export declare const colors: Colors;
+28
View File
@@ -0,0 +1,28 @@
import { type ErrorMetadataGroups, type ErrorMetadataRow } from './types.js';
/**
* Attach metadata to the parsed error as groups, sections
* and rows.
*
* - Groups are rendered as cards
* - Sections are headings within the cards
* - And rows are rendered within HTML tables.
*
* The primitive row values are rendered as it is and rich data-types
* like Objects, Arrays, Maps are printed using dumper.
*/
export declare class Metadata {
#private;
/**
* Define a group, its sections and their rows. In case of
* existing groups/sections, the new data will be merged
* with the existing data
*/
group(name: string, sections: {
[section: string]: ErrorMetadataRow | ErrorMetadataRow[];
}): this;
/**
* Returns the existing metadata groups, sections and
* rows.
*/
toJSON(): ErrorMetadataGroups;
}
+1
View File
@@ -0,0 +1 @@
export declare const publicDirURL: URL;
+61
View File
@@ -0,0 +1,61 @@
import type { ParsedError } from 'youch-core/types';
import { type Metadata } from './metadata.js';
import type { YouchTemplates } from './types.js';
/**
* A super lightweight templates collection that allows composing
* HTML using TypeScript based components with the ability to
* override the component for a pre-defined template.
*
* @example
* ```ts
* const templates = new Templates()
* const html = templates.render(
* {
* title: 'Internal server error',
* error: await new ErrorParser().parse(error)
* }
* )
*
* // Override a template
* class MyHeader extends BaseComponent {
* async render() {}
* }
*
* templates.use('header', new MyHeader(templates.devMode))
* ```
*/
export declare class Templates {
#private;
devMode: boolean;
constructor(devMode: boolean);
/**
* Define a custom component to be used in place of the default component.
* Overriding components allows you control the HTML layout, styles and
* the frontend scripts of an HTML fragment.
*/
use<K extends keyof YouchTemplates>(templateName: K, component: YouchTemplates[K]): this;
/**
* Inject custom styles to the document. Injected styles are
* always placed after the global and the components style
* tags.
*/
injectStyles(cssFragment: string): this;
/**
* Returns the HTML output for the given parsed error
*/
toHTML(props: {
title: string;
ide?: string;
cspNonce?: string;
error: ParsedError;
metadata: Metadata;
}): Promise<string>;
/**
* Returns the ANSI output to be printed on the terminal
*/
toANSI(props: {
title: string;
error: ParsedError;
metadata: Metadata;
}): Promise<string>;
}
+17
View File
@@ -0,0 +1,17 @@
import { BaseComponent } from '../../component.js';
import type { ErrorCauseProps } from '../../types.js';
/**
* Displays the Error cause as a formatted value
*/
export declare class ErrorCause extends BaseComponent<ErrorCauseProps> {
cssFile: URL;
/**
* The toHTML method is used to output the HTML for the
* web view
*/
toHTML(props: ErrorCause['$props']): Promise<string>;
/**
* The toANSI method is used to output the text for the console
*/
toANSI(props: ErrorCauseProps): Promise<string>;
}
+9
View File
@@ -0,0 +1,9 @@
import {
ErrorCause
} from "../../../chunk-PINJDICN.js";
import "../../../chunk-4L7RY2JA.js";
import "../../../chunk-OSUFJZHZ.js";
import "../../../chunk-4YEN7HVQ.js";
export {
ErrorCause
};
+18
View File
@@ -0,0 +1,18 @@
import { BaseComponent } from '../../component.js';
import type { ErrorInfoProps } from '../../types.js';
/**
* Displays the error info including the response status text,
* error name, error message and the hint.
*/
export declare class ErrorInfo extends BaseComponent<ErrorInfoProps> {
cssFile: URL;
/**
* The toHTML method is used to output the HTML for the
* web view
*/
toHTML(props: ErrorInfoProps): Promise<string>;
/**
* The toANSI method is used to output the text for the console
*/
toANSI(props: ErrorInfoProps): Promise<string>;
}
+9
View File
@@ -0,0 +1,9 @@
import {
ErrorInfo
} from "../../../chunk-3X66E37A.js";
import "../../../chunk-4L7RY2JA.js";
import "../../../chunk-OSUFJZHZ.js";
import "../../../chunk-4YEN7HVQ.js";
export {
ErrorInfo
};
+17
View File
@@ -0,0 +1,17 @@
import { BaseComponent } from '../../component.js';
import type { ErrorMetadataProps } from '../../types.js';
/**
* Displays the error metadata as cards
*/
export declare class ErrorMetadata extends BaseComponent<ErrorMetadataProps> {
#private;
/**
* The toHTML method is used to output the HTML for the
* web view
*/
toHTML(props: ErrorMetadataProps): Promise<string>;
/**
* The toANSI method is used to output the text for the console
*/
toANSI(): Promise<string>;
}
+7
View File
@@ -0,0 +1,7 @@
import {
ErrorMetadata
} from "../../../chunk-HFSXRSKS.js";
import "../../../chunk-4YEN7HVQ.js";
export {
ErrorMetadata
};
+20
View File
@@ -0,0 +1,20 @@
import { BaseComponent } from '../../component.js';
import type { ErrorStackProps } from '../../types.js';
/**
* Displays the formatted and raw error stack along with the
* source code for individual stack frames
*/
export declare class ErrorStack extends BaseComponent<ErrorStackProps> {
#private;
cssFile: URL;
scriptFile: URL;
/**
* The toHTML method is used to output the HTML for the
* web view
*/
toHTML(props: ErrorStackProps): Promise<string>;
/**
* The toANSI method is used to output the text for the console
*/
toANSI(props: ErrorStackProps): Promise<string>;
}
+9
View File
@@ -0,0 +1,9 @@
import {
ErrorStack
} from "../../../chunk-JAN2TFI2.js";
import "../../../chunk-4L7RY2JA.js";
import "../../../chunk-OSUFJZHZ.js";
import "../../../chunk-4YEN7HVQ.js";
export {
ErrorStack
};
+18
View File
@@ -0,0 +1,18 @@
import { BaseComponent } from '../../component.js';
import type { ErrorStackSourceProps } from '../../types.js';
/**
* Pretty prints the stack frame source code with syntax
* highlighting.
*/
export declare class ErrorStackSource extends BaseComponent<ErrorStackSourceProps> {
cssFile: URL;
/**
* The toHTML method is used to output the HTML for the
* web view
*/
toHTML(props: ErrorStackSourceProps): Promise<string>;
/**
* The toANSI method is used to output the text for the console
*/
toANSI(props: ErrorStackSourceProps): Promise<string>;
}
+9
View File
@@ -0,0 +1,9 @@
import {
ErrorStackSource
} from "../../../chunk-4XB2BYKC.js";
import "../../../chunk-4L7RY2JA.js";
import "../../../chunk-OSUFJZHZ.js";
import "../../../chunk-4YEN7HVQ.js";
export {
ErrorStackSource
};
+19
View File
@@ -0,0 +1,19 @@
import { BaseComponent } from '../../component.js';
import type { ComponentSharedProps } from '../../types.js';
/**
* Renders the header for the error page. It contains only the
* theme-switcher for now
*/
export declare class Header extends BaseComponent<ComponentSharedProps> {
cssFile: URL;
scriptFile: URL;
/**
* The toHTML method is used to output the HTML for the
* web view
*/
toHTML(): Promise<string>;
/**
* The toANSI method is used to output the text for the console
*/
toANSI(): Promise<string>;
}
+8
View File
@@ -0,0 +1,8 @@
import {
Header
} from "../../../chunk-PUHGL6HA.js";
import "../../../chunk-OSUFJZHZ.js";
import "../../../chunk-4YEN7HVQ.js";
export {
Header
};
+22
View File
@@ -0,0 +1,22 @@
import { BaseComponent } from '../../component.js';
import type { LayoutProps } from '../../types.js';
/**
* Layout component renders the HTML structure for the document
* along with the styles for the global elements.
*
* You can define a custom Layout if you want to modify the HTML
* structure or the CSS variables for the colors.
*/
export declare class Layout extends BaseComponent<LayoutProps> {
cssFile: URL;
scriptFile: URL;
/**
* The toHTML method is used to output the HTML for the
* web view
*/
toHTML(props: LayoutProps): Promise<string>;
/**
* The toANSI method is used to output the text for the console
*/
toANSI(props: LayoutProps): Promise<string>;
}
+8
View File
@@ -0,0 +1,8 @@
import {
Layout
} from "../../../chunk-VE4LENUR.js";
import "../../../chunk-OSUFJZHZ.js";
import "../../../chunk-4YEN7HVQ.js";
export {
Layout
};
+178
View File
@@ -0,0 +1,178 @@
import type { ParsedError, StackFrame } from 'youch-core/types';
import type { Metadata } from './metadata.js';
import type { BaseComponent } from './component.js';
export * from 'youch-core/types';
/**
* Props accepted by the Layout component
*/
export type LayoutProps = ComponentSharedProps & {
title: string;
children: () => string | Promise<string>;
};
/**
* Props accepted by the Error stack source component
*/
export type ErrorStackSourceProps = ComponentSharedProps & {
error: ParsedError;
frame: StackFrame;
};
/**
* Props accepted by the Error stack component
*/
export type ErrorStackProps = ComponentSharedProps & {
error: ParsedError;
ide: string;
sourceCodeRenderer: (error: ParsedError, frame: StackFrame) => Promise<string>;
};
/**
* Props accepted by the Error info component
*/
export type ErrorInfoProps = ComponentSharedProps & {
title: string;
error: ParsedError;
};
/**
* Props accepted by the Error cause component
*/
export type ErrorCauseProps = ComponentSharedProps & {
error: ParsedError;
};
/**
* Props accepted by the Error metadata component
*/
export type ErrorMetadataProps = ComponentSharedProps & {
metadata: Metadata;
};
/**
* Error metadata row represents a key-value pair
*/
export type ErrorMetadataRow = {
key: string;
dump?: boolean;
value: any;
};
/**
* Representation of Error metadata groups. Each group is
* a collection of named sections
*/
export type ErrorMetadataGroups = {
[group: string]: {
[section: string]: ErrorMetadataRow | ErrorMetadataRow[];
};
};
/**
* Props shared with all the components
*/
export type ComponentSharedProps = {
ide?: string;
cspNonce?: string;
};
/**
* Collection of known templates. Only these templates can be
* rendered using the Templates collection
*/
export type YouchTemplates = {
header: BaseComponent<ComponentSharedProps>;
layout: BaseComponent<LayoutProps>;
errorInfo: BaseComponent<ErrorInfoProps>;
errorStack: BaseComponent<ErrorStackProps>;
errorStackSource: BaseComponent<ErrorStackSourceProps>;
errorCause: BaseComponent<ErrorCauseProps>;
errorMetadata: BaseComponent<ErrorMetadataProps>;
};
/**
* Set of options accepted by Youch when rendering error
* to HTML
*/
export type YouchHTMLOptions = {
/**
* Define the offset to skip certain stack frames from
* the top
*/
offset?: number;
/**
* Number of lines of code to display for the error stack frame.
* For example: If you set the frameSourceBuffer=7, then 3 lines
* above the error line and 3 lines after the error line will
* be displayed.
*/
frameSourceBuffer?: number;
/**
* Define the error title. It could be the HTTP status
* text
*/
title?: string;
/**
* Define the name of the IDE in which to open the files when
* the filename anchor tag is clicked.
*
* Following is the list of supported editors
*
* - textmate
* - macvim
* - emacs
* - sublime
* - phpstorm
* - atom
* - vscode
*
* You can also specify the URL for the editor via the `ide` property. Make
* sure to specify the placeholders for the filename and the line number
* as follows.
*
* someprotocol://file/%f:%l
*
* - %f is the filename placeholder
* - %l is the line number placeholder
*/
ide?: string;
/**
* CSP nonce to define on inline style and script tags
*/
cspNonce?: string;
/**
* Specify the HTTP request properties to be printed as
* metadata under the "Request" group
*/
request?: {
url?: string;
method?: string;
headers?: Record<string, string | string[] | undefined>;
};
};
/**
* Set of options accepted by Youch when rendering error
* to ANSI output
*/
export type YouchANSIOptions = {
/**
* Define the offset to skip certain stack frames from
* the top
*/
offset?: number;
/**
* Number of lines of code to display for the error stack frame.
* For example: If you set the frameSourceBuffer=7, then 3 lines
* above the error line and 3 lines after the error line will
* be displayed.
*/
frameSourceBuffer?: number;
};
/**
* Set of options accepted by Youch when rendering error
* to JSON output
*/
export type YouchJSONOptions = {
/**
* Define the offset to skip certain stack frames from
* the top
*/
offset?: number;
/**
* Number of lines of code to display for the error stack frame.
* For example: If you set the frameSourceBuffer=7, then 3 lines
* above the error line and 3 lines after the error line will
* be displayed.
*/
frameSourceBuffer?: number;
};
+2
View File
@@ -0,0 +1,2 @@
// src/types.ts
export * from "youch-core/types";
+48
View File
@@ -0,0 +1,48 @@
import type { Parser, SourceLoader, Transformer } from 'youch-core/types';
import { Metadata } from './metadata.js';
import { Templates } from './templates.js';
import { type YouchANSIOptions, type YouchHTMLOptions, type YouchJSONOptions } from './types.js';
/**
* Youch exposes the API to render errors to HTML output
*/
export declare class Youch {
#private;
/**
* Manage templates used for converting error to the HTML
* output
*/
templates: Templates;
/**
* Define metadata to be displayed alongside the error output
*/
metadata: Metadata;
/**
* Define custom implementation for loading the source code
* of a stack frame.
*/
defineSourceLoader(loader: SourceLoader): this;
/**
* Define a custom parser. Parsers are executed before the
* error gets parsed and provides you with an option to
* modify the error
*/
useParser(parser: Parser): this;
/**
* Define a custom transformer. Transformers are executed
* after the error has been parsed and can mutate the
* properties of the parsed error.
*/
useTransformer(transformer: Transformer): this;
/**
* Parses error to JSON
*/
toJSON(error: unknown, options?: YouchJSONOptions): Promise<import("youch-core/types").ParsedError>;
/**
* Render error to HTML
*/
toHTML(error: unknown, options?: YouchHTMLOptions): Promise<string>;
/**
* Render error to ANSI output
*/
toANSI(error: unknown, options?: YouchANSIOptions): Promise<string>;
}