前端初始化
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2026-present Vercel Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
<p align="center">
|
||||
<img src="./docs/public/nostics.svg" alt="nostics" width="320">
|
||||
</p>
|
||||
|
||||
# nostics
|
||||
|
||||
[](https://npmx.dev/nostics)
|
||||
[](https://npmx.dev/nostics)
|
||||
[](https://github.com/vercel-labs/nostics/actions/workflows/ci.yml)
|
||||
[](https://bundlejs.com/?q=nostics&treeshake=%5B%7B+defineDiagnostics+%7D%5D)
|
||||
|
||||
Errors worth reading.
|
||||
|
||||
`nostics` helps you replace ad hoc error strings with stable diagnostic codes, actionable fixes, source locations, and docs links.
|
||||
|
||||
```txt
|
||||
[NUXT_B2011] Plugin `./runtime/analytics.server.ts` is server-only but was registered with mode `client`.
|
||||
├▶ fix: Rename the file or register it with mode `server`.
|
||||
├▶ sources: modules/analytics.ts:18:5
|
||||
╰▶ see: https://nuxt.com/e/b2011
|
||||
```
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pnpm add nostics
|
||||
```
|
||||
|
||||
## Quick start
|
||||
|
||||
```ts
|
||||
import { createConsoleReporter, defineDiagnostics } from 'nostics'
|
||||
|
||||
export const diagnostics = defineDiagnostics({
|
||||
docsBase: code => `https://nuxt.com/e/${code.replace('NUXT_', '').toLowerCase()}`,
|
||||
reporters: [createConsoleReporter()],
|
||||
codes: {
|
||||
NUXT_B2011: {
|
||||
why: (p: { src: string, mode: 'client' | 'server' }) => {
|
||||
const expected = p.mode === 'client' ? 'server' : 'client'
|
||||
return `Plugin "${p.src}" is ${expected}-only but was registered with mode "${p.mode}".`
|
||||
},
|
||||
fix: (p: { mode: 'client' | 'server' }) => {
|
||||
const expected = p.mode === 'client' ? 'server' : 'client'
|
||||
return `Rename the file or register it with mode "${expected}".`
|
||||
},
|
||||
},
|
||||
NUXT_B5001: {
|
||||
why: (p: { value: string, configPath: string }) =>
|
||||
`Invalid compatibilityDate "${p.value}" in ${p.configPath}.`,
|
||||
fix: (p: { example: string }) => `Use an ISO date like "${p.example}", or "latest".`,
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Use the generated handles where the problem happens:
|
||||
|
||||
```ts
|
||||
const plugin = resolvePlugin()
|
||||
const source = locatePluginCall(plugin)
|
||||
const config = loadNuxtConfig()
|
||||
|
||||
diagnostics.NUXT_B2011({
|
||||
src: plugin.src,
|
||||
mode: plugin.mode,
|
||||
sources: [source],
|
||||
})
|
||||
|
||||
throw diagnostics.NUXT_B5001({
|
||||
configPath: config.filepath,
|
||||
value: config.compatibilityDate,
|
||||
example: '2024-04-03',
|
||||
})
|
||||
```
|
||||
|
||||
Calling a handle reports the diagnostic and returns a `Diagnostic`. Throwing the return value raises it. The params are inferred from your `why` and `fix` functions.
|
||||
|
||||
## Claude Code plugin
|
||||
|
||||
Install the plugin to give Claude skills for your diagnostic catalog:
|
||||
|
||||
```bash
|
||||
claude plugin add https://github.com/vercel-labs/nostics
|
||||
```
|
||||
|
||||
Claude will automatically pick up the `nostics` API reference and an `add-diagnostic` skill that finds the right catalog, chooses the next free code, and wires the call site.
|
||||
|
||||
## Agent skills
|
||||
|
||||
Prefer just the skills, without the plugin? Install them with [`npx skills`](https://github.com/vercel-labs/skills) into any supported agent (Claude Code, Codex, Cursor, opencode, and more):
|
||||
|
||||
```bash
|
||||
npx skills add vercel-labs/nostics
|
||||
```
|
||||
|
||||
## Why use it
|
||||
|
||||
- Stable codes that users can search and docs can link to.
|
||||
- Typed params at the call site.
|
||||
- `Diagnostic` instances that extend `Error`.
|
||||
- Built-in console, file, fetch, and Vite dev reporters.
|
||||
- Plain, ANSI, and JSON formatters.
|
||||
- A build plugin that strips report-only diagnostics from production bundles.
|
||||
|
||||
The structured shape also makes diagnostics easier for tools and coding agents to read, without making that the main workflow.
|
||||
|
||||
## Vite plugins
|
||||
|
||||
Build-time plugins live in the separate [`@nostics/unplugin`](./packages/unplugin) package:
|
||||
|
||||
```bash
|
||||
pnpm add -D @nostics/unplugin
|
||||
```
|
||||
|
||||
For library builds, use the strip plugin:
|
||||
|
||||
```ts
|
||||
import { nosticsStrip } from '@nostics/unplugin/strip-transform'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [nosticsStrip.vite()],
|
||||
})
|
||||
```
|
||||
|
||||
For browser diagnostics during Vite dev, use `createDevReporter()` in the browser and `nosticsCollector` in the consuming app:
|
||||
|
||||
```ts
|
||||
import { nosticsCollector } from '@nostics/unplugin/dev-server-collector'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [nosticsCollector.vite()],
|
||||
})
|
||||
```
|
||||
|
||||
## Docs
|
||||
|
||||
See the docs site for the guide, production build notes, dev collector setup, and API reference.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](./LICENSE)
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
//#region src/utils.d.ts
|
||||
/**
|
||||
* A value of type T, or a function that resolves T from a single params object.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type ValueOrFn<T, P = any> = T | ((params: P) => T);
|
||||
/**
|
||||
* Extracts the param type from a single-arg function, or `never` for
|
||||
* non-function inputs. Pairs with {@link ValueOrFn}.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type ExtractFnParam<T> = T extends ((params: infer P) => any) ? P : never;
|
||||
/**
|
||||
* Converts a union of types to their intersection.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
|
||||
/**
|
||||
* `true` when `T` is the `any` type.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type IsAny<Type> = 0 extends 1 & Type ? true : false;
|
||||
/**
|
||||
* `true` when `T` is the `unknown` type (and not `any`).
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type IsUnknown<Type> = IsAny<Type> extends true ? false : unknown extends Type ? true : false;
|
||||
/**
|
||||
* Expands a type to its property listing so editor hovers show the resolved
|
||||
* shape instead of a chain of aliases / intersections.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type Prettify<Type> = { [Key in keyof Type]: Type[Key] };
|
||||
//#endregion
|
||||
//#region src/diagnostic.d.ts
|
||||
/**
|
||||
* Define-time shape of a diagnostic. Each field can be a static value or a
|
||||
* function that resolves it from a shared `params` object passed at call
|
||||
* time. Runtime-only fields (`cause`, `sources`) from {@link DiagnosticInit}
|
||||
* are intentionally omitted: they're only meaningful at the call site.
|
||||
*/
|
||||
interface DiagnosticDefinition<P = any> {
|
||||
/**
|
||||
* The error message: why this failed. String, or a function of `params`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* why: (p: { name: string }) => `module "${p.name}" failed to load`
|
||||
* ```
|
||||
*/
|
||||
why: ValueOrFn<string, P>;
|
||||
/**
|
||||
* Actionable instructions on how to resolve the problem. String, or a
|
||||
* function of `params`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* fix: (p: { name: string }) => `run "npm install ${p.name}"`
|
||||
* ```
|
||||
*/
|
||||
fix?: ValueOrFn<string, P>;
|
||||
/**
|
||||
* Per-code docs URL. A string overrides
|
||||
* {@link DefineDiagnosticsOptions.docsBase} for this code; `false` opts this
|
||||
* code out entirely, even when `docsBase` is set. When omitted, the URL is
|
||||
* derived from `docsBase`.
|
||||
*/
|
||||
docs?: string | false;
|
||||
}
|
||||
/**
|
||||
* Runtime-only fields that can be passed alongside the interpolation params
|
||||
* at call time. Merged into the same object so callers pass everything in
|
||||
* one place.
|
||||
*/
|
||||
interface DiagnosticCallParams {
|
||||
/**
|
||||
* Original error or exception that triggered this diagnostic. Pass it
|
||||
* through when re-throwing so the original stack trace is preserved.
|
||||
*/
|
||||
cause?: unknown;
|
||||
/**
|
||||
* Locations in user code that contributed to this diagnostic, in
|
||||
* `file:line:column` format. Useful for compilers and other tools where the
|
||||
* JS stack trace doesn't reflect the user's source.
|
||||
*/
|
||||
sources?: string[];
|
||||
}
|
||||
/**
|
||||
* Structured initializer for a {@link Diagnostic}. `why` is the only required
|
||||
* field: it becomes the {@link Diagnostic.message}. The remaining fields are
|
||||
* optional metadata that reporters and consumers can render or forward.
|
||||
*/
|
||||
interface DiagnosticInit extends DiagnosticCallParams {
|
||||
/**
|
||||
* The diagnostic code, e.g. `MATH_E001`. Appear as {@link Diagnostic.name}.
|
||||
*/
|
||||
code: string;
|
||||
/**
|
||||
* The actual error message: why this failed.
|
||||
* Mirrored to `Error.message`.
|
||||
*/
|
||||
why: string;
|
||||
/**
|
||||
* Optional actionable instructions on how to resolve the problem.
|
||||
*/
|
||||
fix?: string;
|
||||
/**
|
||||
* URL to extended documentation for this diagnostic.
|
||||
*/
|
||||
docs?: string;
|
||||
}
|
||||
/**
|
||||
* Represents how to report a diagnostic. Could call `console.log()`, send the
|
||||
* diagnostic to a server, or something else. Reporters declare the shape of
|
||||
* options they need via `ReporterOpts`; `defineDiagnostics` intersects every
|
||||
* reporter's options into a single object passed at the call site.
|
||||
*/
|
||||
type DiagnosticReporter<ReporterOpts extends object = {}> = (diagnostic: Diagnostic, options: ReporterOpts) => void;
|
||||
/**
|
||||
* Permissive reporter constraint used internally so reporters with 1 arg,
|
||||
* required options, or optional options all satisfy the array constraint.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type AnyDiagnosticReporter = (diagnostic: Diagnostic, options: any) => void;
|
||||
/**
|
||||
* The `console` methods a log reporter can route to.
|
||||
*/
|
||||
type ConsoleMethod = "log" | "error" | "warn";
|
||||
/**
|
||||
* Options for {@link createConsoleReporter}.
|
||||
*/
|
||||
interface ConsoleReporterOptions {
|
||||
/**
|
||||
* `console` method used to print the diagnostic. Defaults to `'warn'`. The
|
||||
* returned reporter still accepts a per-call `{ method }` override through
|
||||
* the call-site reporter options.
|
||||
*/
|
||||
method?: ConsoleMethod;
|
||||
/**
|
||||
* Renders the diagnostic into the string handed to `console`. Defaults to
|
||||
* {@link formatDiagnostic}, the plain unicode-decorated formatter.
|
||||
*/
|
||||
formatter?: (diagnostic: Diagnostic) => string;
|
||||
}
|
||||
/**
|
||||
* Creates a console reporter that renders each diagnostic with `formatter` and
|
||||
* prints the result via `console[method]`. Both default sensibly (`'warn'` and
|
||||
* {@link formatDiagnostic}); `method` can also be overridden per call through
|
||||
* the reporter options.
|
||||
*/
|
||||
declare function createConsoleReporter({
|
||||
method: defaultMethod,
|
||||
formatter
|
||||
}?: ConsoleReporterOptions): DiagnosticReporter<{
|
||||
method?: ConsoleMethod;
|
||||
}>;
|
||||
/**
|
||||
* Resolves the `params` type a code expects from the intersection of params
|
||||
* across all function-typed fields, falling back to `{}` when every field is
|
||||
* static. Merged with {@link DiagnosticCallParams} at the call site.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type InferCodeParams<Def> = [ExtractFnParam<Def[keyof Def]>] extends [never] ? {} : UnionToIntersection<ExtractFnParam<Def[keyof Def]>>;
|
||||
/**
|
||||
* Options for {@link defineDiagnostics}.
|
||||
*/
|
||||
interface DefineDiagnosticsOptions<Codes extends Record<string, DiagnosticDefinition>, Reporters extends readonly AnyDiagnosticReporter[]> {
|
||||
/**
|
||||
* Base URL or resolver for documentation links. When a string, the code is
|
||||
* appended as a lowercase path segment (e.g. `"https://docs.example.com"` →
|
||||
* `"https://docs.example.com/math_e001"`). When a function, receives the
|
||||
* code and returns a URL or `undefined`.
|
||||
*/
|
||||
docsBase?: string | ((code: keyof Codes) => string | undefined);
|
||||
/**
|
||||
* Map of diagnostic codes to their definitions.
|
||||
*/
|
||||
codes: Codes;
|
||||
/**
|
||||
* Reporters called every time a diagnostic is produced. Can be used to
|
||||
* integrate with custom logging.
|
||||
*/
|
||||
reporters?: Reporters;
|
||||
}
|
||||
/**
|
||||
* The first positional argument of a {@link DiagnosticHandle} call:
|
||||
* interpolation params merged with the runtime-only call-site fields
|
||||
* (`cause`, `sources`).
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type CallSiteParams<Params> = Params & DiagnosticCallParams;
|
||||
/**
|
||||
* Resolves the full argument tuple for a {@link DiagnosticHandle} call.
|
||||
* Branches on whether params and reporter options each have required fields.
|
||||
* Required positions become required tuple elements, all-optional ones
|
||||
* become `?`, and when no reporter declares any options the parameter is
|
||||
* omitted entirely.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type ActionArgs<Params, ReporterOpts> = keyof ReporterOpts extends never ? {} extends Params ? [params?: CallSiteParams<Params>] : [params: CallSiteParams<Params>] : {} extends ReporterOpts ? {} extends Params ? [params?: CallSiteParams<Params>, reporterOptions?: ReporterOpts] : [params: CallSiteParams<Params>, reporterOptions?: ReporterOpts] : {} extends Params ? [params: CallSiteParams<Params> | undefined, reporterOptions: ReporterOpts] : [params: CallSiteParams<Params>, reporterOptions: ReporterOpts];
|
||||
/**
|
||||
* Per-code handle exposed by {@link defineDiagnostics}. Each code is a
|
||||
* callable: invoke it to build the diagnostic and run every reporter, or
|
||||
* prefix the call with `throw` to raise it.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* diagnostics.MATH_E001({ name: 'x' }) // report
|
||||
* throw diagnostics.MATH_E001({ name: 'x' }) // throw
|
||||
* ```
|
||||
*/
|
||||
interface DiagnosticHandle<Params, ReporterOpts> {
|
||||
/**
|
||||
* Builds the diagnostic, runs every reporter, and returns the diagnostic
|
||||
* instance. The returned diagnostic can be inspected, attached as `cause`,
|
||||
* or thrown with `throw`.
|
||||
*/
|
||||
(...args: ActionArgs<Params, ReporterOpts>): Diagnostic;
|
||||
}
|
||||
/**
|
||||
* Return type of {@link defineDiagnostics}.
|
||||
*/
|
||||
type Diagnostics<Codes extends Record<string, DiagnosticDefinition>, Reporters extends readonly AnyDiagnosticReporter[]> = { [Code in keyof Codes]: DiagnosticHandle<InferCodeParams<Codes[Code]>, Prettify<ExtractReportersOptions<Reporters>>> };
|
||||
declare class Diagnostic extends Error {
|
||||
name: string;
|
||||
/**
|
||||
* The diagnostic code, e.g. `MATH_E001`.
|
||||
* Also appears as the `name` property.
|
||||
*/
|
||||
code: string;
|
||||
/**
|
||||
* URL to extended documentation for this diagnostic code.
|
||||
* Auto-generated from {@link DefineDiagnosticsOptions.docsBase}.
|
||||
*/
|
||||
docs?: string;
|
||||
/**
|
||||
* Optional actionable instructions on how to resolve the problem.
|
||||
*/
|
||||
fix?: string;
|
||||
/**
|
||||
* Locations in user code that contributed to this diagnostic, in
|
||||
* `file:line:column` format. Relevant when the stack trace doesn't reflect
|
||||
* the user's source (e.g. compilers, bundlers), otherwise redundant with the
|
||||
* stack and should be omitted.
|
||||
*/
|
||||
sources?: string[];
|
||||
/**
|
||||
* Alias for {@link Error.message}: the reason this diagnostic was raised.
|
||||
*/
|
||||
get why(): string;
|
||||
/**
|
||||
* @param init structured initializer; `why` is required
|
||||
* @param captureFrom V8 stack-cutoff frame. Defaults to {@link Diagnostic}
|
||||
* so the top of the trace is the `new Diagnostic(...)` call site.
|
||||
* `defineDiagnostics` passes its action method to strip its own frames too.
|
||||
* Ignored on engines without `Error.captureStackTrace`.
|
||||
*/
|
||||
constructor(init: DiagnosticInit, captureFrom?: Function);
|
||||
/**
|
||||
* Converts the diagnostic into a serializable structured object.
|
||||
*/
|
||||
toJSON(): object;
|
||||
}
|
||||
/**
|
||||
* Creates a typed diagnostics object from a set of code definitions. Each
|
||||
* code becomes a callable {@link DiagnosticHandle}: invoke to report, or
|
||||
* `throw` the result to raise. No `new` required, no proxy.
|
||||
*/
|
||||
declare function defineDiagnostics<const Codes extends Record<string, DiagnosticDefinition>, const Reporters extends readonly AnyDiagnosticReporter[]>(options: DefineDiagnosticsOptions<Codes, Reporters>): Diagnostics<Codes, Reporters>;
|
||||
/**
|
||||
* Extracts the options object a reporter accepts as its 2nd argument. Returns
|
||||
* `{}` when the reporter has no 2nd arg (so it contributes nothing to the
|
||||
* merged shape).
|
||||
*/
|
||||
type ExtractSingleReporterOptions<Reporter> = Reporter extends ((diagnostic: Diagnostic, options: infer ReporterOpts) => any) ? IsUnknown<ReporterOpts> extends true ? {} : Exclude<ReporterOpts, undefined> : {};
|
||||
/**
|
||||
* Intersects every reporter's options shape into a single object. If any
|
||||
* reporter has a required field, the merged shape has a required field, and
|
||||
* {@link ActionArgs} flips `reporterOptions` from optional to required via
|
||||
* `{} extends Merged`.
|
||||
*/
|
||||
type ExtractReportersOptions<Reporters extends readonly any[]> = Reporters extends readonly [infer First, ...infer Rest] ? ExtractSingleReporterOptions<First> & ExtractReportersOptions<Rest> : {};
|
||||
//#endregion
|
||||
export { Diagnostic as a, DiagnosticHandle as c, Diagnostics as d, createConsoleReporter as f, DefineDiagnosticsOptions as i, DiagnosticInit as l, ValueOrFn as m, ConsoleMethod as n, DiagnosticCallParams as o, defineDiagnostics as p, ConsoleReporterOptions as r, DiagnosticDefinition as s, AnyDiagnosticReporter as t, DiagnosticReporter as u };
|
||||
//# sourceMappingURL=diagnostic-wduO7saY.d.mts.map
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { a as Diagnostic } from "../diagnostic-wduO7saY.mjs";
|
||||
|
||||
//#region src/formatters/ansi.d.ts
|
||||
interface Colors {
|
||||
red: (s: string) => string;
|
||||
yellow: (s: string) => string;
|
||||
cyan: (s: string) => string;
|
||||
gray: (s: string) => string;
|
||||
bold: (s: string) => string;
|
||||
dim: (s: string) => string;
|
||||
}
|
||||
declare function ansiFormatter(colors: Colors): (d: Diagnostic) => string;
|
||||
//#endregion
|
||||
export { Colors, ansiFormatter };
|
||||
//# sourceMappingURL=ansi.d.mts.map
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
//#region src/formatters/ansi.ts
|
||||
/* @__NO_SIDE_EFFECTS__ */
|
||||
function ansiFormatter(colors) {
|
||||
return (d) => {
|
||||
const header = `${colors.bold(colors.red(`[${d.name}]`))} ${d.message}`;
|
||||
const details = [];
|
||||
if (d.fix) details.push(`${colors.dim("fix:")} ${d.fix}`);
|
||||
if (d.sources?.length) details.push(`${colors.dim("sources:")} ${d.sources.join(", ")}`);
|
||||
if (d.docs) details.push(`${colors.dim("see:")} ${colors.cyan(d.docs)}`);
|
||||
if (details.length === 0) return header;
|
||||
return [header, ...details.map((detail, i) => {
|
||||
return `${colors.dim(i < details.length - 1 ? "├▶" : "╰▶")} ${detail}`;
|
||||
})].join("\n");
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
export { ansiFormatter };
|
||||
|
||||
//# sourceMappingURL=ansi.mjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ansi.mjs","names":[],"sources":["../../src/formatters/ansi.ts"],"sourcesContent":["import type { Diagnostic } from '../diagnostic'\n\nexport interface Colors {\n red: (s: string) => string\n yellow: (s: string) => string\n cyan: (s: string) => string\n gray: (s: string) => string\n bold: (s: string) => string\n dim: (s: string) => string\n}\n\n/* @__NO_SIDE_EFFECTS__ */\nexport function ansiFormatter(colors: Colors): (d: Diagnostic) => string {\n return (d) => {\n const tag = colors.bold(colors.red(`[${d.name}]`))\n const header = `${tag} ${d.message}`\n\n const details: string[] = []\n if (d.fix)\n details.push(`${colors.dim('fix:')} ${d.fix}`)\n if (d.sources?.length)\n details.push(`${colors.dim('sources:')} ${d.sources.join(', ')}`)\n if (d.docs)\n details.push(`${colors.dim('see:')} ${colors.cyan(d.docs)}`)\n\n if (details.length === 0)\n return header\n\n const lines = details.map((detail, i) => {\n const connector = colors.dim(i < details.length - 1 ? '├▶' : '╰▶')\n return `${connector} ${detail}`\n })\n return [header, ...lines].join('\\n')\n }\n}\n"],"mappings":";;AAYA,SAAgB,cAAc,QAA2C;CACvE,QAAQ,MAAM;EAEZ,MAAM,SAAS,GADH,OAAO,KAAK,OAAO,IAAI,IAAI,EAAE,KAAK,EAAE,CAC5B,EAAE,GAAG,EAAE;EAE3B,MAAM,UAAoB,CAAC;EAC3B,IAAI,EAAE,KACJ,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,EAAE,GAAG,EAAE,KAAK;EAC/C,IAAI,EAAE,SAAS,QACb,QAAQ,KAAK,GAAG,OAAO,IAAI,UAAU,EAAE,GAAG,EAAE,QAAQ,KAAK,IAAI,GAAG;EAClE,IAAI,EAAE,MACJ,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,EAAE,GAAG,OAAO,KAAK,EAAE,IAAI,GAAG;EAE7D,IAAI,QAAQ,WAAW,GACrB,OAAO;EAMT,OAAO,CAAC,QAAQ,GAJF,QAAQ,KAAK,QAAQ,MAAM;GAEvC,OAAO,GADW,OAAO,IAAI,IAAI,QAAQ,SAAS,IAAI,OAAO,IAC3C,EAAE,GAAG;EACzB,CACuB,CAAC,CAAC,CAAC,KAAK,IAAI;CACrC;AACF"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { a as Diagnostic } from "../diagnostic-wduO7saY.mjs";
|
||||
|
||||
//#region src/formatters/json.d.ts
|
||||
declare const jsonFormatter: (d: Diagnostic) => string;
|
||||
//#endregion
|
||||
export { jsonFormatter };
|
||||
//# sourceMappingURL=json.d.mts.map
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
//#region src/formatters/json.ts
|
||||
const jsonFormatter = (d) => JSON.stringify(d);
|
||||
//#endregion
|
||||
export { jsonFormatter };
|
||||
|
||||
//# sourceMappingURL=json.mjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"json.mjs","names":[],"sources":["../../src/formatters/json.ts"],"sourcesContent":["import type { Diagnostic } from '../diagnostic'\n\nexport const jsonFormatter = (d: Diagnostic): string => JSON.stringify(d)\n"],"mappings":";AAEA,MAAa,iBAAiB,MAA0B,KAAK,UAAU,CAAC"}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import { a as Diagnostic, c as DiagnosticHandle, d as Diagnostics, f as createConsoleReporter, i as DefineDiagnosticsOptions, l as DiagnosticInit, m as ValueOrFn, n as ConsoleMethod, o as DiagnosticCallParams, p as defineDiagnostics, r as ConsoleReporterOptions, s as DiagnosticDefinition, t as AnyDiagnosticReporter, u as DiagnosticReporter } from "./diagnostic-wduO7saY.mjs";
|
||||
|
||||
//#region src/formatters/plain.d.ts
|
||||
/**
|
||||
* Renders a diagnostic into a multi-line, unicode-decorated string suitable
|
||||
* for terminal output. The first line is `[<name>] <message>`; optional
|
||||
* details (`fix`, `sources`, `docs`) follow with `├▶`/`╰▶` connectors.
|
||||
*/
|
||||
declare function formatDiagnostic(diagnostic: Diagnostic): string;
|
||||
//#endregion
|
||||
//#region src/prod-diagnostics.d.ts
|
||||
/**
|
||||
* Options for {@link defineProdDiagnostics}. A lean subset of
|
||||
* {@link DefineDiagnosticsOptions}: no `codes` map (the proxy serves any code),
|
||||
* only what is needed to keep behaviour correct in production.
|
||||
*/
|
||||
interface DefineProdDiagnosticsOptions<Reporters extends readonly AnyDiagnosticReporter[] = readonly AnyDiagnosticReporter[]> {
|
||||
/**
|
||||
* Base URL or resolver for documentation links, identical to
|
||||
* {@link DefineDiagnosticsOptions.docsBase}. The docs URL is derived from the
|
||||
* accessed code at call time, so links survive even without the catalog.
|
||||
*/
|
||||
docsBase?: string | ((code: string) => string | undefined);
|
||||
/**
|
||||
* Reporters called every time a diagnostic is produced. Omitted by default in
|
||||
* production builds; the strip plugin can copy them into the prod branch when
|
||||
* prod-time reporting (e.g. telemetry) is desired.
|
||||
*/
|
||||
reporters?: Reporters;
|
||||
}
|
||||
/**
|
||||
* Production counterpart to {@link defineDiagnostics}. Returns a `Proxy` that
|
||||
* builds a minimal {@link Diagnostic} for any accessed code: the code becomes
|
||||
* the instance `name`, `docs` is derived from `docsBase`, and `why` points to
|
||||
* the docs URL when one exists (empty otherwise, so the thrown header is just
|
||||
* the code). It carries no catalog text, so it stays tiny in a bundle.
|
||||
*
|
||||
* The strip plugin (`@nostics/unplugin`) can rewrite a `defineDiagnostics()`
|
||||
* call into a `process.env.NODE_ENV === 'production'` ternary that selects this
|
||||
* factory in production, dropping every `why`/`fix` string from the bundle.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const diagnostics = defineProdDiagnostics({ docsBase: 'https://docs.example.com' })
|
||||
* throw diagnostics.NUXT_B2011() // NUXT_B2011: https://docs.example.com/nuxt_b2011
|
||||
* ```
|
||||
*/
|
||||
declare function defineProdDiagnostics<const Codes extends Record<string, DiagnosticDefinition> = Record<string, DiagnosticDefinition>, const Reporters extends readonly AnyDiagnosticReporter[] = readonly AnyDiagnosticReporter[]>(options?: DefineProdDiagnosticsOptions<Reporters>): Diagnostics<Codes, Reporters>;
|
||||
//#endregion
|
||||
export { type AnyDiagnosticReporter, type ConsoleMethod, type ConsoleReporterOptions, type DefineDiagnosticsOptions, type DefineProdDiagnosticsOptions, Diagnostic, type DiagnosticCallParams, type DiagnosticDefinition, type DiagnosticHandle, type DiagnosticInit, type DiagnosticReporter, type Diagnostics, type ValueOrFn as _ValueOrFn, createConsoleReporter, defineDiagnostics, defineProdDiagnostics, formatDiagnostic };
|
||||
//# sourceMappingURL=index.d.mts.map
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
//#region src/formatters/plain.ts
|
||||
/**
|
||||
* Renders a diagnostic into a multi-line, unicode-decorated string suitable
|
||||
* for terminal output. The first line is `[<name>] <message>`; optional
|
||||
* details (`fix`, `sources`, `docs`) follow with `├▶`/`╰▶` connectors.
|
||||
*/
|
||||
function formatDiagnostic(diagnostic) {
|
||||
const header = `[${diagnostic.name}] ${diagnostic.message}`;
|
||||
const details = [];
|
||||
if (diagnostic.fix) details.push(`fix: ${diagnostic.fix}`);
|
||||
if (diagnostic.sources?.length) details.push(`sources: ${diagnostic.sources.join(", ")}`);
|
||||
if (diagnostic.docs) details.push(`see: ${diagnostic.docs}`);
|
||||
if (details.length === 0) return header;
|
||||
return [header, ...details.map((detail, i) => {
|
||||
return `${i < details.length - 1 ? "├▶" : "╰▶"} ${detail}`;
|
||||
})].join("\n");
|
||||
}
|
||||
//#endregion
|
||||
//#region src/utils.ts
|
||||
/**
|
||||
* Transforms a value or a function that returns a value to a value.
|
||||
*
|
||||
* @param valFn either a value or a function that returns a value
|
||||
* @param args arguments to pass to the function if `valFn` is a function
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
function toValueWithArgs(valFn, ...args) {
|
||||
return typeof valFn === "function" ? valFn(...args) : valFn;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/diagnostic.ts
|
||||
/**
|
||||
* Creates a console reporter that renders each diagnostic with `formatter` and
|
||||
* prints the result via `console[method]`. Both default sensibly (`'warn'` and
|
||||
* {@link formatDiagnostic}); `method` can also be overridden per call through
|
||||
* the reporter options.
|
||||
*/
|
||||
/* @__NO_SIDE_EFFECTS__ */
|
||||
function createConsoleReporter({ method: defaultMethod = "warn", formatter = formatDiagnostic } = {}) {
|
||||
return (diagnostic, { method = defaultMethod } = {}) => {
|
||||
console[method](formatter(diagnostic));
|
||||
};
|
||||
}
|
||||
const captureStackTrace = Error.captureStackTrace;
|
||||
var Diagnostic = class Diagnostic extends Error {
|
||||
name;
|
||||
/**
|
||||
* The diagnostic code, e.g. `MATH_E001`.
|
||||
* Also appears as the `name` property.
|
||||
*/
|
||||
code;
|
||||
/**
|
||||
* URL to extended documentation for this diagnostic code.
|
||||
* Auto-generated from {@link DefineDiagnosticsOptions.docsBase}.
|
||||
*/
|
||||
docs;
|
||||
/**
|
||||
* Optional actionable instructions on how to resolve the problem.
|
||||
*/
|
||||
fix;
|
||||
/**
|
||||
* Locations in user code that contributed to this diagnostic, in
|
||||
* `file:line:column` format. Relevant when the stack trace doesn't reflect
|
||||
* the user's source (e.g. compilers, bundlers), otherwise redundant with the
|
||||
* stack and should be omitted.
|
||||
*/
|
||||
sources;
|
||||
/**
|
||||
* Alias for {@link Error.message}: the reason this diagnostic was raised.
|
||||
*/
|
||||
get why() {
|
||||
return this.message;
|
||||
}
|
||||
/**
|
||||
* @param init structured initializer; `why` is required
|
||||
* @param captureFrom V8 stack-cutoff frame. Defaults to {@link Diagnostic}
|
||||
* so the top of the trace is the `new Diagnostic(...)` call site.
|
||||
* `defineDiagnostics` passes its action method to strip its own frames too.
|
||||
* Ignored on engines without `Error.captureStackTrace`.
|
||||
*/
|
||||
constructor(init, captureFrom = Diagnostic) {
|
||||
super(init.why, { cause: init.cause });
|
||||
this.code = this.name = init.code;
|
||||
this.fix = init.fix;
|
||||
this.docs = init.docs;
|
||||
this.sources = init.sources;
|
||||
captureStackTrace?.(this, captureFrom);
|
||||
}
|
||||
/**
|
||||
* Converts the diagnostic into a serializable structured object.
|
||||
*/
|
||||
toJSON() {
|
||||
return {
|
||||
name: this.name,
|
||||
why: this.why,
|
||||
fix: this.fix,
|
||||
docs: this.docs,
|
||||
sources: this.sources,
|
||||
cause: this.cause,
|
||||
stack: this.stack
|
||||
};
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Resolves the docs URL for a code from a `docsBase` (string template or
|
||||
* resolver function). Shared by {@link defineDiagnostics} and
|
||||
* {@link defineProdDiagnostics}. Per-code `docs` overrides are handled by the
|
||||
* caller; this only covers the `docsBase`-derived case.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
function deriveDocs(docsBase, code) {
|
||||
return typeof docsBase === "string" ? `${docsBase}/${code.toLowerCase()}` : docsBase?.(code);
|
||||
}
|
||||
/**
|
||||
* Creates a typed diagnostics object from a set of code definitions. Each
|
||||
* code becomes a callable {@link DiagnosticHandle}: invoke to report, or
|
||||
* `throw` the result to raise. No `new` required, no proxy.
|
||||
*/
|
||||
/* @__NO_SIDE_EFFECTS__ */
|
||||
function defineDiagnostics(options) {
|
||||
const reporters = options.reporters ?? [];
|
||||
const result = {};
|
||||
const { docsBase } = options;
|
||||
for (const code of Object.keys(options.codes)) {
|
||||
const def = options.codes[code];
|
||||
const docs = def.docs === false ? void 0 : def.docs || deriveDocs(docsBase, code);
|
||||
const handle = (params = {}, reporterOptions = {}) => {
|
||||
const diagnostic = new Diagnostic({
|
||||
code,
|
||||
why: toValueWithArgs(def.why, params),
|
||||
fix: toValueWithArgs(def.fix, params),
|
||||
docs,
|
||||
cause: params.cause,
|
||||
sources: params.sources
|
||||
}, handle);
|
||||
for (const reporter of reporters) reporter(diagnostic, reporterOptions);
|
||||
return diagnostic;
|
||||
};
|
||||
result[code] = handle;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/prod-diagnostics.ts
|
||||
/**
|
||||
* Production counterpart to {@link defineDiagnostics}. Returns a `Proxy` that
|
||||
* builds a minimal {@link Diagnostic} for any accessed code: the code becomes
|
||||
* the instance `name`, `docs` is derived from `docsBase`, and `why` points to
|
||||
* the docs URL when one exists (empty otherwise, so the thrown header is just
|
||||
* the code). It carries no catalog text, so it stays tiny in a bundle.
|
||||
*
|
||||
* The strip plugin (`@nostics/unplugin`) can rewrite a `defineDiagnostics()`
|
||||
* call into a `process.env.NODE_ENV === 'production'` ternary that selects this
|
||||
* factory in production, dropping every `why`/`fix` string from the bundle.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const diagnostics = defineProdDiagnostics({ docsBase: 'https://docs.example.com' })
|
||||
* throw diagnostics.NUXT_B2011() // NUXT_B2011: https://docs.example.com/nuxt_b2011
|
||||
* ```
|
||||
*/
|
||||
/* @__NO_SIDE_EFFECTS__ */
|
||||
function defineProdDiagnostics(options = {}) {
|
||||
const { docsBase, reporters = [] } = options;
|
||||
return new Proxy({}, { get(_target, code) {
|
||||
if (typeof code !== "string") return void 0;
|
||||
const handle = (params = {}, reporterOptions = {}) => {
|
||||
const docs = deriveDocs(docsBase, code);
|
||||
const diagnostic = new Diagnostic({
|
||||
code,
|
||||
why: docs ?? "",
|
||||
docs,
|
||||
cause: params.cause,
|
||||
sources: params.sources
|
||||
}, handle);
|
||||
for (const reporter of reporters) reporter(diagnostic, reporterOptions);
|
||||
return diagnostic;
|
||||
};
|
||||
return handle;
|
||||
} });
|
||||
}
|
||||
//#endregion
|
||||
export { Diagnostic, createConsoleReporter, defineDiagnostics, defineProdDiagnostics, formatDiagnostic };
|
||||
|
||||
//# sourceMappingURL=index.mjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
+13
@@ -0,0 +1,13 @@
|
||||
import { u as DiagnosticReporter } from "../diagnostic-wduO7saY.mjs";
|
||||
|
||||
//#region src/reporters/dev.d.ts
|
||||
/**
|
||||
* Creates a reporter for browser code under Vite dev: it forwards each
|
||||
* diagnostic over `import.meta.hot.send('nostics:report', ...)` so the
|
||||
* dev-server collector can file it. Outside Vite (`import.meta.hot` absent) it
|
||||
* warns once and does nothing.
|
||||
*/
|
||||
declare function createDevReporter(): DiagnosticReporter;
|
||||
//#endregion
|
||||
export { createDevReporter };
|
||||
//# sourceMappingURL=dev.d.mts.map
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
//#region src/reporters/dev.ts
|
||||
/**
|
||||
* Creates a reporter for browser code under Vite dev: it forwards each
|
||||
* diagnostic over `import.meta.hot.send('nostics:report', ...)` so the
|
||||
* dev-server collector can file it. Outside Vite (`import.meta.hot` absent) it
|
||||
* warns once and does nothing.
|
||||
*/
|
||||
/* @__NO_SIDE_EFFECTS__ */
|
||||
function createDevReporter() {
|
||||
return (diagnostic) => {
|
||||
if (import.meta.hot && typeof import.meta.hot.send === "function") import.meta.hot.send("nostics:report", diagnostic.toJSON());
|
||||
else console.warn("[nostics]: import.meta.hot.send() is not available. This must be running on Vite.");
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
export { createDevReporter };
|
||||
|
||||
//# sourceMappingURL=dev.mjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"dev.mjs","names":[],"sources":["../../src/reporters/dev.ts"],"sourcesContent":["import type { DiagnosticReporter } from '../diagnostic'\n\n/**\n * Creates a reporter for browser code under Vite dev: it forwards each\n * diagnostic over `import.meta.hot.send('nostics:report', ...)` so the\n * dev-server collector can file it. Outside Vite (`import.meta.hot` absent) it\n * warns once and does nothing.\n */\n/* @__NO_SIDE_EFFECTS__ */\nexport function createDevReporter(): DiagnosticReporter {\n return (diagnostic) => {\n if (import.meta.hot && typeof import.meta.hot.send === 'function') {\n import.meta.hot.send('nostics:report', diagnostic.toJSON())\n }\n else {\n console.warn(\n '[nostics]: import.meta.hot.send() is not available. This must be running on Vite.',\n )\n }\n }\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,oBAAwC;CACtD,QAAQ,eAAe;EACrB,IAAI,OAAO,KAAK,OAAO,OAAO,OAAO,KAAK,IAAI,SAAS,YACrD,OAAO,KAAK,IAAI,KAAK,kBAAkB,WAAW,OAAO,CAAC;OAG1D,QAAQ,KACN,mFACF;CAEJ;AACF"}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { u as DiagnosticReporter } from "../diagnostic-wduO7saY.mjs";
|
||||
|
||||
//#region src/reporters/fetch.d.ts
|
||||
/**
|
||||
* Creates a reporter that POSTs each diagnostic as JSON to the given URL.
|
||||
* Errors are swallowed so reporting never throws into user code.
|
||||
*/
|
||||
declare function createFetchReporter(url: string): DiagnosticReporter;
|
||||
//#endregion
|
||||
export { createFetchReporter };
|
||||
//# sourceMappingURL=fetch.d.mts.map
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
//#region src/reporters/fetch.ts
|
||||
/**
|
||||
* Creates a reporter that POSTs each diagnostic as JSON to the given URL.
|
||||
* Errors are swallowed so reporting never throws into user code.
|
||||
*/
|
||||
/* @__NO_SIDE_EFFECTS__ */
|
||||
function createFetchReporter(url) {
|
||||
return (diagnostic) => {
|
||||
fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(diagnostic)
|
||||
}).catch(() => {});
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
export { createFetchReporter };
|
||||
|
||||
//# sourceMappingURL=fetch.mjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"fetch.mjs","names":[],"sources":["../../src/reporters/fetch.ts"],"sourcesContent":["import type { DiagnosticReporter } from '../diagnostic'\n\n/**\n * Creates a reporter that POSTs each diagnostic as JSON to the given URL.\n * Errors are swallowed so reporting never throws into user code.\n */\n/* @__NO_SIDE_EFFECTS__ */\nexport function createFetchReporter(url: string): DiagnosticReporter {\n return (diagnostic) => {\n fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(diagnostic),\n }).catch(() => {})\n }\n}\n"],"mappings":";;;;;;AAOA,SAAgB,oBAAoB,KAAiC;CACnE,QAAQ,eAAe;EACrB,MAAM,KAAK;GACT,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;GAC9C,MAAM,KAAK,UAAU,UAAU;EACjC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;CACnB;AACF"}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { u as DiagnosticReporter } from "../diagnostic-wduO7saY.mjs";
|
||||
|
||||
//#region src/reporters/node.d.ts
|
||||
interface FileReporterOptions {
|
||||
/**
|
||||
* Path to the log file.
|
||||
* @default '.nostics.log'
|
||||
*/
|
||||
logFile?: string;
|
||||
/**
|
||||
* Stack frames matching ANY of these patterns are removed from
|
||||
* `diagnostic.stack` before it is written to the log file. Useful to strip
|
||||
* `node_modules` and Node internals. The `Error: ...` header line is
|
||||
* always preserved.
|
||||
*
|
||||
* Pass an empty array to keep every frame.
|
||||
* @default [/\/node_modules\//i]
|
||||
*/
|
||||
excludeStackFrames?: readonly RegExp[];
|
||||
}
|
||||
/**
|
||||
* Creates a reporter that appends diagnostics as NDJSON to a local file.
|
||||
* Each diagnostic is written as a single JSON line. The diagnostic's `stack`
|
||||
* (if present) is included in the payload; noisy frames can be removed via
|
||||
* {@link FileReporterOptions.excludeStackFrames}.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { defineDiagnostics } from 'nostics'
|
||||
* import { createFileReporter } from 'nostics/reporters/node'
|
||||
*
|
||||
* const diagnostics = defineDiagnostics({
|
||||
* codes: { ... },
|
||||
* reporters: [createFileReporter({
|
||||
* excludeStackFrames: [/\/node_modules\//, /\(node:/],
|
||||
* })],
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
declare function createFileReporter(options?: FileReporterOptions): DiagnosticReporter;
|
||||
//#endregion
|
||||
export { FileReporterOptions, createFileReporter };
|
||||
//# sourceMappingURL=node.d.mts.map
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import { appendFileSync } from "node:fs";
|
||||
//#region src/reporters/node.ts
|
||||
const DEFAULT_EXCLUDE_STACK_FRAMES = [/\/node_modules\//i];
|
||||
function applyExcludeStackFrames(raw, exclude) {
|
||||
const [header, ...frames] = raw.split("\n");
|
||||
return [header, ...frames.filter((frame) => !exclude.some((re) => re.test(frame)))].join("\n");
|
||||
}
|
||||
/**
|
||||
* Creates a reporter that appends diagnostics as NDJSON to a local file.
|
||||
* Each diagnostic is written as a single JSON line. The diagnostic's `stack`
|
||||
* (if present) is included in the payload; noisy frames can be removed via
|
||||
* {@link FileReporterOptions.excludeStackFrames}.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { defineDiagnostics } from 'nostics'
|
||||
* import { createFileReporter } from 'nostics/reporters/node'
|
||||
*
|
||||
* const diagnostics = defineDiagnostics({
|
||||
* codes: { ... },
|
||||
* reporters: [createFileReporter({
|
||||
* excludeStackFrames: [/\/node_modules\//, /\(node:/],
|
||||
* })],
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
/* @__NO_SIDE_EFFECTS__ */
|
||||
function createFileReporter(options) {
|
||||
const logFile = options?.logFile ?? ".nostics.log";
|
||||
const excludeStackFrames = options?.excludeStackFrames ?? DEFAULT_EXCLUDE_STACK_FRAMES;
|
||||
return (diagnostic) => {
|
||||
try {
|
||||
const d = diagnostic;
|
||||
const base = typeof d.toJSON === "function" ? d.toJSON() : { ...d };
|
||||
if (d.stack) base.stack = excludeStackFrames?.length ? applyExcludeStackFrames(d.stack, excludeStackFrames) : d.stack;
|
||||
appendFileSync(logFile, `${JSON.stringify(base)}\n`);
|
||||
} catch (err) {
|
||||
console.error(`[nostics]: Failed to write log to "${logFile}":`, err);
|
||||
}
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
export { createFileReporter };
|
||||
|
||||
//# sourceMappingURL=node.mjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"node.mjs","names":[],"sources":["../../src/reporters/node.ts"],"sourcesContent":["import type { Diagnostic, DiagnosticReporter } from '../diagnostic'\nimport { appendFileSync } from 'node:fs'\n\nexport interface FileReporterOptions {\n /**\n * Path to the log file.\n * @default '.nostics.log'\n */\n logFile?: string\n\n /**\n * Stack frames matching ANY of these patterns are removed from\n * `diagnostic.stack` before it is written to the log file. Useful to strip\n * `node_modules` and Node internals. The `Error: ...` header line is\n * always preserved.\n *\n * Pass an empty array to keep every frame.\n * @default [/\\/node_modules\\//i]\n */\n excludeStackFrames?: readonly RegExp[]\n}\n\nconst DEFAULT_EXCLUDE_STACK_FRAMES: readonly RegExp[] = [/\\/node_modules\\//i]\n\nfunction applyExcludeStackFrames(raw: string, exclude: readonly RegExp[]): string {\n const [header, ...frames] = raw.split('\\n')\n return [header, ...frames.filter(frame => !exclude.some(re => re.test(frame)))].join('\\n')\n}\n\n/**\n * Creates a reporter that appends diagnostics as NDJSON to a local file.\n * Each diagnostic is written as a single JSON line. The diagnostic's `stack`\n * (if present) is included in the payload; noisy frames can be removed via\n * {@link FileReporterOptions.excludeStackFrames}.\n *\n * @example\n * ```ts\n * import { defineDiagnostics } from 'nostics'\n * import { createFileReporter } from 'nostics/reporters/node'\n *\n * const diagnostics = defineDiagnostics({\n * codes: { ... },\n * reporters: [createFileReporter({\n * excludeStackFrames: [/\\/node_modules\\//, /\\(node:/],\n * })],\n * })\n * ```\n */\n/* @__NO_SIDE_EFFECTS__ */\nexport function createFileReporter(options?: FileReporterOptions): DiagnosticReporter {\n const logFile = options?.logFile ?? '.nostics.log'\n const excludeStackFrames = options?.excludeStackFrames ?? DEFAULT_EXCLUDE_STACK_FRAMES\n return (diagnostic) => {\n try {\n const d = diagnostic as Diagnostic & Record<string, unknown>\n const base: Record<string, unknown>\n = typeof d.toJSON === 'function' ? (d.toJSON() as Record<string, unknown>) : { ...d }\n if (d.stack) {\n base.stack = excludeStackFrames?.length\n ? applyExcludeStackFrames(d.stack, excludeStackFrames)\n : d.stack\n }\n appendFileSync(logFile, `${JSON.stringify(base)}\\n`)\n }\n catch (err: unknown) {\n console.error(`[nostics]: Failed to write log to \"${logFile}\":`, err)\n }\n }\n}\n"],"mappings":";;AAsBA,MAAM,+BAAkD,CAAC,mBAAmB;AAE5E,SAAS,wBAAwB,KAAa,SAAoC;CAChF,MAAM,CAAC,QAAQ,GAAG,UAAU,IAAI,MAAM,IAAI;CAC1C,OAAO,CAAC,QAAQ,GAAG,OAAO,QAAO,UAAS,CAAC,QAAQ,MAAK,OAAM,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI;AAC3F;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,mBAAmB,SAAmD;CACpF,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,qBAAqB,SAAS,sBAAsB;CAC1D,QAAQ,eAAe;EACrB,IAAI;GACF,MAAM,IAAI;GACV,MAAM,OACF,OAAO,EAAE,WAAW,aAAc,EAAE,OAAO,IAAgC,EAAE,GAAG,EAAE;GACtF,IAAI,EAAE,OACJ,KAAK,QAAQ,oBAAoB,SAC7B,wBAAwB,EAAE,OAAO,kBAAkB,IACnD,EAAE;GAER,eAAe,SAAS,GAAG,KAAK,UAAU,IAAI,EAAE,GAAG;EACrD,SACO,KAAc;GACnB,QAAQ,MAAM,sCAAsC,QAAQ,KAAK,GAAG;EACtE;CACF;AACF"}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
{
|
||||
"name": "nostics",
|
||||
"type": "module",
|
||||
"version": "1.2.0",
|
||||
"description": "Structured diagnostic code library",
|
||||
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
|
||||
"contributors": [
|
||||
"Eduardo San Martin Morote <posva13@gmail.com>",
|
||||
"Daniel Roe <daniel@roe.dev>"
|
||||
],
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/vercel-labs/nostics#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vercel-labs/nostics.git"
|
||||
},
|
||||
"bugs": "https://github.com/vercel-labs/nostics/issues",
|
||||
"keywords": [],
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": "./dist/index.mjs",
|
||||
"./formatters/ansi": "./dist/formatters/ansi.mjs",
|
||||
"./formatters/json": "./dist/formatters/json.mjs",
|
||||
"./reporters/dev": "./dist/reporters/dev.mjs",
|
||||
"./reporters/fetch": "./dist/reporters/fetch.mjs",
|
||||
"./reporters/node": "./dist/reporters/node.mjs",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"types": "./dist/index.d.mts",
|
||||
"files": [
|
||||
"dist",
|
||||
"skills"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^9.0.0",
|
||||
"@antfu/ni": "^30.1.0",
|
||||
"@antfu/utils": "^9.3.0",
|
||||
"@posva/prompts": "^2.4.4",
|
||||
"@size-limit/esbuild-why": "^12.1.0",
|
||||
"@size-limit/preset-small-lib": "^12.1.0",
|
||||
"@types/node": "^25.9.3",
|
||||
"@types/semver": "^7.7.1",
|
||||
"@vitest/coverage-v8": "4.1.8",
|
||||
"@vitest/ui": "4.1.8",
|
||||
"conventional-changelog": "^7.2.0",
|
||||
"conventional-changelog-angular": "^8.3.1",
|
||||
"eslint": "^10.5.0",
|
||||
"lint-staged": "^17.0.7",
|
||||
"oxfmt": "^0.54.0",
|
||||
"publint": "^0.3.21",
|
||||
"semver": "^7.8.4",
|
||||
"simple-git-hooks": "^2.13.1",
|
||||
"size-limit": "^12.1.0",
|
||||
"tsdown": "^0.22.2",
|
||||
"tsnapi": "^0.3.3",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.0.16",
|
||||
"vitest": "^4.1.8",
|
||||
"nostics": "1.2.0"
|
||||
},
|
||||
"simple-git-hooks": {
|
||||
"pre-commit": "pnpm i --frozen-lockfile --ignore-scripts --offline && npx lint-staged"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*": "eslint --fix"
|
||||
},
|
||||
"size-limit": [
|
||||
{
|
||||
"name": "defineDiagnostics from source",
|
||||
"path": "src/index.ts",
|
||||
"import": "{ defineDiagnostics }"
|
||||
},
|
||||
{
|
||||
"name": "defineDiagnostics",
|
||||
"path": "dist/index.mjs",
|
||||
"import": "{ defineDiagnostics }"
|
||||
},
|
||||
{
|
||||
"name": "defineProdDiagnostics",
|
||||
"path": "dist/index.mjs",
|
||||
"import": "{ defineProdDiagnostics }"
|
||||
},
|
||||
{
|
||||
"name": "defineDiagnostics + createConsoleReporter",
|
||||
"path": "dist/index.mjs",
|
||||
"import": "{ defineDiagnostics, createConsoleReporter }"
|
||||
},
|
||||
{
|
||||
"name": "defineProdDiagnostics + createConsoleReporter",
|
||||
"path": "dist/index.mjs",
|
||||
"import": "{ defineProdDiagnostics, createConsoleReporter }"
|
||||
},
|
||||
{
|
||||
"name": "formatDiagnostic",
|
||||
"path": "dist/index.mjs",
|
||||
"import": "{ formatDiagnostic }"
|
||||
},
|
||||
{
|
||||
"name": "full root",
|
||||
"path": "dist/index.mjs",
|
||||
"import": "*"
|
||||
},
|
||||
{
|
||||
"name": "ansi formatter",
|
||||
"path": "dist/formatters/ansi.mjs",
|
||||
"import": "*"
|
||||
}
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsdown && pnpm --filter \"./packages/*\" run build",
|
||||
"dev": "vitest",
|
||||
"docs": "pnpm -C docs run dev",
|
||||
"docs:build": "pnpm -C docs run build",
|
||||
"play": "pnpm -C playground run dev",
|
||||
"lint": "eslint",
|
||||
"release": "node scripts/release.ts",
|
||||
"size": "size-limit",
|
||||
"test": "pnpm run build && pnpm run \"/^test:/\"",
|
||||
"test:unit": "vitest run --coverage",
|
||||
"test:types": "pnpm run typecheck",
|
||||
"test:lint": "pnpm run lint",
|
||||
"test:demo": "pnpm -C demo-lib run build && pnpm -C demo-lib run test && pnpm -C playground run build",
|
||||
"typecheck": "tsc && pnpm --filter \"./packages/*\" run typecheck"
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: add-diagnostic
|
||||
description: 'Add a new diagnostic code following the defineDiagnostics() conventions from nostics'
|
||||
user-invocable: true
|
||||
allowed-tools: Read Grep Glob Edit Write
|
||||
license: MIT
|
||||
---
|
||||
|
||||
# Add a New Diagnostic Code
|
||||
|
||||
1. **Find the catalog.** Grep for `defineDiagnostics` to locate the `codes` object the new entry belongs in. With several catalogs, pick by area.
|
||||
2. **Pick the code.** `PREFIX_XNNNN`: `PREFIX` is the project name uppercased (`NUXT`, `I18N`); `X` is the area letter (`B` build, `R` runtime, `C` config, `D` deprecation); `NNNN` is the next free number. Read existing codes to choose. Never rename or reuse a published code.
|
||||
3. **Add the entry:**
|
||||
|
||||
```ts
|
||||
LIB_R0001: {
|
||||
why: (p: { hook: string }) => `${p.hook}() must run at the top of setup().`, // string or typed fn; becomes Error.message (required)
|
||||
fix: 'Move the call into setup() or a composable it calls.', // optional, but add whenever the fix is known
|
||||
docs: 'https://example.com/custom', // optional: overrides docsBase, or `false` to opt out
|
||||
},
|
||||
```
|
||||
|
||||
- `why` is the only required field. Params from `why` and `fix` are intersected and required at the call site.
|
||||
- Runtime fields (`cause`, `sources`) are passed at the call site, never in the definition.
|
||||
|
||||
4. **Call it:** `diagnostics.LIB_R0001({ hook })` to report, `throw diagnostics.LIB_R0001({ hook, cause: err })` to raise. Both run the reporters.
|
||||
|
||||
Full API and reporter/formatter/plugin details: the `nostics` skill.
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
---
|
||||
name: nostics
|
||||
description: "Structured diagnostic code library for JavaScript/TypeScript. Turns errors and other conditions into typed, machine-readable `Diagnostic` instances with stable codes, docs URLs, and actionable fields. Use this skill whenever the project imports `nostics`, or works with `defineDiagnostics`/`defineProdDiagnostics`, the `Diagnostic` class, diagnostic code registries, or structured error handling. Also covers reporters (`createConsoleReporter`, `createFetchReporter` from nostics/reporters/fetch, `createFileReporter` from nostics/reporters/node, `createDevReporter` from nostics/reporters/dev), formatters (`formatDiagnostic`, `ansiFormatter`, `jsonFormatter`), and Vite plugins (`nosticsStrip` from @nostics/unplugin/strip-transform, `nosticsCollector` from @nostics/unplugin/dev-server-collector). Also use when migrating a library's existing `console.warn`/`console.error`/`warn()` helpers or thrown `Error`s to diagnostics: follow `references/migration.md`."
|
||||
license: MIT
|
||||
---
|
||||
|
||||
# nostics
|
||||
|
||||
Every error condition becomes a typed `Diagnostic` (extends `Error`) with a stable code, docs URL, and actionable `fix`. Serializable via `toJSON()`.
|
||||
|
||||
`Diagnostic`: `name` (the code), `message`/`why` (interpolated text), `fix?`, `docs?`, `sources?` (`'file:line:column'`), `cause?`, `toJSON()`. Throw it, catch it with `instanceof Diagnostic`, send `toJSON()` across process boundaries.
|
||||
|
||||
## defineDiagnostics
|
||||
|
||||
Returns one callable handle per code. Calling a handle builds a fresh `Diagnostic`, fires every reporter in order, and returns it. `throw` the return value to raise (reporters still run, so a thrown diagnostic also reports).
|
||||
|
||||
```ts
|
||||
import { createConsoleReporter, defineDiagnostics } from 'nostics'
|
||||
|
||||
const diagnostics = /*#__PURE__*/ defineDiagnostics({
|
||||
docsBase: (code) => `https://nuxt.com/e/${code.replace('NUXT_', '').toLowerCase()}`,
|
||||
reporters: [/*#__PURE__*/ createConsoleReporter()],
|
||||
codes: {
|
||||
NUXT_B1001: {
|
||||
why: 'Could not compile template.',
|
||||
fix: 'Check the template for syntax errors.',
|
||||
},
|
||||
NUXT_B2011: {
|
||||
why: (p: { src: string }) => `Invalid plugin "${p.src}". src option is required.`,
|
||||
fix: 'Pass a string path or an object with a `src` to `addPlugin()`.',
|
||||
},
|
||||
NUXT_W9001: { why: 'message', docs: false }, // per-code: string overrides docsBase, false opts out
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
- **`docsBase`** `string | (code) => string | undefined`: string appends `/${code.toLowerCase()}`; function returns the full URL (or `undefined` to omit).
|
||||
- **`codes`**: each definition needs `why` (`string | (params) => string`, the only required field, becomes `Error.message`); optional `fix` (`string | (params) => string`) and `docs` (`string | false`).
|
||||
- **`reporters`**: fired on every call; optional. Their `options` types are intersected; required reporter options become required at the call site. Omit it (or pass `[]`) for a catalog whose codes are only ever `throw`n: the thrown `Diagnostic` already carries the message, so a console reporter would print it once and surface it again from the uncaught error, a visible duplicate. Keep report-only warnings and fatal throws in separate catalogs when one needs a reporter and the other does not.
|
||||
- **Param inference**: params from `why` and `fix` are intersected and required at the call site. If `why` needs `{ src }` and `fix` needs `{ date }`, the call requires `{ src, date }`.
|
||||
|
||||
## Call sites
|
||||
|
||||
```ts
|
||||
diagnostics.NUXT_B1001() // no params: report only
|
||||
diagnostics.NUXT_B2011({ src: '/plugins/bad.ts' }) // params first
|
||||
diagnostics.NUXT_B2011({
|
||||
src,
|
||||
cause: originalError,
|
||||
sources: ['nuxt.config.ts:42:3'],
|
||||
}) // runtime fields merge in
|
||||
diagnostics.NUXT_B2011({ src }, { method: 'error' }) // reporter options second
|
||||
throw diagnostics.NUXT_B2011({ src }) // raise
|
||||
```
|
||||
|
||||
`cause`/`sources` go in the params object; `sources` matters most for build/config diagnostics where the JS stack points inside the library. Catch with `if (err instanceof Diagnostic)` then read `.name`, `.message`, `.fix`, `.docs`.
|
||||
|
||||
## Reporters
|
||||
|
||||
`(diagnostic: Diagnostic, options?: Opts) => void`. Declaring a required `options` type makes the second call-site argument required and typed.
|
||||
|
||||
| Reporter | Import | Description |
|
||||
| --------------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `createConsoleReporter(options?)` | `nostics` | `console[method](formatter(d))`. `method` defaults `'warn'` (`'log'\|'warn'\|'error'`), `formatter` defaults `formatDiagnostic`; both via options, `method` also overridable per call. |
|
||||
| `createFetchReporter(url)` | `nostics/reporters/fetch` | POSTs diagnostic JSON to the URL; failures swallowed. |
|
||||
| `createFileReporter(options?)` | `nostics/reporters/node` | Appends NDJSON to a local file (default `.nostics.log`). |
|
||||
| `createDevReporter()` | `nostics/reporters/dev` | Sends `toJSON()` to the Vite dev server via `import.meta.hot.send()`. |
|
||||
|
||||
```ts
|
||||
import type { DiagnosticReporter } from 'nostics'
|
||||
const sentryReporter: DiagnosticReporter = (d) =>
|
||||
sentry.captureMessage(d.message, { tags: { code: d.name } })
|
||||
const audited: DiagnosticReporter<{ priority: number }> = (d, o) =>
|
||||
audit.log({ name: d.name, priority: o.priority })
|
||||
// → audited makes diagnostics.X({...}, { priority: 1 }) required and type-checked.
|
||||
```
|
||||
|
||||
## Formatters
|
||||
|
||||
| Formatter | Import | Description |
|
||||
| ----------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
||||
| `formatDiagnostic` | `nostics` | Plain unicode-decorated string (built-in reporters use it). |
|
||||
| `ansiFormatter(colors)` | `nostics/formatters/ansi` | Colorized; accepts a `Colors` interface (`red`/`yellow`/`cyan`/`gray`/`bold`/`dim`, each `(s) => string`). |
|
||||
| `jsonFormatter` | `nostics/formatters/json` | `JSON.stringify(diagnostic)` via `toJSON()`. |
|
||||
|
||||
`formatDiagnostic` output, detail order fixed `fix` → `sources` → `see`, missing fields omitted:
|
||||
|
||||
```
|
||||
[NUXT_B2011] Invalid plugin `/plugins/bad.ts`. src option is required.
|
||||
├▶ fix: Pass a string path or an object with a `src` to `addPlugin()`.
|
||||
├▶ sources: nuxt.config.ts:42:3
|
||||
╰▶ see: https://nuxt.com/e/b2011
|
||||
```
|
||||
|
||||
## Vite plugins (`@nostics/unplugin`, dev dependency)
|
||||
|
||||
`@nostics/unplugin/strip-transform` (library authors, build optimization) and `@nostics/unplugin/dev-server-collector` (app developers, dev-time collection). Both unplugin-based: `.vite()`, `.webpack()`, `.rollup()`, etc.
|
||||
|
||||
- **`nosticsStrip`** marks `defineDiagnostics()` `/*#__PURE__*/` and wraps bare diagnostic expression statements with a `NODE_ENV` guard so they tree-shake out of production. Option `packageName?` (default `'nostics'`). Throws/returns/assignments stay (they are behavior). For tracking: relative imports, export the catalog directly, no factory wrappers or deep barrels.
|
||||
- The plugin is optional. The same production output happens with no build transform if the catalog is annotated by hand: put `/*#__PURE__*/` before `defineDiagnostics(` and before each reporter factory call inside it (as in every example here), and dev-guard each report-only call site (`process.env.NODE_ENV !== 'production' && diagnostics.CODE(p)`). Always write the annotations in source; reach for the plugin when report-only call sites are unguarded and you want stripping without touching them.
|
||||
- **`nosticsCollector`** listens for `createDevReporter()` diagnostics over the Vite WebSocket and writes them as NDJSON via `createFileReporter`. Vite-only. Options `logFile?` (default `.nostics.log`), `debug?` (default `!!process.env.DEBUG`).
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import { nosticsStrip } from '@nostics/unplugin/strip-transform'
|
||||
import { nosticsCollector } from '@nostics/unplugin/dev-server-collector'
|
||||
export default defineConfig({
|
||||
plugins: [nosticsStrip.vite(), nosticsCollector.vite()],
|
||||
})
|
||||
|
||||
// src/diagnostics.ts — pair the collector with createDevReporter()
|
||||
import { createConsoleReporter, defineDiagnostics } from 'nostics'
|
||||
import { createDevReporter } from 'nostics/reporters/dev'
|
||||
export const diagnostics = /*#__PURE__*/ defineDiagnostics({
|
||||
reporters: [/*#__PURE__*/ createConsoleReporter(), /*#__PURE__*/ createDevReporter()],
|
||||
codes: {
|
||||
/* ... */
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Production builds
|
||||
|
||||
- **Report-only** diagnostics (bare `diagnostics.X()`) should disappear: `nosticsStrip` or hand annotations drop them, then the unused catalog tree-shakes.
|
||||
- **Surviving** diagnostics (`throw`/`return`/assigned/argument) stay, and each keeps the _whole_ catalog reachable, so every `why`/`fix` ships. Not every library throws in production: if yours only reports, stripping is enough, stop here.
|
||||
|
||||
When a library _does_ `throw` in production, pick `defineProdDiagnostics` at definition time with a `NODE_ENV` ternary, so a consumer bundler drops the dev branch (all catalog text):
|
||||
|
||||
```ts
|
||||
import { defineDiagnostics, defineProdDiagnostics } from 'nostics'
|
||||
export const diagnostics =
|
||||
process.env.NODE_ENV === 'production'
|
||||
? /*#__PURE__*/ defineProdDiagnostics({ docsBase })
|
||||
: /*#__PURE__*/ defineDiagnostics({
|
||||
docsBase,
|
||||
reporters: [
|
||||
/* ... */
|
||||
],
|
||||
codes: {
|
||||
/* text */
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
The accessed code becomes the instance `name`, `docs` still derives from `docsBase`, `why` points to the docs URL when one exists (empty otherwise), no `why`/`fix` text ships. No `reporters` by default (so a surviving `throw` doesn't also log and then resurface as the uncaught error); pass `reporters` to keep prod telemetry. `nosticsStrip` tracks this ternary like a direct catalog export.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Codes** are stable, fully-qualified `PREFIX_XNNNN` (`B` build, `R` runtime, `C` config, `D` deprecation). Never reuse or reassign a published code.
|
||||
- Always provide `why`; provide `fix` whenever the solution is known (the most actionable field for humans and agents). Use parameterized templates for runtime values, not string concatenation outside the factory.
|
||||
- **`why` is the diagnosis, `fix` is the remedy — split them, don't overlap them.** `why` states only what is wrong; `fix` states only what to do. The reporter prints both, so any wording that appears in both is dead weight. When a single source sentence carries both (`"A hash must start with '#'. Prefix it with '#'."`), cut it in two — diagnosis to `why`, remedy to `fix` — rather than pasting the whole thing into `why` and echoing it in `fix`. `fix` accepts a param function too (`(p) => ...`), so move value-bearing remedies (`use "#${p.hash}"`) into it instead of leaving them in `why`.
|
||||
- Pass `cause` when re-raising; pass `sources` when the JS stack doesn't reflect the user's source.
|
||||
- Split large catalogs by domain (`diagnostics/build.ts`, `runtime.ts`, `config.ts`, re-exported from `index.ts`), each `defineDiagnostics()` sharing `docsBase` with its own code range.
|
||||
|
||||
## References
|
||||
|
||||
- **Migrating an existing library** to nostics (replacing `console.warn`/`console.error`/`warn()`/thrown `Error`s with diagnostic codes, without changing runtime behavior): follow `references/migration.md` start to finish.
|
||||
- Building the error-code documentation site (page template, deployment, agent optimization): `references/documentation-site.md`.
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
# Documentation Site and Error Code Registry
|
||||
|
||||
Every published code needs a stable, public documentation page forever. It serves three audiences: **developers** clicking the `see:` URL from their terminal, **AI agents** fetching the page to help when a user pastes an error, and **search engines** indexing `NUXT_B2011` so it's findable. Plan the URL structure to match `docsBase` (string form → `${docsBase}/${code.toLowerCase()}`; function form → full control).
|
||||
|
||||
## Page template
|
||||
|
||||
Each code page (`https://nuxt.com/e/b2011`) follows this structure. Keep it human-readable and agent-parseable: consistent `##` headings, actionable content early, no critical info hidden in tabs/collapsed sections/JS-rendered content.
|
||||
|
||||
```markdown
|
||||
# {CODE}: {Short title}
|
||||
|
||||
Code: `{CODE}`
|
||||
Level: {error|warn|suggestion|deprecation}
|
||||
|
||||
## What this error means
|
||||
|
||||
{Plain-language explanation, no assumed context: what the system expected vs received. 1-3 sentences. Agents rely on this to explain the error.}
|
||||
|
||||
## Why this happens
|
||||
|
||||
{Bulleted list of the concrete scenarios that trigger this diagnostic.}
|
||||
|
||||
## How to fix it
|
||||
|
||||
{The most important section: copy-pasteable code showing the wrong pattern and the corrected version.}
|
||||
|
||||
## Additional context
|
||||
|
||||
{Optional: links to related docs, changelog, or related codes.}
|
||||
|
||||
## Example output
|
||||
|
||||
{Optional: the formatted terminal output, so users confirm they're on the right page.}
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
- Host on a public URL matching `docsBase`: a static site generator (VitePress, Nuxt Content) with a catch-all `/e/[code]` route, or a dedicated `/errors` route in existing docs.
|
||||
- Return 200 for valid codes, 404 for unknown ones, so agents and crawlers distinguish them.
|
||||
- Add frontmatter/`<meta>` structured data (code, level, title). Keep pages lightweight; avoid SPAs that block fetch-based agents.
|
||||
|
||||
## Keep docs in sync with code
|
||||
|
||||
- Store the markdown alongside the diagnostic definitions or in `docs/errors/`, and add the page in the same PR as a new code.
|
||||
- Generate an index page listing all codes with messages and levels.
|
||||
- In CI, validate that every code in `defineDiagnostics()` has a corresponding page; fail the build if one is missing.
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
# Migrate errors and warnings to nostics
|
||||
|
||||
Follow this start to finish whenever the task is migrating a library's existing user-facing errors, warnings, and logs (`console.warn`/`console.error`, `warn()` helpers, thrown `Error`s) to nostics diagnostics. Turn ad hoc reporting into a catalog of stable diagnostic codes **without changing runtime behavior**. Full API: the `nostics` skill's `SKILL.md` (this reference lives beside it).
|
||||
|
||||
## What to migrate
|
||||
|
||||
Inventory `console.warn`, `console.error`, `warn(...)` helpers, `throw new Error(...)`, `Promise.reject(new Error(...))`. Skip tests, fixtures, snapshots, and generated output. Plain debug `console.log`s are usually not user-facing; leave them.
|
||||
|
||||
Migrate:
|
||||
|
||||
- dev warnings that report and keep going
|
||||
- warnings followed by recovery or a fallback (replace only the report, keep the recovery)
|
||||
- plain user-facing thrown or rejected `Error`s (the diagnostic becomes the thrown/rejected value)
|
||||
- deprecation notices
|
||||
- build/config errors caused by a user's file: always pass **both** the original error as `cause` and the file as `sources`, because the JS stack points inside the library and is useless to the user
|
||||
|
||||
Do **not** migrate:
|
||||
|
||||
- **structured errors other code inspects** (type fields, private symbols, `isXxxError()` guards, `instanceof` checks): they are control flow, not reporting. Leave them unchanged. Only if such an error is also deliberately user-facing, add a separate dev-only report with the error as `cause`; never replace the error object itself.
|
||||
- **catch blocks that only log a native/platform error and fall back** when the library cannot name a likely cause or a concrete fix: the native error is the best available information, keep the plain log. This exception covers platform APIs failing (e.g. `history.pushState`, storage quota), **not** errors caused by the user's own files: a caught parse or config error on a user file should become a diagnostic carrying the original error as `cause` and the file as `sources`.
|
||||
- anything where the diagnostic would only restate "an operation failed". A diagnostic earns its place by naming a likely user-code problem or a concrete fix.
|
||||
|
||||
## Preserve behavior exactly
|
||||
|
||||
A project's dev guard may be `process.env.NODE_ENV !== 'production'` or its own build-time constant (libraries often define a flag for this; recognize whatever the codebase uses). Written as `DEV` below; treat all forms the same:
|
||||
|
||||
- Keep existing dev guards exactly as they are. nostics stripping is additive and does not replace them. If a throw or reject only happened in dev, it must still only happen in dev.
|
||||
- Never add a guard the original did not have. A throw or report that fired in production keeps firing in production builds that do not use stripping; note that migrating an unguarded report-only call makes it strippable, so once `nosticsStrip` runs in the build it disappears from production bundles. That is usually the goal of the migration, but if the library deliberately reports in production, surface that decision instead of changing it silently.
|
||||
- Keep throw vs reject, timing, recovery code, and returned fallbacks.
|
||||
- Keep structured error shapes (fields, symbols). Migrating a throw replaces the thrown message with the diagnostic's `why`: if tests assert the exact old text, update them deliberately as part of the migration, never weaken the message to dodge a test.
|
||||
|
||||
## Catalog shape
|
||||
|
||||
One catalog file per area of the library (a single `src/diagnostics.ts` is fine for small ones), exported directly. No factory wrappers and no deep barrel re-exports: the strip plugin tracks the export across one relative import. `nostics` is a runtime import: add it to `dependencies`, not `devDependencies` (library bundlers refuse or inline it otherwise).
|
||||
|
||||
```ts
|
||||
import { createConsoleReporter, defineDiagnostics } from 'nostics'
|
||||
|
||||
export const diagnostics = /*#__PURE__*/ defineDiagnostics({
|
||||
docsBase: (code) => `https://example.com/e/${code.toLowerCase()}`,
|
||||
reporters: [/*#__PURE__*/ createConsoleReporter()],
|
||||
codes: {
|
||||
LIB_R0001: {
|
||||
why: (p: { hook: string }) => `${p.hook}() must be called at the top of a setup function.`,
|
||||
fix: 'Move the call into setup() or a composable called by setup().',
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
- Codes are `PREFIX_XNNNN`. Pick the category letter by **area**, not severity: `B` build, `R` runtime, `C` config, `D` deprecation. A runtime warning is `R`; reserve `D` for deprecations. Published codes are permanent: never rename or reuse one.
|
||||
- `why` says what happened with runtime values interpolated through typed param functions (both `why` and `fix` accept them; their params are merged and required at the call site). `fix` is the concrete next action, never a restatement of the problem.
|
||||
- **Split the original warning; never copy it whole into `why`.** Most existing warnings bundle the diagnosis and the remedy in one string (`"A hash must start with '#'. Prefix it with '#'."`). The reporter prints `why` **and** `fix`, so pasting the full sentence into `why` and then writing a `fix` duplicates the remedy on screen. Cut the sentence in two: diagnosis to `why`, remedy to `fix`. If the remedy needs the offending value, make `fix` a param function — its params merge with `why`'s.
|
||||
|
||||
```ts
|
||||
// before: warn(`A \`hash\` should start with "#". Replace "${hash}" with "#${hash}".`)
|
||||
|
||||
// ❌ remedy lives in why and is echoed by fix
|
||||
{ why: (p) => `A \`hash\` should start with "#". Replace "${p.hash}" with "#${p.hash}".`,
|
||||
fix: 'Prefix the hash with "#".' }
|
||||
|
||||
// ✅ diagnosis in why, remedy in fix (a function, because it needs the value)
|
||||
{ why: (p) => `A \`hash\` should start with "#" but received "${p.hash}".`,
|
||||
fix: (p) => `Prepend "#": use "#${p.hash}".` }
|
||||
```
|
||||
|
||||
- Extra `console.warn`/`console.error` arguments must not be lost: an error value becomes `cause`; data values are interpolated into `why` (e.g. `JSON.stringify(p.value)`).
|
||||
- `cause` and `sources` (`'file:line:column'` strings pointing at user code) go **inside the params object** (the first argument), merged with the message params. The second argument is reporter options only, e.g. `{ method: 'error' }`.
|
||||
- `docsBase` is optional. If the project has no documented error-page URL scheme, propose one and surface it to the maintainer rather than inventing pages that do not exist. When pointing per-code `docs` at existing documentation with `#hash` anchors, verify each anchor against the built or published HTML (grep the `id=`) instead of guessing it. A custom slugify can keep heading casing and leave a trailing hyphen, so the real anchor may look like `#Using-the-store-outside-of-setup-`.
|
||||
|
||||
## Call-site patterns
|
||||
|
||||
| Before | After |
|
||||
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
||||
| `DEV && warn(msg)` | `DEV && diagnostics.LIB_R0001(params)` (same guard) |
|
||||
| warn, then recover/fallback | diagnostic, then the same recovery |
|
||||
| warn, then `throw new Error(...)` | `throw diagnostics.LIB_R0002(params)` |
|
||||
| warn, then `Promise.reject(new Error(...))` | `return Promise.reject(diagnostics.LIB_R0003(params))` |
|
||||
| `console.error(...)` level | `diagnostics.LIB_B0001(params, { method: 'error' })` |
|
||||
| caught error tied to a user file | `diagnostics.LIB_B0002({ ...params, cause: err, sources: ['src/file.ts:10:5'] }, { method: 'error' })` |
|
||||
| structured/internal error | leave unchanged |
|
||||
|
||||
Calling a handle always runs the reporters, so `throw diagnostics.CODE(params)` reports **and** throws. For a warn-then-throw site that is the same double output it already had. For a bare `throw new Error(...)` it adds a console report before the throw, which duplicates the message the uncaught error already shows. When a catalog's codes are only ever thrown (config validators, fatal asserts), give that catalog **no reporters** (`reporters` is optional) so the throw is the only output, and keep warnings in a separate reporter-backed catalog. Dropping the reporter also keeps a strict test harness happy when its `afterEach` fails on any unasserted `console.warn`/`console.error`.
|
||||
|
||||
Report-only calls must stay bare expression statements (`DEV && diagnostics.LIB_R0001(p)` included) so `nosticsStrip` can remove them in production. `throw`/`return`/assigned diagnostics are behavior and stay.
|
||||
|
||||
Dropping diagnostics from production builds takes two pieces: `/*#__PURE__*/` annotations on the catalog (`defineDiagnostics(...)` and each reporter factory call inside it) so an unused catalog tree-shakes away, and a `DEV` guard on every report-only call site. Both can be written manually in source, or the `nosticsStrip` build plugin adds them at build time (`import { nosticsStrip } from '@nostics/unplugin/strip-transform'`, then the matching unplugin adapter: `nosticsStrip.rolldown()`, `.vite()`, `.rollup()`, ...). Decide from context: when every report-only site is already dev-guarded, manual annotations in the catalog file are enough and avoid a build transform; reach for the plugin when call sites are unguarded and stripping is wanted. Either way the behavior rule holds: if the library deliberately reports unguarded in production, do not silence it with a guard or the plugin; ask the maintainer.
|
||||
|
||||
## Verify
|
||||
|
||||
- Tests for warnings, throws, guards, and error shapes still pass; tests asserting exact message text are updated consciously, not accidentally.
|
||||
- Watch substring assertions when splitting a warning. `toHaveBeenWarned('...')` / `toContain` pin a **fragment**, not the whole message, and a fragment may sit in the remedy half you just moved to `fix`. Before splitting, grep the tests for substrings of each warning: keep pinned **diagnosis** fragments in `why`; when a test pins a **remedy** fragment, update that assertion to the surviving `why` text. The same warning is often pinned by a shared constant duplicated across several spec files — fix every copy.
|
||||
- Dev-only gates are still present everywhere the source had them, and no new gates were added.
|
||||
- Report-only diagnostics remain strippable expression statements. Thrown/returned diagnostics keep their message text in production by design: they are behavior, not reports.
|
||||
Reference in New Issue
Block a user