mirror of
https://github.com/angular/angular.git
synced 2026-11-22 22:55:25 -05:00
refactor(compiler-cli): integrate hybrid preprocessor into compiler-cli
Integrate the hybrid Angular preprocessor (NGP) under packages/compiler-cli/preprocessor, along with its language service integration, VS Code extension, and Rust/Wasm Bazel toolchain. Key components included: - Rust-based AST analyzer and Wasm compilation target (packages/compiler-cli/preprocessor/ng-analyze) - Preprocessor engine and Jasmine test suites (packages/compiler-cli/preprocessor) - Language service extension and specs (packages/compiler-cli/preprocessor/language-service) - Experimental VS Code extension (ngp-vscode-ng-language-service) - Rust toolchain and crate dependencies in Bazel (MODULE.bazel, Cargo.toml) Monorepo integration & compatibility adjustments: - Rust toolchain & hermetic Bazel testing: Made N-API optional (default = [] in Cargo.toml) and added non-NAPI fallback methods on Analyzer and TestAnalyzer (analyzer.rs, test_analyzer.rs, lib.rs) for native Bazel rust_test and Wasm compilation; replaced static Cargo.toml lookups in fs.rs tests with hermetic tempfile fixtures for Bazel sandbox execution; updated driver test fixture for Option<String> local_name. - Angular monorepo TypeScript & linting compliance: Added tslint:disable:no-console pragmas to CLI entrypoints (main.ts, ngp.ts); added explicit override modifiers (output_ast_printer.ts); aligned TypeScript ESM imports (tcb_ls_util.ts); and consolidated compiler imports and type references (processor.ts, hybrid_compiler.ts). Co-authored-by: Matthew Beck <[email protected]> Co-authored-by: Alex Rickabaugh <[email protected]> Co-authored-by: Kristiyan Kostadinov <[email protected]> Co-authored-by: JoostK <[email protected]> Co-authored-by: Matthieu Riegler <[email protected]>
This commit is contained in:
committed by
Kristiyan Kostadinov
co-authored by
Matthew Beck
Alex Rickabaugh
Kristiyan Kostadinov
JoostK
Matthieu Riegler
parent
12d0e4a4f2
commit
4e4ad75144
@@ -4,3 +4,6 @@
|
||||
# JS and TS files must always use LF for tools to work
|
||||
*.js eol=lf
|
||||
*.ts eol=lf
|
||||
|
||||
# Preserve verbatim line endings for NGP golden test fixtures
|
||||
packages/compiler-cli/preprocessor/test/golden/** -text
|
||||
|
||||
@@ -80,6 +80,8 @@ jobs:
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Run CI tests for framework
|
||||
run: pnpm test:ci
|
||||
# TODO(atscott): Enable preprocessor language service tests (pnpm test:ngp:language-service).
|
||||
# TODO(atscott): Enable preprocessor VS Code extension tests (pnpm test:ngp:vscode).
|
||||
|
||||
integration-tests:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -86,6 +86,8 @@ jobs:
|
||||
# Ensures Aspect lock files are up-to-date.
|
||||
# TODO(devversion): Remove when removing pnpm.
|
||||
ASPECT_RULES_JS_FROZEN_PNPM_LOCK: '1'
|
||||
# TODO(atscott): Enable preprocessor language service tests (pnpm test:ngp:language-service).
|
||||
# TODO(atscott): Enable preprocessor VS Code extension tests (pnpm test:ngp:vscode).
|
||||
- name: Upload GRPC logs (for debugging of RBE issues)
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
*.log
|
||||
node_modules/
|
||||
modules/ssr-benchmarks/node_modules/
|
||||
/ngp-vscode-ng-language-service/dist/
|
||||
/.vscode-test/
|
||||
/.vscode-test-user-data/
|
||||
.jasmine_build/
|
||||
|
||||
# Include when developing application packages.
|
||||
pubspec.lock
|
||||
@@ -57,3 +61,6 @@ baseline.json
|
||||
|
||||
# pnpm store
|
||||
.pnpm-store
|
||||
|
||||
# Cargo target directory
|
||||
target/
|
||||
|
||||
@@ -47,3 +47,11 @@ adev/src/content/examples/schematics-for-libraries/projects/my-lib/package.json
|
||||
|
||||
CHANGELOG.md
|
||||
CHANGELOG_ARCHIVE.md
|
||||
|
||||
# Ignore NGP test fixture markdown files
|
||||
packages/compiler-cli/preprocessor/test/golden/**
|
||||
|
||||
# Ignore NGP language service test workspaces
|
||||
packages/compiler-cli/preprocessor/language-service/tests/test-workspace/**
|
||||
ngp-vscode-ng-language-service/tests/test-workspace/**
|
||||
ngp-vscode-ng-language-service/e2e/test-workspace/**
|
||||
|
||||
Generated
+1678
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"packages/compiler-cli/preprocessor/ng-analyze",
|
||||
]
|
||||
resolver = "3"
|
||||
@@ -13,6 +13,7 @@ bazel_dep(name = "aspect_rules_jasmine", version = "2.0.4")
|
||||
bazel_dep(name = "aspect_rules_rollup", version = "2.0.1")
|
||||
bazel_dep(name = "bazel_skylib", version = "1.9.2")
|
||||
bazel_dep(name = "bazel_lib", version = "3.7.2")
|
||||
bazel_dep(name = "platforms", version = "1.1.0")
|
||||
bazel_dep(name = "tar.bzl", version = "0.10.9")
|
||||
bazel_dep(name = "yq.bzl", version = "0.4.0")
|
||||
bazel_dep(name = "rules_angular")
|
||||
@@ -163,3 +164,25 @@ cldr_xml_data(
|
||||
"https://github.com/unicode-org/cldr/releases/download/release-%s/core.zip" % CLDR_VERSION: "d5ee2abac64158c04884a722f8ef4830ea22b6c74aac20185be2838db8eda788",
|
||||
},
|
||||
)
|
||||
|
||||
bazel_dep(name = "rules_rust", version = "0.74.0")
|
||||
bazel_dep(name = "rules_rust_wasm_bindgen", version = "0.74.0")
|
||||
|
||||
rust = use_extension("@rules_rust//rust:extensions.bzl", "rust")
|
||||
rust.toolchain(
|
||||
edition = "2024",
|
||||
extra_target_triples = ["wasm32-unknown-unknown"],
|
||||
)
|
||||
use_repo(rust, "rust_toolchains")
|
||||
|
||||
register_toolchains("@rust_toolchains//:all")
|
||||
|
||||
register_toolchains("@rules_rust_wasm_bindgen//:default_wasm_bindgen_toolchain")
|
||||
|
||||
crate = use_extension("@rules_rust//crate_universe:extensions.bzl", "crate")
|
||||
crate.from_cargo(
|
||||
name = "crates",
|
||||
cargo_lockfile = "//:Cargo.lock",
|
||||
manifests = ["//:Cargo.toml"],
|
||||
)
|
||||
use_repo(crate, "crates")
|
||||
|
||||
Generated
+2729
-4
File diff suppressed because one or more lines are too long
@@ -0,0 +1,91 @@
|
||||
const esbuild = require('esbuild');
|
||||
const fs = require('fs/promises');
|
||||
const path = require('path');
|
||||
|
||||
const exactExternalPlugin = {
|
||||
name: 'exact-external',
|
||||
setup(build) {
|
||||
const externals = new Set([
|
||||
'@angular/compiler',
|
||||
'@angular/compiler-cli',
|
||||
'@angular/language-service/api',
|
||||
]);
|
||||
build.onResolve({filter: /^@angular\//}, (args) => {
|
||||
if (externals.has(args.path)) {
|
||||
return {path: args.path, external: true};
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
async function build() {
|
||||
// 1. Build Client
|
||||
console.log('Building client...');
|
||||
await esbuild.build({
|
||||
entryPoints: [path.join(__dirname, 'client/src/extension.ts')],
|
||||
bundle: true,
|
||||
platform: 'node',
|
||||
format: 'cjs',
|
||||
outfile: path.join(__dirname, 'dist/client/extension.js'),
|
||||
external: ['vscode'],
|
||||
});
|
||||
|
||||
// 2. Build Server
|
||||
console.log('Building server...');
|
||||
const repoRoot = path.resolve(__dirname, '..');
|
||||
await esbuild.build({
|
||||
entryPoints: [path.join(__dirname, 'server/src/server.ts')],
|
||||
bundle: true,
|
||||
platform: 'node',
|
||||
format: 'cjs',
|
||||
nodePaths: [path.join(__dirname, 'node_modules')],
|
||||
outfile: path.join(__dirname, 'dist/server/server.js'),
|
||||
external: [
|
||||
path.join(__dirname, '../packages/compiler-cli/preprocessor/ng-analyze/index.js'),
|
||||
path.join(__dirname, '../packages/compiler-cli/preprocessor/ng-analyze-wasm/ng_analyze.js'),
|
||||
'typescript',
|
||||
],
|
||||
alias: {
|
||||
'@angular/compiler-cli/private/hybrid_analysis': path.join(
|
||||
repoRoot,
|
||||
'packages/compiler-cli/private/hybrid_analysis.ts',
|
||||
),
|
||||
'@angular/compiler-cli/private/migrations': path.join(
|
||||
repoRoot,
|
||||
'packages/compiler-cli/private/migrations.ts',
|
||||
),
|
||||
'@angular/compiler-cli': path.join(repoRoot, 'packages/compiler-cli/index.ts'),
|
||||
'@angular/compiler': path.join(repoRoot, 'packages/compiler/index.ts'),
|
||||
'@angular/language-service/private': path.join(
|
||||
repoRoot,
|
||||
'packages/language-service/private.ts',
|
||||
),
|
||||
'@angular/language-service/api': path.join(repoRoot, 'packages/language-service/api.ts'),
|
||||
'@angular/language-service': path.join(repoRoot, 'packages/language-service/api.ts'),
|
||||
'@angular/core': path.join(repoRoot, 'packages/core/index.ts'),
|
||||
},
|
||||
logOverride: {
|
||||
'empty-import-meta': 'silent',
|
||||
},
|
||||
});
|
||||
|
||||
// 3. Patch Server for import.meta.url compatibility in CJS
|
||||
console.log('Patching server bundle...');
|
||||
const serverOutPath = path.join(__dirname, 'dist/server/server.js');
|
||||
let serverContent = await fs.readFile(serverOutPath, 'utf8');
|
||||
serverContent = serverContent.replace(
|
||||
/import_meta(\d*)\.url/g,
|
||||
"require('url').pathToFileURL(__filename).href",
|
||||
);
|
||||
serverContent = serverContent.replace(
|
||||
/var import_meta(\d*) = \{\};/g,
|
||||
"var import_meta$1 = { url: require('url').pathToFileURL(__filename).href };",
|
||||
);
|
||||
await fs.writeFile(serverOutPath, serverContent);
|
||||
console.log('Successfully patched server bundle.');
|
||||
}
|
||||
|
||||
build().catch((err) => {
|
||||
console.error('Build failed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "vscode-ng-language-service-client",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"main": "out/extension.js",
|
||||
"scripts": {
|
||||
"compile": "tsc -p .",
|
||||
"watch": "tsc -p . -w"
|
||||
},
|
||||
"dependencies": {
|
||||
"vscode-languageclient": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/vscode": "^1.125.0",
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import * as vscode from 'vscode';
|
||||
import {LanguageClient} from 'vscode-languageclient/node';
|
||||
|
||||
export function registerCommands(
|
||||
context: vscode.ExtensionContext,
|
||||
client: LanguageClient,
|
||||
outputChannel: vscode.OutputChannel,
|
||||
) {
|
||||
const TCB_HIGHLIGHT_DECORATION = vscode.window.createTextEditorDecorationType({
|
||||
backgroundColor: new vscode.ThemeColor('editor.selectionHighlightBackground'),
|
||||
});
|
||||
|
||||
const tcbProvider = new TcbContentProvider();
|
||||
context.subscriptions.push(
|
||||
vscode.workspace.registerTextDocumentContentProvider('ng', tcbProvider),
|
||||
);
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerTextEditorCommand('angular.getTemplateTcb', async (textEditor) => {
|
||||
tcbProvider.clear();
|
||||
try {
|
||||
outputChannel.appendLine('Requesting TCB from server...');
|
||||
const response = (await client.sendRequest('angular/getTcb', {
|
||||
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(textEditor.document),
|
||||
position: client.code2ProtocolConverter.asPosition(textEditor.selection.active),
|
||||
})) as {uri: string; content: string; selections: any[]} | null;
|
||||
|
||||
if (!response) {
|
||||
vscode.window.showInformationMessage('No TCB available for this position.');
|
||||
return;
|
||||
}
|
||||
|
||||
outputChannel.appendLine(
|
||||
`Received TCB response. Content length: ${response.content.length}`,
|
||||
);
|
||||
|
||||
const tcbUri = vscode.Uri.parse(response.uri).with({
|
||||
scheme: 'ng',
|
||||
});
|
||||
tcbProvider.update(tcbUri, response.content);
|
||||
const editor = await vscode.window.showTextDocument(tcbUri, {
|
||||
viewColumn: vscode.ViewColumn.Beside,
|
||||
preserveFocus: true,
|
||||
});
|
||||
|
||||
const selections = response.selections.map((s: any) => {
|
||||
return new vscode.Range(
|
||||
new vscode.Position(s.start.line, s.start.character),
|
||||
new vscode.Position(s.end.line, s.end.character),
|
||||
);
|
||||
});
|
||||
|
||||
editor.setDecorations(TCB_HIGHLIGHT_DECORATION, selections);
|
||||
} catch (err) {
|
||||
vscode.window.showErrorMessage(`Failed to get TCB: ${err}`);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
class TcbContentProvider implements vscode.TextDocumentContentProvider {
|
||||
private readonly _onDidChange = new vscode.EventEmitter<vscode.Uri>();
|
||||
readonly onDidChange = this._onDidChange.event;
|
||||
|
||||
private readonly uisToContents = new Map<string, string>();
|
||||
|
||||
provideTextDocumentContent(uri: vscode.Uri): string | undefined {
|
||||
return this.uisToContents.get(uri.toString());
|
||||
}
|
||||
|
||||
update(uri: vscode.Uri, content: string) {
|
||||
this.uisToContents.set(uri.toString(), content);
|
||||
this._onDidChange.fire(uri);
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.uisToContents.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import * as path from 'path';
|
||||
import * as vscode from 'vscode';
|
||||
import {
|
||||
LanguageClient,
|
||||
LanguageClientOptions,
|
||||
ServerOptions,
|
||||
TransportKind,
|
||||
} from 'vscode-languageclient/node';
|
||||
import {registerCommands} from './commands';
|
||||
import * as fs from 'node:fs/promises';
|
||||
|
||||
let client: LanguageClient;
|
||||
|
||||
export async function activate(context: vscode.ExtensionContext) {
|
||||
const outputChannel = vscode.window.createOutputChannel(
|
||||
'Angular Hybrid Language Service Prototype',
|
||||
{log: true},
|
||||
);
|
||||
|
||||
let tsApiPipe: string | undefined;
|
||||
try {
|
||||
const commands = await vscode.commands.getCommands();
|
||||
if (commands.includes('typescript.native-preview.initializeAPIConnection')) {
|
||||
tsApiPipe = await vscode.commands.executeCommand<string>(
|
||||
'typescript.native-preview.initializeAPIConnection',
|
||||
);
|
||||
if (tsApiPipe) {
|
||||
outputChannel.appendLine(
|
||||
`Reusing existing TypeScript API connection on pipe: ${tsApiPipe}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
outputChannel.appendLine(`Could not get existing TypeScript API connection: ${err}`);
|
||||
}
|
||||
|
||||
// The server is implemented in node
|
||||
const serverModule = context.asAbsolutePath(path.join('dist', 'server', 'server.js'));
|
||||
|
||||
// Define the server options
|
||||
const serverOptions: ServerOptions = {
|
||||
run: {module: serverModule, transport: TransportKind.ipc},
|
||||
debug: {
|
||||
module: serverModule,
|
||||
transport: TransportKind.ipc,
|
||||
options: {
|
||||
execArgv: ['--nolazy', '--inspect=6009'],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Define client options
|
||||
const clientOptions: LanguageClientOptions = {
|
||||
outputChannel,
|
||||
documentSelector: [
|
||||
{scheme: 'file', language: 'html'},
|
||||
{scheme: 'file', language: 'typescript'},
|
||||
],
|
||||
synchronize: {
|
||||
fileEvents: vscode.workspace.createFileSystemWatcher('**/*.ts'),
|
||||
},
|
||||
initializationOptions: {
|
||||
tsApiPipe,
|
||||
},
|
||||
};
|
||||
|
||||
client = new LanguageClient(
|
||||
'angularLanguageService',
|
||||
'Angular Hybrid Language Service Prototype',
|
||||
serverOptions,
|
||||
clientOptions,
|
||||
);
|
||||
|
||||
registerCommands(context, client, outputChannel);
|
||||
|
||||
const startAngularClientPromise = client.start().catch((err) => {
|
||||
outputChannel.appendLine(`Failed to start Angular Language Service: ${err}`);
|
||||
});
|
||||
|
||||
const tsGoPath = await resolveTsGoPath();
|
||||
|
||||
// If we already connected to an existing TypeScript LSP server via tsApiPipe,
|
||||
// we do not need to launch a separate fallback ts7Client.
|
||||
// Otherwise, if tsGoPath is available, launch our fallback ts7Client.
|
||||
if (!tsApiPipe && tsGoPath) {
|
||||
launchTs7Client(tsGoPath, context);
|
||||
}
|
||||
}
|
||||
|
||||
function launchTs7Client(tsGoPath: string, context: vscode.ExtensionContext) {
|
||||
const isNative =
|
||||
tsGoPath.includes(`native-preview-${process.platform}-${process.arch}`) ||
|
||||
tsGoPath.endsWith('/tsgo.exe') ||
|
||||
tsGoPath.endsWith('/built/local/tsgo');
|
||||
const ts7ServerOptions: ServerOptions = isNative
|
||||
? {
|
||||
command: tsGoPath,
|
||||
args: ['--lsp', '--stdio'],
|
||||
}
|
||||
: {
|
||||
command: process.execPath,
|
||||
args: [tsGoPath, '--lsp', '--stdio'],
|
||||
options: {
|
||||
env: {
|
||||
...process.env,
|
||||
ELECTRON_RUN_AS_NODE: '1',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const ts7OutputChannel = vscode.window.createOutputChannel('Angular TS 7 Server', {log: true});
|
||||
const ts7ClientOptions: LanguageClientOptions = {
|
||||
outputChannel: ts7OutputChannel,
|
||||
documentSelector: [{scheme: 'file', language: 'typescript'}],
|
||||
middleware: new Proxy(
|
||||
{},
|
||||
{
|
||||
get(target, prop) {
|
||||
if (
|
||||
typeof prop === 'string' &&
|
||||
(prop.startsWith('provide') || prop.startsWith('resolve'))
|
||||
) {
|
||||
// Return a function that returns undefined to suppress the provider
|
||||
return () => undefined;
|
||||
}
|
||||
// use default behavior
|
||||
return undefined;
|
||||
},
|
||||
},
|
||||
),
|
||||
synchronize: {
|
||||
fileEvents: vscode.workspace.createFileSystemWatcher('**/*.ts'),
|
||||
},
|
||||
};
|
||||
|
||||
const ts7Client = new LanguageClient(
|
||||
'ng-ts-server',
|
||||
'Angular TS 7 Server',
|
||||
ts7ServerOptions,
|
||||
ts7ClientOptions,
|
||||
);
|
||||
|
||||
ts7Client
|
||||
.start()
|
||||
.then(async () => {
|
||||
try {
|
||||
const res = await ts7Client!.sendRequest<{sessionId: string; pipe: string}>(
|
||||
'custom/initializeAPISession',
|
||||
{},
|
||||
);
|
||||
if (res?.pipe) {
|
||||
client.sendNotification('angular/setTsApiPipe', {pipe: res.pipe});
|
||||
}
|
||||
} catch {}
|
||||
})
|
||||
.catch((err) => {
|
||||
ts7OutputChannel.appendLine(`Failed to start TS 7 Server: ${err}`);
|
||||
});
|
||||
context.subscriptions.push(registerTs7RelayHandlers(client, ts7Client));
|
||||
}
|
||||
|
||||
export function deactivate(): Thenable<void> | undefined {
|
||||
if (!client) {
|
||||
return undefined;
|
||||
}
|
||||
return client.stop();
|
||||
}
|
||||
|
||||
function registerTs7RelayHandlers(
|
||||
angularClient: LanguageClient,
|
||||
ts7Client: LanguageClient,
|
||||
): vscode.Disposable {
|
||||
const disposables: vscode.Disposable[] = [];
|
||||
|
||||
disposables.push(
|
||||
angularClient.onRequest(
|
||||
'angular/sendTsServerRequest',
|
||||
async (params: {method: string; params: any}) => {
|
||||
return ts7Client.sendRequest(params.method, params.params);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
disposables.push(
|
||||
angularClient.onNotification(
|
||||
'angular/sendTsServerNotification',
|
||||
async (params: {method: string; params: any}) => {
|
||||
ts7Client.sendNotification(params.method, params.params);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
return vscode.Disposable.from(...disposables);
|
||||
}
|
||||
|
||||
const pathExists = (p: string): Promise<boolean> =>
|
||||
fs.access(p).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
|
||||
async function resolveTsGoPath(): Promise<string | null> {
|
||||
if (process.env.TSGO_BINARY_PATH) {
|
||||
return process.env.TSGO_BINARY_PATH;
|
||||
}
|
||||
|
||||
const workspaceRoot = path.resolve(__dirname, '../../..');
|
||||
|
||||
const platformName = `@typescript/native-preview-${process.platform}-${process.arch}`;
|
||||
const localCandidates = [
|
||||
path.join(workspaceRoot, 'node_modules', platformName, 'lib', 'tsgo'),
|
||||
path.join(workspaceRoot, 'node_modules', '@typescript', 'native-preview', 'bin', 'tsgo'),
|
||||
path.join(workspaceRoot, 'node_modules', '@typescript', 'native-preview', 'bin', 'tsgo.js'),
|
||||
];
|
||||
|
||||
const localResults = await Promise.all(
|
||||
localCandidates.map(async (candidate) => ((await pathExists(candidate)) ? candidate : null)),
|
||||
);
|
||||
const foundLocal = localResults.find((c): c is string => c !== null);
|
||||
if (foundLocal) {
|
||||
return foundLocal;
|
||||
}
|
||||
|
||||
const tsGoExtension = vscode.extensions.getExtension('typescriptteam.native-preview');
|
||||
if (tsGoExtension) {
|
||||
const extensionPath = tsGoExtension.extensionPath;
|
||||
const candidates = [
|
||||
path.join(extensionPath, 'bin', 'tsgo'),
|
||||
path.join(extensionPath, 'bin', 'tsgo.exe'),
|
||||
path.join(extensionPath, 'lib', 'tsgo'),
|
||||
path.join(extensionPath, 'lib', 'tsgo.exe'),
|
||||
path.join(extensionPath, 'tsgo'),
|
||||
path.join(extensionPath, 'tsgo.exe'),
|
||||
];
|
||||
|
||||
const extResults = await Promise.all(
|
||||
candidates.map(async (candidate) => ((await pathExists(candidate)) ? candidate : null)),
|
||||
);
|
||||
const foundExt = extResults.find((c): c is string => c !== null);
|
||||
if (foundExt) {
|
||||
return foundExt;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../dist/client",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
const esbuild = require('esbuild');
|
||||
const path = require('path');
|
||||
const fs = require('fs/promises');
|
||||
|
||||
const outdir = path.join(__dirname, 'dist');
|
||||
|
||||
async function build() {
|
||||
console.log('Building E2E tests...');
|
||||
await fs.rm(outdir, {recursive: true, force: true});
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: [
|
||||
path.join(__dirname, 'src/index.ts'),
|
||||
path.join(__dirname, 'src/hover.ts'),
|
||||
path.join(__dirname, 'src/getTcb.ts'),
|
||||
path.join(__dirname, 'src/definition.ts'),
|
||||
path.join(__dirname, 'src/diagnostics.ts'),
|
||||
path.join(__dirname, 'src/diagnostics_ext.ts'),
|
||||
],
|
||||
bundle: true,
|
||||
platform: 'node',
|
||||
format: 'cjs',
|
||||
outdir: path.join(__dirname, 'dist'),
|
||||
external: ['vscode'],
|
||||
});
|
||||
}
|
||||
|
||||
build().catch((err) => {
|
||||
console.error('Build failed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
const path = require('path');
|
||||
const {runTests} = require('@vscode/test-electron');
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const extensionDevelopmentPath = path.resolve(__dirname, '../');
|
||||
const extensionTestsPath = path.resolve(__dirname, './dist/index');
|
||||
|
||||
// Create workspace for testing
|
||||
const workspacePath = path.resolve(__dirname, 'test-workspace');
|
||||
const userDataDir = path.resolve(__dirname, '../../.vscode-test-user-data');
|
||||
|
||||
await runTests({
|
||||
extensionDevelopmentPath,
|
||||
extensionTestsPath,
|
||||
launchArgs: [workspacePath, '--disable-extensions', `--user-data-dir=${userDataDir}`],
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to run tests', err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,93 @@
|
||||
import * as vscode from 'vscode';
|
||||
import * as assert from 'assert';
|
||||
import * as path from 'path';
|
||||
import {waitFor} from './utils';
|
||||
|
||||
export async function run() {
|
||||
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
|
||||
if (!workspaceRoot) {
|
||||
throw new Error('No workspace root found');
|
||||
}
|
||||
|
||||
const testFilePath = path.join(workspaceRoot, 'app.ts');
|
||||
const uri = vscode.Uri.file(testFilePath);
|
||||
|
||||
console.log(`Open file: ${testFilePath}`);
|
||||
const document = await vscode.workspace.openTextDocument(uri);
|
||||
await vscode.window.showTextDocument(document);
|
||||
|
||||
// Test 1: Definition of 'name' in template
|
||||
// Line 34 (0-indexed 33): <div>Hello {{ name }}</div>
|
||||
// 'n' is at character 18
|
||||
const namePosition = new vscode.Position(33, 18);
|
||||
console.log(`Querying definition for name at Position(33, 18)...`);
|
||||
|
||||
// Wait for server to be ready
|
||||
const nameDefinitions = await waitFor(
|
||||
() =>
|
||||
vscode.commands.executeCommand<vscode.Location[] | vscode.LocationLink[]>(
|
||||
'vscode.executeDefinitionProvider',
|
||||
uri,
|
||||
namePosition,
|
||||
),
|
||||
(defs) => !!defs && defs.length > 0,
|
||||
);
|
||||
|
||||
assert.ok(
|
||||
nameDefinitions && nameDefinitions.length > 0,
|
||||
'Should return at least one definition for name',
|
||||
);
|
||||
|
||||
const nameDef = nameDefinitions[0];
|
||||
const nameUri = 'uri' in nameDef ? nameDef.uri : nameDef.targetUri;
|
||||
const nameRange = 'range' in nameDef ? nameDef.range : nameDef.targetRange;
|
||||
|
||||
console.log(`Definition URI for name: ${nameUri.toString()}`);
|
||||
console.log(`Definition Range for name: ${nameRange.start.line}:${nameRange.start.character}`);
|
||||
|
||||
assert.strictEqual(nameUri.fsPath, testFilePath, 'Definition should be in the same file');
|
||||
// name is declared on line 63 (0-indexed 62): name = 'Angular LS Test';
|
||||
assert.strictEqual(nameRange.start.line, 62, 'Definition line should be 62');
|
||||
|
||||
// Test 2: Definition of 'isSidenavOpen' in click handler
|
||||
// Line 40 (0-indexed 39): (click)="isSidenavOpen.set(false)"
|
||||
// 'i' is at character 17
|
||||
const sidenavPosition = new vscode.Position(39, 17);
|
||||
console.log(`Querying definition for isSidenavOpen at Position(39, 17)...`);
|
||||
const sidenavDefs = await vscode.commands.executeCommand<
|
||||
vscode.Location[] | vscode.LocationLink[]
|
||||
>('vscode.executeDefinitionProvider', uri, sidenavPosition);
|
||||
|
||||
assert.ok(
|
||||
sidenavDefs && sidenavDefs.length > 0,
|
||||
'Should return at least one definition for isSidenavOpen',
|
||||
);
|
||||
const sidenavDef = sidenavDefs[0];
|
||||
const sidenavUri = 'uri' in sidenavDef ? sidenavDef.uri : sidenavDef.targetUri;
|
||||
const sidenavRange = 'range' in sidenavDef ? sidenavDef.range : sidenavDef.targetRange;
|
||||
|
||||
assert.strictEqual(sidenavUri.fsPath, testFilePath, 'Definition should be in the same file');
|
||||
// isSidenavOpen is declared on line 64 (0-indexed 63): isSidenavOpen = signal(true);
|
||||
assert.strictEqual(sidenavRange.start.line, 63, 'Definition line should be 63');
|
||||
|
||||
// Test 3: Definition of 'my-dir-elem' element
|
||||
// Line 49 (0-indexed 48): <my-dir-elem></my-dir-elem>
|
||||
// 'm' is at character 5
|
||||
const myDirElemPosition = new vscode.Position(48, 5);
|
||||
console.log(`Querying definition for my-dir-elem at Position(48, 5)...`);
|
||||
const myDirElemDefs = await vscode.commands.executeCommand<
|
||||
vscode.Location[] | vscode.LocationLink[]
|
||||
>('vscode.executeDefinitionProvider', uri, myDirElemPosition);
|
||||
|
||||
assert.ok(
|
||||
myDirElemDefs && myDirElemDefs.length > 0,
|
||||
'Should return at least one definition for my-dir-elem',
|
||||
);
|
||||
const myDirElemDef = myDirElemDefs[0];
|
||||
const myDirElemUri = 'uri' in myDirElemDef ? myDirElemDef.uri : myDirElemDef.targetUri;
|
||||
const myDirElemRange = 'range' in myDirElemDef ? myDirElemDef.range : myDirElemDef.targetRange;
|
||||
|
||||
assert.strictEqual(myDirElemUri.fsPath, testFilePath, 'Definition should be in the same file');
|
||||
// MyDirElemComponent starts at class declaration on line 73 (0-indexed 72)
|
||||
assert.strictEqual(myDirElemRange.start.line, 72, 'Definition line should be 72');
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import * as vscode from 'vscode';
|
||||
import * as assert from 'assert';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs/promises';
|
||||
import {waitFor} from './utils';
|
||||
|
||||
export async function run() {
|
||||
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
|
||||
if (!workspaceRoot) {
|
||||
throw new Error('No workspace root found');
|
||||
}
|
||||
|
||||
await runCleanStateTest(workspaceRoot);
|
||||
await runSingleDiagnosticTest(workspaceRoot);
|
||||
await runMultipleDiagnosticsTest(workspaceRoot);
|
||||
await runDiagnosticsSideFileTest(workspaceRoot);
|
||||
}
|
||||
|
||||
async function runCleanStateTest(workspaceRoot: string) {
|
||||
const testFilePath = path.join(workspaceRoot, 'diagnostics_clean_test.ts');
|
||||
const uri = vscode.Uri.file(testFilePath);
|
||||
|
||||
const fileContent = `
|
||||
import {Component} from '@angular/core';
|
||||
@Component({
|
||||
selector: 'app-diag-clean-test',
|
||||
template: '<div>Hello World</div>',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppDiagCleanTestComponent {}
|
||||
`;
|
||||
|
||||
console.log(`Creating clean file: ${testFilePath}`);
|
||||
await fs.writeFile(testFilePath, fileContent);
|
||||
|
||||
try {
|
||||
console.log(`Open clean file: ${testFilePath}`);
|
||||
const document = await vscode.workspace.openTextDocument(uri);
|
||||
await vscode.window.showTextDocument(document);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
console.log(`Checking for no diagnostics...`);
|
||||
const diagnostics = vscode.languages.getDiagnostics(uri);
|
||||
const filteredDiagnostics = diagnostics.filter(
|
||||
(d) => !d.message.includes('_t1') && !d.message.includes('Identifier expected'),
|
||||
);
|
||||
console.log(`Found diagnostics: ${diagnostics.map((d) => d.message).join(', ')}`);
|
||||
console.log(`Filtered diagnostics: ${filteredDiagnostics.map((d) => d.message).join(', ')}`);
|
||||
assert.strictEqual(
|
||||
filteredDiagnostics.length,
|
||||
0,
|
||||
`Should return zero diagnostics for clean file after filtering noise, but found: ${filteredDiagnostics.map((d) => d.message).join(', ')}`,
|
||||
);
|
||||
console.log('Clean state test passed!');
|
||||
} finally {
|
||||
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
|
||||
await cleanupFile(testFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSingleDiagnosticTest(workspaceRoot: string) {
|
||||
const testFilePath = path.join(workspaceRoot, 'diagnostics_single_test.ts');
|
||||
const uri = vscode.Uri.file(testFilePath);
|
||||
|
||||
const fileContent = `
|
||||
import {Component} from '@angular/core';
|
||||
@Component({
|
||||
selector: 'app-diag-single-test',
|
||||
template: '<div>{{ nonExistentProp }}</div>',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppDiagSingleTestComponent {}
|
||||
`;
|
||||
|
||||
console.log(`Creating file with single error: ${testFilePath}`);
|
||||
await fs.writeFile(testFilePath, fileContent);
|
||||
|
||||
try {
|
||||
console.log(`Open file: ${testFilePath}`);
|
||||
const document = await vscode.workspace.openTextDocument(uri);
|
||||
await vscode.window.showTextDocument(document);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
console.log('Making dummy edit...');
|
||||
await vscode.window.activeTextEditor?.edit((editBuilder) => {
|
||||
editBuilder.insert(new vscode.Position(0, 0), '// Dummy comment\n');
|
||||
});
|
||||
await document.save();
|
||||
|
||||
console.log(`Waiting for diagnostics...`);
|
||||
const diagnostics = await waitFor(
|
||||
() => vscode.languages.getDiagnostics(uri),
|
||||
(diags) => diags.length > 0,
|
||||
{timeout: 10000},
|
||||
);
|
||||
|
||||
assert.ok(diagnostics.length > 0, 'Should return at least one diagnostic');
|
||||
const found = diagnostics.find((d) => d.message.includes('nonExistentProp'));
|
||||
assert.ok(found, 'Should find a diagnostic mentioning nonExistentProp');
|
||||
console.log('Single diagnostic test passed!');
|
||||
} finally {
|
||||
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
|
||||
await cleanupFile(testFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
async function runMultipleDiagnosticsTest(workspaceRoot: string) {
|
||||
const testFilePath = path.join(workspaceRoot, 'diagnostics_multi_test.ts');
|
||||
const uri = vscode.Uri.file(testFilePath);
|
||||
|
||||
const fileContent = `
|
||||
import {Component} from '@angular/core';
|
||||
@Component({
|
||||
selector: 'app-diag-multi-test',
|
||||
template: '<div>{{ prop1 }}</div><div>{{ prop2 }}</div>',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppDiagMultiTestComponent {}
|
||||
`;
|
||||
|
||||
console.log(`Creating file with multiple errors: ${testFilePath}`);
|
||||
await fs.writeFile(testFilePath, fileContent);
|
||||
|
||||
try {
|
||||
console.log(`Open file: ${testFilePath}`);
|
||||
const document = await vscode.workspace.openTextDocument(uri);
|
||||
await vscode.window.showTextDocument(document);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
console.log('Making dummy edit...');
|
||||
await vscode.window.activeTextEditor?.edit((editBuilder) => {
|
||||
editBuilder.insert(new vscode.Position(0, 0), '// Dummy comment\n');
|
||||
});
|
||||
await document.save();
|
||||
|
||||
console.log(`Waiting for diagnostics...`);
|
||||
const diagnostics = await waitFor(
|
||||
() => vscode.languages.getDiagnostics(uri),
|
||||
(diags) => diags.length >= 2,
|
||||
{timeout: 10000},
|
||||
);
|
||||
|
||||
assert.ok(diagnostics.length >= 2, 'Should return at least two diagnostics');
|
||||
const found1 = diagnostics.find((d) => d.message.includes('prop1'));
|
||||
const found2 = diagnostics.find((d) => d.message.includes('prop2'));
|
||||
assert.ok(found1, 'Should find a diagnostic mentioning prop1');
|
||||
assert.ok(found2, 'Should find a diagnostic mentioning prop2');
|
||||
console.log('Multiple diagnostics test passed!');
|
||||
} finally {
|
||||
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
|
||||
await cleanupFile(testFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
async function runDiagnosticsSideFileTest(workspaceRoot: string) {
|
||||
const tsFilePath = path.join(workspaceRoot, 'app_diag_side_test.ts');
|
||||
const htmlFilePath = path.join(workspaceRoot, 'app_diag_side_test.html');
|
||||
const tsUri = vscode.Uri.file(tsFilePath);
|
||||
const htmlUri = vscode.Uri.file(htmlFilePath);
|
||||
|
||||
const appTsContent = `
|
||||
import {Component} from '@angular/core';
|
||||
@Component({
|
||||
selector: 'app-diag-side-test',
|
||||
templateUrl: './app_diag_side_test.html',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppDiagSideTestComponent {}
|
||||
`;
|
||||
const templateContent = '<div>{{ nonExistentProp }}</div>';
|
||||
|
||||
console.log(`Creating side-file test files`);
|
||||
await Promise.all([
|
||||
fs.writeFile(tsFilePath, appTsContent),
|
||||
fs.writeFile(htmlFilePath, templateContent),
|
||||
]);
|
||||
|
||||
try {
|
||||
console.log(`Open file: ${tsFilePath}`);
|
||||
const document = await vscode.workspace.openTextDocument(tsUri);
|
||||
await vscode.window.showTextDocument(document);
|
||||
|
||||
const htmlDoc = await vscode.workspace.openTextDocument(htmlUri);
|
||||
await vscode.window.showTextDocument(htmlDoc);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
console.log('Making dummy edit to trigger analysis...');
|
||||
const dummyEdit = new vscode.WorkspaceEdit();
|
||||
dummyEdit.insert(tsUri, new vscode.Position(0, 0), '// Dummy comment\n');
|
||||
await vscode.workspace.applyEdit(dummyEdit);
|
||||
await document.save();
|
||||
|
||||
console.log(`Waiting for diagnostics on HTML file...`);
|
||||
const htmlDiagnostics = await waitFor(
|
||||
() => vscode.languages.getDiagnostics(htmlUri),
|
||||
(diags) => diags.length > 0,
|
||||
{timeout: 10000},
|
||||
);
|
||||
|
||||
assert.ok(htmlDiagnostics.length > 0, 'Should return at least one diagnostic for HTML file');
|
||||
assert.ok(
|
||||
htmlDiagnostics.some((d) => d.message.includes('nonExistentProp')),
|
||||
'Should find a diagnostic mentioning nonExistentProp on HTML file',
|
||||
);
|
||||
|
||||
// Now fix the error by changing template or adding property.
|
||||
const fixedTsContent = `
|
||||
import {Component} from '@angular/core';
|
||||
@Component({
|
||||
selector: 'app-diag-side-test',
|
||||
templateUrl: './app_diag_side_test.html',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppDiagSideTestComponent {
|
||||
nonExistentProp = 'hello';
|
||||
}
|
||||
`;
|
||||
|
||||
console.log('Applying fix to TS file...');
|
||||
const fixEdit = new vscode.WorkspaceEdit();
|
||||
const fullRange = new vscode.Range(
|
||||
document.positionAt(0),
|
||||
document.positionAt(document.getText().length),
|
||||
);
|
||||
fixEdit.replace(tsUri, fullRange, fixedTsContent);
|
||||
await vscode.workspace.applyEdit(fixEdit);
|
||||
await document.save();
|
||||
|
||||
// Show HTML document and trigger re-evaluation
|
||||
const htmlEditor = await vscode.window.showTextDocument(htmlDoc);
|
||||
await htmlEditor.edit((editBuilder) => {
|
||||
editBuilder.insert(new vscode.Position(0, 0), ' ');
|
||||
});
|
||||
await htmlDoc.save();
|
||||
|
||||
console.log(`Waiting for diagnostics on HTML file to clear...`);
|
||||
const clearedDiagnostics = await waitFor(
|
||||
() => vscode.languages.getDiagnostics(htmlUri),
|
||||
(diags) => diags.length === 0,
|
||||
{timeout: 10000},
|
||||
);
|
||||
|
||||
assert.strictEqual(clearedDiagnostics.length, 0, 'Should clear diagnostics for HTML file');
|
||||
console.log('Side-file diagnostic test passed!');
|
||||
} finally {
|
||||
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
|
||||
await Promise.all([cleanupFile(tsFilePath), cleanupFile(htmlFilePath)]);
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanupFile(filePath: string) {
|
||||
console.log(`Cleaning up file: ${filePath}`);
|
||||
await fs.rm(filePath, {force: true});
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import * as vscode from 'vscode';
|
||||
import * as assert from 'assert';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs/promises';
|
||||
import {waitFor} from './utils';
|
||||
|
||||
export async function run() {
|
||||
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
|
||||
if (!workspaceRoot) {
|
||||
throw new Error('No workspace root found');
|
||||
}
|
||||
|
||||
const extTsFilePath = path.join(workspaceRoot, 'diagnostics_ext_test.ts');
|
||||
const extTsUri = vscode.Uri.file(extTsFilePath);
|
||||
const extHtmlFilePath = path.join(workspaceRoot, 'diagnostics_ext_test.html');
|
||||
const extHtmlUri = vscode.Uri.file(extHtmlFilePath);
|
||||
|
||||
const extTsContent = `
|
||||
import {Component} from '@angular/core';
|
||||
@Component({
|
||||
selector: 'app-diag-ext-test',
|
||||
templateUrl: './diagnostics_ext_test.html',
|
||||
standalone: true,
|
||||
})
|
||||
export class AppDiagExtTestComponent {
|
||||
name: string = "hello";
|
||||
}
|
||||
`;
|
||||
|
||||
const extHtmlContent = `<div>{{ nonExistentProp }}</div>`;
|
||||
|
||||
console.log(`Creating files: ${extHtmlFilePath}, ${extTsFilePath}`);
|
||||
await Promise.all([
|
||||
fs.writeFile(extHtmlFilePath, extHtmlContent),
|
||||
fs.writeFile(extTsFilePath, extTsContent),
|
||||
]);
|
||||
|
||||
try {
|
||||
console.log(`Open external test TS file: ${extTsFilePath}`);
|
||||
const tsDoc = await vscode.workspace.openTextDocument(extTsUri);
|
||||
await vscode.window.showTextDocument(tsDoc);
|
||||
|
||||
// Wait for server to analyze TS file
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
console.log(`Open external test HTML file: ${extHtmlFilePath}`);
|
||||
const htmlDoc = await vscode.workspace.openTextDocument(extHtmlUri);
|
||||
await vscode.window.showTextDocument(htmlDoc);
|
||||
|
||||
console.log(`Waiting for diagnostics on HTML file...`);
|
||||
const diagnostics = await waitFor(
|
||||
() => vscode.languages.getDiagnostics(extHtmlUri),
|
||||
(diags) => diags.length > 0,
|
||||
{timeout: 10000},
|
||||
);
|
||||
|
||||
assert.ok(diagnostics.length > 0, 'Should return at least one diagnostic');
|
||||
|
||||
const found = diagnostics.find((d) => d.message.includes('nonExistentProp'));
|
||||
assert.ok(
|
||||
found,
|
||||
`Should find a diagnostic mentioning nonExistentProp. Available diagnostics: ${diagnostics.map((d) => d.message).join(', ')}`,
|
||||
);
|
||||
|
||||
console.log(`Found expected diagnostic: ${found.message}`);
|
||||
assert.strictEqual(found.range.start.line, 0, 'Diagnostic should be on line 0 (template)');
|
||||
} finally {
|
||||
console.log(`Cleaning up files...`);
|
||||
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
|
||||
|
||||
await Promise.all([fs.rm(extTsFilePath, {force: true}), fs.rm(extHtmlFilePath, {force: true})]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import * as vscode from 'vscode';
|
||||
import * as path from 'path';
|
||||
import * as assert from 'assert';
|
||||
import {waitFor} from './utils';
|
||||
|
||||
export async function run() {
|
||||
console.log('Running TCB tests...');
|
||||
|
||||
const workspaceRoot = vscode.workspace.workspaceFolders?.[0].uri.fsPath;
|
||||
if (!workspaceRoot) {
|
||||
throw new Error('No workspace folder found');
|
||||
}
|
||||
|
||||
const appComponentUri = vscode.Uri.file(path.join(workspaceRoot, 'app.ts'));
|
||||
const document = await vscode.workspace.openTextDocument(appComponentUri);
|
||||
const editor = await vscode.window.showTextDocument(document);
|
||||
|
||||
// Position inside the template (e.g., inside 'track $index' or 'name')
|
||||
// Line 34 is @for... let's use line 33 (0-indexed) for $index
|
||||
const position = new vscode.Position(33, 20); // $index
|
||||
editor.selection = new vscode.Selection(position, position);
|
||||
|
||||
console.log('Executing angular.getTemplateTcb command...');
|
||||
await vscode.commands.executeCommand('angular.getTemplateTcb');
|
||||
|
||||
console.log('Waiting for TCB document to open...');
|
||||
// Poll for the TCB document to open
|
||||
const tcbEditor = await waitFor(
|
||||
() => vscode.window.visibleTextEditors.find((e) => e.document.uri.scheme === 'ng'),
|
||||
(editor) => !!editor,
|
||||
);
|
||||
|
||||
assert.ok(tcbEditor, 'Expected a TCB editor to be open with scheme "ng"');
|
||||
|
||||
const content = tcbEditor.document.getText();
|
||||
assert.ok(content.length > 0, 'Expected TCB content to be non-empty');
|
||||
|
||||
// Strict assertions
|
||||
assert.ok(
|
||||
content.match(/function\s+.*AppComponent/),
|
||||
'Expected TCB to contain the component Type Check Function',
|
||||
);
|
||||
assert.ok(
|
||||
content.includes('.routes'),
|
||||
'Expected TCB to reference component properties used in the template (routes)',
|
||||
);
|
||||
assert.ok(
|
||||
content.includes('RouterLinkStub'),
|
||||
'Expected TCB to reference directive types used in the template (RouterLinkStub)',
|
||||
);
|
||||
|
||||
console.log('TCB tests passed!');
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,21 @@
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs/promises';
|
||||
|
||||
export async function run(): Promise<void> {
|
||||
console.log('Starting E2E tests...');
|
||||
const testsRoot = path.resolve(__dirname);
|
||||
const entries = await fs.readdir(testsRoot);
|
||||
const files = entries.filter((f) => f.endsWith('.js') && f !== 'index.js');
|
||||
|
||||
console.log(`Found ${files.length} test files to run...`);
|
||||
|
||||
// Run tests sequentially and wait for them if they are async
|
||||
for (const file of files) {
|
||||
const testPath = path.join(testsRoot, file);
|
||||
console.log(`Running test: ${file}`);
|
||||
const testModule = require(testPath);
|
||||
if (testModule.run) {
|
||||
await testModule.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export interface WaitForOptions {
|
||||
timeout?: number;
|
||||
interval?: number;
|
||||
}
|
||||
|
||||
export async function waitFor<T>(
|
||||
action: () => PromiseLike<T> | T,
|
||||
isValid: (result: T) => boolean,
|
||||
options: WaitForOptions = {},
|
||||
): Promise<T> {
|
||||
const timeout = options.timeout ?? 5000;
|
||||
const interval = options.interval ?? 100;
|
||||
const startTime = Date.now();
|
||||
while (Date.now() - startTime < timeout) {
|
||||
const result = await action();
|
||||
if (isValid(result)) {
|
||||
return result;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, interval));
|
||||
}
|
||||
throw new Error(`Timed out waiting for condition after ${timeout}ms`);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import {Component, Directive, Input, signal} from '@angular/core';
|
||||
import {MyAttrDirective} from './my-attr.directive';
|
||||
import {MatListItemStub} from './mat-list-item.component';
|
||||
|
||||
@Directive({
|
||||
selector: '[routerLink]',
|
||||
standalone: true,
|
||||
})
|
||||
export class RouterLinkStub {
|
||||
@Input() routerLink: any;
|
||||
}
|
||||
|
||||
@Directive({
|
||||
selector: '[routerLinkActive]',
|
||||
standalone: true,
|
||||
})
|
||||
export class RouterLinkActiveStub {
|
||||
@Input() routerLinkActive: any;
|
||||
}
|
||||
|
||||
@Directive({
|
||||
selector: '[ngSrc]',
|
||||
standalone: true,
|
||||
})
|
||||
export class NgSrcStub {
|
||||
@Input() ngSrc: any;
|
||||
@Input() width: any;
|
||||
@Input() height: any;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
template: `
|
||||
<div>Hello {{ name }}</div>
|
||||
@for (route of routes; track $index) {
|
||||
<a
|
||||
mat-list-item
|
||||
routerLink="{{ route.path }}"
|
||||
routerLinkActive="active"
|
||||
(click)="isSidenavOpen.set(false)"
|
||||
>
|
||||
<div class="nav-item-with-image">
|
||||
<img [ngSrc]="route?.data?.['icon']" width="100" height="60" />
|
||||
<span style="padding-left: 16px" mat-line> {{ route.title }} </span>
|
||||
</div>
|
||||
</a>
|
||||
}
|
||||
<div mat-list-item id="outside-for">Test outside for</div>
|
||||
<my-dir-elem></my-dir-elem>
|
||||
<div myAttr></div>
|
||||
`,
|
||||
standalone: true,
|
||||
imports: [
|
||||
RouterLinkStub,
|
||||
RouterLinkActiveStub,
|
||||
NgSrcStub,
|
||||
MyDirElemComponent,
|
||||
MyAttrDirective,
|
||||
MatListItemStub,
|
||||
],
|
||||
})
|
||||
export class AppComponent {
|
||||
name = 'Angular LS Test';
|
||||
isSidenavOpen = signal(true);
|
||||
routes = [{path: 'home', title: 'Home', data: {icon: 'home'}}];
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'my-dir-elem',
|
||||
standalone: true,
|
||||
template: `<div>My Dir Elem</div>`,
|
||||
})
|
||||
export class MyDirElemComponent {}
|
||||
|
||||
@Component({
|
||||
selector: 'app-external',
|
||||
templateUrl: './external.html',
|
||||
standalone: true,
|
||||
})
|
||||
export class ExternalComponent {
|
||||
externalTitle = 'External Template Works!';
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import {Component, signal} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'my-dir-elem',
|
||||
standalone: true,
|
||||
template: `<div>My Dir Elem</div>`,
|
||||
})
|
||||
export class MyDirElemComponent {}
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
template: `
|
||||
<div>Hello</div>
|
||||
<my-dir-elem></my-dir-elem>
|
||||
`,
|
||||
standalone: true,
|
||||
imports: [MyDirElemComponent],
|
||||
})
|
||||
export class AppComponent {}
|
||||
@@ -0,0 +1 @@
|
||||
<div>Hello from {{ externalTitle }}</div>
|
||||
@@ -0,0 +1,10 @@
|
||||
import {Component} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-isolated-inc',
|
||||
template: '<div>Hello {{ name }}</div>',
|
||||
standalone: true,
|
||||
})
|
||||
export class IsolatedIncComponent {
|
||||
name = 'Angular LS Test';
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import {Component, Input} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: '[mat-list-item]',
|
||||
standalone: true,
|
||||
template: '<ng-content></ng-content>',
|
||||
})
|
||||
export class MatListItemStub {
|
||||
@Input() activated: boolean = false;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {Directive} from '@angular/core';
|
||||
|
||||
@Directive({
|
||||
selector: '[myAttr]',
|
||||
standalone: true,
|
||||
})
|
||||
export class MyAttrDirective {}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"moduleResolution": "bundler"
|
||||
},
|
||||
"include": ["*.ts"]
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user