Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

refactor(webv2): migrate architecture analyzers to the TypeScript 7 API

joshistoastbbba223867ae
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index 9a4dffc664..022bda52cc 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -76,7 +76,6 @@
"oxlint": "^1.77.0",
"playwright": "1.62.1",
"typescript": "^7.0.2",
- "typescript-legacy": "npm:[email protected]",
"vite": "^8.2.0",
"vitest": "^4.1.10"
},
diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yaml
index a45c1f60a1..638b002673 100644
--- a/invokeai/frontend/webv2/pnpm-lock.yaml
+++ b/invokeai/frontend/webv2/pnpm-lock.yaml
@@ -129,9 +129,6 @@ importers:
typescript:
specifier: ^7.0.2
version: 7.0.2
- typescript-legacy:
- specifier: npm:[email protected]
vite:
specifier: ^8.2.0
@@ -1909,11 +1906,6 @@ packages:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
- resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==}
- engines: {node: '>=14.17'}
- hasBin: true
-
resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==}
engines: {node: '>=16.20.0'}
@@ -3989,8 +3981,6 @@ snapshots:
-
optionalDependencies:
'@typescript/typescript-aix-ppc64': 7.0.2
diff --git a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs
index 7968581f12..b5fdaadae7 100644
--- a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs
+++ b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs
@@ -1,8 +1,9 @@
import assert from 'node:assert/strict';
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
-import ts from 'typescript-legacy';
+import { isExportDeclaration, isImportDeclaration, isStringLiteralLikeNode } from 'typescript/unstable/ast';
+import { parseSource, primeSources } from './parse-source.mjs';
import {
BUILD_METRIC_KEYS,
checkRouteBudget,
@@ -175,19 +176,22 @@ const collectFiles = async (directory) => {
};
const productionFiles = await collectFiles(resolve(root, 'src'));
const importerCounts = new Map(Object.values(baseline.developmentInvalidation).map((budget) => [budget.specifier, 0]));
-for (const path of productionFiles) {
- const source = await readFile(path, 'utf8');
- const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const productionSources = await Promise.all(productionFiles.map(async (path) => [path, await readFile(path, 'utf8')]));
+// One snapshot for the whole tree keeps the sweep to a single round trip.
+primeSources(productionSources, { jsx: true });
+
+for (const [path, source] of productionSources) {
+ const sourceFile = parseSource(path, source, { jsx: true });
const seen = new Set();
const visit = (node) => {
if (
- (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
+ (isImportDeclaration(node) || isExportDeclaration(node)) &&
node.moduleSpecifier &&
- ts.isStringLiteralLike(node.moduleSpecifier)
+ isStringLiteralLikeNode(node.moduleSpecifier)
) {
seen.add(node.moduleSpecifier.text);
}
- ts.forEachChild(node, visit);
+ node.forEachChild(visit);
};
visit(sourceFile);
for (const specifier of seen) {
diff --git a/invokeai/frontend/webv2/scripts/parse-source.mjs b/invokeai/frontend/webv2/scripts/parse-source.mjs
new file mode 100644
index 0000000000..1ea45dbc71
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/parse-source.mjs
@@ -0,0 +1,106 @@
+import { createVirtualFileSystem } from 'typescript/unstable/fs';
+import { API } from 'typescript/unstable/sync';
+
+/**
+ * TypeScript 7 removed the in-process `ts.createSourceFile` parser. The
+ * replacement surface only hands out ASTs for files that belong to a program,
+ * so the architecture analyzers parse through a virtual filesystem backed by a
+ * single long-lived tsgo session instead of parsing detached strings.
+ *
+ * Files are staged into the virtual project and flushed in one `updateSnapshot`
+ * call, which keeps a whole-tree sweep to a single round trip.
+ */
+const PARSE_ROOT = '/architecture-sources';
+const CONFIG_PATH = `${PARSE_ROOT}/tsconfig.json`;
+const SEED_PATH = `${PARSE_ROOT}/seed.tsx`;
+
+// `noLib` keeps lib.d.ts out of the program: these analyzers only ever walk
+// syntax, so skipping the default library removes the bulk of the load cost.
+const CONFIG = JSON.stringify({
+ compilerOptions: { allowJs: true, jsx: 'preserve', module: 'esnext', noLib: true, target: 'esnext' },
+ include: ['**/*'],
+});
+
+let fileSystem;
+let api;
+let snapshot;
+let nextId = 0;
+const virtualPaths = new Map();
+const stagedText = new Map();
+const created = [];
+const changed = [];
+
+const ensureSession = () => {
+ if (!api) {
+ fileSystem = createVirtualFileSystem({ [CONFIG_PATH]: CONFIG, [SEED_PATH]: 'export {};' });
+ api = new API({ cwd: PARSE_ROOT, fs: fileSystem });
+ snapshot = api.updateSnapshot({ openProjects: [CONFIG_PATH] });
+ }
+ return api;
+};
+
+/**
+ * Logical paths are analyzer-facing labels rather than real files, so each one
+ * gets an opaque virtual path. The extension carries the only parse-visible
+ * decision: `.tsx` parses `<T>` as JSX, `.ts` parses it as a type assertion.
+ */
+const virtualPathFor = (fileName, jsx) => {
+ const key = `${jsx ? 'x' : ''}:${fileName}`;
+ let virtualPath = virtualPaths.get(key);
+ if (!virtualPath) {
+ virtualPath = `${PARSE_ROOT}/${nextId++}.${jsx ? 'tsx' : 'ts'}`;
+ virtualPaths.set(key, virtualPath);
+ }
+ return virtualPath;
+};
+
+const stage = (fileName, text, jsx) => {
+ ensureSession();
+ const virtualPath = virtualPathFor(fileName, jsx);
+ if (stagedText.get(virtualPath) === text) {
+ return virtualPath;
+ }
+ (stagedText.has(virtualPath) ? changed : created).push(virtualPath);
+ stagedText.set(virtualPath, text);
+ fileSystem.writeFile(virtualPath, text);
+ return virtualPath;
+};
+
+const flush = () => {
+ if (created.length === 0 && changed.length === 0) {
+ return;
+ }
+ snapshot = api.updateSnapshot({
+ fileChanges: { changed: [...changed], created: [...created] },
+ openProjects: [CONFIG_PATH],
+ });
+ created.length = 0;
+ changed.length = 0;
+};
+
+const read = (virtualPath, fileName) => {
+ const sourceFile = snapshot.getProjects()[0]?.program.getSourceFile(virtualPath);
+ if (!sourceFile) {
+ throw new Error(`Failed to parse ${fileName} through the TypeScript API.`);
+ }
+ return sourceFile;
+};
+
+const resolveJsx = (fileName, jsx) => jsx ?? fileName.endsWith('x');
+
+/**
+ * Stage many sources and load them with one snapshot update. Use this before a
+ * whole-tree sweep; parsing each file on its own costs a round trip apiece.
+ */
+export const primeSources = (entries, { jsx } = {}) => {
+ for (const [fileName, text] of entries) {
+ stage(fileName, text, resolveJsx(fileName, jsx));
+ }
+ flush();
+};
+
+export const parseSource = (fileName, text, { jsx } = {}) => {
+ const virtualPath = stage(fileName, text, resolveJsx(fileName, jsx));
+ flush();
+ return read(virtualPath, fileName);
+};
diff --git a/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjs b/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjs
index 919bae110f..03d5666cf5 100644
--- a/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjs
+++ b/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjs
@@ -1,6 +1,13 @@
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { dirname, extname, join, relative, resolve } from 'node:path';
-import ts from 'typescript-legacy';
+import {
+ isImportDeclaration,
+ isNamedImports,
+ isNamespaceImport,
+ isStringLiteralLikeNode,
+} from 'typescript/unstable/ast';
+
+import { parseSource } from './parse-source.mjs';
const packageRoot = process.cwd();
const sourceRoot = resolve(packageRoot, 'src');
@@ -86,10 +93,10 @@ const importedSymbols = (clause) => {
if (clause.name) {
symbols.push('default');
}
- if (clause.namedBindings && ts.isNamespaceImport(clause.namedBindings)) {
+ if (clause.namedBindings && isNamespaceImport(clause.namedBindings)) {
symbols.push('*');
}
- if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
+ if (clause.namedBindings && isNamedImports(clause.namedBindings)) {
for (const element of clause.namedBindings.elements) {
symbols.push((element.propertyName ?? element.name).text);
}
@@ -103,15 +110,9 @@ for (const source of paths.filter(isProduction)) {
continue;
}
const text = readFileSync(resolve(sourceRoot, source), 'utf8');
- const file = ts.createSourceFile(
- source,
- text,
- ts.ScriptTarget.Latest,
- true,
- source.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS
- );
+ const file = parseSource(source, text);
for (const statement of file.statements) {
- if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier)) {
+ if (!isImportDeclaration(statement) || !isStringLiteralLikeNode(statement.moduleSpecifier)) {
continue;
}
const target = resolveImport(source, statement.moduleSpecifier.text);
diff --git a/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs b/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs
index f33310f04f..b98b71aab9 100644
--- a/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs
+++ b/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs
@@ -1,6 +1,17 @@
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { dirname, extname, join, relative, resolve } from 'node:path';
-import ts from 'typescript-legacy';
+import {
+ isExportDeclaration,
+ isIdentifier,
+ isImportDeclaration,
+ isNamedExports,
+ isNamedImports,
+ isStringLiteralLikeNode,
+ isVariableStatement,
+ ModifierFlags,
+} from 'typescript/unstable/ast';
+
+import { parseSource } from './parse-source.mjs';
const packageRoot = process.cwd();
const sourceRoot = resolve(packageRoot, 'src');
@@ -94,32 +105,24 @@ const resolveImport = (sourcePath, specifier) => {
return stem ? (pathByStem.get(stem) ?? pathByStem.get(`${stem}/index`) ?? null) : null;
};
-const parse = (path) =>
- ts.createSourceFile(
- path,
- sources.get(path),
- ts.ScriptTarget.Latest,
- true,
- path.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS
- );
+const parse = (path) => parseSource(path, sources.get(path));
const exportedSymbols = (path) => {
const symbols = new Set();
for (const statement of parse(path).statements) {
- const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;
- if (modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
- if (statement.name && ts.isIdentifier(statement.name)) {
+ if ((statement.modifierFlags & ModifierFlags.Export) !== 0) {
+ if (statement.name && isIdentifier(statement.name)) {
symbols.add(statement.name.text);
}
- if (ts.isVariableStatement(statement)) {
+ if (isVariableStatement(statement)) {
for (const declaration of statement.declarationList.declarations) {
- if (ts.isIdentifier(declaration.name)) {
+ if (isIdentifier(declaration.name)) {
symbols.add(declaration.name.text);
}
}
}
}
- if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
+ if (isExportDeclaration(statement) && statement.exportClause && isNamedExports(statement.exportClause)) {
for (const element of statement.exportClause.elements) {
symbols.add(element.name.text);
}
@@ -139,9 +142,9 @@ const addCaller = (hub, symbol, caller) => {
for (const path of paths) {
for (const statement of parse(path).statements) {
if (
- !ts.isImportDeclaration(statement) ||
+ !isImportDeclaration(statement) ||
!statement.importClause ||
- !ts.isStringLiteralLike(statement.moduleSpecifier)
+ !isStringLiteralLikeNode(statement.moduleSpecifier)
) {
continue;
}
@@ -150,7 +153,7 @@ for (const path of paths) {
continue;
}
const bindings = statement.importClause.namedBindings;
- if (bindings && ts.isNamedImports(bindings)) {
+ if (bindings && isNamedImports(bindings)) {
for (const element of bindings.elements) {
addCaller(target, (element.propertyName ?? element.name).text, path);
}
diff --git a/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjs b/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjs
index 6b6907874d..3c8cbdf088 100644
--- a/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjs
+++ b/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjs
@@ -1,6 +1,24 @@
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { dirname, extname, join, relative, resolve } from 'node:path';
-import ts from 'typescript-legacy';
+import {
+ isCallExpression,
+ isEmptyStatement,
+ isExportAssignment,
+ isExportDeclaration,
+ isIdentifier,
+ isImportDeclaration,
+ isImportTypeNode,
+ isInterfaceDeclaration,
+ isLiteralTypeNode,
+ isNamedExports,
+ isStringLiteralLikeNode,
+ isTypeAliasDeclaration,
+ isVariableStatement,
+ ModifierFlags,
+ SyntaxKind,
+} from 'typescript/unstable/ast';
+
+import { parseSource } from './parse-source.mjs';
const packageRoot = process.cwd();
const sourceRoot = resolve(packageRoot, 'src');
@@ -96,30 +114,30 @@ const targetRule = (path) => {
};
const targetOwner = (path) => (path.startsWith('workbench/') ? targetRule(path)?.targetOwner : currentOwner(path));
-const parse = (path, source) => ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const parse = (path, source) => parseSource(path, source, { jsx: true });
const imports = (path, source) => {
const sourceFile = parse(path, source);
const specifiers = [];
const visit = (node) => {
if (
- (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
+ (isImportDeclaration(node) || isExportDeclaration(node)) &&
node.moduleSpecifier &&
- ts.isStringLiteralLike(node.moduleSpecifier)
+ isStringLiteralLikeNode(node.moduleSpecifier)
) {
specifiers.push(node.moduleSpecifier.text);
} else if (
- ts.isImportTypeNode(node) &&
- ts.isLiteralTypeNode(node.argument) &&
- ts.isStringLiteralLike(node.argument.literal)
+ isImportTypeNode(node) &&
+ isLiteralTypeNode(node.argument) &&
+ isStringLiteralLikeNode(node.argument.literal)
) {
specifiers.push(node.argument.literal.text);
- } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
+ } else if (isCallExpression(node) && node.expression.kind === SyntaxKind.ImportKeyword) {
const argument = node.arguments[0];
- if (argument && ts.isStringLiteralLike(argument)) {
+ if (argument && isStringLiteralLikeNode(argument)) {
specifiers.push(argument.text);
}
}
- ts.forEachChild(node, visit);
+ node.forEachChild(visit);
};
visit(sourceFile);
return specifiers;
@@ -128,26 +146,25 @@ const imports = (path, source) => {
const publicExports = (path, source) => {
const names = new Set();
for (const statement of parse(path, source).statements) {
- const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;
- if (modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
- if (statement.name && ts.isIdentifier(statement.name)) {
+ if ((statement.modifierFlags & ModifierFlags.Export) !== 0) {
+ if (statement.name && isIdentifier(statement.name)) {
names.add(statement.name.text);
}
- if (ts.isVariableStatement(statement)) {
+ if (isVariableStatement(statement)) {
for (const declaration of statement.declarationList.declarations) {
- if (ts.isIdentifier(declaration.name)) {
+ if (isIdentifier(declaration.name)) {
names.add(declaration.name.text);
}
}
}
}
- if (ts.isExportAssignment(statement)) {
+ if (isExportAssignment(statement)) {
names.add('default');
}
- if (ts.isExportDeclaration(statement)) {
+ if (isExportDeclaration(statement)) {
if (!statement.exportClause) {
names.add('*');
- } else if (ts.isNamedExports(statement.exportClause)) {
+ } else if (isNamedExports(statement.exportClause)) {
for (const element of statement.exportClause.elements) {
names.add(element.name.text);
}
@@ -159,16 +176,16 @@ const publicExports = (path, source) => {
const isTypeOnly = (path, source) =>
parse(path, source).statements.every((statement) => {
- if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) {
+ if (isInterfaceDeclaration(statement) || isTypeAliasDeclaration(statement)) {
return true;
}
- if (ts.isImportDeclaration(statement)) {
- return Boolean(statement.importClause?.isTypeOnly);
+ if (isImportDeclaration(statement)) {
+ return statement.importClause?.phaseModifier === SyntaxKind.TypeKeyword;
}
- if (ts.isExportDeclaration(statement)) {
+ if (isExportDeclaration(statement)) {
return statement.isTypeOnly;
}
- return ts.isEmptyStatement(statement);
+ return isEmptyStatement(statement);
});
const inbound = new Map();
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
index e187d1cab6..0432d7e72f 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
@@ -7,6 +7,7 @@ import {
formatViolation,
getModuleOwner,
isExcepted,
+ primeImportSources,
resolveImportPath,
} from './dependencyPolicy';
import { FEATURE_PUBLIC_INTERFACES } from './featureInterfaces';
@@ -211,6 +212,8 @@ describe('feature public-interface registry', () => {
describe('production dependency graph', () => {
it('classifies every production import and has no unowned violation', () => {
+ primeImportSources(Object.entries(sources).map(([path, source]) => [toSourcePath(path), source] as const));
+
const violations = Object.entries(sources)
.filter(([path]) => isProduction(path))
.flatMap(([path, source]) => checkSource(toSourcePath(path), source))
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
index 0a35ff0739..cd97a21e0f 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
@@ -1,6 +1,20 @@
-import ts from 'typescript-legacy';
+import type { Node } from 'typescript/unstable/ast';
+
+import {
+ isCallExpression,
+ isExportDeclaration,
+ isImportDeclaration,
+ isImportTypeNode,
+ isLiteralTypeNode,
+ isNamedImports,
+ isNamespaceExport,
+ isNamespaceImport,
+ isStringLiteralLikeNode,
+ SyntaxKind,
+} from 'typescript/unstable/ast';
import { FEATURE_PUBLIC_INTERFACES } from './featureInterfaces';
+import { parseSource, primeSources } from './tsSourceParser';
export type ModuleOwner = 'app' | 'platform' | 'workbench' | `feature:${string}`;
@@ -55,44 +69,57 @@ const normalizePath = (path: string): string => {
return parts.join('/');
};
+/**
+ * Loads a whole corpus into the parser in one round trip. Call this before
+ * sweeping a tree with {@link collectImportReferences} or {@link checkSource};
+ * the entries must be the same `[fileName, source]` pairs the sweep passes, so
+ * each later call is served from the already-loaded program.
+ */
+export const primeImportSources = (entries: Iterable<readonly [string, string]>): void => {
+ primeSources(entries, { jsx: true });
+};
+
export const collectImportReferences = (source: string, fileName = 'source.ts'): ImportReference[] => {
- const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const sourceFile = parseSource(fileName, source, { jsx: true });
const references: ImportReference[] = [];
- const pushLiteral = (kind: ImportReference['kind'], node: ts.Node | undefined, exposesCanvasEngine = false): void => {
- if (node && ts.isStringLiteralLike(node)) {
+ const pushLiteral = (kind: ImportReference['kind'], node: Node | undefined, exposesCanvasEngine = false): void => {
+ if (node && isStringLiteralLikeNode(node)) {
references.push({ exposesCanvasEngine, kind, specifier: node.text });
}
};
- const visit = (node: ts.Node): void => {
- if (ts.isImportDeclaration(node)) {
+ const visit = (node: Node): void => {
+ if (isImportDeclaration(node)) {
const bindings = node.importClause?.namedBindings;
const exposesCanvasEngine =
- Boolean(bindings && ts.isNamespaceImport(bindings)) ||
+ Boolean(bindings && isNamespaceImport(bindings)) ||
Boolean(
bindings &&
- ts.isNamedImports(bindings) &&
+ isNamedImports(bindings) &&
bindings.elements.some((element) => (element.propertyName ?? element.name).text === 'CanvasEngine')
);
- pushLiteral(node.importClause?.isTypeOnly ? 'import-type' : 'import', node.moduleSpecifier, exposesCanvasEngine);
- } else if (ts.isExportDeclaration(node)) {
+ // TypeScript 7 models `import type` as a phase modifier alongside
+ // `import defer`, which replaced the old `isTypeOnly` flag.
+ const isTypeOnly = node.importClause?.phaseModifier === SyntaxKind.TypeKeyword;
+ pushLiteral(isTypeOnly ? 'import-type' : 'import', node.moduleSpecifier, exposesCanvasEngine);
+ } else if (isExportDeclaration(node)) {
const exposesCanvasEngine =
!node.exportClause ||
- ts.isNamespaceExport(node.exportClause) ||
+ isNamespaceExport(node.exportClause) ||
node.exportClause.elements.some((element) => (element.propertyName ?? element.name).text === 'CanvasEngine');
pushLiteral(
- !node.exportClause || ts.isNamespaceExport(node.exportClause) ? 'export-star' : 'export',
+ !node.exportClause || isNamespaceExport(node.exportClause) ? 'export-star' : 'export',
node.moduleSpecifier,
exposesCanvasEngine
);
- } else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
+ } else if (isImportTypeNode(node) && isLiteralTypeNode(node.argument)) {
pushLiteral('import-type', node.argument.literal, node.qualifier?.getText(sourceFile).includes('CanvasEngine'));
- } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
+ } else if (isCallExpression(node) && node.expression.kind === SyntaxKind.ImportKeyword) {
pushLiteral('dynamic-import', node.arguments[0]);
}
- ts.forEachChild(node, visit);
+ node.forEachChild(visit);
};
visit(sourceFile);
diff --git a/invokeai/frontend/webv2/src/architecture/tsSourceParser.ts b/invokeai/frontend/webv2/src/architecture/tsSourceParser.ts
new file mode 100644
index 0000000000..1aa6e1e59a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/architecture/tsSourceParser.ts
@@ -0,0 +1,112 @@
+import type { SourceFile } from 'typescript/unstable/ast';
+
+import { createVirtualFileSystem } from 'typescript/unstable/fs';
+import { API } from 'typescript/unstable/sync';
+
+/**
+ * TypeScript 7 removed the in-process `ts.createSourceFile` parser. The
+ * replacement surface only hands out ASTs for files that belong to a program,
+ * so the architecture analyzers parse through a virtual filesystem backed by a
+ * single long-lived tsgo session instead of parsing detached strings.
+ *
+ * Files are staged into the virtual project and flushed in one `updateSnapshot`
+ * call, which keeps a whole-tree sweep to a single round trip.
+ */
+const PARSE_ROOT = '/architecture-sources';
+const CONFIG_PATH = `${PARSE_ROOT}/tsconfig.json`;
+const SEED_PATH = `${PARSE_ROOT}/seed.tsx`;
+
+// `noLib` keeps lib.d.ts out of the program: these analyzers only ever walk
+// syntax, so skipping the default library removes the bulk of the load cost.
+const CONFIG = JSON.stringify({
+ compilerOptions: { allowJs: true, jsx: 'preserve', module: 'esnext', noLib: true, target: 'esnext' },
+ include: ['**/*'],
+});
+
+interface ParseOptions {
+ /** Defaults to the logical file name's extension. */
+ jsx?: boolean;
+}
+
+let fileSystem: ReturnType<typeof createVirtualFileSystem> | undefined;
+let api: API | undefined;
+let snapshot: ReturnType<API['updateSnapshot']> | undefined;
+let nextId = 0;
+const virtualPaths = new Map<string, string>();
+const stagedText = new Map<string, string>();
+const created: string[] = [];
+const changed: string[] = [];
+
+const ensureSession = (): void => {
+ if (!api) {
+ fileSystem = createVirtualFileSystem({ [CONFIG_PATH]: CONFIG, [SEED_PATH]: 'export {};' });
+ api = new API({ cwd: PARSE_ROOT, fs: fileSystem });
+ snapshot = api.updateSnapshot({ openProjects: [CONFIG_PATH] });
+ }
+};
+
+/**
+ * Logical paths are analyzer-facing labels rather than real files, so each one
+ * gets an opaque virtual path. The extension carries the only parse-visible
+ * decision: `.tsx` parses `<T>` as JSX, `.ts` parses it as a type assertion.
+ */
+const virtualPathFor = (fileName: string, jsx: boolean): string => {
+ const key = `${jsx ? 'x' : ''}:${fileName}`;
+ let virtualPath = virtualPaths.get(key);
+ if (!virtualPath) {
+ virtualPath = `${PARSE_ROOT}/${nextId++}.${jsx ? 'tsx' : 'ts'}`;
+ virtualPaths.set(key, virtualPath);
+ }
+ return virtualPath;
+};
+
+const stage = (fileName: string, text: string, jsx: boolean): string => {
+ ensureSession();
+ const virtualPath = virtualPathFor(fileName, jsx);
+ if (stagedText.get(virtualPath) === text) {
+ return virtualPath;
+ }
+ (stagedText.has(virtualPath) ? changed : created).push(virtualPath);
+ stagedText.set(virtualPath, text);
+ fileSystem?.writeFile?.(virtualPath, text);
+ return virtualPath;
+};
+
+const flush = (): void => {
+ if (created.length === 0 && changed.length === 0) {
+ return;
+ }
+ snapshot = api?.updateSnapshot({
+ fileChanges: { changed: [...changed], created: [...created] },
+ openProjects: [CONFIG_PATH],
+ });
+ created.length = 0;
+ changed.length = 0;
+};
+
+const read = (virtualPath: string, fileName: string): SourceFile => {
+ const sourceFile = snapshot?.getProjects()[0]?.program.getSourceFile(virtualPath);
+ if (!sourceFile) {
+ throw new Error(`Failed to parse ${fileName} through the TypeScript API.`);
+ }
+ return sourceFile;
+};
+
+const resolveJsx = (fileName: string, jsx: boolean | undefined): boolean => jsx ?? fileName.endsWith('x');
+
+/**
+ * Stage many sources and load them with one snapshot update. Use this before a
+ * whole-tree sweep; parsing each file on its own costs a round trip apiece.
+ */
+export const primeSources = (entries: Iterable<readonly [string, string]>, { jsx }: ParseOptions = {}): void => {
+ for (const [fileName, text] of entries) {
+ stage(fileName, text, resolveJsx(fileName, jsx));
+ }
+ flush();
+};
+
+export const parseSource = (fileName: string, text: string, { jsx }: ParseOptions = {}): SourceFile => {
+ const virtualPath = stage(fileName, text, resolveJsx(fileName, jsx));
+ flush();
+ return read(virtualPath, fileName);
+};
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnership.test.ts b/invokeai/frontend/webv2/src/architecture/workbenchOwnership.test.ts
index 0d2e2707cf..c83062602b 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnership.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnership.test.ts
@@ -1,7 +1,25 @@
-import ts from 'typescript-legacy';
+import type { SourceFile, Statement } from 'typescript/unstable/ast';
+
+import {
+ isClassDeclaration,
+ isEmptyStatement,
+ isEnumDeclaration,
+ isExportAssignment,
+ isExportDeclaration,
+ isFunctionDeclaration,
+ isIdentifier,
+ isImportDeclaration,
+ isInterfaceDeclaration,
+ isNamedExports,
+ isTypeAliasDeclaration,
+ isVariableStatement,
+ ModifierFlags,
+ SyntaxKind,
+} from 'typescript/unstable/ast';
import { describe, expect, it } from 'vitest';
-import { collectImportReferences, getModuleOwner, resolveImportPath } from './dependencyPolicy';
+import { collectImportReferences, getModuleOwner, primeImportSources, resolveImportPath } from './dependencyPolicy';
+import { parseSource } from './tsSourceParser';
import { getWorkbenchTargetOwner, getWorkbenchTargetPath, workbenchOwnershipManifest } from './workbenchOwnership';
const sources = import.meta.glob('../**/*.{ts,tsx}', {
@@ -35,36 +53,42 @@ const resolveSourceFile = (sourcePath: string, specifier: string): string | null
const getTargetOwner = (path: string) =>
path.startsWith('workbench/') ? getWorkbenchTargetOwner(path) : getModuleOwner(path);
-const collectPublicExports = (sourceFile: ts.SourceFile): string[] => {
+// TypeScript 7 folds the modifier list into `modifierFlags`, which only the
+// statement kinds that accept modifiers declare.
+const hasExportModifier = (statement: Statement): boolean => {
+ const { modifierFlags } = statement as { modifierFlags?: ModifierFlags };
+ return modifierFlags !== undefined && (modifierFlags & ModifierFlags.Export) !== 0;
+};
+
+const collectPublicExports = (sourceFile: SourceFile): string[] => {
const exports = new Set<string>();
for (const statement of sourceFile.statements) {
- const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;
- if (modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
+ if (hasExportModifier(statement)) {
if (
- (ts.isClassDeclaration(statement) ||
- ts.isFunctionDeclaration(statement) ||
- ts.isInterfaceDeclaration(statement) ||
- ts.isTypeAliasDeclaration(statement) ||
- ts.isEnumDeclaration(statement)) &&
+ (isClassDeclaration(statement) ||
+ isFunctionDeclaration(statement) ||
+ isInterfaceDeclaration(statement) ||
+ isTypeAliasDeclaration(statement) ||
+ isEnumDeclaration(statement)) &&
statement.name
) {
exports.add(statement.name.text);
- } else if (ts.isVariableStatement(statement)) {
+ } else if (isVariableStatement(statement)) {
for (const declaration of statement.declarationList.declarations) {
- if (ts.isIdentifier(declaration.name)) {
+ if (isIdentifier(declaration.name)) {
exports.add(declaration.name.text);
}
}
}
}
- if (ts.isExportAssignment(statement)) {
+ if (isExportAssignment(statement)) {
exports.add('default');
}
- if (ts.isExportDeclaration(statement)) {
+ if (isExportDeclaration(statement)) {
if (!statement.exportClause) {
exports.add('*');
- } else if (ts.isNamedExports(statement.exportClause)) {
+ } else if (isNamedExports(statement.exportClause)) {
for (const element of statement.exportClause.elements) {
exports.add(element.name.text);
}
@@ -75,18 +99,18 @@ const collectPublicExports = (sourceFile: ts.SourceFile): string[] => {
return [...exports].sort();
};
-const isTypeOnlyModule = (sourceFile: ts.SourceFile): boolean => {
+const isTypeOnlyModule = (sourceFile: SourceFile): boolean => {
return sourceFile.statements.every((statement) => {
- if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) {
+ if (isInterfaceDeclaration(statement) || isTypeAliasDeclaration(statement)) {
return true;
}
- if (ts.isImportDeclaration(statement)) {
- return Boolean(statement.importClause?.isTypeOnly);
+ if (isImportDeclaration(statement)) {
+ return statement.importClause?.phaseModifier === SyntaxKind.TypeKeyword;
}
- if (ts.isExportDeclaration(statement)) {
+ if (isExportDeclaration(statement)) {
return statement.isTypeOnly;
}
- return ts.isEmptyStatement(statement);
+ return isEmptyStatement(statement);
});
};
@@ -137,6 +161,7 @@ const stronglyConnectedComponents = (graph: Map<string, Set<string>>): string[][
describe('Workbench ownership manifest', () => {
it('classifies every production Workbench module exactly once and emits an inspectable inventory', () => {
const workbenchSources = Object.entries(productionSources).filter(([path]) => path.startsWith('workbench/'));
+ primeImportSources(Object.entries(productionSources));
const importReferencesByPath = new Map(
Object.entries(productionSources).map(([path, source]) => [path, collectImportReferences(source, path)] as const)
);
@@ -193,7 +218,7 @@ describe('Workbench ownership manifest', () => {
const records = workbenchSources.map(([path, source]) => {
const targetOwner = getWorkbenchTargetOwner(path);
expect(targetOwner, `Unclassified: ${path}`).not.toBeNull();
- const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const sourceFile = parseSource(path, source, { jsx: true });
const outboundOwners = new Set<string>();
for (const reference of importReferencesByPath.get(path) ?? []) {