logo

Markdown Rendering Simplified

tests ai-integration-tests GitHub license codecov npm npm

Features

Table of Contents

Getting Started

> npm install writr

Then you can use it like this:

import { Writr } from 'writr';

const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);

const html = await writr.render(); // <h1>Hello World πŸ™‚</h1><p>This is a test.</p>

Its just that simple. Want to add some options? No problem.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
const options  = {
	emoji: false
}
const html = await writr.render(options); // <h1>Hello World ::-):</h1><p>This is a test.</p>

An example passing in the options also via the constructor:

import { Writr, WritrOptions } from 'writr';
const writrOptions = {
  renderOptions: {
    emoji: true,
    toc: true,
    slug: true,
    highlight: true,
    gfm: true,
    math: true,
    mdx: true,
    rawHtml: false,
    caching: true,
  }
};
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`, writrOptions);
const html = await writr.render(options); // <h1>Hello World ::-):</h1><p>This is a test.</p>

API

new Writr(arg?: string | WritrOptions, options?: WritrOptions)

By default the constructor takes in a markdown string or WritrOptions in the first parameter. You can also send in nothing and set the markdown via .content property. If you want to pass in your markdown and options you can easily do this with new Writr('## Your Markdown Here', { ...options here}). You can access the WritrOptions from the instance of Writr. Here is an example of WritrOptions.

import { Writr, WritrOptions } from 'writr';
const writrOptions = {
  renderOptions: {
    emoji: true,
    toc: true,
    slug: true,
    highlight: true,
    gfm: true,
    math: true,
    mdx: true,
    rawHtml: false,
    caching: true,
  }
};
const writr = new Writr(writrOptions);

.content

Setting the markdown content for the instance of Writr. This can be set via the constructor or directly on the instance and can even handle frontmatter.


import { Writr } from 'writr';
const writr = new Writr();
writr.content = `---
title: Hello World
---
# Hello World ::-):\n\n This is a test.`;

.body

gets the body of the markdown content. This is the content without the frontmatter.

import { Writr } from 'writr';
const writr = new Writr();
writr.content = `---
title: Hello World
---
# Hello World ::-):\n\n This is a test.`;
console.log(writr.body); // '# Hello World ::-):\n\n This is a test.'

.options

Accessing the default options for this instance of Writr. Here is the default settings for WritrOptions. These are the default settings for the WritrOptions:

{
  renderOptions: {
    emoji: true,
    toc: true,
    slug: true,
    highlight: true,
    gfm: true,
    math: true,
    mdx: false,
    rawHtml: false,
    caching: true,
  }
}

By default, raw HTML in markdown (such as &lt;iframe&gt;, &lt;video&gt;, or &lt;div&gt; tags) is stripped during rendering. Set rawHtml: true to preserve raw HTML elements and their attributes in the rendered output. This is useful for embedding videos, widgets, or custom HTML in your markdown content.

Note: Setting mdx: true also enables raw HTML passthrough as part of the MDX specification. The rawHtml option is for enabling raw HTML in standard markdown without using MDX.

.frontmatter

Accessing the frontmatter for this instance of Writr. This is a Record&lt;string, any&gt; and can be set via the .content property.

import { Writr } from 'writr';
const writr = new Writr();
writr.content = `---
title: Hello World
---
# Hello World ::-):\n\n This is a test.`;
console.log(writr.frontmatter); // { title: 'Hello World' }

you can also set the front matter directly like this:

import { Writr } from 'writr';
const writr = new Writr();
writr.frontmatter = { title: 'Hello World' };

.frontMatterRaw

Accessing the raw frontmatter for this instance of Writr. This is a string and can be set via the .content property.

import { Writr } from 'writr';
const writr = new Writr();
writr.content = `---
title: Hello World
---
# Hello World ::-):\n\n This is a test.`;
console.log(writr.frontMatterRaw); // '---\ntitle: Hello World\n---'

.cache

Accessing the cache for this instance of Writr. By default this is an in memory cache and is disabled (set to false) by default. You can enable this by setting caching: true in the RenderOptions of the WritrOptions or when calling render passing the RenderOptions like here:

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
const options  = {
  caching: true
}
const html = await writr.render(options); // <h1>Hello World ::-):</h1><p>This is a test.</p>

.engine

Accessing the underlying engine for this instance of Writr. This is a Processor&lt;Root, Root, Root, undefined, undefined&gt; from the core unified project and uses the familiar .use() plugin pattern. You can chain additional unified plugins on this processor to customize the render pipeline. Learn more about the unified engine at unifiedjs.com and check out the getting started guide for examples.

.render(options?: RenderOptions)

Rendering markdown to HTML. the options are based on RenderOptions. Which you can access from the Writr instance.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
const html = await writr.render(); // <h1>Hello World πŸ™‚</h1><p>This is a test.</p>

//passing in with render options
const options  = {
  emoji: false
}

const html = await writr.render(options); // <h1>Hello World ::-):</h1><p>This is a test.</p>

.renderSync(options?: RenderOptions)

Rendering markdown to HTML synchronously. the options are based on RenderOptions. Which you can access from the Writr instance. The parameters are the same as the .render() function.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
const html = writr.renderSync(); // <h1>Hello World πŸ™‚</h1><p>This is a test.</p>

