by jax

Spectral is an open-source linting engine for JSON and YAML documents, with built-in rulesets for OpenAPI, AsyncAPI, and Arazzo, plus full support for custom rules and functions.
This block provides the full Spectral monorepo source: a programmable JSON/YAML linter with support for custom rulesets, built-in OpenAPI/AsyncAPI/Arazzo validation, and a CLI entry point. Typical buyers are platform teams embedding API governance into CI pipelines or Node.js services that need programmatic linting with custom rules.
cli/ - Yargs-based CLI (spectral lint), proxy support, command wiringcore/ - Core Spectral class, Document, Ruleset, Rule, runner, and all type definitionsformats/ - Format detection helpers (OpenAPI, AsyncAPI, Arazzo, etc.)formatters/ - Output formatters: text, JSON, JUnit, stylish, code-climate, SARIFfunctions/ - Built-in rule functions: alphabetical, casing, defined, enumeration, length, pattern, schema, truthy, unreferencedReusableObject, xorparsers/ - YAML and JSON document parsersref-resolver/ - $ref resolution engine used by the coreruleset-bundler/ - Bundles ruleset files (JS/TS/YAML/JSON) into portable artifactsruleset-migrator/ - Migrates Spectral v5 rulesets to v6+ formatrulesets/ - Official bundled rulesets: spectral:oas, spectral:asyncapi, spectral:arazzoruntime/ - Shared runtime utilities (fetch agent, request options)npm install @stoplight/spectral-core \
@stoplight/spectral-formats \
@stoplight/spectral-formatters \
@stoplight/spectral-functions \
@stoplight/spectral-parsers \
@stoplight/spectral-ref-resolver \
@stoplight/spectral-ruleset-bundler \
@stoplight/spectral-rulesets \
@stoplight/spectral-runtime \
@stoplight/json \
@stoplight/yaml \
ajv \
ajv-formats \
yargs \
minimatch \
lodash
No native modules or pod installs are required. All packages are pure JS/TS.
Spin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This TypeScript cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 1ca2bdb717e507fc…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
Copy the source/packages/ directory into your project, e.g. vendor/spectral/.
Add path aliases in tsconfig.json so local imports resolve correctly:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@stoplight/spectral-core": ["vendor/spectral/core/src/index.ts"],
"@stoplight/spectral-formats": ["vendor/spectral/formats/src/index.ts"],
"@stoplight/spectral-functions": ["vendor/spectral/functions/src/index.ts"],
"@stoplight/spectral-rulesets": ["vendor/spectral/rulesets/src/index.ts"],
"@stoplight/spectral-parsers": ["vendor/spectral/parsers/src/index.ts"],
"@stoplight/spectral-runtime": ["vendor/spectral/runtime/src/index.ts"]
},
"module": "commonjs",
"target": "ES2020",
"strict": true
}
}
If using Webpack or esbuild for the CLI, alias the same packages in your bundler config.
No required environment variables for programmatic use. For CLI proxy support, set PROXY=http://your-proxy:3128 before running the spectral binary.
To build the CLI entry point directly: ts-node vendor/spectral/cli/src/index.ts lint myapi.yaml.
import { Spectral } from '@stoplight/spectral-core';
class Spectral {
constructor(options?: { resolver?: IResolver });
ruleset: Ruleset | undefined;
run(input: string | Document): Promise<ISpectralDiagnostic[]>;
}
The main linting engine. Instantiate it, assign a Ruleset, then call run() with a raw string or a Document instance. Returns an array of diagnostics describing every rule violation found.
import { Document } from '@stoplight/spectral-core';
class Document {
constructor(
content: string,
parser: IParser,
source?: string
);
}
Wraps raw document content with a parser (YAML or JSON). Pass the result directly to Spectral.run(). Supplying source enables correct $ref resolution relative to that path.
import type { ISpectralDiagnostic } from '@stoplight/spectral-core';
interface ISpectralDiagnostic {
code: string | number;
message: string;
severity: 0 | 1 | 2 | 3; // error, warn, info, hint
path: (string | number)[];
range: { start: { line: number; character: number }; end: { line: number; character: number } };
source?: string;
}
Every item returned from Spectral.run(). Use severity === 0 to gate CI failure. path gives the JSON Pointer segments to the offending node.
import { CLIError } from './errors'; // vendor/spectral/cli/src/errors/index.ts
class CLIError extends Error {}
Thrown by CLI services when unrecoverable errors occur (bad ruleset path, unreadable file). Catch this in custom CLI wrappers to emit clean user-facing messages without stack traces.
Load an OpenAPI 3 document from disk, apply the built-in OAS ruleset, and print all errors to stdout.
import { Spectral, Document } from '@stoplight/spectral-core';
import { Parsers } from '@stoplight/spectral-parsers';
import { bundleAndLoadRuleset } from '@stoplight/spectral-ruleset-bundler/with-loader';
import * as fs from 'fs';
import * as path from 'path';
async function lintOpenAPI(filePath: string): Promise<void> {
const content = fs.readFileSync(filePath, 'utf8');
const doc = new Document(content, Parsers.Yaml, filePath);
const spectral = new Spectral();
spectral.ruleset = await bundleAndLoadRuleset(
path.resolve(__dirname, '.spectral.yaml'),
{ fs, fetch }
);
const results = await spectral.run(doc);
const errors = results.filter(d => d.severity === 0);
if (errors.length > 0) {
errors.forEach(e =>
console.error(`[${e.code}] ${e.message} at ${e.path.join('.')} (line ${e.range.start.line + 1})`)
);
process.exit(1);
}
console.log('No errors found.');
}
lintOpenAPI('./openapi.yaml').catch(console.error);
Define a ruleset entirely in code without a file on disk, useful for embedded governance logic.
import { Spectral, Document, Ruleset } from '@stoplight/spectral-core';
import { truthy } from '@stoplight/spectral-functions';
import { Parsers } from '@stoplight/spectral-parsers';
async function runCustomRuleset(yamlContent: string): Promise<void> {
const doc = new Document(yamlContent, Parsers.Yaml);
const ruleset = new Ruleset({
rules: {
'require-info-title': {
given: '$.info.title',
severity: 'error',
then: { function: truthy },
message: 'API must have an info.title',
},
},
});
const spectral = new Spectral();
spectral.ruleset = ruleset;
const diagnostics = await spectral.run(doc);
diagnostics.forEach(d => console.log(`${d.severity === 0 ? 'ERROR' : 'WARN'}: ${d.message}`));
}
const sample = `info:\n version: '1.0'\npaths: {}`;
runCustomRuleset(sample).catch(console.error);
Invoke the Spectral CLI command object directly from Node rather than spawning a subprocess.
import yargs from 'yargs';
import lintCommand from './vendor/spectral/cli/src/commands/lint';
const cli = yargs
.scriptName('spectral')
.command(lintCommand)
.help(false)
.version(false);
// Equivalent to: spectral lint api.yaml --ruleset .spectral.yaml --fail-severity error
cli.parse(['lint', 'api.yaml', '--ruleset', '.spectral.yaml', '--fail-severity', 'error']);
cli/ - Yargs CLI entrypoint; src/commands/lint.ts is the lint command; src/services/linter/ handles file collection, ruleset loading, and output; src/errors/ defines CLIError.core/ - Contains Spectral, Document, ParsedDocument, Ruleset, Rule, runner logic, type guards, and all shared TypeScript types.formats/ - Format detection functions (e.g. isOpenApiv3, isAsyncApi2) used in ruleset formats fields.formatters/ - Output formatters consumed by the CLI; each exports a function (diagnostics, options) => string.functions/ - Pure rule functions (truthy, pattern, schema, etc.) imported directly into ruleset then.function fields.parsers/ - Exports Parsers.Yaml and Parsers.Json for use with Document constructor.ref-resolver/ - Resolves $ref pointers within and across documents; wraps @stoplight/json-ref-resolver.ruleset-bundler/ - Bundles ruleset files that import JS/TS functions into self-contained objects.ruleset-migrator/ - CLI tool and API to migrate .spectral.yml v5 rulesets to v6 format.rulesets/ - Prebuilt rulesets (oas, asyncapi, arazzo) with all rules and aliases defined.runtime/ - Exports DEFAULT_REQUEST_OPTIONS and shared fetch helpers used by the CLI and ref-resolver.ERR_REQUIRE_ESM, set "moduleResolution": "bundler" or "node16" in tsconfig.json and use dynamic import().fetch global in Node < 18: The ref-resolver uses fetch; polyfill with npm install node-fetch and global.fetch = require('node-fetch') before importing Spectral.ajv version conflict: Spectral requires ajv@^8; if another dependency pins ajv@6, hoist ajv@8 explicitly in package.json#resolutions (Yarn) or overrides (npm 8+).bundleAndLoadRuleset resolves extends relative to the ruleset file's directory, not process.cwd(); always pass an absolute path via path.resolve().source missing on Document: Without a source path, cross-file $ref resolution fails silently; always supply the absolute file path as the third constructor argument.strict mode errors in runner: The runner uses mapped types that require "strictNullChecks": true; ensure it is not disabled in your tsconfig.I have dropped the Stoplight Spectral monorepo source into `vendor/spectral/`
(from the upstream package `stoplightio_spectral`). I also have USAGE.md in
the same directory describing the real exports and setup steps.
Please help me integrate Spectral into my Node.js/TypeScript project step by step:
1. Read USAGE.md and vendor/spectral/ to understand the available packages and
their exports (Spectral, Document, ISpectralDiagnostic, Ruleset, CLIError, etc.).
2. Add the required tsconfig paths so @stoplight/spectral-* imports resolve to
vendor/spectral/<package>/src/index.ts.
3. Install any missing npm dependencies listed in USAGE.md ## Required dependencies.
4. Create a `src/lint.ts` module that: accepts a file path, parses it with
Parsers.Yaml, loads a ruleset from `.spectral.yaml`, runs Spectral, and
returns all ISpectralDiagnostic results.
5. Add a CI check script `scripts/ci-lint.ts` that exits with code 1 if any
diagnostic has severity 0 (error).
6. If I have a custom rule requirement, show me how to define an inline Ruleset
with a custom function imported from vendor/spectral/functions/.
Use only exports that exist in vendor/spectral/ and are documented in USAGE.md.
Do not invent APIs.
Spectral is released under the Apache 2.0 License (see source/cli/LICENSE and source/core/LICENSE). Upstream repository and package: @stoplight/spectral-core by Stoplight.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
Automation, Utilities & Developer Tools
Free