Skip to content

Scanner Overview

Index

Functions

scanDirectory

async function scanDirectory(dir: string, options: ScanOptions = {}): Promise<ScanAllResult>
TypeScript

Use scanDirectory to extract all API elements from a source directory (or single file) and feed them into skrypt's documentation pipeline.

Reach for this when you're building a custom generation workflow — for example, when you need to pre-process or filter API elements before passing them to the AI doc generator, or when you want to scan programmatically instead of using the CLI.

It recursively walks the target path, matches files against glob patterns, and dispatches each file to the appropriate language scanner (TypeScript, Python, Go, Rust, etc.). The result is a unified collection of every function, class, and type signature found across all matched files.

Parameters

NameTypeRequiredDescription
dirstringYesPath to the directory or single file to scan. Relative paths are resolved from the current working directory.
optionsScanOptionsNoControls which files are scanned. Omitting this uses sensible defaults: all major language extensions are included and common build/dependency folders (node_modules, dist, vendor, etc.) are excluded.
options.includestring[]NoGlob patterns for files to include. Overrides the default language list entirely — specify all extensions you need, not just additions.
options.excludestring[]NoGlob patterns for files to skip. Overrides the default exclusion list, so re-include **/node_modules/** and friends if you provide a custom value.

Returns

Returns a Promise<ScanAllResult> — an object containing the discovered API elements grouped by file and language. Pass this result directly to skrypt's doc generation functions to produce MDX output, or inspect result.elements to filter or transform signatures before generation.

Heads up

  • Providing a custom include or exclude array replaces the defaults entirely — it doesn't merge with them. If you only want to add a pattern, spread the defaults alongside your additions.
  • Pointing dir at a monorepo root without a tight exclude list can be slow; explicitly exclude build artifacts and lockfile directories to keep scans fast.

Example:

// Inline types to keep this self-contained
interface ScanOptions {
  include?: string[];
  exclude?: string[];
}

interface ApiElement {
  name: string;
  kind: "function" | "class" | "type" | "interface";
  signature: string;
  file: string;
  language: string;
  docstring?: string;
}

interface ScanAllResult {
  elements: ApiElement[];
  fileCount: number;
  durationMs: number;
}

// Mock implementation of scanDirectory
async function scanDirectory(
  dir: string,
  options: ScanOptions = {}
): Promise<ScanAllResult> {
  const start = Date.now();

  // Simulate discovering API elements across files
  const mockElements: ApiElement[] = [
    {
      name: "createPayment",
      kind: "function",
      signature: "async function createPayment(amount: number, currency: string, customerId: string): Promise<Payment>",
      file: `${dir}/payments/create.ts`,
      language: "typescript",
      docstring: "Creates a new payment intent for the given customer.",
    },
    {
      name: "PaymentService",
      kind: "class",
      signature: "class PaymentService",
      file: `${dir}/payments/service.ts`,
      language: "typescript",
    },
    {
      name: "refund_payment",
      kind: "function",
      signature: "def refund_payment(payment_id: str, amount: float | None = None) -> Refund",
      file: `${dir}/payments/refund.py`,
      language: "python",
      docstring: "Issues a full or partial refund for a completed payment.",
    },
  ];

  return {
    elements: mockElements,
    fileCount: 3,
    durationMs: Date.now() - start,
  };
}

async function main() {
  try {
    const result = await scanDirectory("./src", {
      include: ["**/*.ts", "**/*.py"],
      exclude: ["**/node_modules/**", "**/dist/**", "**/*.test.ts"],
    });

    console.log(`Scanned ${result.fileCount} files in ${result.durationMs}ms`);
    console.log(`Found ${result.elements.length} API elements:\n`);

    for (const el of result.elements) {
      console.log(`[${el.language}] ${el.kind}: ${el.name}`);
      console.log(`  ${el.signature}`);
      if (el.docstring) console.log(`  → ${el.docstring}`);
      console.log();
    }
  } catch (err) {
    console.error("Scan failed:", err);
    process.exit(1);
  }
}

main();