.renderToFile(filePath: string, options?: RenderOptions)

Rendering markdown to a file. The options are based on RenderOptions.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
await writr.renderToFile('path/to/file.html');

.renderToFileSync(filePath: string, options?: RenderOptions)

Rendering markdown to a file synchronously. The options are based on RenderOptions.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
writr.renderToFileSync('path/to/file.html');

.renderReact(options?: RenderOptions, reactOptions?: HTMLReactParserOptions)

Rendering markdown to React. The options are based on RenderOptions and now HTMLReactParserOptions from html-react-parser.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
const reactElement = await writr.renderReact(); // Will return a React.JSX.Element

.renderReactSync( options?: RenderOptions, reactOptions?: HTMLReactParserOptions)

Rendering markdown to React. The options are based on RenderOptions and now HTMLReactParserOptions from html-react-parser.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
const reactElement = writr.renderReactSync(); // Will return a React.JSX.Element

.validate(content?: string, options?: RenderOptions)

Validate markdown content by attempting to render it. Returns a WritrValidateResult object with a valid boolean and optional error property. Note that this will disable caching on render to ensure accurate validation.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World\n\nThis is a test.`);

// Validate current content
const result = await writr.validate();
console.log(result.valid); // true

// Validate external content without changing the instance
const externalResult = await writr.validate('## Different Content');
console.log(externalResult.valid); // true
console.log(writr.content); // Still "# Hello World\n\nThis is a test."

// Handle validation errors
const invalidWritr = new Writr('Put invalid markdown here');
const errorResult = await invalidWritr.validate();
console.log(errorResult.valid); // false
console.log(errorResult.error?.message); // "Invalid plugin"

.validateSync(content?: string, options?: RenderOptions)

Synchronously validate markdown content by attempting to render it. Returns a WritrValidateResult object with a valid boolean and optional error property.

This is the synchronous version of .validate() with the same parameters and behavior.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World\n\nThis is a test.`);

// Validate current content synchronously
const result = writr.validateSync();
console.log(result.valid); // true

// Validate external content without changing the instance
const externalResult = writr.validateSync('## Different Content');
console.log(externalResult.valid); // true
console.log(writr.content); // Still "# Hello World\n\nThis is a test."

.loadFromFile(filePath: string)

Load your markdown content from a file path.

import { Writr } from 'writr';
const writr = new Writr();
await writr.loadFromFile('path/to/file.md');

.loadFromFileSync(filePath: string)

Load your markdown content from a file path synchronously.

import { Writr } from 'writr';
const writr = new Writr();
writr.loadFromFileSync('path/to/file.md');

.saveToFile(filePath: string)

Save your markdown and frontmatter (if included) content to a file path.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
await writr.saveToFile('path/to/file.md');

.saveToFileSync(filePath: string)

Save your markdown and frontmatter (if included) content to a file path synchronously.

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
writr.saveToFileSync('path/to/file.md');

Caching On Render

Caching is built into Writr and is an in-memory cache using CacheableMemory from Cacheable. It is turned off by default and can be enabled by setting caching: true in the RenderOptions of the WritrOptions or when calling render passing the RenderOptions like here:

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`, { renderOptions: { caching: true } });

or via RenderOptions such as:

import { Writr } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
await writr.render({ caching: true});

If you want to set the caching options for the instance of Writr you can do so like this:

// we will set the lruSize of the cache and the default ttl
import {Writr} from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`, { renderOptions: { caching: true } });
writr.cache.store.lruSize = 100;
writr.cache.store.ttl = '5m'; // setting it to 5 minutes

GitHub Flavored Markdown (GFM)

Writr includes full support for GitHub Flavored Markdown (GFM) through the remark-gfm and remark-github-blockquote-alert plugins. GFM is enabled by default and adds several powerful features to standard Markdown.

GFM Features

When GFM is enabled (which it is by default), you get access to the following features:

Tables

Create tables using pipes and hyphens:

| Feature | Supported |
|---------|-----------|
| Tables  | Yes       |
| Alerts  | Yes       |

Strikethrough

Use ~~ to create strikethrough text:

~~This text is crossed out~~

Task Lists

Create interactive checkboxes:

- [x] Completed task
- [ ] Incomplete task
- [ ] Another task

URLs are automatically converted to clickable links:

https://github.com

GitHub Blockquote Alerts

GitHub-style alerts are supported to emphasize critical information. These are blockquote-based admonitions that render with special styling:

> [!NOTE]
> Useful information that users should know, even when skimming content.

> [!TIP]
> Helpful advice for doing things better or more easily.

> [!IMPORTANT]
> Key information users need to know to achieve their goal.

> [!WARNING]
> Urgent info that needs immediate user attention to avoid problems.

> [!CAUTION]
> Advises about risks or negative outcomes of certain actions.

Using GFM

GFM is enabled by default. Here's an example:

import { Writr } from 'writr';

const markdown = `
# Task List Example

- [x] Learn Writr basics
- [ ] Master GFM features

> [!NOTE]
> GitHub Flavored Markdown is enabled by default!

| Feature | Status |
|---------|--------|
| GFM     | βœ“      |
`;

const writr = new Writr(markdown);
const html = await writr.render(); // Renders with full GFM support

Disabling GFM

