JavaScript API

rewrite

Rewrite an AST with plugins.

function rewrite(ast: Ast, options?: RewriteOptions): Promise<AstResult>;

function rewrite(
    program: Program,
    code: string,
    options?: RewriteOptions,
): Promise<AstResult>;

Rewrites an AST with plugins, in memory.

The AST's own input map wins; otherwise the resolved input source map is attached before the stages run.

Parameters

The function accepts either an Ast instance, or a bare ESTree Program together with its source text.

NameTypeDescription
astAstAn AST instance.
optionsRewriteOptionsOptional rewrite options.
NameTypeDescription
programProgramA bare ESTree program.
codestringThe source text the program's spans anchor to. Required with program.
optionsRewriteOptionsOptional rewrite options.

RewriteOptions

FieldTypeDefaultDescription
cwdstringprocess.cwd()Current working directory.
filestringindex.tsThe file being rewritten. Its extension is the final fallback for the grammar.
languageLanguageinferredThe grammar of the code. Overrides the AST language and extension inference.
sourceTypeSourceTypeinferredThe module system of the code. Overrides the grammar's module kind.
inputSourceMapInputSourceMapoffThe input source-map request for the step.
pluginsPluginOption[][]The plugins to run.

The grammar precedence is options.language > Ast.language > file extension.

InputSourceMap is a SourceMap value, a literal input mode ("inline", "external", or "auto"), or { mode, path? }; in the options form, mode accepts a SourceMap value or a literal input mode.

rewrite produces an AST, so it has no output source map. The shared plugin options bag presents this request as sourceMap.input; a plugin-set sourceMap.output or top-level output is ignored by rewrite.

Returns

Promise<AstResult>, where AstResult is { ast: Ast }. The returned Ast carries the resolved language.

Example

import type { AstResult } from "telarel";

import { parse, rewrite } from "telarel";

const { ast }: AstResult = await parse("const x: number = 1;");

const result: AstResult = await rewrite(ast);

Last updated on

Copyright © 2026, Alpheus

On this page