unified

  • Version 11.0.5
  • Published
  • 146 kB
  • 7 dependencies
  • MIT license

Install

npm i unified
yarn add unified
pnpm add unified

Overview

parse, inspect, transform, and serialize content through syntax trees

Index

Variables

variable emptyObjectSymbol

const emptyObjectSymbol: Symbol;

    variable unified

    const unified: Processor<undefined, undefined, undefined, undefined, undefined>;
    • Create a new processor.

      Returns

      New *unfrozen* processor (processor).

      This processor is configured to work the same as its ancestor. When the descendant processor is configured in the future it does not affect the ancestral processor.

      Example 1

      This example shows how a new processor can be created (from remark) and linked to **stdin**(4) and **stdout**(4).

      ```js import process from 'node:process' import concatStream from 'concat-stream' import {remark} from 'remark'

      process.stdin.pipe( concatStream(function (buf) { process.stdout.write(String(remark().processSync(buf))) }) ) ```

    Classes

    class Processor

    class Processor<
    ParseTree extends import('unist').Node | undefined = undefined,
    HeadTree extends import('unist').Node | undefined = undefined,
    TailTree extends import('unist').Node | undefined = undefined,
    CompileTree extends import('unist').Node | undefined = undefined,
    CompileResult extends CompileResults | undefined = undefined
    > extends CallableInstance<
    [],
    Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>
    > {}
    • {Node | undefined} [ParseTree=undefined] Output of parse (optional). {Node | undefined} [HeadTree=undefined] Input for run (optional). {Node | undefined} [TailTree=undefined] Output for run (optional). {Node | undefined} [CompileTree=undefined] Input of stringify (optional). {CompileResults | undefined} [CompileResult=undefined] Output of stringify (optional). {CallableInstance<[], Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>>}

    constructor

    constructor();
    • Create a processor.

    property attachers

    attachers: [
    plugin: Plugin<unknown[], undefined, undefined>,
    ...parameters: unknown[]
    ][];
    • Internal list of configured plugins.

      Deprecated

      This is a private internal property and should not be used. {Array<PluginTuple<Array>>}

    property compiler

    compiler: Compiler<
    CompileTree extends undefined ? any : CompileTree,
    CompileResult extends undefined ? CompileResults : CompileResult
    >;
    • Compiler to use.

      {( Compiler< CompileTree extends undefined ? Node : CompileTree, CompileResult extends undefined ? CompileResults : CompileResult > | undefined )}

    property Compiler

    Compiler: Compiler<
    CompileTree extends undefined ? any : CompileTree,
    CompileResult extends undefined ? CompileResults : CompileResult
    >;
    • Compiler to use (deprecated).

      Deprecated

      Use compiler instead. {( Compiler< CompileTree extends undefined ? Node : CompileTree, CompileResult extends undefined ? CompileResults : CompileResult > | undefined )}

    property freezeIndex

    freezeIndex: number;
    • Internal state to track where we are while freezing.

      Deprecated

      This is a private internal property and should not be used. {number}

    property frozen

    frozen: boolean;
    • Internal state to track whether we’re frozen.

      Deprecated

      This is a private internal property and should not be used. {boolean | undefined}

    property namespace

    namespace: Data;
    • Internal state.

      Deprecated

      This is a private internal property and should not be used. {Data}

    property parser

    parser: Parser<ParseTree extends undefined ? any : ParseTree>;
    • Parser to use.

      {( Parser<ParseTree extends undefined ? Node : ParseTree> | undefined )}

    property Parser

    Parser: Parser<ParseTree extends undefined ? any : ParseTree>;
    • Parser to use (deprecated).

      Deprecated

      Use parser instead. {( Parser<ParseTree extends undefined ? Node : ParseTree> | undefined )}

    property transformers

    transformers: any;
    • Internal list of configured transformers.

      Deprecated

      This is a private internal property and should not be used. {Pipeline}

    method copy

    copy: () => Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>;
    • Copy a processor.

      Returns

      {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>} New *unfrozen* processor () that is configured to work the same as its ancestor. When the descendant processor is configured in the future it does not affect the ancestral processor.

      Deprecated

      This is a private internal method and should not be used.

    method data

    data: {
    <Key extends string | number | symbol>(): Data;
    <Key extends string | number | symbol>(dataset: Data): Processor<
    ParseTree,
    HeadTree,
    TailTree,
    CompileTree,
    CompileResult
    >;
    <Key extends string | number | symbol>(key: Key): any;
    <Key extends string | number | symbol>(key: Key, value: any): Processor<
    ParseTree,
    HeadTree,
    TailTree,
    CompileTree,
    CompileResult
    >;
    };
    • Configure the processor with info available to all plugins. Information is stored in an object.

      Typically, options can be given to a specific plugin, but sometimes it makes sense to have information shared with several plugins. For example, a list of HTML elements that are self-closing, which is needed during all phases.

      > **Note**: setting information cannot occur on *frozen* processors. > Call the processor first to create a new unfrozen processor.

      > **Note**: to register custom data in TypeScript, augment the > interface.

      Parameter dataset

      Parameter key

      Parameter key

      Parameter value

      Parameter key

      Key to get or set, or entire dataset to set, or nothing to get the entire dataset (optional).

      Parameter value

      Value to set (optional).

      Returns

      {unknown} The current processor when setting, the value at key when getting, or the entire dataset when getting without key.

      Example 1

      This example show how to get and set info:

      ```js import {unified} from 'unified'

      const processor = unified().data('alpha', 'bravo')

      processor.data('alpha') // => 'bravo'

      processor.data() // => {alpha: 'bravo'}

      processor.data({charlie: 'delta'})

      processor.data() // => {charlie: 'delta'} ```

      {keyof Data} Key

    method freeze

    freeze: () => Processor<
    ParseTree,
    HeadTree,
    TailTree,
    CompileTree,
    CompileResult
    >;
    • Freeze a processor.

      Frozen processors are meant to be extended and not to be configured directly.

      When a processor is frozen it cannot be unfrozen. New processors working the same way can be created by calling the processor.

      It’s possible to freeze processors explicitly by calling .freeze(). Processors freeze automatically when .parse(), .run(), .runSync(), .stringify(), .process(), or .processSync() are called.

      Returns

      {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>} The current processor.

    method parse

    parse: (
    file?: Compatible | undefined
    ) => ParseTree extends undefined ? Node : ParseTree;
    • Parse text to a syntax tree.

      > **Note**: parse freezes the processor if not already *frozen*.

      > **Note**: parse performs the parse phase, not the run phase or other > phases.

      Parameter file

      file to parse (optional); typically string or VFile; any value accepted as x in new VFile(x).

      Returns

      {ParseTree extends undefined ? Node : ParseTree} Syntax tree representing file.

    method process

    process: {
    (
    file: Compatible | undefined,
    done: ProcessCallback<VFileWithOutput<CompileResult>>
    ): undefined;
    (file?: any): Promise<VFileWithOutput<CompileResult>>;
    };
    • Process the given file as configured on the processor.

      > **Note**: process freezes the processor if not already *frozen*.

      > **Note**: process performs the parse, run, and stringify phases.

      Parameter file

      Parameter done

      Parameter file

      Parameter file

      File (optional); typically string or VFile]; any value accepted as x in new VFile(x).

      Parameter done

      Callback (optional).

      Returns

      {Promise | undefined} Nothing if done is given. Otherwise a promise, rejected with a fatal error or resolved with the processed file.

      The parsed, transformed, and compiled value is available at file.value (see note).

      > **Note**: unified typically compiles by serializing: most > compilers return string (or Uint8Array). > Some compilers, such as the one configured with > [rehype-react][rehype-react], return other values (in this case, a > React tree). > If you’re using a compiler that doesn’t serialize, expect different > result values. > > To register custom results in TypeScript, add them to > .

      [rehype-react]: https://github.com/rehypejs/rehype-react

    method processSync

    processSync: (file?: Compatible | undefined) => VFileWithOutput<CompileResult>;
    • Process the given file as configured on the processor.

      An error is thrown if asynchronous transforms are configured.

      > **Note**: processSync freezes the processor if not already *frozen*.

      > **Note**: processSync performs the parse, run, and stringify phases.

      Parameter file

      File (optional); typically string or VFile; any value accepted as x in new VFile(x).

      Returns

      {VFileWithOutput} The processed file.

      The parsed, transformed, and compiled value is available at file.value (see note).

      > **Note**: unified typically compiles by serializing: most > compilers return string (or Uint8Array). > Some compilers, such as the one configured with > [rehype-react][rehype-react], return other values (in this case, a > React tree). > If you’re using a compiler that doesn’t serialize, expect different > result values. > > To register custom results in TypeScript, add them to > .

      [rehype-react]: https://github.com/rehypejs/rehype-react

    method run

    run: {
    (
    tree: HeadTree extends undefined ? Node : HeadTree,
    done: RunCallback<TailTree extends undefined ? Node : TailTree>
    ): undefined;
    (
    tree: HeadTree extends undefined ? any : HeadTree,
    file: any,
    done: RunCallback<TailTree extends undefined ? any : TailTree>
    ): undefined;
    (tree: HeadTree extends undefined ? any : HeadTree, file?: any): Promise<
    TailTree extends undefined ? any : TailTree
    >;
    };
    • Run *transformers* on a syntax tree.

      > **Note**: run freezes the processor if not already *frozen*.

      > **Note**: run performs the run phase, not other phases.

      Parameter tree

      Parameter done

      Parameter tree

      Parameter file

      Parameter done

      Parameter tree

      Parameter file

      Parameter tree

      Tree to transform and inspect.

      Parameter file

      File associated with node (optional); any value accepted as x in new VFile(x).

      Parameter done

      Callback (optional).

      Returns

      {Promise<TailTree extends undefined ? Node : TailTree> | undefined} Nothing if done is given. Otherwise, a promise rejected with a fatal error or resolved with the transformed tree.

    method runSync

    runSync: (
    tree: HeadTree extends undefined ? Node : HeadTree,
    file?: Compatible | undefined
    ) => TailTree extends undefined ? Node : TailTree;
    • Run *transformers* on a syntax tree.

      An error is thrown if asynchronous transforms are configured.

      > **Note**: runSync freezes the processor if not already *frozen*.

      > **Note**: runSync performs the run phase, not other phases.

      Parameter tree

      Tree to transform and inspect.

      Parameter file

      File associated with node (optional); any value accepted as x in new VFile(x).

      Returns

      {TailTree extends undefined ? Node : TailTree} Transformed tree.

    method stringify

    stringify: (
    tree: CompileTree extends undefined ? Node : CompileTree,
    file?: Compatible | undefined
    ) => CompileResult extends undefined ? Value : CompileResult;
    • Compile a syntax tree.

      > **Note**: stringify freezes the processor if not already *frozen*.

      > **Note**: stringify performs the stringify phase, not the run phase > or other phases.

      Parameter tree

      Tree to compile.

      Parameter file

      File associated with node (optional); any value accepted as x in new VFile(x).

      Returns

      {CompileResult extends undefined ? Value : CompileResult} Textual representation of the tree (see note).

      > **Note**: unified typically compiles by serializing: most compilers > return string (or Uint8Array). > Some compilers, such as the one configured with > [rehype-react][rehype-react], return other values (in this case, a > React tree). > If you’re using a compiler that doesn’t serialize, expect different > result values. > > To register custom results in TypeScript, add them to > .

      [rehype-react]: https://github.com/rehypejs/rehype-react

    method use

    use: {
    <
    Parameters_1 extends unknown[] = [],
    Input extends unknown = undefined,
    Output = Input
    >(
    preset?: Preset | null | undefined
    ): Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>;
    <
    Parameters_1 extends unknown[] = [],
    Input extends unknown = undefined,
    Output = Input
    >(
    list: PluggableList
    ): Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>;
    <
    Parameters_1 extends unknown[] = [],
    Input extends unknown = undefined,
    Output = Input
    >(
    plugin: Plugin<Parameters_1, Input, Output>,
    ...parameters: Parameters_1 | [boolean]
    ): UsePlugin<
    ParseTree,
    HeadTree,
    TailTree,
    CompileTree,
    CompileResult,
    Input,
    Output
    >;
    };
    • Configure the processor to use a plugin, a list of usable values, or a preset.

      If the processor is already using a plugin, the previous plugin configuration is changed based on the options that are passed in. In other words, the plugin is not added a second time.

      > **Note**: use cannot be called on *frozen* processors. > Call the processor first to create a new unfrozen processor.

      Parameter preset

      Parameter list

      Parameter plugin

      Parameter parameters

      Parameter value

      Usable value.

      Parameter parameters

      Parameters, when a plugin is given as a usable value.

      Returns

      {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>} Current processor.

      Example 1

      There are many ways to pass plugins to .use(). This example gives an overview:

      ```js import {unified} from 'unified'

      unified() // Plugin with options: .use(pluginA, {x: true, y: true}) // Passing the same plugin again merges configuration (to {x: true, y: false, z: true}): .use(pluginA, {y: false, z: true}) // Plugins: .use([pluginB, pluginC]) // Two plugins, the second with options: .use([pluginD, [pluginE, {}]]) // Preset with plugins and settings: .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}}) // Settings only: .use({settings: {position: false}}) ```

      {Array} [Parameters=[]] {Node | string | undefined} [Input=undefined] [Output=Input]

    Interfaces

    interface CompileResultMap

    interface CompileResultMap {}
    • Interface of known results from compilers.

      Normally, compilers result in text ( of vfile). When you compile to something else, such as a React node (as in, rehype-react), you can augment this interface to include that type.

      import type {ReactNode} from 'somewhere'
      declare module 'unified' {
      interface CompileResultMap {
      // Register a new result (value is used, key should match it).
      ReactNode: ReactNode
      }
      }
      export {} // You may not need this, but it makes sure the file is a module.

      Use to access the values.

    property string

    string: string;

      property Uint8Array

      Uint8Array: Uint8Array;

        interface Data

        interface Data {}
        • Interface of known data that can be supported by all plugins.

          Typically, options can be given to a specific plugin, but sometimes it makes sense to have information shared with several plugins. For example, a list of HTML elements that are self-closing, which is needed during all phases.

          To type this, do something like:

          declare module 'unified' {
          interface Data {
          htmlVoidElements?: Array<string> | undefined
          }
          }
          export {} // You may not need this, but it makes sure the file is a module.

        property settings

        settings?: Settings | undefined;

          interface Settings

          interface Settings {}
          • Interface of known extra options, that can be supported by parser and compilers.

            This exists so that users can use packages such as remark, which configure both parsers and compilers (in this case remark-parse and remark-stringify), and still provide options for them.

            When you make parsers or compilers, that could be packaged up together, you should support this.data('settings') as input and merge it with explicitly passed options. Then, to type it, using remark-stringify as an example, do something like:

            declare module 'unified' {
            interface Settings {
            bullet: '*' | '+' | '-'
            // …
            }
            }
            export {} // You may not need this, but it makes sure the file is a module.

          property [emptyObjectSymbol]

          [emptyObjectSymbol]?: never;

            Type Aliases

            type Compiler

            type Compiler<
            Tree extends import('unist').Node = import('unist').Node,
            Result extends CompileResults = CompileResults
            > = (tree: Tree, file: VFile) => Result;
            • A **compiler** handles the compiling of a syntax tree to something else (in most cases, text) (TypeScript type).

              It is used in the stringify phase and called with a and representation of the document to compile. It should return the textual representation of the given tree (typically string).

              > **Note**: unified typically compiles by serializing: most compilers > return string (or Uint8Array). > Some compilers, such as the one configured with > [rehype-react][rehype-react], return other values (in this case, a > React tree). > If you’re using a compiler that doesn’t serialize, expect different > result values. > > To register custom results in TypeScript, add them to > .

              [rehype-react]: https://github.com/rehypejs/rehype-react

            type CompileResults

            type CompileResults = CompileResultMap[keyof CompileResultMap];
            • Acceptable results from compilers.

              To register custom results, add them to .

            type Parser

            type Parser<Tree extends import('unist').Node = import('unist').Node> = (
            document: string,
            file: VFile
            ) => Tree;
            • A **parser** handles the parsing of text to a syntax tree.

              It is used in the parse phase and is called with a string and of the document to parse. It must return the syntax tree representation of the given file ().

            type Pluggable

            type Pluggable =
            | Plugin<Array<any>, any, any>
            | PluginTuple<Array<any>, any, any>
            | Preset;
            • Union of the different ways to add plugins and settings.

            type PluggableList

            type PluggableList = Array<Pluggable>;
            • List of plugins and presets.

            type Plugin

            type Plugin<
            PluginParameters extends unknown[] = [],
            Input extends string | import('unist').Node | undefined = import('unist').Node,
            Output = Input
            > = (
            this: Processor,
            ...parameters: PluginParameters
            ) => Input extends string
            ? Output extends Node | undefined
            ? undefined | void
            : never
            : Output extends CompileResults
            ? Input extends Node | undefined
            ? undefined | void
            : never
            :
            | Transformer<
            Input extends Node ? Input : Node,
            Output extends Node ? Output : Node
            >
            | undefined
            | void;
            • Single plugin.

              Plugins configure the processors they are applied on in the following ways:

              * they change the processor, such as the parser, the compiler, or by configuring data * they specify how to handle trees and files

              In practice, they are functions that can receive options and configure the processor (this).

              > **Note**: plugins are called when the processor is *frozen*, not when > they are applied.

            type PluginTuple

            type PluginTuple<
            TupleParameters extends unknown[] = [],
            Input extends string | import('unist').Node | undefined = undefined,
            Output = undefined
            > = [plugin: Plugin<TupleParameters, Input, Output>, ...parameters: TupleParameters];
            • Tuple of a plugin and its configuration.

              The first item is a plugin, the rest are its parameters.

            type Preset

            type Preset = {
            /**
            * List of plugins and presets (optional).
            */
            plugins?: PluggableList | undefined;
            /**
            * Shared settings for parsers and compilers (optional).
            */
            settings?: Settings | undefined;
            };
            • Sharable configuration.

              They can contain plugins and settings.

            type ProcessCallback

            type ProcessCallback<File extends VFile = VFile> = (
            error?: Error | undefined,
            file?: File | undefined
            ) => undefined;
            • Callback called when the process is done.

              Called with either an error or a result.

            type RunCallback

            type RunCallback<Tree extends import('unist').Node = import('unist').Node> = (
            error?: Error | undefined,
            tree?: Tree | undefined,
            file?: VFile | undefined
            ) => undefined;
            • Callback called when transformers are done.

              Called with either an error or results.

            type TransformCallback

            type TransformCallback<Output extends import('unist').Node = import('unist').Node> =
            (
            error?: Error | undefined,
            tree?: Output | undefined,
            file?: VFile | undefined
            ) => undefined;
            • Callback passed to transforms.

              If the signature of a transformer accepts a third argument, the transformer may perform asynchronous operations, and must call it.

            type Transformer

            type Transformer<
            Input extends import('unist').Node = import('unist').Node,
            Output extends import('unist').Node = Input
            > = (
            tree: Input,
            file: VFile,
            next: TransformCallback<Output>
            ) =>
            | Promise<Output | undefined | void>
            | Promise<never> // For some reason this is needed separately.
            | Output
            | Error
            | undefined
            | void;
            • Transformers handle syntax trees and files.

              They are functions that are called each time a syntax tree and file are passed through the run phase. When an error occurs in them (either because it’s thrown, returned, rejected, or passed to next), the process stops.

              The run phase is handled by [trough][trough], see its documentation for the exact semantics of these functions.

              > **Note**: you should likely ignore next: don’t accept it. > it supports callback-style async work. > But promises are likely easier to reason about.

              [trough]: https://github.com/wooorm/trough#function-fninput-next

            Package Files (2)

            Dependencies (7)

            Dev Dependencies (12)

            Peer Dependencies (0)

            No peer dependencies.

            Badge

            To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

            You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/unified.

            • Markdown
              [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/unified)
            • HTML
              <a href="https://www.jsdocs.io/package/unified"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>