If you need to disable GFM features, you can set gfm: false in the render options:

import { Writr } from 'writr';

const writr = new Writr('~~strikethrough~~ text');

// Disable GFM
const html = await writr.render({ gfm: false });
// Output: <p>~~strikethrough~~ text</p>

// With GFM enabled (default)
const htmlWithGfm = await writr.render({ gfm: true });
// Output: <p><del>strikethrough</del> text</p>

Note: When GFM is disabled, GitHub blockquote alerts will not be processed and will render as regular blockquotes.

Hooks

Hooks are a way to add additional parsing to the render pipeline. You can add hooks to the the Writr instance. Here is an example of adding a hook to the instance of Writr:

import { Writr, WritrHooks } from 'writr';
const writr = new Writr(`# Hello World ::-):\n\n This is a test.`);
writr.onHook(WritrHooks.beforeRender, data => {
  data.body = 'Hello, Universe!';
});
const result = await writr.render();
console.log(result); // Hello, Universe!

For beforeRender the data object is a renderData object. Here is the interface for renderData:

export type renderData = {
  body: string
  options: RenderOptions;
}

For afterRender the data object is a resultData object. Here is the interface for resultData:

export type resultData = {
  result: string;
}

For saveToFile the data object is an object with the filePath and content. Here is the interface for saveToFileData:

export type saveToFileData = {
  filePath: string;
  content: string;
}

This is called when you call saveToFile, saveToFileSync.

For renderToFile the data object is an object with the filePath and content. Here is the interface for renderToFileData:

export type renderToFileData = {
  filePath: string;
  content: string;
}

This is called when you call renderToFile, renderToFileSync.

For loadFromFile the data object is an object with content so you can change before it is set on writr.content. Here is the interface for loadFromFileData:

export type loadFromFileData = {
  content: string;
}

This is called when you call loadFromFile, loadFromFileSync.

Emitters

Writr extends the Hookified class, which provides event emitter capabilities. This means you can listen to events emitted by Writr during its lifecycle, particularly error events.

Error Events

Writr emits an error event whenever an error occurs in any of its methods. This provides a centralized way to handle errors without wrapping every method call in a try/catch block.

Listening to Error Events

You can listen to error events using the .on() method:

import { Writr } from 'writr';

const writr = new Writr('# Hello World');

// Listen for any errors
writr.on('error', (error) => {
  console.error('An error occurred:', error.message);
  // Handle the error appropriately
  // Log to error tracking service, display to user, etc.
});

// With a listener registered, errors are emitted to the listener
// and the method returns its fallback value (e.g. "" for render)
const html = await writr.render();

Methods that Emit Errors

All methods use an emit-only error pattern β€” they call this.emit('error', error) but never explicitly re-throw. If no error listener is registered and throwOnEmptyListeners is true (the default), the emit('error') call itself will throw, following standard Node.js EventEmitter behavior.

Rendering Methods β€” emit error, return "":

Validation Methods:

File Operations β€” emit error, return void:

Front Matter Operations β€” emit error, return fallback:

Error Event Examples

Example 1: Global Error Handler

import { Writr } from 'writr';

const writr = new Writr();

// Set up a global error handler
writr.on('error', (error) => {
  // Log to your monitoring service
  console.error('Writr error:', error);

  // Send to error tracking (e.g., Sentry, Rollbar)
  // errorTracker.captureException(error);
});

// All errors will be emitted to the listener above
await writr.loadFromFile('./content.md');
const html = await writr.render();

Example 2: Validation with Error Listening

import { Writr } from 'writr';

const writr = new Writr('# My Content');
let lastError = null;

writr.on('error', (error) => {
  lastError = error;
});

const result = await writr.validate();

if (!result.valid) {
  console.log('Validation failed');
  console.log('Error details:', lastError);
  // result.error is also available
}

Example 3: File Operations Without Try/Catch

import { Writr } from 'writr';

const writr = new Writr('# Content');

writr.on('error', (error) => {
  console.error('File operation failed:', error.message);
  // Handle gracefully - maybe use default content
});

// With a listener registered, errors are emitted and the method returns normally
await writr.loadFromFile('./maybe-missing.md');
// Note: without a listener, this will throw by default (throwOnEmptyListeners is true)

Event Emitter Methods

Since Writr extends Hookified, you have access to standard event emitter methods:

For more information about event handling capabilities, see the Hookified documentation.

AI

Writr includes built-in AI capabilities for metadata generation, SEO, and translation powered by the Vercel AI SDK. Plug in any supported model provider (OpenAI, Anthropic, Google, etc.) via the ai option.

import { Writr } from 'writr';
import { openai } from '@ai-sdk/openai';

const writr = new Writr('# My Document\n\nSome markdown content here.', {
  ai: { model: openai('gpt-4.1-mini') },
});

// Generate metadata
const metadata = await writr.ai.getMetadata();

// Generate only specific fields
const metadata = await writr.ai.getMetadata({ title: true, description: true });

// Generate SEO metadata
const seo = await writr.ai.getSEO();

// Translate to Spanish
const translated = await writr.ai.getTranslation({ to: 'es' });

// Apply generated metadata to frontmatter
const result = await writr.ai.applyMetadata({
  generate: { description: true, category: true },
  overwrite: true,
});

AI Options

