Include Processor Extension Example

Purpose

Handle include directives targeting remote JSON files over HTTPS. When the as=attributes option is set, each key-value pair in the JSON object is injected as an AsciiDoc document attribute (:key: value). Without this option, the raw JSON content is included as-is.

versions.json

{
  "version": "3.1.0",
  "node-min": "18"
}

sample-versions-doc.adoc

include::https://raw.githubusercontent.com/org/repo/main/versions.json[as=attributes]

= Release Notes {version}

Requires Node.js >= {node-min}.

JsonIncludeProcessor

json-include-processor.js
export function register(registry) {
  registry.includeProcessor(function () {
    this.handles(target => target.startsWith('https://') && target.endsWith('.json'))
    this.process(async function (doc, reader, target, attrs) {
      const response = await fetch(target)
      const data = await response.json()
      const lines = attrs.as === 'attributes'
        ? Object.entries(data).map(([k, v]) => `:${k}: ${v}`)
        : [JSON.stringify(data, null, 2)]
      return reader.pushInclude(lines, target, target, 1, attrs)
    })
  })
}

Usage

API

import { Extensions, convert } from '@asciidoctor/core'
import { register } from './json-include-processor.js'

const registry = Extensions.create()
register(registry)

const html = await convert(
  'include::https://raw.githubusercontent.com/org/repo/main/versions.json[as=attributes]',
  { extension_registry: registry }
)
// The JSON keys are now available as document attributes:
// :version: 3.1.0
// :node-min: 18

CLI

$ asciidoctor --extension ./json-include-processor.js sample-versions-doc.adoc