- Overview - Back to API reference index
- Library Reference - Creating and managing .chalk libraries
- Compiler Reference - Using the .chalk compiler programmatically
- Custom Parsers - Creating custom parsers and parser priority
- Primitives Reference - Built-in data types and elements in .chalk
- Troubleshooting - Common issues and solutions
Type Reference
Complete TypeScript type definitions for the dotchalk public API. This reference documents all exported types, interfaces, and type aliases used throughout the library.
Table of Contents
Core Types
Result
A discriminated union type representing operations that can succeed or fail.
type Result<T, E = string> =
| { ok: true; data: T }
| { ok: false; error: E };
Type Parameters:
T- The type of the success valueE- The type of the error value (default:string)
Usage:
const result: Result<number> = divide(10, 2);
if (result.ok) {
console.log('Result:', result.data); // Type: number
} else {
console.error('Error:', result.error); // Type: string
}
CompileResult
The return type for compilation functions (compile and compileFile).
type CompileResult = Result<ChalkDocument, string>;
Expands to:
type CompileResult =
| { ok: true; data: ChalkDocument }
| { ok: false; error: string };
Usage:
const result: CompileResult = chalk.compile(source, library);
if (result.ok) {
const document: ChalkDocument = result.data;
console.log('Compiled:', document.class);
} else {
console.error('Compilation failed:', result.error);
}
FileMap
A map of file paths to file content for in-memory file resolution with the compile() function.
type FileMap = Record<string, string>;
Usage:
const files: FileMap = {
'header.part.chalk': 'para{Welcome}',
'footer.part.chalk': 'para{Goodbye}',
'components/nav.part.chalk': 'para{Navigation}'
};
const result = chalk.compile(
'@include(src: header.part.chalk)',
library,
undefined,
undefined,
files
);
Notes:
- Keys are file paths (relative or absolute) to be used in
@includedirectives - Values are the file content as strings
- Only available for
compile(), notcompileFile()(which reads from filesystem) - For details and examples, see In-Memory File Resolution
ContentPolicy
Defines what types of content are allowed within elements and documents.
type ContentPolicy =
| null
| "literal"
| "all"
| string[]
| string;
Values:
null- No content allowed (elements only, not valid for documents)"literal"- Raw text content with no parsing (elements only, not valid for documents)"all"- All element types allowedstring[]- Array of specific element type identifiersstring- Single element identifier
Usage:
// Allow all elements
const policy1: ContentPolicy = "all";
// Allow specific elements
const policy2: ContentPolicy = ["paragraph", "h1", "h2"];
// No content
const policy3: ContentPolicy = null;
// Literal text only
const policy4: ContentPolicy = "literal";
InlinePolicy
Defines what types of inline elements are allowed within text content (paragraphs, headings, inline element bodies).
type InlinePolicy = {
type: 'all' | 'list' | 'none';
elements?: string[];
};
Created using the inline() helper function:
function inline(elements: 'all' | string[] | null): InlinePolicy;
Values:
inline('all')- All inline elements allowed (default)inline(['bold', 'italic'])- Only specific inline elementsinline(null)- No inline elements, literal text only
Usage:
import chalk from '@jackhgns/dotchalk';
// Allow all inline elements
const policy1: InlinePolicy = chalk.inline('all');
// Allow specific inline elements
const policy2: InlinePolicy = chalk.inline(['bold', 'italic', 'code']);
// No inline elements - literal text only
const policy3: InlinePolicy = chalk.inline(null);
// Used in element definitions
lib.element({
id: 'code-block',
body: chalk.inline(null) // No inline formatting in code blocks
});
lib.inlineElement({
id: 'highlight',
body: chalk.inline(['bold', 'italic']) // Only bold/italic inside highlights
});
Document Types
ChalkDocument
Represents a compiled .chalk document - the primary output from compilation functions.
interface ChalkDocument {
instance_id: string;
class: string;
header: Record<string, any>;
body: DocumentContent;
}
Properties:
instance_id- Unique identifier for this document instance (format:doc_<timestamp><counter>)class- The document class name as defined in the libraryheader- Document-level attributes from the header sectionbody- Array of compiled elements that make up the document content
Example:
const document: ChalkDocument = {
instance_id: "doc_1766629364403001",
class: "article",
header: {
title: "Getting Started",
author: "Jane Doe"
},
body: [/* ChalkElement instances */]
};
DocumentContent
Type alias for document body content.
type DocumentContent = ChalkElement[] | Record<string, unknown>[];
The body can contain:
- An array of
ChalkElementinstances (most common) - An array of generic records (for custom element types)
DocumentValidationError
Error thrown when document validation fails during compilation.
class DocumentValidationError extends Error {
constructor(
message: string,
public readonly document_class: string,
public readonly instance_id?: string,
public readonly code?: string,
public readonly context?: Record<string, any>
);
}
Properties:
message- Human-readable error messagedocument_class- The document class that failed validationinstance_id- Optional instance ID of the documentcode- Optional error code for programmatic handlingcontext- Optional additional context about the error
Element Types
ChalkElement
Represents a compiled element within a document.
interface ChalkElement {
instance_id: string;
identifier: string;
body: ElementContent;
detail: ElementContent;
attributes: ChalkAttribute[];
}
Properties:
instance_id- Unique identifier for this element instance (format:elem_<timestamp><counter>)identifier- The element type identifier as defined in the librarybody- Primary content area (structure depends on body policy)detail- Secondary content area (optional)attributes- Array of attributes attached to this element
Example:
const element: ChalkElement = {
instance_id: "elem_1766629364412002",
identifier: "section",
body: [/* nested elements */],
detail: null,
attributes: [
{ instance_id: "attr_001", identifier: "title", value: "Introduction" }
]
};
ElementContent
Type alias for element body or detail content.
type ElementContent =
| ChalkElement[]
| Record<string, unknown>[]
| (string | ChalkElement)[]
| string
| null;
The content can be:
- An array of
ChalkElementinstances (for container elements) - An array of generic records (for custom element types)
- An array of mixed strings and elements (for formatted text)
- A plain string (for literal text content)
null(when no content is present)
ElementValidationError
Error thrown when element validation fails during compilation.
class ElementValidationError extends Error {
constructor(
message: string,
public readonly element_identifier: string,
public readonly instance_id?: string,
public readonly code?: string,
public readonly context?: Record<string, any>
);
}
Properties:
message- Human-readable error messageelement_identifier- The element identifier that failed validationinstance_id- Optional instance ID of the elementcode- Optional error code for programmatic handlingcontext- Optional additional context about the error
Attribute Types
ChalkAttribute
Represents a compiled attribute instance on an element or in a document header.
interface ChalkAttribute {
instance_id: string;
identifier: string;
value: any;
}
Properties:
instance_id- Unique identifier for this attribute instance (format:attr_<timestamp><counter>)identifier- The canonical attribute identifier (aliases are resolved)value- The parsed value, typed according to the attribute’s type definition
Example:
const attribute: ChalkAttribute = {
instance_id: "attr_1766629364413005",
identifier: "priority",
value: "high"
};
// Different value types based on attribute type
const numericAttr: ChalkAttribute = {
instance_id: "attr_002",
identifier: "level",
value: 2 // number
};
const booleanAttr: ChalkAttribute = {
instance_id: "attr_003",
identifier: "enabled",
value: true // boolean
};
AttributeError
Error thrown when attribute operations fail during compilation.
class AttributeError extends Error {
constructor(
message: string,
public readonly identifier: string,
public readonly instance_id?: string,
public readonly code?: string,
public readonly context?: Record<string, any>
);
}
Properties:
message- Human-readable error messageidentifier- The attribute identifier that caused the errorinstance_id- Optional instance ID of the attributecode- Optional error code for programmatic handlingcontext- Optional additional context about the error
Library Specification Types
These types are used when defining libraries using the fluent API (.element(), .document(), etc.).
Library
The library builder interface for defining document schemas and element types.
interface Library {
element(spec: ElementSpec): Library;
type(spec: TypeSpec): Library;
enum(spec: EnumSpec): Library;
document(spec: DocumentSpec): Library;
config(options: LibraryConfig): Library;
}
Methods:
element(spec)- Define an element typetype(spec)- Define a custom attribute typeenum(spec)- Define an enumeration typedocument(spec)- Define a document classconfig(options)- Configure library-level settings
Usage:
const lib: Library = chalk.library()
.document({ name: 'article', body: 'all' })
.element({ id: 'section', body: ['paragraph'], attributes: [] });
ElementSpec
Specification object for defining element types.
interface ElementSpec {
id: string;
aliases?: string[];
body?: ContentPolicy;
detail?: ContentPolicy;
attributes?: AttributeSpec[];
parser?: (input: string) => Result<ElementContent>;
parserPriority?: number;
documentClasses?: string[];
}
Properties:
id- Unique identifier for the element (required)aliases- Alternative names for the elementbody- Content policy for the element’s body (default:"all")detail- Content policy for the element’s detail section (default:null)attributes- Array of attribute definitionsparser- Custom parsing function for non-standard syntaxparserPriority- Priority for custom parser execution (default:5)documentClasses- Document classes this element is scoped to (empty = all)
InlineElementSpec
Specification object for defining inline element types.
interface InlineElementSpec {
id: string;
aliases?: string[];
body?: InlinePolicy;
attributes?: AttributeSpec[];
shorthand?: string;
documentClasses?: string[];
}
Properties:
id- Unique identifier for the inline element (required)aliases- Alternative names for the inline elementbody- Inline policy controlling nested inline elements (default:inline('all'))attributes- Array of attribute definitionsshorthand- Custom shorthand delimiter (e.g.,'==='for===text===)documentClasses- Document classes this inline element is scoped to (empty = all)
Usage:
import chalk from '@jackhgns/dotchalk';
const spec: InlineElementSpec = {
id: 'highlight',
body: chalk.inline('all'),
attributes: [
{ id: 'color', type: 'string', default: 'yellow' }
],
shorthand: '==='
};
DocumentSpec
Specification object for defining document classes.
interface DocumentSpec {
name: string;
body?: ContentPolicy;
attributes?: AttributeSpec[];
config?: LibraryConfig;
}
Properties:
name- Document class name (required)body- Content policy for the document body (default:"all")attributes- Array of header attribute definitionsconfig- Document-specific configuration
Note: Documents cannot use null or "literal" body policies.
TypeSpec
Specification for custom attribute types with validation/parsing logic.
interface TypeSpec {
id: string;
parse?: (input: string) => any | { value: any; error?: string };
documentClasses?: string[];
}
Properties:
id- Unique identifier for the type (required)parse- Custom parsing/validation functiondocumentClasses- Document classes this type is scoped to (empty = all)
Parse Function Return Values:
- Direct value (any type) - success
{ value: any }- success with explicit value{ value: any, error: string }- success with warning{ error: string }- validation failure
EnumSpec
Specification for enumeration types with fixed allowed values.
interface EnumSpec {
id: string;
values: string[];
documentClasses?: string[];
}
Properties:
id- Unique identifier for the enum (required)values- Array of allowed string values (required)documentClasses- Document classes this enum is scoped to (empty = all)
AttributeSpec
Specification for defining attributes on elements or documents.
interface AttributeSpec {
id: string;
type?: string;
required?: boolean;
default?: any;
aliases?: string[];
description?: string;
}
Properties:
id- Attribute identifier (required)type- Type identifier (default:"string")required- Whether the attribute must be provided (default:false)default- Default value if not providedaliases- Alternative names for the attributedescription- Human-readable description
LibraryConfig
Configuration options for a library or document class.
interface LibraryConfig {
formatting?: FormattingOptions;
}
Properties:
formatting- Inline formatting options for text content
FormattingOptions
Inline formatting configuration.
interface FormattingOptions {
bold?: boolean;
italic?: boolean;
code?: boolean;
latex?: boolean;
links?: boolean;
}
Properties:
bold- Enable/disable**bold**syntax (default:true)italic- Enable/disable*italic*syntax (default:true)code- Enable/disable`code`syntax (default:true)latex- Enable/disable$math$syntax (default:true)links- Enable/disable[text](url)syntax (default:true)
Utility Types
ChalkError
Base interface for all dotchalk error types.
interface ChalkError {
name: string;
message: string;
code?: string;
context?: Record<string, any>;
}
Properties:
name- Error name/typemessage- Human-readable error messagecode- Optional error code for programmatic handlingcontext- Optional additional context
Implementing Error Classes:
Usage Examples
Working with Results
import chalk, { CompileResult, ChalkDocument } from '@jackhgns/dotchalk';
function compileDocument(source: string, lib: Library): ChalkDocument | null {
const result: CompileResult = chalk.compile(source, lib);
if (result.ok) {
return result.data;
} else {
console.error('Compilation failed:', result.error);
return null;
}
}
Type-Safe Element Processing
import { ChalkElement, ChalkAttribute } from '@jackhgns/dotchalk';
function findAttribute(
element: ChalkElement,
name: string
): ChalkAttribute | undefined {
return element.attributes.find(attr => attr.identifier === name);
}
function processElement(element: ChalkElement): void {
console.log(`Processing ${element.identifier}`);
const titleAttr = findAttribute(element, 'title');
if (titleAttr) {
console.log(` Title: ${titleAttr.value}`);
}
// Process nested elements
if (Array.isArray(element.body)) {
element.body.forEach(child => {
if (typeof child === 'object' && 'identifier' in child) {
processElement(child as ChalkElement);
}
});
}
}
Custom Type Parser
import { TypeSpec, Result } from '@jackhgns/dotchalk';
const emailType: TypeSpec = {
id: 'email',
parse: (input: string): Result<string> => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(input)) {
return { ok: false, error: 'Invalid email format' };
}
return { ok: true, data: input.toLowerCase() };
}
};
Error Handling
import {
CompileResult,
DocumentValidationError,
ElementValidationError
} from '@jackhgns/dotchalk';
function handleCompilationErrors(result: CompileResult): void {
if (!result.ok) {
console.error('Compilation failed:', result.error);
// You can also check for specific error types if thrown
try {
// ... compilation code
} catch (error) {
if (error instanceof DocumentValidationError) {
console.error('Document error:', error.document_class);
} else if (error instanceof ElementValidationError) {
console.error('Element error:', error.element_identifier);
}
}
}
}
See Also
- Library Reference - Using these types to build libraries
- Compiler Reference - Functions that return these types
- Primitives Reference - Built-in types available by default