Skip to content

Commit ef339af

Browse files
authored
Use regular imports instead of require where possible (#59017)
1 parent e70904a commit ef339af

File tree

11 files changed

+47
-122
lines changed

11 files changed

+47
-122
lines changed

package-lock.json

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
"@esfx/canceltoken": "^1.0.0",
4545
"@octokit/rest": "^20.1.1",
4646
"@types/chai": "^4.3.16",
47+
"@types/diff": "^5.2.1",
4748
"@types/minimist": "^1.2.5",
4849
"@types/mocha": "^10.0.6",
4950
"@types/ms": "^0.7.34",

src/harness/fourslashImpl.ts

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import sourceMapSupport from "source-map-support";
12
import * as fakes from "./_namespaces/fakes.js";
23
import * as FourSlashInterface from "./_namespaces/FourSlashInterface.js";
34
import * as Harness from "./_namespaces/Harness.js";
@@ -4659,22 +4660,9 @@ function runCode(code: string, state: TestState, fileName: string): void {
46594660
const generatedFile = ts.changeExtension(fileName, ".js");
46604661
const wrappedCode = `(function(ts, test, goTo, config, verify, edit, debug, format, cancellation, classification, completion, verifyOperationIsCancelled, ignoreInterpolations) {${code}\n//# sourceURL=${ts.getBaseFileName(generatedFile)}\n})`;
46614662

4662-
type SourceMapSupportModule = typeof import("source-map-support") & {
4663-
// TODO(rbuckton): This is missing from the DT definitions and needs to be added.
4664-
resetRetrieveHandlers(): void;
4665-
};
4666-
46674663
// Provide the content of the current test to 'source-map-support' so that it can give us the correct source positions
46684664
// for test failures.
4669-
let sourceMapSupportModule: SourceMapSupportModule | undefined;
4670-
try {
4671-
sourceMapSupportModule = require("source-map-support");
4672-
}
4673-
catch {
4674-
// do nothing
4675-
}
4676-
4677-
sourceMapSupportModule?.install({
4665+
sourceMapSupport.install({
46784666
retrieveFile: path => {
46794667
return path === generatedFile ? wrappedCode :
46804668
undefined!;
@@ -4700,7 +4688,7 @@ function runCode(code: string, state: TestState, fileName: string): void {
47004688
throw err;
47014689
}
47024690
finally {
4703-
sourceMapSupportModule?.resetRetrieveHandlers();
4691+
sourceMapSupport.resetRetrieveHandlers();
47044692
}
47054693
}
47064694

src/harness/harnessIO.ts

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import * as Diff from "diff";
2+
import fs from "fs";
3+
import pathModule from "path";
14
import * as compiler from "./_namespaces/compiler.js";
25
import * as documents from "./_namespaces/documents.js";
36
import * as fakes from "./_namespaces/fakes.js";
@@ -54,14 +57,6 @@ export const virtualFileSystemRoot = "/";
5457

5558
function createNodeIO(): IO {
5659
const workspaceRoot = Utils.findUpRoot();
57-
let fs: any, pathModule: any;
58-
if (require) {
59-
fs = require("fs");
60-
pathModule = require("path");
61-
}
62-
else {
63-
fs = pathModule = {};
64-
}
6560

6661
function deleteFile(path: string) {
6762
try {
@@ -1022,7 +1017,6 @@ export namespace Compiler {
10221017
}
10231018
else if (original.text !== doc.text) {
10241019
jsCode += `\r\n\r\n!!!! File ${Utils.removeTestPathPrefixes(doc.file)} differs from original emit in noCheck emit\r\n`;
1025-
const Diff = require("diff");
10261020
const expected = original.text;
10271021
const actual = doc.text;
10281022
const patch = Diff.createTwoFilesPatch("Expected", "Actual", expected, actual, "The full check baseline", "with noCheck set");
@@ -1518,8 +1512,7 @@ export namespace Baseline {
15181512
IO.writeFile(actualFileName, encodedActual);
15191513
}
15201514
const errorMessage = getBaselineFileChangedErrorMessage(relativeFileName);
1521-
if (!!require && opts && opts.PrintDiff) {
1522-
const Diff = require("diff");
1515+
if (opts && opts.PrintDiff) {
15231516
const patch = Diff.createTwoFilesPatch("Expected", "Actual", expected, actual, "The current baseline", "The new version");
15241517
throw new Error(`${errorMessage}${ts.ForegroundColorEscapeSequences.Grey}\n\n${patch}`);
15251518
}

src/harness/harnessUtils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import vm from "vm";
12
import * as Harness from "./_namespaces/Harness.js";
23
import * as ts from "./_namespaces/ts.js";
34

@@ -6,7 +7,6 @@ export function encodeString(s: string): string {
67
}
78

89
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
9-
const vm = require("vm");
1010
if (nodeContext) {
1111
vm.runInNewContext(fileContents, nodeContext, fileName);
1212
}

src/testRunner/parallel/host.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
import { fork } from "child_process";
2+
import { statSync } from "fs";
3+
import Mocha from "mocha";
4+
import ms from "ms";
5+
import os from "os";
6+
import path from "path";
7+
import readline from "readline";
8+
import tty from "tty";
19
import {
210
configOption,
311
globalTimeout,
@@ -26,20 +34,12 @@ import * as ts from "../_namespaces/ts.js";
2634
import * as Utils from "../_namespaces/Utils.js";
2735

2836
export function start(importTests: () => Promise<unknown>) {
29-
const Mocha = require("mocha") as typeof import("mocha");
3037
const Base = Mocha.reporters.Base;
3138
const color = Base.color;
3239
const cursor = Base.cursor;
33-
const ms = require("ms") as typeof import("ms");
34-
const readline = require("readline") as typeof import("readline");
35-
const os = require("os") as typeof import("os");
36-
const tty = require("tty") as typeof import("tty");
3740
const isatty = tty.isatty(1) && tty.isatty(2);
38-
const path = require("path") as typeof import("path");
39-
const { fork } = require("child_process") as typeof import("child_process");
40-
const { statSync } = require("fs") as typeof import("fs");
4141

42-
// NOTE: paths for module and types for FailedTestReporter _do not_ line up due to our use of --outFile for run.js
42+
// NOTE: paths for module and types for FailedTestReporter _do not_ line up when bundled
4343
const FailedTestReporter = require(Utils.findUpFile("scripts/failed-tests.cjs")) as typeof import("../../../scripts/failed-tests.cjs");
4444

4545
const perfdataFileNameFragment = ".parallelperf";

src/testRunner/parallel/worker.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import Mocha from "mocha";
12
import {
23
createRunner,
34
globalTimeout,
@@ -39,9 +40,6 @@ export function start(importTests: () => Promise<unknown>) {
3940
let exceptionsHooked = false;
4041
hookUncaughtExceptions();
4142

42-
// Capitalization is aligned with the global `Mocha` namespace for typespace/namespace references.
43-
const Mocha = require("mocha") as typeof import("mocha");
44-
4543
/**
4644
* Mixin helper.
4745
* @param base The base class constructor.

src/testRunner/unittests/skipJSDocParsing.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1+
import * as Diff from "diff";
12
import * as Harness from "../_namespaces/Harness.js";
23
import * as ts from "../_namespaces/ts.js";
34
import * as Utils from "../_namespaces/Utils.js";
45

56
describe("unittests:: skipJSDocParsing", () => {
6-
const Diff = require("diff");
7-
87
const kinds = [
98
ts.JSDocParsingMode.ParseAll,
109
ts.JSDocParsingMode.ParseForTypeErrors,

src/tsserver/nodeServer.ts

Lines changed: 10 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
import childProcess from "child_process";
2+
import fs from "fs";
3+
import net from "net";
4+
import os from "os";
5+
import readline from "readline";
16
import {
27
CharacterCodes,
38
combinePaths,
@@ -9,7 +14,6 @@ import {
914
getDirectoryPath,
1015
getRootLength,
1116
LanguageServiceMode,
12-
MapLike,
1317
noop,
1418
noopFileWatcher,
1519
normalizePath,
@@ -37,24 +41,6 @@ interface LogOptions {
3741
logToFile?: boolean;
3842
}
3943

40-
interface NodeChildProcess {
41-
send(message: any, sendHandle?: any): void;
42-
on(message: "message" | "exit", f: (m: any) => void): void;
43-
kill(): void;
44-
pid: number;
45-
}
46-
47-
interface ReadLineOptions {
48-
input: NodeJS.ReadableStream;
49-
output?: NodeJS.WritableStream;
50-
terminal?: boolean;
51-
historySize?: number;
52-
}
53-
54-
interface NodeSocket {
55-
write(data: string, encoding: string): boolean;
56-
}
57-
5844
function parseLoggingEnvironmentString(logEnvStr: string | undefined): LogOptions {
5945
if (!logEnvStr) {
6046
return {};
@@ -123,41 +109,6 @@ function parseServerMode(): LanguageServiceMode | string | undefined {
123109
/** @internal */
124110
export function initializeNodeSystem(): StartInput {
125111
const sys = Debug.checkDefined(ts.sys) as ts.server.ServerHost;
126-
const childProcess: {
127-
execFileSync(file: string, args: string[], options: { stdio: "ignore"; env: MapLike<string>; }): string | Buffer;
128-
} = require("child_process");
129-
130-
interface Stats {
131-
isFile(): boolean;
132-
isDirectory(): boolean;
133-
isBlockDevice(): boolean;
134-
isCharacterDevice(): boolean;
135-
isSymbolicLink(): boolean;
136-
isFIFO(): boolean;
137-
isSocket(): boolean;
138-
dev: number;
139-
ino: number;
140-
mode: number;
141-
nlink: number;
142-
uid: number;
143-
gid: number;
144-
rdev: number;
145-
size: number;
146-
blksize: number;
147-
blocks: number;
148-
atime: Date;
149-
mtime: Date;
150-
ctime: Date;
151-
birthtime: Date;
152-
}
153-
154-
const fs: {
155-
openSync(path: string, options: string): number;
156-
close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void;
157-
writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number;
158-
statSync(path: string): Stats;
159-
stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
160-
} = require("fs");
161112

162113
class Logger implements Logger {
163114
private seq = 0;
@@ -231,7 +182,7 @@ export function initializeNodeSystem(): StartInput {
231182
if (this.fd >= 0) {
232183
const buf = Buffer.from(s);
233184
// eslint-disable-next-line no-restricted-syntax
234-
fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null!); // TODO: GH#18217
185+
fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null);
235186
}
236187
if (this.traceToConsole) {
237188
console.warn(s);
@@ -326,7 +277,7 @@ export function initializeNodeSystem(): StartInput {
326277

327278
let cancellationToken: ts.server.ServerCancellationToken;
328279
try {
329-
const factory = require("./cancellationToken");
280+
const factory = require("./cancellationToken.js");
330281
cancellationToken = factory(sys.args);
331282
}
332283
catch (e) {
@@ -439,31 +390,14 @@ function parseEventPort(eventPortStr: string | undefined) {
439390
return eventPort !== undefined && !isNaN(eventPort) ? eventPort : undefined;
440391
}
441392
function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger, cancellationToken: ts.server.ServerCancellationToken) {
442-
const childProcess: {
443-
fork(modulePath: string, args: string[], options?: { execArgv: string[]; env?: MapLike<string>; }): NodeChildProcess;
444-
} = require("child_process");
445-
446-
const os: {
447-
homedir?(): string;
448-
tmpdir(): string;
449-
} = require("os");
450-
451-
const net: {
452-
connect(options: { port: number; }, onConnect?: () => void): NodeSocket;
453-
} = require("net");
454-
455-
const readline: {
456-
createInterface(options: ReadLineOptions): NodeJS.EventEmitter;
457-
} = require("readline");
458-
459393
const rl = readline.createInterface({
460394
input: process.stdin,
461395
output: process.stdout,
462396
terminal: false,
463397
});
464398

465399
class NodeTypingsInstallerAdapter extends ts.server.TypingsInstallerAdapter {
466-
protected override installer!: NodeChildProcess;
400+
protected override installer!: childProcess.ChildProcess;
467401
// This number is essentially arbitrary. Processing more than one typings request
468402
// at a time makes sense, but having too many in the pipe results in a hang
469403
// (see https://github.com/nodejs/node/issues/7657).
@@ -533,7 +467,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger
533467

534468
const typingsInstaller = combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typingsInstaller.js");
535469
this.installer = childProcess.fork(typingsInstaller, args, { execArgv });
536-
this.installer.on("message", m => this.handleMessage(m));
470+
this.installer.on("message", m => this.handleMessage(m as any));
537471

538472
// We have to schedule this event to the next tick
539473
// cause this fn will be called during
@@ -550,7 +484,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger
550484

551485
class IOSession extends ts.server.Session {
552486
private eventPort: number | undefined;
553-
private eventSocket: NodeSocket | undefined;
487+
private eventSocket: net.Socket | undefined;
554488
private socketEventQueue: { body: any; eventName: string; }[] | undefined;
555489
/** No longer needed if syntax target is es6 or above. Any access to "this" before initialized will be a runtime error. */
556490
private constructed: boolean | undefined;

src/tsserver/server.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os from "os";
12
import * as ts from "../typescript/typescript.js";
23
import { StartInput } from "./common.js";
34
import { initializeNodeSystem } from "./nodeServer.js";
@@ -53,4 +54,4 @@ function start({ args, logger, cancellationToken, serverMode, unknownServerMode,
5354
}
5455

5556
ts.setStackTraceLimit();
56-
start(initializeNodeSystem(), require("os").platform());
57+
start(initializeNodeSystem(), os.platform());

src/typingsInstaller/nodeTypingsInstaller.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { execFileSync } from "child_process";
12
import * as fs from "fs";
23
import * as path from "path";
34

@@ -79,10 +80,8 @@ interface ExecSyncOptions {
7980
cwd: string;
8081
encoding: "utf-8";
8182
}
82-
type ExecSync = (command: string, options: ExecSyncOptions) => string;
8383

8484
export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInstaller {
85-
private readonly nodeExecSync: ExecSync;
8685
private readonly npmPath: string;
8786
readonly typesRegistry: Map<string, MapLike<string>>;
8887

@@ -109,7 +108,6 @@ export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInst
109108
this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${ts.server.Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`);
110109
this.log.writeLine(`validateDefaultNpmLocation: ${validateDefaultNpmLocation}`);
111110
}
112-
({ execSync: this.nodeExecSync } = require("child_process"));
113111

114112
this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
115113

@@ -174,7 +172,7 @@ export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInst
174172
this.log.writeLine(`Exec: ${command}`);
175173
}
176174
try {
177-
const stdout = this.nodeExecSync(command, { ...options, encoding: "utf-8" });
175+
const stdout = execFileSync(command, { ...options, encoding: "utf-8" });
178176
if (this.log.isEnabled()) {
179177
this.log.writeLine(` Succeeded. stdout:${indent(sys.newLine, stdout)}`);
180178
}

0 commit comments

Comments
 (0)