or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-commands.mdconfiguration.mdindex.mdprogrammatic-api.mdreporters.md
tile.json

programmatic-api.mddocs/

Programmatic API

Core spell checking functions for integration into Node.js applications, providing lint, trace, check, and suggestion capabilities with full TypeScript support.

Capabilities

Lint Function

Primary programmatic spell checking function that processes file globs and returns comprehensive results.

/**
 * Spell check files using glob patterns with configurable options and optional custom reporter
 * @param fileGlobs - Array of file glob patterns to check
 * @param options - Linter configuration options
 * @param reporter - Optional custom reporter for handling results
 * @returns Promise resolving to RunResult with check statistics
 */
function lint(
  fileGlobs: string[], 
  options: LinterCliOptions, 
  reporter?: CSpellReporter
): Promise<RunResult>;

interface RunResult {
  /** Total number of files processed */
  files: number;
  /** Set of file paths that contained spelling issues */
  filesWithIssues: Set<string>;
  /** Total number of spelling issues found */
  issues: number;
  /** Total number of errors encountered during processing */
  errors: number;
  /** Number of files loaded from cache */
  cachedFiles: number;
}

interface LinterCliOptions extends BaseOptions, CacheOptions, ReporterConfiguration {
  /** Display verbose information */
  verbose?: boolean;
  /** Show extensive debug output */
  debug?: boolean;
  /** Glob patterns to exclude files from checking */
  exclude?: string[] | string;
  /** Only report words, no line numbers or file names */
  wordsOnly?: boolean;
  /** Unique errors per file only */
  unique?: boolean;
  /** Root directory, defaults to current working directory */
  root?: string;
  /** Include files/directories starting with '.' in glob search */
  dot?: boolean;
  /** Show context around issues (true for default, number for character count) */
  showContext?: boolean | number;
  /** Show spelling suggestions for misspelled words */
  showSuggestions?: boolean;
  /** Enable file caching for performance */
  cache?: boolean;
  /** Cache file or directory location */
  cacheLocation?: string;
  /** Use .gitignore files to exclude files */
  gitignore?: boolean;
  /** Custom reporter modules or built-in reporter names */
  reporter?: string[];
  /** Custom template for issue output formatting */
  issueTemplate?: string;
}

Usage Examples:

import { lint } from "cspell";

// Basic spell checking
const result = await lint(
  ["src/**/*.js", "docs/**/*.md"],
  {
    verbose: true,
    showSuggestions: true
  }
);

console.log(`Checked ${result.files} files`);
console.log(`Found ${result.issues} issues in ${result.filesWithIssues.size} files`);

// Advanced configuration with caching
const result = await lint(
  ["**/*.{ts,tsx}"],
  {
    config: "./custom-cspell.json",
    cache: true,
    cacheLocation: "./.cspell-cache",
    exclude: ["node_modules/**", "dist/**"],
    showContext: 10,
    gitignore: true
  }
);

// With custom reporter
import { MyCustomReporter } from "./reporters";

const result = await lint(
  ["src/**/*.py"],
  {
    languageId: "python",
    locale: "en-US"
  },
  new MyCustomReporter()
);

Trace Function

Async generator that traces words through dictionaries and configurations to debug word lookup and understand spell checking behavior.

/**
 * Trace words through dictionaries and configuration to debug lookup behavior
 * @param words - Array of words to trace through the spell checking system
 * @param options - Trace configuration options
 * @returns AsyncIterableIterator yielding TraceWordResult for each word
 */
function trace(words: string[], options: TraceOptions): AsyncIterableIterator<TraceWordResult>;

interface TraceOptions extends BaseOptions {
  /** Enable compound word checking during trace */
  allowCompoundWords?: boolean;
  /** Ignore case and accents when searching dictionaries */
  ignoreCase?: boolean;
  /** Specific dictionaries to enable for tracing */
  dictionary?: string[];
  /** Read additional words from stdin */
  stdin?: boolean;
}