Pass ai in the WritrOptions to enable AI features:

Property Type Required Description
model LanguageModel Yes The AI SDK model instance (e.g. openai("gpt-4.1-mini")).
cache boolean No Enables in-memory caching of AI results.
prompts WritrAIPrompts No Custom prompt overrides for metadata, SEO, and translation.
const writr = new Writr('# My Document', {
  ai: {
    model: openai('gpt-4.1-mini'),
    cache: true,
  },
});

AI Provider Configuration

By default, the provider imports read API keys from environment variables:

Provider Import Environment Variable
OpenAI openai from @ai-sdk/openai OPENAI_API_KEY
Anthropic anthropic from @ai-sdk/anthropic ANTHROPIC_API_KEY
Google google from @ai-sdk/google GOOGLE_GENERATIVE_AI_API_KEY
// Uses OPENAI_API_KEY from environment
import { openai } from '@ai-sdk/openai';

const writr = new Writr('# Hello', { ai: { model: openai('gpt-4.1-mini') } });

To set API keys programmatically, use the provider factory functions instead:

import { Writr } from 'writr';
import { createOpenAI } from '@ai-sdk/openai';
import { createAnthropic } from '@ai-sdk/anthropic';
import { createGoogleGenerativeAI } from '@ai-sdk/google';

// OpenAI
const openai = createOpenAI({ apiKey: 'your-openai-key' });
const writr = new Writr('# Hello', { ai: { model: openai('gpt-4.1-mini') } });

// Anthropic
const anthropic = createAnthropic({ apiKey: 'your-anthropic-key' });
const writr = new Writr('# Hello', { ai: { model: anthropic('claude-sonnet-4-20250514') } });

// Google
const google = createGoogleGenerativeAI({ apiKey: 'your-google-key' });
const writr = new Writr('# Hello', { ai: { model: google('gemini-2.0-flash') } });

Metadata

Generate metadata from your document content using writr.ai.getMetadata(), or generate and apply it directly to frontmatter with writr.ai.applyMetadata().

Generating Metadata

getMetadata() analyzes the document and returns a WritrMetadata object. By default all fields are generated. Pass options to select specific fields.

// Generate all metadata fields
const metadata = await writr.ai.getMetadata();
console.log(metadata.title);       // "Getting Started with Writr"
console.log(metadata.tags);        // ["markdown", "rendering", "typescript"]
console.log(metadata.description); // "A guide to using Writr for markdown processing."
console.log(metadata.readingTime); // 3 (minutes)
console.log(metadata.wordCount);   // 450

// Generate only specific fields
const partial = await writr.ai.getMetadata({
  title: true,
  description: true,
  tags: true,
});

Generated fields:

Field Type Description
title string The best-fit title for the document.
description string A concise meta-style description of the document.
tags string[] Human-friendly labels for organizing the document.
keywords string[] Search-oriented terms related to the document content.
preview string A short teaser or preview snippet of the content.
summary string A slightly longer overview of the document.
category string A broad grouping such as "docs", "guide", or "blog".
topic string The primary subject the document is about.
audience string The intended audience for the document.
difficulty "beginner" | "intermediate" | "advanced" The estimated skill level required.
readingTime number Estimated reading time in minutes (computed, not AI-generated).
wordCount number Total word count of the document (computed, not AI-generated).

Constraining Generated Values

When you have a controlled vocabulary β€” for example a CMS taxonomy, a fixed set of categories, or an SEO keyword list β€” pass allowedTags, allowedKeywords, or allowedCategories and the AI will pick only from that list. When omitted, the AI generates freely.

const metadata = await writr.ai.getMetadata({
  allowedTags: ['javascript', 'typescript', 'python', 'rust'],
  allowedKeywords: ['async', 'promises', 'callbacks'],
  allowedCategories: ['tutorial', 'guide', 'reference', 'blog'],
});

// metadata.tags is guaranteed to be a subset of allowedTags
// metadata.category is guaranteed to be one of allowedCategories
Option Type Description
allowedTags string[] Constrains AI-generated tags to this list. A non-empty array implicitly enables tags.
allowedKeywords string[] Constrains AI-generated keywords to this list. A non-empty array implicitly enables keywords.
allowedCategories string[] Constrains AI-generated category to one of these values. A non-empty array implicitly enables category.

How the constraint is enforced

The constraint is applied on three reinforcing layers, so the model both knows about and is prevented from violating the list:

  1. Schema enforcement (the hard guarantee). The Zod response schema uses z.array(z.enum(allowedTags)) for tags, z.array(z.enum(allowedKeywords)) for keywords, and z.enum(allowedCategories) for category. The AI SDK's structured-output mode forces the model to return values from the enum β€” it literally cannot produce anything outside the list.
  2. Prompt instruction. A Constraints: block is appended to the prompt with lines like Tags must be selected from: foo, bar, baz and Category must be one of: tutorial, guide, reference, so the model also sees the list in natural language.
  3. Schema field description. The Zod field description is rewritten to inline the allowed values (e.g. Human-friendly labels selected from: foo, bar, baz), which most providers surface to the model alongside the schema.

Behavior notes

// Implicit enablement: tags is generated, even without `tags: true`
const metadata = await writr.ai.getMetadata({
  allowedTags: ['docs', 'guide', 'blog'],
});