// Expected output:
// Scanned 3 files in 2ms
// Found 3 API elements:
//
// [typescript] function: createPayment
//   async function createPayment(amount: number, currency: string, customerId: string): Promise<Payment>
//   → Creates a new payment intent for the given customer.
//
// [typescript] class: PaymentService
//   class PaymentService
//
// [python] function: refund_payment
//   def refund_payment(payment_id: str, amount: float | None = None) -> Refund
//   → Issues a full or partial refund for a completed payment.
TypeScript

scanFile

async function scanFile(filePath: string): Promise<ScanResult>
TypeScript

Use scanFile to extract all API signatures, types, and exports from a single source file — giving you the structured data skrypt needs to generate documentation.

Reach for this when you want to scan a specific file rather than an entire directory, or when building a custom documentation pipeline where you control which files get processed. It's the per-file primitive that skrypt generate uses internally.

scanFile detects the language from the file extension, routes to the appropriate scanner (TypeScript, Python, etc.), and returns a normalized ScanResult regardless of source language. Unsupported extensions resolve to language: 'unknown' rather than throwing.

Parameters

NameTypeRequiredDescription
filePathstringYesAbsolute or relative path to the source file to scan. The file extension determines which language scanner runs — .ts/.tsx for TypeScript, .py for Python, etc.

Returns

Returns a Promise<ScanResult> containing the file's detected language, extracted exports, function signatures, type definitions, and any docstrings found. Pass the result directly to your doc generator, or collect results from multiple scanFile calls and merge them before generating output.

Heads up

  • Passing a file with an unrecognized extension won't throw — it returns a result with language: 'unknown' and empty exports. Check the language field if you need to guard against unsupported files.
  • Paths are resolved relative to the current working directory, so prefer absolute paths when calling from scripts that may run in different contexts.

Example:

import { readFileSync } from 'fs'
import { resolve } from 'path'

// Inline types matching ScanResult shape (do not import from autodocs)
interface ExportedItem {
  name: string
  kind: 'function' | 'class' | 'type' | 'const'
  signature: string
  docstring?: string
  parameters?: { name: string; type: string }[]
  returnType?: string
}

interface ScanResult {
  filePath: string
  language: 'typescript' | 'javascript' | 'python' | 'go' | 'rust' | 'unknown'
  exports: ExportedItem[]
}

// Mock implementation of scanFile for demonstration
async function scanFile(filePath: string): Promise<ScanResult> {
  const ext = filePath.split('.').pop() ?? ''
  const langMap: Record<string, ScanResult['language']> = {
    ts: 'typescript', tsx: 'typescript',
    js: 'javascript', jsx: 'javascript',
    py: 'python', go: 'go', rs: 'rust',
  }

  const language = langMap[ext] ?? 'unknown'

  // Simulate extracted exports from a real TypeScript file
  return {
    filePath,
    language,
    exports: [
      {
        name: 'createUser',
        kind: 'function',
        signature: 'async function createUser(email: string, role: Role): Promise<User>',
        docstring: 'Creates a new user and sends a welcome email.',
        parameters: [
          { name: 'email', type: 'string' },
          { name: 'role', type: 'Role' },
        ],
        returnType: 'Promise<User>',
      },
      {
        name: 'Role',
        kind: 'type',
        signature: "type Role = 'admin' | 'member' | 'viewer'",
      },
    ],
  }
}

async function main() {
  const targetFile = resolve('./src/users.ts')

  try {
    const result = await scanFile(targetFile)

    console.log(`Language detected: ${result.language}`)
    console.log(`Exports found: ${result.exports.length}`)

    for (const item of result.exports) {
      console.log(`\n[${item.kind}] ${item.name}`)
      console.log(`  Signature : ${item.signature}`)
      if (item.docstring) console.log(`  Docstring : ${item.docstring}`)
      if (item.returnType) console.log(`  Returns   : ${item.returnType}`)
    }
  } catch (err) {
    console.error('Failed to scan file:', err)
  }
}

main()

// Expected output:
// Language detected: typescript
// Exports found: 2
//
// [function] createUser
//   Signature : async function createUser(email: string, role: Role): Promise<User>
//   Docstring : Creates a new user and sends a welcome email.
//   Returns   : Promise<User>
//
// [type] Role
//   Signature : type Role = 'admin' | 'member' | 'viewer'
TypeScript
Was this helpful?