Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions build/BUILD_EVENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Extension build lifecycle events

Set `VSCODE_BUILD_EVENTS=1` to add machine-readable lifecycle events to extension TypeScript watch compilations (`watch-extension:*`) and extension builds using `extensions/esbuild-common.mts`. Other values, including an unset variable, disable events. Existing human-readable compilation logs remain available.

Each event is one uncolored JSON object on its own stdout line. Human-readable logs remain interleaved with these records; stdout as a whole is not a JSONL-only stream.

```jsonl
{"type":"vscode.build","version":1,"event":"start"}
{"type":"vscode.build","version":1,"event":"finish","success":true}
{"type":"vscode.build","version":1,"event":"finish","success":false}
```

`start` begins a cycle. Exactly one `finish` event follows once all overlapping builds in that cycle finish: `success: false` if any build failed, otherwise `success: true`. A later cycle starts with a clean failure state. Before-build hooks, esbuild plugins, and asynchronous postprocessing are part of the build: readiness is not reported until they finish, and their errors fail the cycle.

Consumers should parse complete lines and recognize records by `type: "vscode.build"`. Version 1 defines `event: "start"` and `event: "finish"` with a required boolean `success` on finish. Ignore unrelated log lines and unknown additional fields; field order is not significant. Additional metadata can be introduced without a version bump. Incompatible changes require a new version, which consumers should report as unsupported rather than treating as successful completion.

Aggregation is local to each runner process and lifecycle: the gulp extension watcher aggregates TypeScript compilations, and each esbuild runner process aggregates its concurrent builds. Consumers must keep separate processes' output separate; these events do not describe the readiness of the entire repository. Watcher subscription errors remain diagnostics, not completed build cycles.

Without the opt-in, no event lines are printed. Build errors still follow the existing behavior: one-shot esbuild runners exit unsuccessfully, while watchers log failures and allow subsequent rebuilds. One-shot failures now allow overlapping builds to finish before the process exits, and print hook errors before exiting.

Run the focused tests with Node 24 or later:

```sh
node --test build/lib/test/buildEvents.test.ts extensions/esbuild-common.test.mts
```
26 changes: 8 additions & 18 deletions build/gulpfile.extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,28 +23,18 @@ import { createTsgoStream, spawnTsgo } from './lib/tsgo.ts';
import { getCompilerOptionsFromTsConfig } from './lib/tsconfigUtils.ts';
import * as util from './lib/util.ts';
import watcher from './lib/watch/index.ts';
import { BuildLifecycle } from './lib/buildEvents.ts';

const root = path.dirname(import.meta.dirname);
const commit = getVersion(root);

// Tracks active extension compilations to emit aggregate
// "Starting compilation" / "Finished compilation" messages
// that the problem matcher in tasks.json relies on.
let activeExtensionCompilations = 0;

function onExtensionCompilationStart(): void {
if (activeExtensionCompilations === 0) {
fancyLog('Starting compilation');
}
activeExtensionCompilations++;
}

function onExtensionCompilationEnd(): void {
activeExtensionCompilations--;
if (activeExtensionCompilations === 0) {
fancyLog('Finished compilation');
}
}
const extensionCompilation = new BuildLifecycle(
() => fancyLog('Starting compilation'),
() => fancyLog('Finished compilation'),
);

