Skip to content
Closed
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
</p>

> [!IMPORTANT]
> **Extension Migration:** This extension is being moved from `esbenp.prettier-vscode` to [`prettier.prettier-vscode`](https://marketplace.visualstudio.com/items?itemName=prettier.prettier-vscode). Version 12+ is only published to the new for now as it is a major change. Once it is stable, we will publish v12 to both extensions and deprecate the `esbenp.prettier-vscode` extension. **Version 12.x is currently not stable, use with caution in production environments.**
> **Extension Migration:** This extension is being moved from `esbenp.prettier-vscode` to [`prettier.prettier-vscode`](https://marketplace.visualstudio.com/items?itemName=prettier.prettier-vscode). Version 12+ is only published to the new for now as it is a major change. Once it is stable, we will publish v12 to both extensions and deprecate the `esbenp.prettier-vscode` extension. **Version 12.x is currently not stable, use with caution in production environments.**

## Installation

Expand Down
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,12 @@
"default": "end",
"markdownDescription": "%ext.config.experimentalOperatorPosition%",
"scope": "language-overridable"
},
"prettier.timeout": {
"type": "number",
"default": 30000,
"markdownDescription": "%ext.config.timeout%",
"scope": "resource"
}
}
},
Expand Down
1 change: 1 addition & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,6 @@
"ext.config.experimentalTernaries": "Try prettier's [new ternary formatting](https://github.com/prettier/prettier/pull/13183) before it becomes the default behavior.",
"ext.config.objectWrap": "Controls how object literals are wrapped.\nValid options:\n- `preserve` - Preserve the original wrapping of object literals.\n- `collapse` - Collapse object literals to fit on one line when possible.",
"ext.config.experimentalOperatorPosition": "Controls where to break lines around binary operators.\nValid options:\n- `end` - Break lines after operators.\n- `start` - Break lines before operators.",
"ext.config.timeout": "Maximum time in milliseconds to wait for Prettier to format a document. Use 0 to disable timeout (not recommended). Default is 30000 (30 seconds).",
"ext.capabilities.untrustedWorkspaces.description": "Only the built-in version of Prettier will be used when running in untrusted mode."
}
5 changes: 5 additions & 0 deletions src/ModuleResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,11 @@ export class ModuleResolver implements ModuleResolverInterface {
} else {
this.loggingService.logDebug(`Using prettier version ${version}`);
}

// Set timeout from configuration
const { timeout } = getWorkspaceConfig(Uri.file(fileName));
moduleInstance.setTimeoutMs(timeout);

return moduleInstance;
} else {
this.loggingService.logDebug(USING_BUNDLED_PRETTIER);
Expand Down
31 changes: 19 additions & 12 deletions src/PrettierEditProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,33 +16,40 @@ export class PrettierEditProvider
private provideEdits: (
document: TextDocument,
options: ExtensionFormattingOptions,
token?: CancellationToken,
) => Promise<TextEdit[]>,
) {}

public async provideDocumentRangeFormattingEdits(
document: TextDocument,
range: Range,
// eslint-disable-next-line @typescript-eslint/no-unused-vars

options: FormattingOptions,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
token: CancellationToken,
): Promise<TextEdit[]> {
return this.provideEdits(document, {
rangeEnd: document.offsetAt(range.end),
rangeStart: document.offsetAt(range.start),
force: false,
});
return this.provideEdits(
document,
{
rangeEnd: document.offsetAt(range.end),
rangeStart: document.offsetAt(range.start),
force: false,
},
token,
);
}

