functional-examples
A language-agnostic library for treating code examples as first-class citizens.
Features
- Pluggable metadata extraction: YAML frontmatter and meta.yml built-in
- Language-aware region parsing: Extracts code regions with comment-style detection
- Flexible scanning: Directory-based and file-based example discovery
- Type-safe API: Full TypeScript support with generic metadata types
Installation
npm install functional-examples
# or
pnpm add functional-examples
# or
yarn add functional-examples
Quick Start
Scanning for Examples
/**
* Basic example: Scanning for examples programmatically
*/
import { scan } from 'functional-examples';
async function main() {
// scan() auto-discovers config and plugins
const result = await scan();
console.log(`Found ${result.examples.length} examples:`);
for (const example of result.examples) {
console.log(` - ${example.title} (${example.id})`);
}
if (result.errors.length > 0) {
console.log(`\n${result.errors.length} errors occurred:`);
for (const error of result.errors) {
console.log(` - ${error.path}: ${error.message}`);
}
}
}
main().catch(console.error);
Example Formats
Directory-based (meta.yml)
id: basic-usage
title: Basic Usage
description: |
Demonstrates scanning for examples in a directory
using the functional-examples library.
tags:
- getting-started
- api
This meta.yml defines metadata for one example directory.
File-based (YAML frontmatter)
// ---
// id: hello
// title: Hello World
// description: A minimal example
// ---
export function hello() {
return 'Hello from functional-examples!';
}
Region Markers
/**
* ---
* id: region-markers
* title: Region Markers Demo
* ---
*/
import { scan } from 'functional-examples';
// #region setup
const result = await scan();
// #endregion
// #region execution
console.log(result.examples);
// #endregion
Supports 30+ languages with automatic comment syntax detection.
Custom Extractors
/**
* Custom TOML-based extractor example.
*
* This demonstrates how to create your own extractor that:
* 1. Scans for a specific file pattern (meta.toml)
* 2. Parses metadata from that file format
* 3. Claims files and returns Example objects
*/
import {
ExampleFile,
type Example,
type Extractor,
type ExtractorResult,
} from 'functional-examples';
import { readdirSync, type Dirent } from 'node:fs';
import { readFile } from 'node:fs/promises';
import path, { join } from 'node:path';
/**
* Metadata structure for TOML examples.
* You can define any shape that fits your use case.
*/
export interface TomlMetadata {
id: string;
title: string;
description?: string;
author?: string;
[key: string]: unknown;
}
/**
* Create a custom extractor that reads TOML metadata files.
*
* Extractors implement a candidate-based pattern: they're called with
* pre-filtered candidates (files and directories) and decide which to handle.
*/
export function createTomlExtractor(): Extractor<TomlMetadata> {
return {
name: 'toml-extractor',
async extract(
candidates: Dirent[]
): Promise<ExtractorResult<TomlMetadata>> {
const examples: Example<TomlMetadata>[] = [];
const claimedFiles = new Set<string>();
const errors: { path: string; message: string }[] = [];
// Find meta.toml files from candidates
const tomlFiles: string[] = [];
for (const candidate of candidates) {
const fullPath = path.join(candidate.parentPath, candidate.name);
if (candidate.isFile()) {
// Direct file candidate: check if it's a meta.toml
if (candidate.name === 'meta.toml') {
tomlFiles.push(fullPath);
}
} else if (candidate.isDirectory()) {
// Directory candidate: look for meta.toml inside
const metaPath = path.join(fullPath, 'meta.toml');
try {
await readFile(metaPath, 'utf-8');
tomlFiles.push(metaPath);
} catch {
// No meta.toml in this directory, skip
}
}
}
for (const tomlFile of tomlFiles) {
try {
const content = await readFile(tomlFile, 'utf-8');
const metadata = parseSimpleToml(content);
const exampleDir = path.dirname(tomlFile);
// Collect all files in the example directory
const files = collectExampleFiles(exampleDir);
// Claim all files
for (const file of files) {
claimedFiles.add(file);
}
examples.push({
id: metadata.id,
title: metadata.title,
description: metadata.description,
rootPath: exampleDir,
files: files.map((f) => new ExampleFile({
absolutePath: f,
relativePath: path.relative(exampleDir, f),
})),
metadata,
extractorName: 'toml-extractor',
});
} catch (err) {
errors.push({
path: tomlFile,
message: `Failed to parse: ${(err as Error).message}`,
});
}
}
return { examples, errors, claimedFiles };
},
};
}
/**
* Simplified TOML parser for demonstration.
* In production, use a proper TOML library like @iarna/toml.
*/
function parseSimpleToml(content: string): TomlMetadata {
const lines = content.split('\n');
const result: Record<string, string> = {};
for (const line of lines) {
// Match: key = "value"
const match = line.match(/^(\w+)\s*=\s*"(.*)"/);
if (match) {
result[match[1]] = match[2];
}
}
if (!result['id'] || !result['title']) {
throw new Error('TOML must have id and title fields');
}
return {
id: result['id'],
title: result['title'],
description: result['description'],
author: result['author'],
};
}
function collectExampleFiles(root: string) {
if (root.endsWith('node_modules')) {
return [];
}
let files: string[] = [];
const entries = readdirSync(root, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
files = files.concat(
collectExampleFiles(join(entry.parentPath, entry.name))
);
} else {
files.push(join(entry.parentPath, entry.name));
}
}
return files;
}
API Reference
Scanner
scan(options?)- Discover config and scan in one callscanExamples(resolvedConfig)- Scan with a pre-resolved config
Configuration
findConfigFile(root?)loadConfig(configPath)resolveConfig(config)validateConfig(config)mergeConfigs(...configs)
Plugins and Validation
PluginRegistrycreateInitialContext(context)runParsePipeline(context, parsers)validatePluginOptions(context)validateExampleMetadata(context)
File Helpers
readExampleFile(path, options?)readExampleFiles(root, files)
Schema Utilities
mergeConfigSchema(...)mergeMetadataSchemas(...)generateTypes(...)
License
MIT
API EXPORTS
Functions
createInitialContextfunctionCreate the initial parse context for a file.
findConfigFilefunctiongenerateTypesfunctionGenerate TypeScript type declarations from merged metadata schema and plugin schemas, emitting a single `declare module` block that contains both the ExampleMetadataRegistry and (when plugins are present) PluginOptionsRegistry interface augmentations.
loadConfigfunctionmergeConfigsfunctionMerge multiple configuration sources with later configs taking precedence.
mergeConfigSchemafunctionMerge plugin schemas into a complete config schema.
mergeMetadataSchemasfunctionMerge metadata schemas from config and plugins. Config schema takes priority on conflicts.
readExampleFilefunctionRead an example file's contents.
readExampleFilesfunctionRead multiple files from an example directory.
resolveConfigfunctionResolve a configuration to actual plugin and extractor instances. Plugin resolution follows this priority: 1. If `config.plugins` contains Plugin instances (from TS configs), use directly 2. If `config.plugins` contains string/tuple references (from JSON configs), resolve them by dynamically importing the package and calling its factory 3. If no plugins specified at all, auto-detect installed plugin packages
runParsePipelinefunctionRun file content through a parser pipeline. Parsers execute in order, each receiving the output of the previous. Hunks are accumulated across parsers automatically. Each parser receives an empty hunks array and only needs to return its own hunks. The pipeline merges them in order so parsers don't need to preserve earlier hunks.
scanfunctionScan for examples using automatic config discovery. This is the simplest entry point for programmatic scanning. It discovers the nearest config file, loads it, resolves plugins, and runs the scanner — all in one call.
scanExamplesfunctionScan a directory for examples using the provided extractors. The scanner: 1. Runs all extractors in parallel against the root 2. Collects claimed files and detects conflicts 3. Resolves conflicts via path mappings (or errors if unresolved) 4. Applies include/exclude filters AFTER extraction 5. Returns unified results
validateConfigfunctionvalidateExampleMetadatafunctionValidate example metadata after extraction. Runs all metadata validators against each example's metadata.
validatePluginOptionsfunctionValidate plugin options before extraction. Runs each plugin's options validator against its configured options.
Classes
Interfaces
BaseMetadatainterfaceBase metadata that all examples should have. Used for type constraints when users want stricter typing.
ConfiginterfaceConfigValidationErrorinterfaceError from config validation.
ExampleinterfaceA discovered example with metadata and files. This is the base type returned by extractors. Metadata is typed via `ExampleMetadata` by default, which can be augmented by running `functional-examples generate`. You can also pass an explicit generic parameter for custom typing.
ExampleMetadataRegistryinterfaceAugmentable registry for example metadata typing. Run `functional-examples generate` to create a declaration file that augments this interface, providing type-safe metadata for your examples.
ExtractorinterfaceCandidate-based extractor interface. Called with pre-filtered candidates (files and/or directories). Extractor decides which candidates it can handle.
ExtractorConfiginterfaceReference to an extractor package (for config files)
ExtractorErrorinterfaceError encountered during extraction
ExtractorOptionsinterfaceOptions passed to extractor during extraction
ExtractorResultinterfaceResult from a candidate-based extractor
FileConflictinterfaceConflict when multiple extractors claim the same file
FileContentsParserinterfaceParser that processes file contents in a pipeline. Receives accumulated context, transforms it, returns updated context.
FileParseContextinterfaceContext passed through the FileContentsParser pipeline. Each parser receives this, transforms it, and returns an updated version.
GenerateConfiginterfaceConfiguration for the generate command output.
GenerateTypesOptionsinterfaceJSONSchemainterfaceJSON Schema type (subset of JSON Schema spec).
JSONSchemaObjectinterfaceJSON Schema object for metadata validation. Subset of JSON Schema spec used for config files.
MergeConfigSchemaOptionsinterfaceMergeMetadataSchemasOptionsinterfaceMetadataValidationContextinterfaceContext for validating example metadata.
MetadataValidationErrorinterfaceError from metadata validation with example context.
MetadataValidationResultinterfaceResult of validating example metadata.
OptionsValidationErrorinterfaceError from options validation with plugin context.
OptionsValidationResultinterfaceResult of validating plugin options.
ParsedRegioninterfaceParsed code region from #region markers.
PathMappinginterfacePath-to-extractor mapping for conflict resolution.
PlugininterfacePlugin containing optional extractors, parsers, schemas, and validators. Auto-registers for declared file extensions.
PluginOptionsValidationContextinterfaceContext for validating plugin options.
PluginSchemaEntryinterfaceSchema entry from a plugin with plugin name context.
PluginSchemasinterfaceSchema definitions for a plugin (JSON Schema format). Used for IDE autocomplete and documentation generation.
PluginValidatorinterfaceWrapper for a plugin's validator function with plugin name context.
PluginValidatorsinterfaceValidator functions for a plugin. Allows plugins to use any validation library (Zod, TypeBox, etc.)
ResolvedConfiginterfaceResolved configuration with actual extractor instances. This is the runtime-ready configuration after all plugins are loaded.
ScanConfiginterfaceScan configuration options.
ScanOptionsinterfaceOptions for the convenience `scan()` function.
ScanResultinterfaceResult of scanning for examples
ValidationErrorinterfaceA single validation error.
ValidationResultinterfaceResult of a validation operation.
Types
ExampleMetadatatypeResolved example metadata type. If `ExampleMetadataRegistry` has been augmented with a `metadata` property, this resolves to that type. Otherwise, falls back to `Record<string, unknown>`. This allows the `generate` command to provide project-specific types that automatically apply to all `Example` types without explicit generic parameters.
ExtractorConfigOrFunctiontypeAn extractor can be a reference (to load) or an instance
ExtractorFactorytypeFactory function to create an extractor with options
ExtractorReferencetypeExtractor can be specified as string (package name) or full config
PluginCommandstypePlugin commands can be a static array or a function that receives the resolved config and returns commands (sync or async). Uses `CLI<any, any, any, any>` because each command defines its own args/handler shape — the plugin system doesn't need to know specifics.