Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | 12x 12x 138x 12x 12x 12x 138x 95x 95x 95x 95x 35x 17x 34x 43x 43x 43x 43x 43x 43x 12x 355x 226x 4x 2x 34x 1x 98x 32x 51x 38x 12x 16x 16x 66x 16x 42x 63x 16x 16x 16x 25x 20x 42x 42x 2x 1x 42x 142x 2x 104x 5x 1x | /**
* TypeScript 7 API adapter.
*
* TS 7 is the native (Go) compiler port: the classic `import ts from 'typescript'`
* no longer exposes the compiler API. AST construction, type-guards, the parser,
* and the printer all moved under `typescript/unstable/*`, and the raw
* `factory.create*` constructors take different (more verbose) argument shapes
* than the ergonomic TS 6 `ts.factory`.
*
* This module bridges that gap so the code-gen blocks read the same as before:
* - `factory` re-implements the exact TS 6 factory subset this package uses,
* delegating to the raw TS 7 constructors and filling in the new
* `questionDotToken` / `flags` / `tokenFlags` / modifiers arguments.
* - `printNode` / `printNodes` replace `ts.createPrinter().printFile/printNode`
* via the sync `Emitter` (runs over an RPC channel to the native process).
* - `parseExpression` replaces `ts.createSourceFile(...)` for parsing a
* condition string, using a virtual file system + program snapshot.
*
* Nodes produced by the parser cannot be mixed into synthetic trees directly
* (the native printer panics); `getSynthesizedDeepClone` converts them first.
*/
import { API, type PrintNodeOptions } from '@typescript/native/unstable/sync';
import { createVirtualFileSystem } from '@typescript/native/unstable/fs';
import * as f from '@typescript/native/unstable/ast/factory';
import {
SyntaxKind,
NodeFlags,
getSynthesizedDeepClone,
type Node,
type Expression,
type Statement,
type TypeNode,
type Block,
type HeritageClause,
type ClassElement,
type ModifierLike,
type ClassDeclaration,
type GetAccessorDeclaration,
type PropertyDeclaration,
type ImportDeclaration,
type CallExpression,
type PropertyAccessExpression,
type ElementAccessExpression,
type Identifier,
type BinaryOperatorToken,
} from '@typescript/native/unstable/ast';
export { getSynthesizedDeepClone, SyntaxKind, NodeFlags };
export type { Node, Expression, TypeNode, Block, ClassElement };
export * from '@typescript/native/unstable/ast/is';
// --- Printer / parser ----------------------------------------------------
//
// The native API only exposes an `Emitter` (printer) via `Project.emitter`,
// and has no in-process parser — both require a loaded project. We keep one
// shared API backed by a virtual FS that always contains a tsconfig plus a
// scratch file we rewrite per parse. A single snapshot gives us a Project
// whose `emitter` prints synthetic nodes and whose `program` parses source
// text.
const SCRATCH = '/scratch.ts';
const TSCONFIG = '/tsconfig.json';
// Single process-wide API + scratch file, created lazily. NOT reentrant: every
// parse rewrites the same `SCRATCH` path and reads back `statements[0]`, so
// concurrent `parseExpression` calls would clobber each other. Code generation
// is sequential today; if it's ever parallelized (e.g. worker-per-component),
// give each worker its own API/scratch instead of sharing this singleton.
let _api: API | undefined;
let _vfs: ReturnType<typeof createVirtualFileSystem> | undefined;
function ensureApi() {
if (!_api) {
_vfs = createVirtualFileSystem({
[SCRATCH]: '',
[TSCONFIG]: JSON.stringify({ compilerOptions: {}, files: ['scratch.ts'] }),
});
_api = new API({ fs: _vfs, cwd: '/' });
// The native compiler runs in a child process; close it on exit so we don't
// leak it in long-lived hosts (tests, watch mode). One handler per API
// lifecycle — `disposeTs` clears `_api`, so a re-created API re-registers.
process.once('exit', disposeTs);
}
return _api;
}
/** Load (or refresh) the scratch project. Pass `changed` after writing to the VFS. */
function project(changed = false) {
const snap = ensureApi().updateSnapshot({
openProjects: [TSCONFIG],
openFiles: [SCRATCH],
...(changed ? { fileChanges: { changed: [SCRATCH] } } : {}),
});
const proj = snap.getDefaultProjectForFile(SCRATCH) ?? snap.getProjects()[0];
Iif (!proj) throw new Error('Failed to load TypeScript project for code generation');
return proj;
}
/** Print a single AST node back to source text. */
export function printNode(node: Node, opts?: PrintNodeOptions): string {
return project().emitter.printNode(node, opts);
}
/** Print a list of top-level nodes as a source file body (one statement per line). */
export function printNodes(nodes: readonly Node[]): string {
const emitter = project().emitter;
return nodes.map((n) => emitter.printNode(n)).join('\n') + '\n';
}
/**
* Release the native compiler process. Registered as a `process.exit` handler
* by `ensureApi`, and safe to call manually (e.g. test teardown) — it's
* idempotent, and the next `parseExpression`/`printNode` lazily re-creates the
* API and re-registers the handler.
*
* `close()` does a synchronous RPC round-trip to the child. During process exit
* the child may already be tearing down, so that read can throw (`Unexpected
* EOF`); a teardown routine must never abort the process, so we swallow it — the
* OS reaps the child regardless.
*/
export function disposeTs(): void {
try {
_api?.close();
} catch {
// Child already gone / mid-shutdown — nothing left to release.
}
_api = undefined;
_vfs = undefined;
}
/**
* Parse a single JS expression string into a TS AST node.
*
* TS 7 has no in-process parser, so we write the expression (wrapped as
* `(expr);` to force an expression statement) into the scratch file, refresh
* the snapshot, and return the unwrapped inner expression.
*/
export function parseExpression(expression: string): Expression {
ensureApi();
// createVirtualFileSystem always provides writeFile (optional in the type).
_vfs!.writeFile!(SCRATCH, `(${expression});`);
const sourceFile = project(true).program.getSourceFile(SCRATCH);
Iif (!sourceFile) throw new Error(`Failed to parse condition: ${expression}`);
// statements[0] is an ExpressionStatement whose expression is the paren wrapper.
const stmt = sourceFile.statements[0] as any;
return stmt.expression.expression as Expression;
}
// --- Ergonomic factory (TS 6 shape over TS 7 raw constructors) -----------
/* eslint-disable @typescript-eslint/no-explicit-any */
export const factory = {
createIdentifier: (text: string) => f.createIdentifier(text),
createStringLiteral: (text: string) => f.createStringLiteral(text, 0),
createNumericLiteral: (value: string | number) => f.createNumericLiteral(String(value), 0),
createTrue: () => f.createKeywordExpression(SyntaxKind.TrueKeyword),
createFalse: () => f.createKeywordExpression(SyntaxKind.FalseKeyword),
createNull: () => f.createKeywordExpression(SyntaxKind.NullKeyword),
createThis: () => f.createKeywordExpression(SyntaxKind.ThisKeyword),
/** TS 6 `createModifier(kind)` -> TS 7 `createToken(kind)`. */
createModifier: (kind: any) => f.createToken(kind),
createToken: (kind: any) => f.createToken(kind),
createKeywordTypeNode: (kind: any) => f.createKeywordTypeNode(kind),
createLiteralTypeNode: (literal: Node) => f.createLiteralTypeNode(literal),
createUnionTypeNode: (types: readonly TypeNode[]) => f.createUnionTypeNode(types),
createHeritageClause: (token: any, types: readonly any[]) => f.createHeritageClause(token, types),
createExpressionWithTypeArguments: (expression: Expression, typeArguments?: readonly TypeNode[]) =>
f.createExpressionWithTypeArguments(expression, typeArguments),
createDecorator: (expression: any) => f.createDecorator(expression),
createClassDeclaration: (
modifiers: readonly ModifierLike[] | undefined,
name: Identifier | undefined,
typeParameters: readonly any[] | undefined,
heritageClauses: readonly HeritageClause[] | undefined,
members: readonly ClassElement[],
): ClassDeclaration => f.createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members),
createGetAccessorDeclaration: (
modifiers: readonly ModifierLike[] | undefined,
name: any,
parameters: readonly any[],
type: TypeNode | undefined,
body: Block | undefined,
): GetAccessorDeclaration =>
f.createGetAccessorDeclaration(modifiers, name, undefined, parameters, type, body),
createPropertyDeclaration: (
modifiers: readonly ModifierLike[] | undefined,
name: any,
postfixToken: any,
type: TypeNode | undefined,
initializer: Expression | undefined,
): PropertyDeclaration => f.createPropertyDeclaration(modifiers, name, postfixToken, type, initializer),
createImportDeclaration: (
modifiers: readonly ModifierLike[] | undefined,
importClause: any,
moduleSpecifier: Expression,
): ImportDeclaration => f.createImportDeclaration(modifiers, importClause, moduleSpecifier),
createImportClause: (phaseModifier: any, name: Identifier | undefined, namedBindings: any) =>
f.createImportClause(phaseModifier, name, namedBindings),
createNamedImports: (elements: readonly any[]) => f.createNamedImports(elements),
createImportSpecifier: (isTypeOnly: boolean | undefined, propertyName: any, name: Identifier) =>
f.createImportSpecifier(isTypeOnly, propertyName, name),
createArrayLiteralExpression: (elements: readonly Expression[], multiLine?: boolean) =>
f.createArrayLiteralExpression(elements, multiLine),
createBlock: (statements: readonly Statement[], multiLine?: boolean) =>
f.createBlock(statements, multiLine),
createReturnStatement: (expression?: Expression) => f.createReturnStatement(expression),
createExpressionStatement: (expression: Expression) => f.createExpressionStatement(expression),
createParenthesizedExpression: (expression: Expression) => f.createParenthesizedExpression(expression),
createCallExpression: (
expression: Expression,
typeArguments: readonly TypeNode[] | undefined,
args: readonly Expression[],
): CallExpression => f.createCallExpression(expression, undefined, typeArguments, args, 0),
/** Accepts a string `name` (TS 6 convenience) or an already-built MemberName. */
createPropertyAccessExpression: (
expression: Expression,
name: string | Identifier,
): PropertyAccessExpression =>
f.createPropertyAccessExpression(
expression,
undefined,
typeof name === 'string' ? f.createIdentifier(name) : name,
0,
),
createElementAccessExpression: (
expression: Expression,
argumentExpression: Expression,
): ElementAccessExpression => f.createElementAccessExpression(expression, undefined, argumentExpression, 0),
/** TS 6 `createBinaryExpression(left, operator, right)`; operator is a SyntaxKind. */
createBinaryExpression: (left: Expression, operator: any, right: Expression) =>
f.createBinaryExpression(
undefined,
left,
undefined,
f.createToken(operator) as BinaryOperatorToken,
right,
),
createPrefixUnaryExpression: (operator: any, operand: Expression) =>
f.createPrefixUnaryExpression(operator, operand),
createConditionalExpression: (
condition: Expression,
_questionToken: any,
whenTrue: Expression,
_colonToken: any,
whenFalse: Expression,
) =>
f.createConditionalExpression(
condition,
f.createToken(SyntaxKind.QuestionToken),
whenTrue,
f.createToken(SyntaxKind.ColonToken),
whenFalse,
),
};
/* eslint-enable @typescript-eslint/no-explicit-any */
|