JavaScript API

generate

Generate code from an AST.

function generate(ast: Ast, options?: GenerateOptions): Promise<CodeResult>;

function generate(
    program: Program,
    code: string,
    options?: GenerateOptions,
): Promise<CodeResult>;

Generates code from an AST with plugins, in memory.

The builtin generator is the terminal fallback after every generate plugin hook defers, and the resolved output source-map mode is applied to the winning result.

Parameters

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

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

GenerateOptions

FieldTypeDefaultDescription
cwdstringprocess.cwd()Current working directory.
filestringindex.tsThe file being generated. Its extension is the final fallback for the grammar.
languageLanguageinferredThe grammar to generate with. Overrides the AST language and extension inference.
outputOutputOptions{ file: file }Output code settings. output.file derives the default source-map URL.
sourceMapSourceMapOptionsoffThe source-map inputs and outputs requested for the step.
pluginsPluginOption[][]The plugins to run.

The grammar precedence is options.language > Ast.language > file extension. Module kind remains owned by ast.program.sourceType: there is no generate sourceType option.

An empty output.file or sourceMap.output.url is treated as unset, same as absent.

Returns

Promise<CodeResult>:

FieldTypeDescription
codestringThe generated code.
mapSourceMap | nullThe source map for the generated code, when one was produced.

Example

import type { AstResult, CodeResult } from "telarel";

import { parse, generate } from "telarel";

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

const result: CodeResult = await generate(ast);

Last updated on

Copyright © 2026, Alpheus

On this page