// Explicit `false` wins: tags is not generated
const metadata = await writr.ai.getMetadata({
  tags: false,
  allowedTags: ['docs', 'guide', 'blog'],
});

Applying Metadata to Frontmatter

applyMetadata() generates metadata and writes it into the document's frontmatter. The result tells you exactly what happened:

const result = await writr.ai.applyMetadata();
console.log(result.applied);     // ["description", "tags", "category"]
console.log(result.skipped);     // ["title"] (already existed)
console.log(result.overwritten); // []

Overwrite

By default, applyMetadata() only fills in missing fields β€” existing frontmatter values are never touched. The overwrite option changes this behavior:

// Overwrite all generated fields, even if they already exist
const result = await writr.ai.applyMetadata({
  generate: { title: true, description: true },
  overwrite: true,
});

// Only overwrite title, leave description alone if it already exists
const result = await writr.ai.applyMetadata({
  generate: { title: true, description: true, category: true },
  overwrite: ['title'],
});

Field Mapping

The fieldMap option maps generated metadata keys to different frontmatter field names. This is useful when your frontmatter schema uses different naming conventions than the default metadata keys.

const result = await writr.ai.applyMetadata({
  generate: { description: true, tags: true },
  fieldMap: {
    description: 'meta_description',
    tags: 'labels',
  },
});
// writr.frontMatter.meta_description === "A guide to..."
// writr.frontMatter.labels === ["markdown", "rendering"]

The mapping applies to all behaviors β€” field existence checks, overwrites, and skips all use the mapped key when checking frontmatter.

SEO

Generate SEO metadata using writr.ai.getSEO(). By default all fields are generated. Pass options to select specific fields.

const seo = await writr.ai.getSEO();
console.log(seo.slug);              // "getting-started-with-writr"
console.log(seo.openGraph?.title);  // "Getting Started with Writr"

// Generate only a slug
const seo = await writr.ai.getSEO({ slug: true });

Available fields: slug, openGraph (includes title, description, image).

Translation

Translate the document into another language using writr.ai.getTranslation(). Returns a new Writr instance with the translated content.

const spanish = await writr.ai.getTranslation({ to: 'es' });
console.log(spanish.body); // Spanish markdown

// With source language and frontmatter translation
const french = await writr.ai.getTranslation({
  to: 'fr',
  from: 'en',
  translateFrontMatter: true,
});
Option Type Required Description
to string Yes Target language or locale.
from string No Source language or locale.
translateFrontMatter boolean No Also translate frontmatter string values.

Using WritrAI Directly

WritrAI is exported as a named export and can be instantiated independently from the Writr constructor. This is useful when you want to configure the AI instance separately or swap models on the fly.

import { Writr, WritrAI } from 'writr';
import { openai } from '@ai-sdk/openai';

const writr = new Writr('# My Document\n\nSome markdown content here.');
const ai = new WritrAI(writr, {
  model: openai('gpt-4.1-mini'),
  cache: true,
});

// Generate metadata
const metadata = await ai.getMetadata();
console.log(metadata.title);
console.log(metadata.tags);

// Generate SEO data
const seo = await ai.getSEO();
console.log(seo.slug);

// Translate
const translated = await ai.getTranslation({ to: 'es' });
console.log(translated.body);

// Apply metadata to frontmatter
const result = await ai.applyMetadata({
  generate: { title: true, description: true, tags: true },
  overwrite: true,
});

Migrating to v6

Writr v6 upgrades hookified from v1 to v2 and removes throwErrors in favor of hookified's built-in error handling options.

Breaking Changes

throwErrors removed

The throwErrors option has been removed from WritrOptions. Use throwOnEmitError instead, which is provided by hookified's HookifiedOptions (now spread into WritrOptions).

Before (v5):

const writr = new Writr('# Hello', { throwErrors: true });

After (v6):

const writr = new Writr('# Hello', { throwOnEmitError: true });

Error handling redesign

All methods now use an emit-only pattern β€” errors are emitted via emit('error', error) but never explicitly re-thrown. Methods return fallback values on error ("" for render methods, {} for frontMatter getter, { valid: false, error } for validate).

How errors propagate:

Other changes:

hookified v2

Writr now uses hookified v2 which introduces several new options available through WritrOptions:

See the hookified documentation for full details.

Unified Processor Engine

Writr builds on top of the open source unified processor – the core project that powers remark, rehype, and many other content tools. Unified provides a pluggable pipeline where each plugin transforms a syntax tree. Writr configures a default set of plugins to turn Markdown into HTML, but you can access the processor through the .engine property to add your own behavior with writr.engine.use(myPlugin). The unified documentation has more details and guides for building plugins and working with the processor directly.

Benchmarks

This is a comparison with minimal configuration where we have disabled all rendering pipeline and just did straight caching + rendering to compare it against the fastest:

name summary ops/sec time/op margin samples
Writr (Sync) (Caching) πŸ₯‡ 83K 14Β΅s Β±0.27% 74K
Writr (Async) (Caching) -3% 80K 14Β΅s Β±0.27% 71K
markdown-it -30% 58K 20Β΅s Β±0.37% 50K
marked -33% 56K 25Β΅s Β±0.50% 40K
Writr (Sync) -94% 5K 225Β΅s Β±0.88% 10K
Writr (Async) -94% 5K 229Β΅s Β±0.89% 10K

