RTI API Reference

rti

Root namespace for the RTI Transpiler.

Summary

Static Properties

indentingNodeTypes

Node types whose renderer increases the indentation level by one (this.

nodeChildren

Map of Babel node types to their child keys that contain traversable AST nodes.

parserOptions

We use the same options in different places, so it's nice to keep them in sync without changing them in multiple locations.

requiredTypeofs

Static Methods

addTypeChecks

Simple facade which does all the processing.

annotate

Attaches JSDoc comment blocks to the AST nodes which carry TypeScript types.

ast2json
ast2jsonForComparison
attachComment

Attaches a JSDoc comment (built from lines) to a suitable statement-level host node.

capitalize
code2ast2code

A roundtrip between code -> AST -> code to validate Stringifier.

collectVariableTypeComments

Attaches @type comments for typed variable declarations.

compareAST
expandType

Transforms a type string into a structured type representation.

expandTypeBabelTS
expandTypeDepFree

'DepFree' refers to the fact that this function has no dependencies, while expandType depends on TypeScript itself for maximum compatibility.

extractCurlyContent

Extracts the content of a string that is delimited by curly braces.

extractNameAndOptionality

Extracts the parameter name and its optionality from a JSDoc parameter string.

findCommentHost

Finds the statement-ish node where a JSDoc comment should live.

formatCommentBreaks

Moves a statement that follows a generated JSDoc block onto its own line, e.

functionSignatureToJSDoc
hasTypedParams
importTypeToJSDoc

Renders a JSDoc @import comment for type-only import specifiers, e.

inferTypeFromDefault

Infers a JSDoc type from a default value literal.

injectParameterProperties

Injects this.

jsdocLinesFromFunction

Returns the JSDoc lines for a function-like node.

jsImportSource

Rewrites a TypeScript import specifier to its JavaScript counterpart, e.

literalToJSDoc

Converts a literal type node to its JSDoc representation.

makeComment

Creates a Babel CommentBlock node with a fabricated loc.

nodeIsFunctionLike

Checks if the provided node is a function-like structure.

paramToJSDoc

Extracts param information and produces a @param JSDoc line, or nothing when nothing can be said about the parameter.

parseJSDoc

Parses JSDoc comments to extract parameter type information.

parseJSDocSetter
parseJSDocTemplates

Parses JSDoc comments to extract parameter type information.

parseJSDocTypedef

Parses JSDoc comments to extract and expand typedefs and their associated properties.

parseTS

Parses TypeScript code, automatically falling back to TSX (JSX) mode when the input contains JSX elements.

parseType
parseTypeBabelTS
propertySignatureToJSDoc
renderIndentDepth

Counts the renderer indentation levels that nest node, so comments can be placed at the column the stringifier will use (2 spaces per level).

restElementType

Unwraps the trailing [] of an array type in a rest parameter context, e.

simplifyReference

Reduces a possibly namespace-qualified type name to its local identifier, e.

simplifyType
statReset
templateLiteralToJSDoc
toSourceBabelTS

Converts a Babel AST node to its source string representation or structured type object.

toSourceTS

Converts a TypeScript AST node to a source string representation or to an intermediate object describing the type.

trimEndSpaces
ts2js

A roundtrip between TypeScript code -> JavaScript code with JSDoc types.

tsTypeToJSDoc

Converts a Babel-TS type AST node into a JSDoc compatible type string, e.

typeLiteralMembersToJSDoc

Converts a TSTypeLiteral's members into a JSDoc object type string, e.

Details

Static Properties

indentingNodeTypes

Node types whose renderer increases the indentation level by one (this.numSpaces++).

nodeChildren

Map of Babel node types to their child keys that contain traversable AST nodes.

parserOptions

We use the same options in different places, so it's nice to keep them in sync without changing them in multiple locations.

requiredTypeofs

Static Methods

addTypeChecks(src, [options]) #

Simple facade which does all the processing. Processes the input source string, adding runtime type checks based on JSDoc comments.

This function takes JavaScript source code as input, parses it to an AST, traverses the AST to find type annotations in JSDoc comments, and generates appropriate runtime type assertions. These are then inserted into the source, producing a new version of the code that includes runtime type checking based on the original JSDoc annotations.

Parameters

srcstring

The input source code containing JSDoc comments to be processed for type checks.

optionsimport('./Asserter.js').Options

Configuration options that dictate how the processing is performed.

Returns

string

The transformed source code with inserted runtime type checks, or the original source code commented with an error if processing fails.

annotate(node, parents) #

Attaches JSDoc comment blocks to the AST nodes which carry TypeScript types.

Parameters

nodeNode

The node to annotate recursively.

parentsNode[]

The current parent stack.

ast2json(ast) #

Parameters

astobject

The Babel AST.

Returns

string

String representation in JSON format for debugging/inspecting the AST.

ast2jsonForComparison(ast) #

setRight(ast2jsonForComparison(parseSync("/** *"))); // Close comment with / after last *

Parameters

astobject

The Babel AST.

Returns

string

String representation in JSON format for debugging/inspecting the AST.

attachComment(node, lines, parents) #

Attaches a JSDoc comment (built from lines) to a suitable statement-level host node.

Parameters

nodeNode

The annotated node.

linesstring[]

The JSDoc lines.

parentsNode[]

The parent stack.

capitalize(_) #

capitalize("hello"); // Outputs: Hello

Parameters

_string

The input string.

Returns

string

The capitalized output string.

code2ast2code(code) #

A roundtrip between code -> AST -> code to validate Stringifier.

Parameters

codestring

The code.

Returns

string, undefined

The new and once parsed and stringified code.

collectVariableTypeComments(node, parents) #

Attaches @type comments for typed variable declarations.

Parameters

nodeimport('@babel/types').VariableDeclaration

The declaration node.

parentsNode[]

The parent stack.

compareAST(left, right) #

Parameters

leftstring

Left source code.

rightstring

Right source code.

Returns

boolean

Whether source codes are identical on the AST level.

expandType(type) #

Transforms a type string into a structured type representation.

This function parses a given type string and converts it into a TypeScript Abstract Syntax Tree (AST), then uses that AST to return a structured type representation that can be further utilized or interpreted.

const {expandType} = await import("./src-transpiler/expandType.js");
expandType('[string, Array|AnyTypedArray, number[]]|[ONNXTensor]');
expandType('(123)                    '); // Outputs: '123'
expandType('  ( ( 123 ) )            '); // Outputs: '123'
expandType('Array            '); // Outputs: {type: 'array', elementType: 'number'}
expandType('Array<(123) >            '); // Outputs: {type: 'array', elementType: '123'}
expandType('Array<"abc" | 123>       '); // Outputs: {type: 'array', elementType: {type: 'union', members: ['"abc"', '123']}}
expandType('  (string ) |(number )   '); // Outputs: {type: 'union', members: [ 'string', 'number']}
expandType(' "apples" | ( "bananas") '); // Outputs: {type: 'union', members: [ '"apples"', '"bananas"']}
expandType('123?                     '); // Outputs: {"type":"union","members":["123","null"]}
expandType('123|null                 '); // Outputs: {"type":"union","members":["123","null"]}
expandType('Map         '); // Outputs:
expandType('typeof Number            '); // Outputs:

Parameters

typestring

The type string to be expanded into a structured representation.

Returns

string | number | boolean | {type: string, [key: string]: any} | undefined

The structured type representation obtained from parsing and converting the provided type string.

expandTypeBabelTS(type) #

const {expandTypeBabelTS} = await import("./src-transpiler/expandTypeBabelTS.js");
expandTypeBabelTS('[string, Array|AnyTypedArray, number[]]|[ONNXTensor]');
expandTypeBabelTS('(123)                    '); // Outputs: '123'
expandTypeBabelTS('  ( ( 123 ) )            '); // Outputs: '123'
expandTypeBabelTS('Array            '); // Outputs: {type: 'array', elementType: 'number'}
expandTypeBabelTS('Array<(123) >            '); // Outputs: {type: 'array', elementType: '123'}
expandTypeBabelTS('Array<"abc" | 123>       '); // Outputs: {type: 'array', elementType: {type: 'union', members: ['"abc"', '123']}}
expandTypeBabelTS('  (string ) |(number )   '); // Outputs: {type: 'union', members: [ 'string', 'number']}
expandTypeBabelTS(' "apples" | ( "bananas") '); // Outputs: {type: 'union', members: [ '"apples"', '"bananas"']}
expandTypeBabelTS('123?                     '); // Outputs: {type: 'union', members: ['123', 'null']}
expandTypeBabelTS('123|null                 '); // Outputs: {type: 'union', members: ['123', 'null']}
expandTypeBabelTS('Map         '); // Outputs: {type: 'map', key: 'string', val: 'any'}
expandTypeBabelTS("(a: number, b: number) => number")

Parameters

typestring

The input type.

Returns

string, object, undefined
  • See toSourceBabelTS.

expandTypeDepFree(type) #

'DepFree' refers to the fact that this function has no dependencies, while expandType depends on TypeScript itself for maximum compatibility.

expandTypeDepFree('(123)                   '); // Outputs: '123'
expandTypeDepFree('Array           '); // Outputs: { type: 'array', elementType: 'number' }
expandTypeDepFree('Array<(123) >           '); // Outputs: { type: 'array', elementType: '123' }
expandTypeDepFree('  ( ( 123 ) )           '); // Outputs: '123'
expandTypeDepFree('  (string ) |(number )  '); // Outputs: { type: 'union', members: ['string', 'number'] }
expandTypeDepFree(' ((  Object  ) )        '); // Outputs: { type: 'object', properties: {} }

Parameters

typestring

The input type to expand.

Returns

string, ExpandTypeReturnValue

Object containing parsed information from type string.

extractCurlyContent(line) #

Extracts the content of a string that is delimited by curly braces.

extractCurlyContent('{ {inner} }'); // Returns: {content: ' {inner} ', nextIndex: 11}

Parameters

linestring

The string to extract from.

Returns

Object

An object containing the extracted content, and the index of the character immediately following the closing curly brace.

extractNameAndOptionality(rest) #

Extracts the parameter name and its optionality from a JSDoc parameter string.

This function takes a rest parameter string from a JSDoc comment, trims it, and determines the parameter's name and whether it is optional. The optionality is inferred based on the presence of square brackets around the parameter name.

Parameters

reststring

The rest part of a JSDoc parameter string to parse.

Returns

[string, boolean]

A tuple where the first element is the name of the parameter, and the second element is a boolean indicating if the parameter is optional.

findCommentHost(node, parents) #

Finds the statement-ish node where a JSDoc comment should live. For const f = (a) => {} the comment belongs on the VariableDeclaration, for export function f it belongs on the ExportNamedDeclaration.

Parameters

nodeNode

The function/property node.

parentsNode[]

The parent stack.

Returns

Node

The host node.

formatCommentBreaks(source) #

Moves a statement that follows a generated JSDoc block onto its own line, e.g. a closing comment marker directly followed by export function f() {} becomes the closing marker, a newline, then export function f() {}.

Parameters

sourcestring

The generated source code.

Returns

string

The source with fixed comment/statement breaks.

functionSignatureToJSDoc(node) #

Parameters

nodeNode

A function-like type node (TSFunctionType, TSCallSignatureDeclaration, ...).

Returns

string

The (a: A) => R style JSDoc type string.

hasTypedParams(node) #

Parameters

nodeNode

The function-like node.

Returns

boolean

True if any parameter carries a type annotation.

importTypeToJSDoc(specifiers, source) #

Renders a JSDoc @import comment for type-only import specifiers, e.g. import type {OnlyType} from './types' becomes the single line @import { OnlyType } from './types.js' and carries the type information without creating a runtime import.

Parameters

specifiersimport('@babel/types').ImportSpecifier[]|import('@babel/types').ImportDefaultSpecifier[]|import('@babel/types').ImportNamespaceSpecifier[]

The import specifiers.

sourceimport('@babel/types').StringLiteral

The import source.

Returns

string

The @import JSDoc comment (or an empty string).

inferTypeFromDefault(node) #

Infers a JSDoc type from a default value literal.

Parameters

nodeNode

The default value node.

Returns

import('@babel/types').Node|undefined

A primitive keyword node or undefined.

injectParameterProperties(node) #

Injects this.prop = prop; statements for constructor parameter properties (constructor(public prop: number)).

Parameters

nodeimport('@babel/types').ClassMethod|import('@babel/types').ClassPrivateMethod

The constructor node.

jsdocLinesFromFunction(node) #

Returns the JSDoc lines for a function-like node.

Parameters

nodeNode

The function-like node.

Returns

string[]

The JSDoc lines (without @param/@returns separators).

jsImportSource(source) #

Rewrites a TypeScript import specifier to its JavaScript counterpart, e.g. ./types becomes ./types.js.

Parameters

sourceimport('@babel/types').StringLiteral

The import source.

Returns

string

The JavaScript module specifier.

literalToJSDoc(literal) #

Converts a literal type node to its JSDoc representation.

Parameters

literalNode

The literal node.

Returns

string

The JSDoc type string.

makeComment(node, lines, parents) #

Creates a Babel CommentBlock node with a fabricated loc. The column is derived from the renderer indentation depth of the annotated node (2 spaces per indenting ancestor) so that the comment aligns with the spaces of the node's rendered position, independent of the original (namespace-shifted) source column.

Parameters

nodeNode

The annotated node.

linesstring[]

The JSDoc lines.

parentsNode[]

The parent stack.

Returns

import('@babel/types').CommentBlock

The comment node.

nodeIsFunctionLike(node) #

Checks if the provided node is a function-like structure.

Parameters

nodeNode

The Babel AST node to be tested.

Returns

node is Function
  • true if the node is a function-like structure, otherwise false.

paramToJSDoc(param, index) #

Extracts param information and produces a @param JSDoc line, or nothing when nothing can be said about the parameter.

Parameters

paramNode

The parameter node.

indexnumber

The index of the parameter.

Returns

string, undefined

The @param line.

parseJSDoc(src, [expandType]) #

Parses JSDoc comments to extract parameter type information.

Parameters

srcstring

The JSDoc comment string to parse.

expandTypeExpandType

An optional function to process the types found in the JSDoc.

Returns

Record<string, ExpandTypeReturnType>, undefined

An object mapping parameter names to their parsed types, or undefined if no parameters are found.

parseJSDocSetter(src, expandType) #

Parameters

srcstring

JSDoc comment of the setter.

expandTypefunction

The expandType function.

Returns

string, DocType, undefined

The parsed and possibly expanded type from the JSDoc comment, or undefined if parsing fails to find @type.

parseJSDocTemplates(src, [expandType]) #

Parses JSDoc comments to extract parameter type information.

Parameters

srcstring

The JSDoc comment string to parse.

expandTypeExpandType

An optional function to process the types found in the JSDoc.

Returns

Record<string, ExpandTypeReturnType>, undefined

An object mapping template names to their parsed types, or undefined if no template tags were found.

parseJSDocTypedef(typedefs, warn, comment, expandType) #

Parses JSDoc comments to extract and expand typedefs and their associated properties.

It iterates through the lines of a CommentBlock from the Babel AST, looking for @typedef and @property annotations. When it finds a typedef, it stores it in the typedefs record. When it finds a property, it adds it to the last found typedef if it is an object type.

Parameters

typedefsRecord.<string, object>

An object to store typedefs, mapping type names to their expanded definitions.

warnConsole["warn"]

A warn function used for emitting warnings about non-extensible types.

commentimport("@babel/types").Comment

A comment extracted from Babel's AST, expected to be a CommentBlock containing type definitions.

expandTypefunction

A function that takes a type expression as a string and returns a structured representation of the type.

parseTS(code) #

Parses TypeScript code, automatically falling back to TSX (JSX) mode when the input contains JSX elements.

Parameters

codestring

The TypeScript code.

Returns

import('@babel/parser').ParseResult<import('@babel/types').File>

The parsed AST.

parseType(str) #

Parameters

strstring

The type string.

Returns

ts.TypeNode, undefined
  • The node containing all the information about the input type string.

parseTypeBabelTS(str) #

Parameters

strstring

The type string.

Returns

import('@babel/types').Node
  • The node containing all the information about the input type string.

propertySignatureToJSDoc(node) #

Parameters

nodeNode

The TSPropertySignature node.

Returns

string

The name: type (or optional name?: type) string.

renderIndentDepth(node, parents) #

Counts the renderer indentation levels that nest node, so comments can be placed at the column the stringifier will use (2 spaces per level).

Parameters

nodeNode

The annotated node.

parentsNode[]

The parent stack.

Returns

number

The indentation depth of the node.

restElementType(typeStr) #

Unwraps the trailing [] of an array type in a rest parameter context, e.g. @param {...string[]} rest becomes @param {...string} rest.

Parameters

typeStrstring

The JSDoc type string.

Returns

string

The element type.

simplifyReference(node) #

Reduces a possibly namespace-qualified type name to its local identifier, e.g. Validation.StringValidator becomes StringValidator, since flattened namespaces hoist their interfaces/classes to plain identifiers.

Parameters

nodeNode

The referenced name node.

Returns

string

The simplified JSDoc type string.

simplifyType(type, optional) #

Parameters

typestring, DocType

The type.

optionalboolean

Optionality

Returns

string, DocType

The simplified type.

statReset(stat) #

Parameters

statStat

the Stat.

templateLiteralToJSDoc(node) #

Parameters

nodeNode

The TSTemplateLiteralType node.

Returns

string

The template literal type as string.

toSourceBabelTS(node) #

Converts a Babel AST node to its source string representation or structured type object.

This function handles a variety of node types provided by Babel and converts them into a string or an intermediate object representing the type, depending on the complexity of the type described by the node.

Parameters

nodeimport('@babel/types').Node

The Babel AST node to convert.

Returns

string, object, undefined
  • A string, object representing a structured type, or undefined for unhandled types. Depending on the node, it may return a simple type string (e.g., "string" for TSStringKeyword), a structured type object (e.g., a record type for TSTypeReference with type arguments), or undefined if the encountered type is not handled. Unhandled types trigger a warning and enter a debugger statement.

toSourceTS(node) #

Converts a TypeScript AST node to a source string representation or to an intermediate object describing the type.

This function handles various TypeScript AST node types and converts them into a string or an object representing the type.

Parameters

nodets.TypeNode, ts.Identifier, ts.QualifiedName, undefined

The TypeScript AST node to convert.

Returns

string | number | boolean | {type: string, [key: string]: any} | undefined

The source string/number, or an object with type information based on the node, or undefined if the node kind is not handled.

trimEndSpaces(str) #

trimEndSpaces('test   \n   '); // Returns: 'test   \n'

Parameters

strstring

The input string.

Returns

string

Output string without spaces at the end.

ts2js(code, [options]) #

A roundtrip between TypeScript code -> JavaScript code with JSDoc types.

Parameters

codestring

The TypeScript code.

optionsobject

Options for the conversion.

options.filenameboolean

Unused placeholder, kept for API symmetry.

Returns

string

The converted JavaScript code.

tsTypeToJSDoc(node) #

Converts a Babel-TS type AST node into a JSDoc compatible type string, e.g. number, string[], Map<string, number> or {a: number, b?: string}.

The produced strings are valid TypeScript types as well, so they can be fed back into expandType/parseJSDoc of this very project.

Parameters

nodeNode

The Babel-TS type node.

Returns

string

The JSDoc-compatible type string.

typeLiteralMembersToJSDoc(members) #

Converts a TSTypeLiteral's members into a JSDoc object type string, e.g. {a: number, b?: string}.

Parameters

membersNode[]

The members of the type literal.

Returns

string

The JSDoc object type string.