Skip to the content.

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:

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:

ContentPolicy

Defines what types of content are allowed within elements and documents.

type ContentPolicy =
  | null
  | "literal"
  | "all"
  | string[]
  | string;

Values:

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:

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:

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:

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:


Element Types

ChalkElement

Represents a compiled element within a document.

interface ChalkElement {
  instance_id: string;
  identifier: string;
  body: ElementContent;
  detail: ElementContent;
  attributes: ChalkAttribute[];
}

Properties:

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:

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:


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:

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:


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:

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:

InlineElementSpec

Specification object for defining inline element types.

interface InlineElementSpec {
  id: string;
  aliases?: string[];
  body?: InlinePolicy;
  attributes?: AttributeSpec[];
  shorthand?: string;
  documentClasses?: string[];
}

Properties:

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:

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:

Parse Function Return Values:

EnumSpec

Specification for enumeration types with fixed allowed values.

interface EnumSpec {
  id: string;
  values: string[];
  documentClasses?: string[];
}

Properties:

AttributeSpec

Specification for defining attributes on elements or documents.

interface AttributeSpec {
  id: string;
  type?: string;
  required?: boolean;
  default?: any;
  aliases?: string[];
  description?: string;
}

Properties:

LibraryConfig

Configuration options for a library or document class.

interface LibraryConfig {
  formatting?: FormattingOptions;
}

Properties:

FormattingOptions

Inline formatting configuration.

interface FormattingOptions {
  bold?: boolean;
  italic?: boolean;
  code?: boolean;
  latex?: boolean;
  links?: boolean;
}

Properties:


Utility Types

ChalkError

Base interface for all dotchalk error types.

interface ChalkError {
  name: string;
  message: string;
  code?: string;
  context?: Record<string, any>;
}

Properties:

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