interface TraceWordResult {
  /** The word being traced */
  word: string;
  /** Whether the word was found in any dictionary */
  found: boolean;
  /** The actual word found (may differ due to case/compound word matching) */
  foundWord?: string;
  /** Whether the word is marked as forbidden */
  forbidden?: boolean;
  /** Whether the word should not generate suggestions */
  noSuggest?: boolean;
  /** Detailed results from each dictionary consulted */
  dictionaries: DictionaryTraceResult[];
}

interface DictionaryTraceResult {
  /** Name of the dictionary */
  name: string;
  /** Whether this dictionary contained the word */
  found: boolean;
  /** Weight/priority of this dictionary */
  weight?: number;
  /** Errors encountered when accessing this dictionary */
  errors?: string[];
}

Usage Examples:

import { trace } from "cspell";

// Basic word tracing
const words = ["JavaScript", "camelCase", "mispelled"];
for await (const result of trace(words, { config: "./cspell.json" })) {
  console.log(`Word: ${result.word}`);
  console.log(`Found: ${result.found}`);
  if (result.found) {
    console.log(`Found as: ${result.foundWord}`);
  }
  console.log(`Dictionaries checked: ${result.dictionaries.length}`);
}

// Advanced tracing with compound words
for await (const result of trace(
  ["XMLHttpRequest", "backgroundColor"], 
  {
    allowCompoundWords: true,
    ignoreCase: true,
    dictionary: ["typescript", "css"]
  }
)) {
  console.log(`${result.word} -> ${result.found ? 'FOUND' : 'NOT FOUND'}`);
  result.dictionaries.forEach(dict => {
    if (dict.found) {
      console.log(`  Found in: ${dict.name}`);
    }
  });
}

// Reading from stdin
import { createReadStream } from "fs";
import { createInterface } from "readline";

const rl = createInterface({
  input: createReadStream("words.txt"),
  crlfDelay: Infinity
});

const wordsFromFile: string[] = [];
for await (const line of rl) {
  wordsFromFile.push(line.trim());
}

for await (const result of trace(wordsFromFile, { stdin: true })) {
  if (!result.found) {
    console.log(`Unknown word: ${result.word}`);
  }
}

Check Text Function

Check spelling in a specific text file with detailed configuration options and return comprehensive analysis.

/**
 * Check spelling in a specific text file with detailed analysis
 * @param filename - Path to the file to check
 * @param options - Configuration options combining base and legacy settings
 * @returns Promise resolving to CheckTextResult with detailed analysis
 */
function checkText(filename: string, options: BaseOptions & LegacyOptions): Promise<CheckTextResult>;

interface CheckTextResult {
  /** Document representation of the checked file */
  document: TextDocument;
  /** Configuration settings used for checking */
  options: CSpellSettings;
  /** Array of spelling issues found in the document */
  issues: TextIssue[];
}

interface TextDocument {
  /** URI/path of the document */
  uri: string;
  /** Programming language identifier */
  languageId: string;
  /** Document version number */
  version: number;
  /** Full text content of the document */
  text: string;
  /** Locale used for spell checking */
  locale: string;
}

interface TextIssue {
  /** The misspelled text */
  text: string;
  /** Start position in the document */
  offset: number;
  /** Length of the misspelled text */
  length: number;
  /** Line number (1-based) */
  line: number;
  /** Column number (1-based) */
  col: number;
  /** Issue context information */
  context: IssueContext;
  /** Suggested replacements */
  suggestions?: string[];
}

interface LegacyOptions {
  /** Validate in-document CSpell directives */
  validateDirectives?: boolean;
}

Usage Examples:

import { checkText } from "cspell";

// Basic file checking
const result = await checkText("./src/app.ts", {
  config: "./cspell.json",
  languageId: "typescript"
});

console.log(`Document: ${result.document.uri}`);
console.log(`Language: ${result.document.languageId}`);
console.log(`Issues found: ${result.issues.length}`);

result.issues.forEach(issue => {
  console.log(`Line ${issue.line}:${issue.col} - "${issue.text}"`);
  if (issue.suggestions?.length) {
    console.log(`  Suggestions: ${issue.suggestions.join(", ")}`);
  }
});

// Advanced checking with directive validation
const result = await checkText("./docs/README.md", {
  config: "./cspell.json",
  locale: "en-US",
  validateDirectives: true,
  defaultConfiguration: true
});