public async provideDocumentFormattingEdits(
document: TextDocument,
// eslint-disable-next-line @typescript-eslint/no-unused-vars

options: FormattingOptions,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
token: CancellationToken,
): Promise<TextEdit[]> {
return this.provideEdits(document, {
force: false,
});
return this.provideEdits(
document,
{
force: false,
},
token,
);
}
}
33 changes: 32 additions & 1 deletion src/PrettierEditService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
CancellationToken,
Disposable,
DocumentFilter,
languages,
Expand Down Expand Up @@ -363,9 +364,21 @@ export default class PrettierEditService implements Disposable {
private provideEdits = async (
document: TextDocument,
options: ExtensionFormattingOptions,
token?: CancellationToken,
): Promise<TextEdit[]> => {
// Check if already cancelled before starting
if (token?.isCancellationRequested) {
this.loggingService.logInfo("Formatting cancelled before starting.");
return [];
}

const startTime = new Date().getTime();
const result = await this.format(document.getText(), document, options);
const result = await this.format(
document.getText(),
document,
options,
token,
);
if (!result) {
// No edits happened, return never so VS Code can try other formatters
return [];
Expand Down Expand Up @@ -413,6 +426,7 @@ export default class PrettierEditService implements Disposable {
text: string,
doc: TextDocument,
options: ExtensionFormattingOptions,
token?: CancellationToken,
): Promise<string | undefined> {
const { fileName, uri, languageId } = doc;

Expand Down Expand Up @@ -523,12 +537,29 @@ export default class PrettierEditService implements Disposable {

this.loggingService.logInfo("Prettier Options:", prettierOptions);

// Check for cancellation before formatting
if (token?.isCancellationRequested) {
this.loggingService.logInfo(
"Formatting cancelled before prettierInstance.format.",
);
return;
}

try {
// Since Prettier v3, `format` returns Promise.
const formattedText = await prettierInstance.format(
text,
prettierOptions,
);

// Check for cancellation after formatting
if (token?.isCancellationRequested) {
this.loggingService.logInfo(
"Formatting cancelled after prettierInstance.format.",
);
return;
}

this.statusBar.update(FormatterStatus.Success);

return formattedText;
Expand Down
1 change: 1 addition & 0 deletions src/PrettierInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface PrettierInstance {
fileName: string,
options?: ResolveConfigOptions,
): Promise<PrettierOptions | null>;
setTimeoutMs(timeoutMs: number): void;
}

export interface PrettierInstanceConstructor {
Expand Down
11 changes: 10 additions & 1 deletion src/PrettierMainThreadInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,19 @@ import {
} from "./types";
import { PrettierNodeModule } from "./ModuleResolver";
import { loadNodeModule } from "./utils/resolvers";
import { withTimeout } from "./utils/timeout";

export const PrettierMainThreadInstance: PrettierInstanceConstructor = class PrettierMainThreadInstance implements PrettierInstance {
public version: string | null = null;
private prettierModule: PrettierNodeModule | undefined;
private timeoutMs: number = 30000; // Default 30 seconds

constructor(private modulePath: string) {}

public setTimeoutMs(timeoutMs: number): void {
this.timeoutMs = timeoutMs;
}

public async import(): Promise</* version of imported prettier */ string> {
this.prettierModule = loadNodeModule(this.modulePath);
this.version = this.prettierModule?.version ?? null;
Expand All @@ -33,7 +39,10 @@ export const PrettierMainThreadInstance: PrettierInstanceConstructor = class Pre
if (!this.prettierModule) {
await this.import();
}
return this.prettierModule!.format(source, options);
return withTimeout(
this.prettierModule!.format(source, options),
this.timeoutMs,
);
}

public async getFileInfo(
Expand Down
11 changes: 10 additions & 1 deletion src/PrettierWorkerInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
PrettierInstanceConstructor,
} from "./PrettierInstance";
import { ResolveConfigOptions, Options } from "prettier";
import { withTimeout } from "./utils/timeout";

let currentCallId = 0;

Expand All @@ -32,6 +33,7 @@ export const PrettierWorkerInstance: PrettierInstanceConstructor = class Prettie
> = new Map();

public version: string | null = null;
private timeoutMs: number = 30000; // Default 30 seconds

constructor(private modulePath: string) {
worker.on("message", ({ type, id, payload }) => {
Expand Down Expand Up @@ -70,11 +72,18 @@ export const PrettierWorkerInstance: PrettierInstanceConstructor = class Prettie
return promise as Promise<string>;
}

public setTimeoutMs(timeoutMs: number): void {
this.timeoutMs = timeoutMs;
}

public async format(
source: string,
options?: PrettierOptions,
): Promise<string> {
const result = await this.callMethod("format", [source, options]);
const result = await withTimeout(
this.callMethod("format", [source, options]),
this.timeoutMs,
);
return result;
}

Expand Down
59 changes: 59 additions & 0 deletions src/test/suite/timeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import * as assert from "node:assert";
import { withTimeout } from "../../utils/timeout";

suite("Timeout Tests", () => {
test("withTimeout resolves when promise completes before timeout", async () => {
const promise = new Promise<string>((resolve) => {
setTimeout(() => resolve("success"), 100);
});

const result = await withTimeout(promise, 500);
assert.strictEqual(result, "success");
});

test("withTimeout rejects when promise exceeds timeout", async () => {
const promise = new Promise<string>((resolve) => {
setTimeout(() => resolve("success"), 500);
});

try {
await withTimeout(promise, 100);
assert.fail("Expected timeout error");
} catch (error) {
assert.ok(error instanceof Error);
assert.ok(error.message.includes("timed out after 100ms"));
}
});

test("withTimeout allows zero timeout (no timeout)", async () => {
const promise = new Promise<string>((resolve) => {
setTimeout(() => resolve("success"), 100);
});

const result = await withTimeout(promise, 0);
assert.strictEqual(result, "success");
});

test("withTimeout allows negative timeout (no timeout)", async () => {
const promise = new Promise<string>((resolve) => {
setTimeout(() => resolve("success"), 100);
});

const result = await withTimeout(promise, -1);
assert.strictEqual(result, "success");
});

test("withTimeout rejects when promise itself rejects", async () => {
const promise = new Promise<string>((_, reject) => {
setTimeout(() => reject(new Error("promise error")), 100);
});

try {
await withTimeout(promise, 500);
assert.fail("Expected promise error");
} catch (error) {
assert.ok(error instanceof Error);
assert.strictEqual(error.message, "promise error");
}
});
});
4 changes: 4 additions & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ interface IExtensionConfig {
* If true, enabled debug logs
*/
enableDebugLogs: boolean;
/**
* Timeout in milliseconds for Prettier formatting operations
*/
timeout: number;
}
/**
* Configuration for prettier-vscode
Expand Down
36 changes: 36 additions & 0 deletions src/utils/timeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Wraps a promise with a timeout
* @param promise The promise to wrap
* @param ms Timeout in milliseconds (0 or negative means no timeout)
* @returns The promise result or timeout error
*/
export async function withTimeout<T>(
promise: Promise<T>,
ms: number,
): Promise<T> {
if (ms <= 0) {
// No timeout
return promise;
}

let timeoutId: NodeJS.Timeout | undefined;

const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => {
reject(
new Error(
`Prettier formatting timed out after ${ms}ms. This may indicate an issue with Prettier or a plugin.`,
),
);
}, ms);
});

try {
return await Promise.race([promise, timeoutPromise]);
} finally {
// Clean up the timeout to prevent memory leaks
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
}
}