As you can see this module is performant with caching enabled but was built to be performant enough but with all the features added in. If you are just wanting performance and not features then markdown-it or marked is the solution unless you use Writr with caching.

name summary ops/sec time/op margin samples
Writr (Async) (Caching) πŸ₯‡ 26K 39Β΅s Β±0.12% 25K
Writr (Sync) (Caching) -0.92% 26K 40Β΅s Β±0.15% 25K
Writr (Sync) -93% 2K 630Β΅s Β±0.97% 10K
Writr (Async) -93% 2K 649Β΅s Β±0.96% 10K

The benchmark shows rendering performance via Sync and Async methods with caching enabled and disabled and all features.

ESM and Node Version Support

This package is ESM only and tested on the current lts version and its previous. Please don't open issues for questions regarding CommonJS / ESM or previous Nodejs versions.

Code of Conduct and Contributing

Please use our Code of Conduct and Contributing guidelines for development and testing. We appreciate your contributions!

License

MIT & Β© Jared Wray

Contributors

Changelog

v6.1.6 September 17, 2026

[email protected] β€” 2026-09-17

Supply-chain hardening and unpublished writr-rs fixes; JS engine source is unchanged.

Bug Fixes

  • restore writr-rs goldens on Windows CRLF checkouts β€” unify CR/CRLF to LF before parse so markdown-rs does not keep CR in mdast text (#516)
  • copy async batch buffer input so callers can reuse the packed buffer after `renderBatchBufferAsync` (#540)
  • lock down the Node WASI loader: instantiate WASI with preview1 only (no `process.env`, no filesystem preopens) (#545)
  • bound internal math caches and honor `caching: false` without clearing other callers' entries (#546)
  • gate Rust/WASM parity and fix MDX rendering compatibility in writr-rs (#547)

Documentation

  • retire obsolete Rust divergence document (#549)

Internal

  • upgrade code quality dependencies (#490)
  • upgrade TypeScript and build tooling (#491)
  • upgrade package manager tooling (#492)
  • upgrade GitHub Actions (#493)
  • upgrade React dependencies (#494)
  • upgrade AI SDK dependencies (#495)
  • upgrade hookified (#496)
  • upgrade js-yaml (#497)
  • upgrade marked (#498)
  • upgrade markdown-it (#499)
  • upgrade tinybench (#500)
  • upgrade workspace code quality dependencies (#501)
  • refresh taiki-e/install-action SHA pin (#502)
  • upgrade napi-rs dependencies (#503)
  • upgrade fancy-regex to 0.19.0 (#504)
  • upgrade rquickjs to 0.12.2 (#505)
  • harden supply chain and CI (#506)
  • stage npm releases via OIDC (#507)
  • record npm stage-only, Drydock, and 2FA (#508)
  • replace dummy secrets in benchmark markdown fixtures (#509)
  • record repository lockdown (#510)
  • upgrade katex to 0.18.2 (AIKIDO-2026-293837) (#511)
  • pin `@ungap/structured-clone` to 1.3.3 (AIKIDO-2026-11068) (#512)
  • uniquify AI integration check name (#513)
  • replace dummy secrets in harness markdown fixtures (#514)
  • add CODEOWNERS for high-risk paths (#517)
  • bootstrap Aikido Safe Chain (#518)
  • set pnpm `trustPolicy` to `no-downgrade` (#519)
  • add Socket Firewall to every job (#520)
  • switch release to `pnpm stage` (#521)
  • record repository lockdown (#522)
  • pin taiki-e/install-action to an authentic v2.86.5 SHA (#523)
  • disable setup-node cache in deploy-site to prevent cache poisoning (#524)
  • remove property-information override (#525)
  • update katex override to 0.18.7 (#526)
  • remove `@ungap/structured-clone` override (#527)
  • upgrade code quality dependencies (#528)
  • upgrade TypeScript and build tooling (#529)
  • upgrade package manager and monorepo tooling (#530)
  • upgrade GitHub Actions (#531)
  • pin Dev Container images (#532)
  • upgrade React dependencies (#533)
  • upgrade AI SDK dependencies (#534)
  • upgrade hookified (#535)
  • upgrade js-yaml (#536)
  • upgrade zod (#537)
  • upgrade docula (#538)
  • remove undici override (#539)
  • upgrade markdown-it (#541)
  • upgrade marked (#542)
  • upgrade tinybench (#543)
  • upgrade property-information (#544)
  • compare native Rust and JavaScript rendering (#548)

Notes

  • `src/` is unchanged since `v6.1.5`.** The published tarball is still `files: ["dist", "README.md", "LICENSE"]`; `writr-rs/` is not published. Runtime source matches 6.1.5. The tarball-affecting changes are production dependency ranges in `package.json` (`hookified`, `js-yaml`, `react`, `html-react-parser`, `zod`, `ai`) plus scripts/`packageManager`. The katex `0.18.7` and `property-information` `7.2.0` pins live in `pnpm-workspace.yaml` (this repo’s install), not in the npm tarball.
  • Titles that include `(breaking)` are upgrades of dev tools or unpublished Rust crates, not writr’s public JS API.

Contributors

  • @jaredwray (62)

Full List of Changes

  • root - chore: upgrade code quality dependencies by @jaredwray in #490
  • root - chore: upgrade TypeScript and build tooling (breaking) by @jaredwray in #491
  • root - chore: upgrade package manager tooling by @jaredwray in #492
  • root - chore: upgrade GitHub Actions (breaking) by @jaredwray in #493
  • root - chore: upgrade React dependencies by @jaredwray in #494
  • root - chore: upgrade AI SDK dependencies by @jaredwray in #495
  • root - chore: upgrade hookified by @jaredwray in #496
  • root - chore: upgrade js-yaml by @jaredwray in #497
  • root - chore: upgrade marked by @jaredwray in #498
  • root - chore: upgrade markdown-it (breaking) by @jaredwray in #499
  • root - chore: upgrade tinybench by @jaredwray in #500
  • workspace - chore: upgrade code quality dependencies (breaking) by @jaredwray in #501
  • workspace - chore: upgrade GitHub Actions by @jaredwray in #502
  • workspace - chore: upgrade napi dependencies by @jaredwray in #503
  • workspace - chore: upgrade fancy-regex to 0.19.0 (breaking) by @jaredwray in #504
  • workspace - chore: upgrade rquickjs to 0.12.2 by @jaredwray in #505
  • writr - chore: defense - harden supply chain and CI by @jaredwray in #506
  • writr - chore: defense - stage npm releases via OIDC by @jaredwray in #507
  • writr - chore: defense - record npm stage-only, Drydock, and 2FA by @jaredwray in #508
  • chore: replace dummy secrets in benchmark markdown fixtures by @jaredwray in #509
  • chore: upgrade katex to 0.18.2 (AIKIDO-2026-293837) by @jaredwray in #511
  • writr - chore: defense - record repository lockdown by @jaredwray in #510
  • chore: pin @ungap/structured-clone to 1.3.3 (AIKIDO-2026-11068) by @jaredwray in #512
  • writr - chore: defense - uniquify AI integration check name by @jaredwray in #513
  • chore: replace dummy secrets in harness markdown fixtures by @jaredwray in #514
  • fix: restore writr-rs goldens on Windows CRLF checkouts by @jaredwray in #516
  • writr - chore: defense - add CODEOWNERS for high-risk paths by @jaredwray in #517
  • writr - chore: defense - bootstrap Aikido Safe Chain by @jaredwray in #518
  • writr - chore: defense - set pnpm trustPolicy no-downgrade by @jaredwray in #519
  • writr - chore: defense - add Socket Firewall to every job by @jaredwray in #520
  • writr - chore: defense - switch release to pnpm stage by @jaredwray in #521
  • writr - chore: defense - record repository lockdown by @jaredwray in #522
  • ci: pin taiki-e/install-action to an authentic v2.86.5 SHA by @jaredwray in #523
  • ci: disable setup-node cache in deploy-site to prevent cache poisoning by @jaredwray in #524
  • mono - chore: remove property-information override by @jaredwray in #525
  • mono - chore: update katex override by @jaredwray in #526
  • mono - chore: remove @ungap/structured-clone override by @jaredwray in #527
  • mono - chore: upgrade code quality dependencies by @jaredwray in #528
  • mono - chore: upgrade TypeScript and build tooling by @jaredwray in #529
  • mono - chore: upgrade package manager and monorepo tooling by @jaredwray in #530
  • mono - chore: upgrade GitHub Actions by @jaredwray in #531
  • mono - chore: pin Dev Container images by @jaredwray in #532
  • mono - chore: upgrade React dependencies by @jaredwray in #533
  • mono - chore: upgrade AI SDK dependencies by @jaredwray in #534
  • mono - chore: upgrade hookified by @jaredwray in #535
  • mono - chore: upgrade js-yaml by @jaredwray in #536
  • mono - chore: upgrade zod by @jaredwray in #537
  • mono - chore: upgrade docula by @jaredwray in #538
  • mono - chore: remove undici override by @jaredwray in #539
  • Fix async batch buffer ownership by @jaredwray in #540
  • mono - chore: upgrade markdown-it by @jaredwray in #541
  • mono - chore: upgrade marked by @jaredwray in #542
  • mono - chore: upgrade tinybench by @jaredwray in #543
  • mono - chore: upgrade property-information by @jaredwray in #544
  • Lock down the Node WASI loader: no host env or filesystem by @jaredwray in #545
  • fix: bound internal math caches and honor caching: false by @jaredwray in #546
  • test: gate Rust/WASM parity and fix MDX rendering compatibility by @jaredwray in #547
  • bench: compare native Rust and JavaScript rendering by @jaredwray in #548
  • docs: retire obsolete Rust divergence document by @jaredwray in #549

Full diff: https://github.com/jaredwray/writr/compare/v6.1.5...v6.1.6

v6.1.5 July 25, 2026

[email protected] β€” 2026-07-25

Widens `engines.node` to allow Node 24+; adds the unpublished `writr-rs` Rust engine workspace.

Bug Fixes

  • allow Node 24+ in `engines.node` β€” `^22.18.0` resolves to `>=22.18.0 <23.0.0`, excluding the Node versions writr is tested on, so installs under `engine-strict=true` aborted with `ERR_PNPM_UNSUPPORTED_ENGINE` (cf8efa4, #488)

Internal

  • writr-rs: byte-exact Rust markdown engine β€” Cargo workspace with a commonmark-exact core, GFM alerts, toc/emoji/slug transforms, raw-HTML replay over html5ever, a highlight.js 11.11.1 engine port, and a KaTeX 0.16.45 bridge (097608b, 5997924, 684b143, 0ddec57, fc83338, f425e5f, #487)
  • writr-rs: napi bindings (native + wasm32-wasip1 + browser ESM) with golden-harness parity across all 2,041 goldens on seven profiles, plus packed `renderBatchBuffer` batch rendering (a51b7d6, bacd8d9, 126ca04, #487)
  • writr-rs: optimization pass β€” streaming serializer, copy-free hljs hot loop, 40-byte `u32` parser events, `wasm-opt -O3` + SIMD128, opt-in PGO build (87e09f0, 708a55e, 06c0fa4, 758e6ef, ef79f3c, a77fe00, f97d743, #487)
  • add `build:rs`, `build:rs:wasm`, and `build:rs:pgo` scripts plus `benchmark/benchmark-rust.ts` (#487)
  • add `.github/workflows/writr-rs.yml` β€” fmt, clippy `-D warnings`, tests, coverage gate, codegen-freshness check, harness parity, native build matrix (b676fde, e68b3c4, edaa457, b19791f, #487)
  • refresh performance numbers after the M10 optimization pass (e88ce86, #487)
  • pin browser install to the pinned playwright-core (f70fa36, #488)

Notes

  • The published package's runtime is unchanged in this release. `src/**` has zero changes since `v6.1.4`, so `dist/` builds byte-identical to `6.1.4`. `writr-rs/` is not part of the npm tarball (`files: ["dist", "README.md", "LICENSE"]`) β€” it is built from source via `pnpm build:rs`. The only tarball-affecting change is the `engines.node` widening, which is why this is a patch rather than a minor.

Contributors

  • @jaredwray (23 β€” writr-rs commits agent-authored)

Full List of Changes

  • writr-rs: byte-exact Rust markdown engine (native + wasm + browser) with multi-core rendering by @jaredwray in #487
  • root - fix: allow Node 24+ in engines.node by @jaredwray in #488

Full diff: https://github.com/jaredwray/writr/compare/v6.1.4...v6.1.5

v6.1.4 July 15, 2026

[email protected] β€” 2026-07-15

Dependency maintenance sweep: refresh dev and runtime dependencies β€” including the AI SDK (v7) and js-yaml (v5) majors β€” with no changes to writr's own API.

Internal

  • upgrade code quality dependencies β€” biome 2.5.3, vitest & coverage-v8 4.1.10 (9eec344, #472)
  • upgrade TypeScript & build tooling β€” tsx 4.23.0, tsdown 0.22.5, @types/node 24.13.3 (311a4e6, #473)
  • upgrade GitHub Actions majors β€” checkout v7, setup-node v7, pnpm/action-setup v6, codecov v7, wrangler v4 (7712657, #475)
  • upgrade tsx 4.23.1 & tsdown 0.22.7 (09aaf63, #476)
  • upgrade marked 18.0.6 & markdown-it 14.3.0 (b4c31e7, #477)
  • upgrade docula 2.2.0 (f180192, #478)
  • upgrade cacheable 2.5.0 (f92029c, #479)
  • upgrade hashery 3.0.1 (7c40bba, #480)
  • upgrade hookified 3.0.1 (9bd5293, #481)
  • upgrade html-react-parser 6.1.4 (bd2136f, #482)
  • upgrade AI SDK to v7 β€” ai 7.0.23, @ai-sdk/* 4.x (2bf2be5, d6bb09f, #483, #485)
  • upgrade js-yaml to v5; drop now-redundant @types/js-yaml (0610007, #484)
  • add npm homepage & bugs metadata (8d1e4b0, #471)

Notes

  • AI SDK v7 (runtime): consumers of the `WritrAI` feature should supply AI SDK v7-compatible model providers (e.g. `@ai-sdk/anthropic@4`).
  • TypeScript 7 was intentionally deferred (experimental native compiler API; revisit when stable).

Contributors

  • @jaredwray (13, dependency sweep β€” commits automated)
  • @jiapengwang-code (1)

Full List of Changes

  • add npm homepage and bugs metadata by @jiapengwang-code in #471
  • upgrade code quality dependencies by @jaredwray in #472
  • upgrade TypeScript and build tooling by @jaredwray in #473
  • upgrade GitHub Actions (breaking) by @jaredwray in #475
  • upgrade tsx and tsdown by @jaredwray in #476
  • upgrade marked and markdown-it by @jaredwray in #477
  • upgrade docula by @jaredwray in #478
  • upgrade cacheable by @jaredwray in #479
  • upgrade hashery by @jaredwray in #480
  • upgrade hookified by @jaredwray in #481
  • upgrade html-react-parser by @jaredwray in #482
  • upgrade ai SDK to v7 (breaking) by @jaredwray in #483
  • upgrade js-yaml to v5 (breaking) by @jaredwray in #484
  • upgrade ai to 7.0.23 by @jaredwray in #485

Full diff: https://github.com/jaredwray/writr/compare/v6.1.3...v6.1.4

Full Changelog