Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Module conversion #46567

Closed
wants to merge 7 commits into from
Closed
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Some require -> import conversions
  • Loading branch information
elibarzilay committed Jan 11, 2022
commit 91e115ddd48391afa93d90de9ae2332380d21f71
2 changes: 1 addition & 1 deletion src/cancellationToken/cancellationToken.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// <reference types="node"/>

import fs = require("fs");
import * as fs from "fs";

interface ServerCancellationToken {
isCancellationRequested(): boolean;
4 changes: 2 additions & 2 deletions src/harness/findUpDir.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { join, resolve, dirname } = require("path") as typeof import("path");
const { existsSync } = require("fs") as typeof import("fs");
import { join, resolve, dirname } from "path";
import { existsSync } from "fs";

// search directories upward to avoid hard-wired paths based on the
// build tree (same as scripts/build/findUpDir.js)
17 changes: 7 additions & 10 deletions src/harness/harnessGlobals.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { isArray } from "./ts";
import * as chai from "chai";

declare global {
// Block scoped definitions work poorly for global variables, temporarily enable var
/* eslint-disable no-var */

// this will work in the browser via browserify
var assert: typeof _chai.assert;
}
declare global {
var expect: typeof _chai.expect;
var assert: typeof chai.assert;
var expect: typeof chai.expect;
}
var _chai: typeof import("chai") = require("chai");
globalThis.assert = _chai.assert;

globalThis.assert = chai.assert;
{
// chai's builtin `assert.isFalse` is featureful but slow - we don't use those features,
// so we'll just overwrite it as an alterative to migrating a bunch of code off of chai
@@ -39,7 +39,4 @@ globalThis.assert = _chai.assert;
}
};
}
globalThis.expect = _chai.expect;
/* eslint-enable no-var */
// empty ts namespace so this file is included in the `ts.ts` namespace file generated by the module swapover
// This way, everything that ends up importing `ts` downstream also imports this file and picks up its augmentation
globalThis.expect = chai.expect;
4 changes: 2 additions & 2 deletions src/instrumenter/instrumenter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs = require("fs");
import path = require("path");
import * as fs from "fs";
import * as path from "path";