// Check if any issues are in code blocks vs regular text
result.issues.forEach(issue => {
  const contextStart = Math.max(0, issue.offset - 50);
  const contextEnd = Math.min(result.document.text.length, issue.offset + issue.length + 50);
  const context = result.document.text.slice(contextStart, contextEnd);
  
  console.log(`Issue: "${issue.text}" at line ${issue.line}`);
  console.log(`Context: ${context}`);
});

Suggestions Function

Async generator providing spelling suggestions for words with configurable suggestion algorithms and timing information.

/**
 * Generate spelling suggestions for words with configurable algorithms
 * @param words - Array of words to generate suggestions for
 * @param options - Suggestion configuration options
 * @returns AsyncIterable yielding TimedSuggestionsForWordResult with suggestions and timing
 */
function suggestions(
  words: string[], 
  options: SuggestionOptions
): AsyncIterable<TimedSuggestionsForWordResult>;

interface SuggestionOptions extends BaseOptions {
  /** Number of character changes allowed in suggestions (default: 4) */
  numChanges?: number;
  /** Maximum number of suggestions to return (default: 8) */
  numSuggestions?: number;
  /** Include suggestions with tied scores */
  includeTies?: boolean;
  /** Enable interactive REPL mode */
  repl?: boolean;
  /** Read words from stdin */
  useStdin?: boolean;
  /** Ignore case and accents when generating suggestions */
  ignoreCase?: boolean;
}

interface TimedSuggestionsForWordResult extends SuggestionsForWordResult {
  /** Time elapsed generating suggestions in milliseconds */
  elapsedTimeMs?: number;
}

interface SuggestionsForWordResult {
  /** The original word */
  word: string;
  /** Array of suggested corrections */
  suggestions: SuggestedWord[];
}

interface SuggestedWord {
  /** Suggested word text */
  word: string;
  /** Confidence cost (lower is better) */
  cost: number;
  /** Whether this word is preferred */
  isPreferred?: boolean;
  /** Dictionaries that contain this suggestion */
  dictionaries?: string[];
}

Usage Examples:

import { suggestions } from "cspell";

// Basic suggestions
const words = ["teh", "recieve", "seperate"];
for await (const result of suggestions(words, {
  numSuggestions: 5,
  config: "./cspell.json"
})) {
  console.log(`\nWord: ${result.word}`);
  console.log(`Suggestions (${result.suggestions.length}):`);
  result.suggestions.forEach((suggestion, index) => {
    console.log(`  ${index + 1}. ${suggestion.word} (cost: ${suggestion.cost})`);
  });
  
  if (result.elapsedTimeMs) {
    console.log(`Time: ${result.elapsedTimeMs}ms`);
  }
}

// Advanced suggestions with custom parameters
for await (const result of suggestions(
  ["javscript", "typescirpt"],
  {
    numChanges: 2,        // Limit character changes
    numSuggestions: 3,    // Limit suggestions
    includeTies: false,   // Strict limit
    ignoreCase: true,     // Case insensitive
    locale: "en-US"
  }
)) {
  console.log(`"${result.word}" suggestions:`);
  result.suggestions.forEach(s => {
    const preferred = s.isPreferred ? " (preferred)" : "";
    console.log(`  ${s.word}${preferred}`);
  });
}

// Interactive REPL mode
async function* interactiveSuggestions() {
  yield* suggestions([], {
    repl: true,
    numSuggestions: 10,
    config: "./cspell.json"
  });
}

// Use stdin for batch processing
async function* stdinSuggestions() {
  yield* suggestions([], {
    useStdin: true,
    numChanges: 3,
    ignoreCase: true
  });
}

Configuration Initialization

Create and initialize new CSpell configuration files programmatically with customizable settings.

/**
 * Create and initialize a new CSpell configuration file
 * @param options - Configuration initialization options
 * @returns Promise that resolves when configuration file is created
 */
function createInit(options: InitOptions): Promise<void>;

