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): consume shared source analysis

joshistoastde6d9497ec80
diff --git a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
index bda23229e7..04a4baec93 100644
--- a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
@@ -1,6 +1,20 @@
import { describe, expect, it } from 'vitest';
describe('architecture workflow', () => {
+ it('confines unstable TypeScript imports to the source-analysis adapter', () => {
+ const modules = import.meta.glob('./*.ts', { eager: true, import: 'default', query: '?raw' }) as Record<
+ string,
+ string
+ >;
+ const unstablePrefix = ['typescript', 'unstable'].join('/');
+ const offenders = Object.entries(modules)
+ .filter(([path]) => !path.endsWith('/tsSourceAnalysis.ts'))
+ .filter(([, source]) => source.includes(unstablePrefix))
+ .map(([path]) => path)
+ .sort();
+ expect(offenders).toEqual([]);
+ });
+
it('retains architecture inventories and performance reports in one CI artifact even on failure', () => {
const workflows = import.meta.glob('../../../../../.github/workflows/frontend-tests.yml', {
eager: true,
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
index 0432d7e72f..f526cff46e 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { afterAll, describe, expect, it } from 'vitest';
import {
checkDependency,
@@ -12,6 +12,7 @@ import {
} from './dependencyPolicy';
import { FEATURE_PUBLIC_INTERFACES } from './featureInterfaces';
import { migrationExceptions } from './migrationExceptions';
+import { closeSourceAnalysis } from './tsSourceAnalysis';
const sources = import.meta.glob('../**/*.{ts,tsx}', {
eager: true,
@@ -22,6 +23,8 @@ const sources = import.meta.glob('../**/*.{ts,tsx}', {
const toSourcePath = (path: string): string => path.replace(/^\.\.\//, '');
const isProduction = (path: string): boolean => !/\.(?:test|browser\.test)\.[^.]+$/.test(path);
+afterAll(closeSourceAnalysis);
+
describe('dependency policy parser', () => {
it('classifies every supported TypeScript import form', () => {
const references = collectImportReferences(`
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
index cd97a21e0f..d314faf6d7 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
@@ -1,20 +1,5 @@
-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';
+import { analyzeSource, primeSourceAnalysis } from './tsSourceAnalysis';
export type ModuleOwner = 'app' | 'platform' | 'workbench' | `feature:${string}`;
@@ -76,55 +61,20 @@ const normalizePath = (path: string): string => {
* each later call is served from the already-loaded program.
*/
export const primeImportSources = (entries: Iterable<readonly [string, string]>): void => {
- primeSources(entries, { jsx: true });
+ primeSourceAnalysis(entries, { jsx: true });
};
-export const collectImportReferences = (source: string, fileName = 'source.ts'): ImportReference[] => {
- const sourceFile = parseSource(fileName, source, { jsx: true });
- const references: ImportReference[] = [];
-
- 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: Node): void => {
- if (isImportDeclaration(node)) {
- const bindings = node.importClause?.namedBindings;
- const exposesCanvasEngine =
- Boolean(bindings && isNamespaceImport(bindings)) ||
- Boolean(
- bindings &&
- isNamedImports(bindings) &&
- bindings.elements.some((element) => (element.propertyName ?? element.name).text === 'CanvasEngine')
- );
- // 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 ||
- isNamespaceExport(node.exportClause) ||
- node.exportClause.elements.some((element) => (element.propertyName ?? element.name).text === 'CanvasEngine');
- pushLiteral(
- !node.exportClause || isNamespaceExport(node.exportClause) ? 'export-star' : 'export',
- node.moduleSpecifier,
- exposesCanvasEngine
- );
- } else if (isImportTypeNode(node) && isLiteralTypeNode(node.argument)) {
- pushLiteral('import-type', node.argument.literal, node.qualifier?.getText(sourceFile).includes('CanvasEngine'));
- } else if (isCallExpression(node) && node.expression.kind === SyntaxKind.ImportKeyword) {
- pushLiteral('dynamic-import', node.arguments[0]);
- }
-
- node.forEachChild(visit);
- };
+export const collectImportReferences = (source: string, fileName = 'source.ts'): ImportReference[] =>
+ analyzeSource(fileName, source, { jsx: true }).moduleReferences.map((reference) => {
+ const exposesCanvasEngine =
+ (reference.form === 'import-declaration' &&
+ (reference.namespace || reference.symbols.includes('CanvasEngine'))) ||
+ (reference.form === 'export-declaration' &&
+ (reference.namespace || reference.symbols.includes('CanvasEngine'))) ||
+ (reference.form === 'import-type' && reference.qualifier?.includes('CanvasEngine') === true);
- visit(sourceFile);
- return references;
-};
+ return { exposesCanvasEngine, kind: reference.kind, specifier: reference.specifier };
+ });
export const resolveImportPath = (sourcePath: string, specifier: string): string | null => {
if (specifier.startsWith('.')) {
diff --git a/invokeai/frontend/webv2/src/architecture/tsSourceParser.ts b/invokeai/frontend/webv2/src/architecture/tsSourceParser.ts
deleted file mode 100644
index 1aa6e1e59a..0000000000
--- a/invokeai/frontend/webv2/src/architecture/tsSourceParser.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-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 c83062602b..4dfed99f57 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnership.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnership.test.ts
@@ -1,25 +1,7 @@
-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 { afterAll, describe, expect, it } from 'vitest';
import { collectImportReferences, getModuleOwner, primeImportSources, resolveImportPath } from './dependencyPolicy';
-import { parseSource } from './tsSourceParser';
+import { analyzeSource, closeSourceAnalysis } from './tsSourceAnalysis';
import { getWorkbenchTargetOwner, getWorkbenchTargetPath, workbenchOwnershipManifest } from './workbenchOwnership';
const sources = import.meta.glob('../**/*.{ts,tsx}', {
@@ -53,66 +35,7 @@ const resolveSourceFile = (sourcePath: string, specifier: string): string | null
const getTargetOwner = (path: string) =>
path.startsWith('workbench/') ? getWorkbenchTargetOwner(path) : getModuleOwner(path);
-// 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) {
- if (hasExportModifier(statement)) {
- if (
- (isClassDeclaration(statement) ||
- isFunctionDeclaration(statement) ||
- isInterfaceDeclaration(statement) ||
- isTypeAliasDeclaration(statement) ||
- isEnumDeclaration(statement)) &&
- statement.name
- ) {
- exports.add(statement.name.text);
- } else if (isVariableStatement(statement)) {
- for (const declaration of statement.declarationList.declarations) {
- if (isIdentifier(declaration.name)) {
- exports.add(declaration.name.text);
- }
- }
- }
- }
- if (isExportAssignment(statement)) {
- exports.add('default');
- }
- if (isExportDeclaration(statement)) {
- if (!statement.exportClause) {
- exports.add('*');
- } else if (isNamedExports(statement.exportClause)) {
- for (const element of statement.exportClause.elements) {
- exports.add(element.name.text);
- }
- }
- }
- }
-
- return [...exports].sort();
-};
-
-const isTypeOnlyModule = (sourceFile: SourceFile): boolean => {
- return sourceFile.statements.every((statement) => {
- if (isInterfaceDeclaration(statement) || isTypeAliasDeclaration(statement)) {
- return true;
- }
- if (isImportDeclaration(statement)) {
- return statement.importClause?.phaseModifier === SyntaxKind.TypeKeyword;
- }
- if (isExportDeclaration(statement)) {
- return statement.isTypeOnly;
- }
- return isEmptyStatement(statement);
- });
-};
+afterAll(closeSourceAnalysis);
const stronglyConnectedComponents = (graph: Map<string, Set<string>>): string[][] => {
let nextIndex = 0;
@@ -218,7 +141,7 @@ describe('Workbench ownership manifest', () => {
const records = workbenchSources.map(([path, source]) => {
const targetOwner = getWorkbenchTargetOwner(path);
expect(targetOwner, `Unclassified: ${path}`).not.toBeNull();
- const sourceFile = parseSource(path, source, { jsx: true });
+ const analysis = analyzeSource(path, source, { jsx: true });
const outboundOwners = new Set<string>();
for (const reference of importReferencesByPath.get(path) ?? []) {
@@ -240,10 +163,10 @@ describe('Workbench ownership manifest', () => {
return {
currentOwner: 'workbench',
inboundOwners: [] as string[],
- moduleKind: isTypeOnlyModule(sourceFile) ? 'type-only' : 'runtime',
+ moduleKind: analysis.typeOnly ? 'type-only' : 'runtime',
outboundOwners: [...outboundOwners].sort(),
path,
- publicExports: collectPublicExports(sourceFile),
+ publicExports: [...analysis.publicExports],
targetOwner,
targetPath: getWorkbenchTargetPath(path),
testCompanions,