function instrumentForRecording(fn: string, tscPath: string) {
instrument(tscPath, `
6 changes: 3 additions & 3 deletions src/testRunner/externalCompileRunner.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { RunnerBase, IO, isWorker, Baseline, TestRunnerKind } from "./Harness";
import { Debug, Version, flatten, comparePathsCaseSensitive, compareValues, compareStringsCaseSensitive, stringContains } from "./ts";
const fs: typeof import("fs") = require("fs");
const path: typeof import("path") = require("path");
const del: typeof import("del") = require("del");
import * as fs from "fs";
import * as path from "path";
import * as del from "del";

interface ExecResult {
stdout: Buffer;
4 changes: 2 additions & 2 deletions src/testRunner/unittests/services/languageService.ts
Original file line number Diff line number Diff line change
@@ -2,8 +2,8 @@ import { ScriptSnapshot, getDefaultLibFilePath, emptyArray, LanguageServiceHost,
import { libFile, createServerHost } from "../../ts.projectSystem";
import { projectRoot } from "../../ts.tscWatch";
import * as ts from "../../ts";
const _chai: typeof import("chai") = require("chai");
const expect: typeof _chai.expect = _chai.expect;
import { expect } from "chai";

describe("unittests:: services:: languageService", () => {
const files: {
[index: string]: string;
10 changes: 3 additions & 7 deletions src/tsserver/nodeServer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { LogLevel, getLogLevel, findArgument, StartInput, ServerHost, BaseLogger, Msg, stringifyIndented, RequireResult, ServerCancellationToken, nullCancellationToken, StartSessionOptions, Logger, ITypingsInstaller, ProjectService, Event, InstallPackageOptionsWithProject, InstallPackageRequest, Arguments, Project, TypingInstallerRequestUnion, createInstallTypingsRequest, TypesRegistryResponse, PackageInstalledResponse, SetTypings, InvalidateCachedTypings, BeginInstallTypes, EndInstallTypes, InitializationFailedResponse, EventTypesRegistry, ActionPackageInstalled, EventInitializationFailed, protocol, EventBeginInstallTypes, EventEndInstallTypes, ActionInvalidate, ActionSet, Session, nullTypingsInstaller, formatMessage, toEvent, indent, hasArgument } from "./ts.server";
import { CharacterCodes, stripQuotes, LanguageServiceMode, Debug, MapLike, noop, getNodeMajorVersion, combinePaths, noopFileWatcher, WatchFileKind, resolveJSModule, validateLocaleAndSetLanguage, normalizeSlashes, directorySeparator, toFileNameLowerCase, getRootLength, DirectoryWatcherCallback, WatchOptions, FileWatcher, ESMap, ApplyCodeActionCommandResult, JsTyping, getDirectoryPath, TypeAcquisition, SortedReadonlyArray, getEntries, assertType, sys, tracing, startTracing, versionMajorMinor } from "./ts";
import * as ts from "./ts";
import { execFileSync } from "child_process";

/*@internal*/
interface LogOptions {
file?: string;
@@ -100,12 +102,6 @@ function parseServerMode(): LanguageServiceMode | string | undefined {
/* @internal */
export function initializeNodeSystem(): StartInput {
const sys = Debug.checkDefined(ts.sys) as ServerHost;
const childProcess: {
execFileSync(file: string, args: string[], options: {
stdio: "ignore";
env: MapLike<string>;
}): string | Buffer;
} = require("child_process");

interface Stats {
isFile(): boolean;
@@ -207,7 +203,7 @@ export function initializeNodeSystem(): StartInput {
if (logger.hasLevel(LogLevel.verbose)) {
logger.info(`Starting ${process.execPath} with args:${stringifyIndented(args)}`);
}
childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } });
execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } });
status = true;
if (logger.hasLevel(LogLevel.verbose)) {
logger.info(`WatchGuard for path ${path} returned: OK`);
22 changes: 7 additions & 15 deletions src/typingsInstaller/nodeTypingsInstaller.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
import { Log, TypingsInstaller, RequestCompletedAction, installNpmPackages } from "./ts.server.typingsInstaller";
import { nowString, InstallTypingHost, InitializationFailedResponse, Arguments, TypingInstallerRequestUnion, TypesRegistryResponse, EventTypesRegistry, PackageInstalledResponse, ActionPackageInstalled, TypingInstallerResponseUnion, findArgument, hasArgument } from "./ts.server";
import { sys, MapLike, ESMap, getEntries, combinePaths, normalizeSlashes, toPath, createGetCanonicalFileName, stringContains, Debug, version, forEachAncestorDirectory, getDirectoryPath } from "./ts";
import * as ts from "./ts";
const fs: {
appendFileSync(file: string, content: string): void;
} = require("fs");

const path: {
join(...parts: string[]): string;
dirname(path: string): string;
basename(path: string, extension?: string): string;
} = require("path");
import { sys, MapLike, Map, ESMap, getEntries, combinePaths, normalizeSlashes, toPath, createGetCanonicalFileName, stringContains, Debug, version, forEachAncestorDirectory, getDirectoryPath } from "./ts";
import { appendFileSync } from "fs";
import * as path from "path";

class FileLog implements Log {
constructor(private logFile: string | undefined) {
@@ -24,7 +16,7 @@ class FileLog implements Log {
return;

try {
fs.appendFileSync(this.logFile, `[${nowString()}] ${text}${sys.newLine}`);
appendFileSync(this.logFile, `[${nowString()}] ${text}${sys.newLine}`);
}
catch (e) {
this.logFile = undefined;
@@ -55,17 +47,17 @@ function loadTypesRegistryFile(typesRegistryFilePath: string, host: InstallTypin
if (log.isEnabled()) {
log.writeLine(`Types registry file '${typesRegistryFilePath}' does not exist`);
}
return new ts.Map<string, MapLike<string>>();
return new Map<string, MapLike<string>>();
}
try {
const content = JSON.parse(host.readFile(typesRegistryFilePath)!) as TypesRegistryFile;
return new ts.Map(getEntries(content.entries));
return new Map(getEntries(content.entries));
}
catch (e) {
if (log.isEnabled()) {
log.writeLine(`Error when loading types registry file '${typesRegistryFilePath}': ${(e as Error).message}, ${(e as Error).stack}`);
}
return new ts.Map<string, MapLike<string>>();
return new Map<string, MapLike<string>>();
}
}

8 changes: 4 additions & 4 deletions src/watchGuard/watchGuard.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
/// <reference types="node" />

import { watch } from "fs";

if (process.argv.length < 3) {
process.exit(1);
}
const directoryName = process.argv[2];
const fs: {
watch(directoryName: string, options: any, callback: () => {}): any;
} = require("fs");

// main reason why we need separate process to check if it is safe to watch some path
// is to guard against crashes that cannot be intercepted with protected blocks and
// code in tsserver already can handle normal cases, like non-existing folders.
// This means that here we treat any result (success or exception) from fs.watch as success since it does not tear down the process.
// The only case that should be considered as failure - when watchGuard process crashes.
try {
const watcher = fs.watch(directoryName, { recursive: true }, () => ({}));
const watcher = watch(directoryName, { recursive: true }, () => ({}));
watcher.close();
}
catch { /*ignore*/ }