interface InitOptions {
  /** Path to the configuration file to create */
  config?: string;
  /** Output file path (alternative to config) */
  output?: string;
  /** Configuration file format (yaml|yml|json|jsonc) */
  format?: string;
  /** Import configuration files or dictionary packages */
  import?: string[];
  /** Define locales for spell checking */
  locale?: string[];
  /** Enable specific dictionaries */
  dictionary?: string[];
  /** Add explanatory comments to the configuration file */
  comments?: boolean;
  /** Include JSON schema reference in the configuration */
  schema?: boolean;
  /** Write configuration to stdout instead of file */
  stdout?: boolean;
}

Usage Examples:

import { createInit } from "cspell";

// Basic configuration file creation
await createInit({
  config: "./cspell.yaml",
  format: "yaml",
  locale: ["en-US"],
  dictionary: ["typescript", "node"]
});

// Advanced configuration with imports
await createInit({
  output: "./.cspell.json",
  format: "json", 
  import: ["@cspell/dict-python", "./custom-words.txt"],
  locale: ["en-US", "es-ES"],
  dictionary: ["python", "medical"],
  comments: true,
  schema: true
});

// Output to stdout for processing
await createInit({
  format: "yaml",
  locale: ["en-GB"],
  dictionary: ["typescript"],
  stdout: true
});

CLI Application Runner

Run the complete CLI application programmatically with full command parsing and execution.

/**
 * Run the complete CSpell CLI application programmatically
 * @param command - Optional Commander.js command instance
 * @param argv - Optional command line arguments array
 * @returns Promise that resolves when CLI execution completes
 */
function run(command?: Command, argv?: string[]): Promise<void>;

Usage Examples:

import { run } from "cspell/app";

// Run with custom arguments
await run(undefined, ["node", "cspell", "lint", "src/**/*.js", "--verbose"]);

// Run with current process arguments
await run(undefined, process.argv);

// Custom command setup
import { program } from "commander";
const customCommand = program
  .name("my-spell-checker")
  .version("1.0.0");

await run(customCommand, ["node", "my-spell-checker", "check", "README.md"]);

Utility Functions

Feature Flags

Parse and manage application feature flags for advanced functionality.

/**
 * Parse application-specific feature flags
 * @param flags - Array of flag strings in format "name:value"
 * @returns FeatureFlags object with parsed flags
 */
function parseApplicationFeatureFlags(flags: string[] | undefined): FeatureFlags;

interface FeatureFlags {
  /** Check if a feature flag is enabled */
  isEnabled(flagName: string): boolean;
  /** Get feature flag value */
  getValue(flagName: string): string | undefined;
  /** Register a new feature flag */
  register(flag: FeatureFlagDefinition): void;
}

interface FeatureFlagDefinition {
  /** Flag name */
  name: string;
  /** Flag description */
  description: string;
  /** Default value */
  defaultValue?: string | boolean;
}

Usage Examples:

import { parseApplicationFeatureFlags } from "cspell";

// Parse feature flags
const flags = parseApplicationFeatureFlags(["timer:true", "debug:verbose"]);

if (flags.isEnabled("timer")) {
  console.log("Timer feature is enabled");
}

const debugLevel = flags.getValue("debug");
console.log(`Debug level: ${debugLevel}`);

Error Handling

The programmatic API uses custom error classes for different failure scenarios:

/**
 * General application-level error
 */
class ApplicationError extends Error {
  constructor(message: string);
}

/**
 * Spell check failure with specific exit code
 */
class CheckFailed extends Error {
  /** Exit code indicating type of failure */
  exitCode: number;
  
  constructor(message: string, exitCode: number);
}

Common Error Scenarios:

import { lint, ApplicationError, CheckFailed } from "cspell";

try {
  const result = await lint(["src/**/*.js"], {
    config: "./cspell.json"
  });
} catch (error) {
  if (error instanceof ApplicationError) {
    console.error("Application error:", error.message);
    // Handle configuration or setup errors
  } else if (error instanceof CheckFailed) {
    console.error("Spell check failed:", error.message);
    console.error("Exit code:", error.exitCode);
    // Handle spell checking failures
  } else {
    console.error("Unexpected error:", error);
  }
}