// To save 250ms for each gulp startup, we are caching the result here
// const compilations = glob.sync('**/tsconfig.json', {
Expand Down Expand Up @@ -198,10 +188,10 @@ export function createExtensionTasks(tsconfigFile: string, repoRoot = root) {

const watchTask = task.define(`watch-extension:${name}`, task.series(cleanTask, () => {
const nonts = gulp.src(src, srcOpts).pipe(filter(['**', '!**/*.{ts,mts,cts}'], { dot: true }));
const watchInput = watcher(src, { ...srcOpts, ...{ readDelay: 200 } });
const watchInput = watcher(path.relative(repoRoot, src).split(path.sep).join('/'), { ...srcOpts, ...{ readDelay: 200 } });
const watchNonTs = watchInput.pipe(filter(['**', '!**/*.{ts,mts,cts}'], { dot: true })).pipe(gulp.dest(out));
const tsgoStream = watchInput.pipe(util.debounce(() => {
onExtensionCompilationStart();
const onExtensionCompilationEnd = extensionCompilation.start();
const stream = createTsgoStream(absolutePath, { taskName: 'extensions' }, () => rewriteTsgoSourceMappingUrlsIfNeeded(false, out, baseUrl));
// Wrap in a result stream that always emits 'end' (even on
// error) so the debounce resets to idle and can process future
Expand All @@ -214,7 +204,7 @@ export function createExtensionTasks(tsconfigFile: string, repoRoot = root) {
result.emit('end');
});
stream.on('error', () => {
onExtensionCompilationEnd();
onExtensionCompilationEnd(true);
result.emit('end');
});
return result;
Expand Down
47 changes: 47 additions & 0 deletions build/lib/buildEvents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

export class BuildLifecycle {
private _activeBuilds = 0;
private _failed = false;
private readonly _onStart: (() => void) | undefined;
private readonly _onEnd: (() => void) | undefined;

constructor(onStart?: () => void, onEnd?: () => void) {
this._onStart = onStart;
this._onEnd = onEnd;
}

start(): (failed?: boolean) => void {
if (this._activeBuilds++ === 0) {
this._failed = false;
try {
this._onStart?.();
this._emit({ event: 'start' });
} catch (error) {
this._activeBuilds--;
throw error;
}
}
let completed = false;
return (failed = false) => {
if (completed) {
return;
}
completed = true;
this._failed ||= failed;
if (--this._activeBuilds === 0) {
this._onEnd?.();
this._emit({ event: 'finish', success: !this._failed });
}
};
}

private _emit(event: { event: 'start' } | { event: 'finish'; success: boolean }): void {
if (process.env.VSCODE_BUILD_EVENTS === '1') {
console.log(JSON.stringify({ type: 'vscode.build', version: 1, ...event }));
}
}
}
89 changes: 89 additions & 0 deletions build/lib/test/buildEvents.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import assert from 'node:assert/strict';
import { test } from 'node:test';
import { BuildLifecycle } from '../buildEvents.ts';

test('overlapping builds retain failures, finish once, and recover next cycle', t => {
const log = t.mock.method(console, 'log');
const previous = process.env.VSCODE_BUILD_EVENTS;
t.after(() => restoreBuildEvents(previous));
process.env.VSCODE_BUILD_EVENTS = '1';
const messages = () => log.mock.calls.map(call => JSON.parse(call.arguments[0]));
const lifecycle = new BuildLifecycle();
const first = lifecycle.start();
const second = lifecycle.start();
first(true);
assert.deepEqual(messages(), [{ type: 'vscode.build', version: 1, event: 'start' }]);
first();
second();
assert.deepEqual(messages(), [
{ type: 'vscode.build', version: 1, event: 'start' },
{ type: 'vscode.build', version: 1, event: 'finish', success: false },
]);
lifecycle.start()();
assert.deepEqual(messages(), [
{ type: 'vscode.build', version: 1, event: 'start' },
{ type: 'vscode.build', version: 1, event: 'finish', success: false },
{ type: 'vscode.build', version: 1, event: 'start' },
{ type: 'vscode.build', version: 1, event: 'finish', success: true },
]);
});

test('events require an explicit opt-in and preserve existing log callbacks', t => {
const log = t.mock.method(console, 'log');
const previous = process.env.VSCODE_BUILD_EVENTS;
t.after(() => restoreBuildEvents(previous));
for (const value of [undefined, '', '0', 'true']) {
restoreBuildEvents(value);
const callbacks: string[] = [];
const lifecycle = new BuildLifecycle(() => callbacks.push('start'), () => callbacks.push('end'));
const first = lifecycle.start();
const second = lifecycle.start();
first(true);
second();
assert.deepEqual(callbacks, ['start', 'end']);
}
assert.equal(log.mock.callCount(), 0);
});

function restoreBuildEvents(value: string | undefined): void {
if (value === undefined) {
delete process.env.VSCODE_BUILD_EVENTS;
} else {
process.env.VSCODE_BUILD_EVENTS = value;
}
}

for (const phase of ['callback', 'emit']) {
test(`a failed start ${phase} does not leak an active build`, t => {
const previous = process.env.VSCODE_BUILD_EVENTS;
t.after(() => restoreBuildEvents(previous));
process.env.VSCODE_BUILD_EVENTS = '1';
let fail = true;
const messages: unknown[] = [];
t.mock.method(console, 'log', (message: string) => {
if (fail && phase === 'emit') {
throw new Error('emit failed');
}
messages.push(JSON.parse(message));
});
let ended = 0;
const lifecycle = new BuildLifecycle(() => {
if (fail && phase === 'callback') {
throw new Error('callback failed');
}
}, () => ended++);
assert.throws(() => lifecycle.start(), new RegExp(`${phase} failed`));
fail = false;
lifecycle.start()();
assert.equal(ended, 1);
assert.deepEqual(messages, [
{ type: 'vscode.build', version: 1, event: 'start' },
{ type: 'vscode.build', version: 1, event: 'finish', success: true },
]);
});
}
63 changes: 63 additions & 0 deletions build/lib/test/extensionTranspilation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,79 @@
*--------------------------------------------------------------------------------------------*/

import assert from 'assert';
import { spawn } from 'child_process';
import { once } from 'events';
import * as fs from 'fs/promises';
import * as os from 'os';
import * as path from 'path';
import { createRequire } from 'module';
import { pathToFileURL } from 'url';
import { suite, test } from 'node:test';
import { setTimeout as delay } from 'timers/promises';
import { createExtensionTasks } from '../../gulpfile.extensions.ts';
import * as task from '../gulp/task.ts';

suite('extension transpilation pipeline', () => {
test('watcher recompiles source edits and recovers from compiler errors', async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'vscode-extension-watch-'));
try {
const extension = path.join(root, 'extensions', 'watch-fixture');
const source = path.join(extension, 'src', 'entry.ts');
const output = path.join(extension, 'out', 'entry.js');
await fs.mkdir(path.dirname(source), { recursive: true });
await fs.writeFile(path.join(extension, 'package.json'), '{"type":"commonjs"}');
await fs.writeFile(path.join(extension, 'tsconfig.json'), JSON.stringify({
compilerOptions: { module: 'commonjs', target: 'es2024', rootDir: './src', outDir: './out', types: [] },
include: ['src/**/*'],
}));
await fs.writeFile(source, 'export const value: number = 1;');

const child = spawn(process.execPath, ['--input-type=module', '-e', `
process.once('message', () => process.exit(0));
const { createExtensionTasks } = await import(${JSON.stringify(new URL('../../gulpfile.extensions.ts', import.meta.url).href)});
const task = await import(${JSON.stringify(new URL('../gulp/task.ts', import.meta.url).href)});
await task.series(createExtensionTasks('extensions/watch-fixture/tsconfig.json', process.cwd()).watchTask)();
`], { cwd: root, env: process.env, stdio: ['ignore', 'pipe', 'pipe', 'ipc'] });
const exited = once(child, 'exit');
let stdout = '';
let stderr = '';
child.stdout!.on('data', data => { stdout += data; });
child.stderr!.on('data', data => { stderr += data; });

async function waitForCompilation(count: number) {
const deadline = Date.now() + 30_000;
while (stdout.split('Finished compilation').length - 1 < count) {
assert.strictEqual(child.exitCode, null, stdout + stderr);
assert.ok(Date.now() < deadline, `Timed out waiting for compilation ${count}:\n${stdout}${stderr}`);
await delay(50);
}
}

try {
await waitForCompilation(1);
assert.match(await fs.readFile(output, 'utf8'), /value = 1/);
await fs.writeFile(source, 'export const value: number = 2;');
await waitForCompilation(2);
assert.match(await fs.readFile(output, 'utf8'), /value = 2/);

await fs.writeFile(source, 'export const value: number = "invalid";');
await waitForCompilation(3);
assert.match(stdout, /error TS2322:/);

await fs.writeFile(source, 'export const value: number = 3;');
await waitForCompilation(4);
assert.match(await fs.readFile(output, 'utf8'), /value = 3/);
} finally {
if (child.connected) {
child.send('stop');
}
await exited;
}
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});

test('emits loadable modules for ts, mts and cts without copying sources or declarations', async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'vscode-extension-pipeline-'));
try {
Expand Down
78 changes: 78 additions & 0 deletions build/lib/test/tsgo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import assert from 'node:assert/strict';
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import { after, before, suite, test } from 'node:test';
import { setImmediate } from 'node:timers/promises';
import { createTsgoStream, spawnTsgo } from '../tsgo.ts';

suite('tsgo completion callbacks', () => {
let root: string;
let project: string;

before(async () => {
root = await fs.mkdtemp(path.join(os.tmpdir(), 'vscode-tsgo-completion-'));
project = path.join(root, 'tsconfig.json');
await fs.writeFile(project, JSON.stringify({
compilerOptions: { types: [], target: 'es2024' },
files: ['entry.ts'],
}));
await fs.writeFile(path.join(root, 'entry.ts'), 'export const value = 1;');
});

after(async () => {
await fs.rm(root, { recursive: true, force: true });
});

test('rejects a synchronous completion exception', async () => {
const failure = new Error('completion failed');
await assert.rejects(spawnTsgo(project, { taskName: 'test', noEmit: true }, () => {
throw failure;
}), error => error === failure);
});

test('rejects an asynchronous completion failure', async () => {
const failure = new Error('completion failed');
await assert.rejects(spawnTsgo(project, { taskName: 'test', noEmit: true }, () => Promise.reject(failure)), error => error === failure);
});

test('waits for asynchronous completion', async () => {
const started = Promise.withResolvers<void>();
const completion = Promise.withResolvers<void>();
let settled = false;
const build = spawnTsgo(project, { taskName: 'test', noEmit: true }, () => {
started.resolve();
return completion.promise;
}).then(() => { settled = true; });
await started.promise;
await setImmediate();
try {
assert.equal(settled, false);
} finally {
completion.resolve();
}
await build;
assert.equal(settled, true);
});

test('succeeds without a completion callback', async () => {
await spawnTsgo(project, { taskName: 'test', noEmit: true });
});

test('reports a synchronous completion exception through the stream', async () => {
const failure = new Error('completion failed');
const stream = createTsgoStream(project, { taskName: 'test', noEmit: true }, () => {
throw failure;
});
const error = await new Promise<Error>((resolve, reject) => {
stream.once('end', () => reject(new Error('Expected a stream error')));
stream.once('error', resolve);
});
assert.equal(error, failure);
});
});
2 changes: 1 addition & 1 deletion build/lib/tsgo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export function spawnTsgo(projectPath: string, config: { taskName: string; noEmi
runReporter(lines.join('\n'));

if (code === 0) {
Promise.resolve(onComplete?.()).then(() => resolve(), reject);
Promise.resolve().then(() => onComplete?.()).then(() => resolve(), reject);
} else {
reject(new Error(`tsgo exited with code ${code ?? 'unknown'}`));
}
Expand Down
Loading