From 158ae0bfe900d2bac3076390c4fe3d2b54d94fe5 Mon Sep 17 00:00:00 2001 From: Stanislav <62983943+stanislavstrelnikov@users.noreply.github.com> Date: Tue, 7 Jul 2020 04:45:39 +0300 Subject: [PATCH] clean up code in cli/js (#6611) --- cli/js/compiler.ts | 14 ++-- cli/js/compiler_api.ts | 4 +- cli/js/deno.ts | 3 +- cli/js/error_stack.ts | 21 +++--- cli/js/errors.ts | 59 ++++++++++------ cli/js/files.ts | 16 ++--- cli/js/internals.ts | 3 +- cli/js/io.ts | 3 +- cli/js/main.ts | 1 + cli/js/net.ts | 12 ++-- cli/js/net_unstable.ts | 14 ++-- cli/js/ops/dispatch_json.ts | 16 ++--- cli/js/ops/dispatch_minimal.ts | 10 +-- cli/js/ops/errors.ts | 8 +-- cli/js/ops/fetch.ts | 6 +- cli/js/ops/fs/chmod.ts | 7 +- cli/js/ops/fs/chown.ts | 7 +- cli/js/ops/fs/copy_file.ts | 17 ++--- cli/js/ops/fs/dir.ts | 1 + cli/js/ops/fs/link.ts | 1 + cli/js/ops/fs/make_temp.ts | 1 + cli/js/ops/fs/mkdir.ts | 19 ++++-- cli/js/ops/fs/open.ts | 11 +-- cli/js/ops/fs/read_dir.ts | 9 +-- cli/js/ops/fs/read_link.ts | 1 + cli/js/ops/fs/real_path.ts | 1 + cli/js/ops/fs/remove.ts | 13 ++-- cli/js/ops/fs/rename.ts | 1 + cli/js/ops/fs/seek.ts | 1 + cli/js/ops/fs/stat.ts | 45 ++++++------ cli/js/ops/fs/symlink.ts | 9 +-- cli/js/ops/fs/sync.ts | 1 + cli/js/ops/fs/truncate.ts | 7 +- cli/js/ops/fs/umask.ts | 1 + cli/js/ops/fs/utime.ts | 1 + cli/js/ops/fs_events.ts | 11 ++- cli/js/ops/get_random_values.ts | 1 + cli/js/ops/io.ts | 26 ++++--- cli/js/ops/net.ts | 11 ++- cli/js/ops/os.ts | 3 +- cli/js/ops/permissions.ts | 12 ++-- cli/js/ops/plugins.ts | 5 +- cli/js/ops/process.ts | 1 + cli/js/ops/resources.ts | 5 +- cli/js/ops/signal.ts | 13 +++- cli/js/ops/timers.ts | 11 +-- cli/js/ops/tls.ts | 1 + cli/js/ops/tty.ts | 7 +- cli/js/ops/worker_host.ts | 7 +- cli/js/permissions.ts | 1 + cli/js/process.ts | 15 ++-- cli/js/rbtree.ts | 4 +- cli/js/read_file.ts | 1 + cli/js/read_text_file.ts | 14 ++-- cli/js/repl.ts | 1 + cli/js/runtime.ts | 1 + cli/js/signals.ts | 3 +- cli/js/testing.ts | 15 ++-- cli/js/tls.ts | 3 +- cli/js/util.ts | 1 + cli/js/version.ts | 1 + cli/js/web/README.md | 4 +- cli/js/web/abort_controller.ts | 1 + cli/js/web/base64.ts | 2 + cli/js/web/blob.ts | 1 + cli/js/web/body.ts | 2 + cli/js/web/console.ts | 9 +-- cli/js/web/console_table.ts | 2 + cli/js/web/custom_event.ts | 3 +- cli/js/web/decode_utf8.ts | 2 + cli/js/web/dom_exception.ts | 2 +- cli/js/web/dom_file.ts | 1 + cli/js/web/dom_iterable.ts | 1 + cli/js/web/error_event.ts | 10 +-- cli/js/web/fetch.ts | 7 +- cli/js/web/fetch/multipart.ts | 7 +- cli/js/web/form_data.ts | 12 ++-- cli/js/web/headers.ts | 1 + cli/js/web/performance.ts | 1 + cli/js/web/promise.ts | 8 ++- cli/js/web/request.ts | 4 +- cli/js/web/streams/internals.ts | 117 ++++++++++++-------------------- cli/js/web/text_encoding.ts | 7 +- cli/js/web/timers.ts | 1 + cli/js/web/url.ts | 11 +-- cli/js/web/url_search_params.ts | 2 +- cli/js/web/workers.ts | 2 +- cli/js/write_file.ts | 1 + cli/js/write_text_file.ts | 10 +-- 89 files changed, 395 insertions(+), 354 deletions(-) diff --git a/cli/js/compiler.ts b/cli/js/compiler.ts index 33fef4002f..500716a64b 100644 --- a/cli/js/compiler.ts +++ b/cli/js/compiler.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + // TODO(ry) Combine this implementation with //deno_typescript/compiler_main.js // This module is the entry point for "compiler" isolate, ie. the one @@ -286,8 +287,7 @@ class SourceFile { ): string | undefined { const containingCache = RESOLVED_SPECIFIER_CACHE.get(containingFile); if (containingCache) { - const resolvedUrl = containingCache.get(moduleSpecifier); - return resolvedUrl; + return containingCache.get(moduleSpecifier); } return undefined; } @@ -315,8 +315,8 @@ function getAssetInternal(filename: string): SourceFile { class Host implements ts.CompilerHost { protected _options = DEFAULT_COMPILE_OPTIONS; - #target: CompilerHostTarget; - #writeFile: WriteFileCallback; + readonly #target: CompilerHostTarget; + readonly #writeFile: WriteFileCallback; /* Deno specific APIs */ constructor({ @@ -519,7 +519,7 @@ class Host implements ts.CompilerHost { } class IncrementalCompileHost extends Host { - #buildInfo: undefined | string = undefined; + readonly #buildInfo?: string; constructor(options: IncrementalCompilerHostOptions) { super(options); @@ -1123,9 +1123,7 @@ function buildBundle( target === ts.ScriptTarget.ES3 || target === ts.ScriptTarget.ES5 || target === ts.ScriptTarget.ES2015 || - target === ts.ScriptTarget.ES2016 - ? true - : false; + target === ts.ScriptTarget.ES2016; return `${ es5Bundle ? SYSTEM_LOADER_ES5 : SYSTEM_LOADER }\n${data}\n${instantiate}`; diff --git a/cli/js/compiler_api.ts b/cli/js/compiler_api.ts index 88d99e5b41..0f4aec8872 100644 --- a/cli/js/compiler_api.ts +++ b/cli/js/compiler_api.ts @@ -52,8 +52,8 @@ export async function compile( const emitMap: Record = {}; - for (const [key, emmitedSource] of Object.entries(result.emitMap)) { - emitMap[key] = emmitedSource.contents; + for (const [key, emittedSource] of Object.entries(result.emitMap)) { + emitMap[key] = emittedSource.contents; } return [maybeDiagnostics, emitMap]; diff --git a/cli/js/deno.ts b/cli/js/deno.ts index 5bc69fc7b1..6570042af5 100644 --- a/cli/js/deno.ts +++ b/cli/js/deno.ts @@ -1,6 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -// Public deno module. +// This module exports stable Deno APIs. + export { Buffer, readAll, diff --git a/cli/js/error_stack.ts b/cli/js/error_stack.ts index 39561ad854..4c46675ca0 100644 --- a/cli/js/error_stack.ts +++ b/cli/js/error_stack.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + // Some of the code here is adapted directly from V8 and licensed under a BSD // style license available here: https://github.com/v8/v8/blob/24886f2d1c565287d33d71e4109a53bf0b54b75c/LICENSE.v8 import * as colors from "./colors.ts"; @@ -94,10 +95,10 @@ function getMethodCall(callSite: CallSite): string { return result; } -function getFileLocation(callSite: CallSite, isInternal = false): string { - const cyan = isInternal ? colors.gray : colors.cyan; - const yellow = isInternal ? colors.gray : colors.yellow; - const black = isInternal ? colors.gray : (s: string): string => s; +function getFileLocation(callSite: CallSite, internal = false): string { + const cyan = internal ? colors.gray : colors.cyan; + const yellow = internal ? colors.gray : colors.yellow; + const black = internal ? colors.gray : (s: string): string => s; if (callSite.isNative()) { return cyan("native"); } @@ -130,9 +131,9 @@ function getFileLocation(callSite: CallSite, isInternal = false): string { return result; } -function callSiteToString(callSite: CallSite, isInternal = false): string { - const cyan = isInternal ? colors.gray : colors.cyan; - const black = isInternal ? colors.gray : (s: string): string => s; +function callSiteToString(callSite: CallSite, internal = false): string { + const cyan = internal ? colors.gray : colors.cyan; + const black = internal ? colors.gray : (s: string): string => s; let result = ""; const functionName = callSite.getFunctionName(); @@ -164,13 +165,11 @@ function callSiteToString(callSite: CallSite, isInternal = false): string { } else if (functionName) { result += colors.bold(colors.italic(black(functionName))); } else { - result += getFileLocation(callSite, isInternal); + result += getFileLocation(callSite, internal); return result; } - result += ` ${black("(")}${getFileLocation(callSite, isInternal)}${black( - ")" - )}`; + result += ` ${black("(")}${getFileLocation(callSite, internal)}${black(")")}`; return result; } diff --git a/cli/js/errors.ts b/cli/js/errors.ts index 69afcf1481..52c5e50ad9 100644 --- a/cli/js/errors.ts +++ b/cli/js/errors.ts @@ -26,7 +26,11 @@ export enum ErrorKind { Busy = 23, } -export function getErrorClass(kind: ErrorKind): { new (msg: string): Error } { +interface ErrorClass { + new (msg: string): Error; +} + +export function getErrorClass(kind: ErrorKind): ErrorClass { switch (kind) { case ErrorKind.TypeError: return TypeError; @@ -79,102 +83,119 @@ class NotFound extends Error { this.name = "NotFound"; } } + class PermissionDenied extends Error { constructor(msg: string) { super(msg); this.name = "PermissionDenied"; } } + class ConnectionRefused extends Error { constructor(msg: string) { super(msg); this.name = "ConnectionRefused"; } } + class ConnectionReset extends Error { constructor(msg: string) { super(msg); this.name = "ConnectionReset"; } } + class ConnectionAborted extends Error { constructor(msg: string) { super(msg); this.name = "ConnectionAborted"; } } + class NotConnected extends Error { constructor(msg: string) { super(msg); this.name = "NotConnected"; } } + class AddrInUse extends Error { constructor(msg: string) { super(msg); this.name = "AddrInUse"; } } + class AddrNotAvailable extends Error { constructor(msg: string) { super(msg); this.name = "AddrNotAvailable"; } } + class BrokenPipe extends Error { constructor(msg: string) { super(msg); this.name = "BrokenPipe"; } } + class AlreadyExists extends Error { constructor(msg: string) { super(msg); this.name = "AlreadyExists"; } } + class InvalidData extends Error { constructor(msg: string) { super(msg); this.name = "InvalidData"; } } + class TimedOut extends Error { constructor(msg: string) { super(msg); this.name = "TimedOut"; } } + class Interrupted extends Error { constructor(msg: string) { super(msg); this.name = "Interrupted"; } } + class WriteZero extends Error { constructor(msg: string) { super(msg); this.name = "WriteZero"; } } + class UnexpectedEof extends Error { constructor(msg: string) { super(msg); this.name = "UnexpectedEof"; } } + class BadResource extends Error { constructor(msg: string) { super(msg); this.name = "BadResource"; } } + class Http extends Error { constructor(msg: string) { super(msg); this.name = "Http"; } } + class Busy extends Error { constructor(msg: string) { super(msg); @@ -183,22 +204,22 @@ class Busy extends Error { } export const errors = { - NotFound: NotFound, - PermissionDenied: PermissionDenied, - ConnectionRefused: ConnectionRefused, - ConnectionReset: ConnectionReset, - ConnectionAborted: ConnectionAborted, - NotConnected: NotConnected, - AddrInUse: AddrInUse, - AddrNotAvailable: AddrNotAvailable, - BrokenPipe: BrokenPipe, - AlreadyExists: AlreadyExists, - InvalidData: InvalidData, - TimedOut: TimedOut, - Interrupted: Interrupted, - WriteZero: WriteZero, - UnexpectedEof: UnexpectedEof, - BadResource: BadResource, - Http: Http, - Busy: Busy, + NotFound, + PermissionDenied, + ConnectionRefused, + ConnectionReset, + ConnectionAborted, + NotConnected, + AddrInUse, + AddrNotAvailable, + BrokenPipe, + AlreadyExists, + InvalidData, + TimedOut, + Interrupted, + WriteZero, + UnexpectedEof, + BadResource, + Http, + Busy, }; diff --git a/cli/js/files.ts b/cli/js/files.ts index 83922627a0..3dc48420d9 100644 --- a/cli/js/files.ts +++ b/cli/js/files.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { Reader, Writer, @@ -97,10 +98,7 @@ export class File } class Stdin implements Reader, ReaderSync, Closer { - readonly rid: number; - constructor() { - this.rid = 0; - } + readonly rid = 0; read(p: Uint8Array): Promise { return read(this.rid, p); @@ -116,10 +114,7 @@ class Stdin implements Reader, ReaderSync, Closer { } class Stdout implements Writer, WriterSync, Closer { - readonly rid: number; - constructor() { - this.rid = 1; - } + readonly rid = 1; write(p: Uint8Array): Promise { return write(this.rid, p); @@ -135,10 +130,7 @@ class Stdout implements Writer, WriterSync, Closer { } export class Stderr implements Writer, WriterSync, Closer { - readonly rid: number; - constructor() { - this.rid = 2; - } + readonly rid = 2; write(p: Uint8Array): Promise { return write(this.rid, p); diff --git a/cli/js/internals.ts b/cli/js/internals.ts index dd02a5fa9a..b3fec8f4d7 100644 --- a/cli/js/internals.ts +++ b/cli/js/internals.ts @@ -1,9 +1,10 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + export const internalSymbol = Symbol("Deno.internal"); // The object where all the internal fields for testing will be living. // eslint-disable-next-line @typescript-eslint/no-explicit-any -export const internalObject: { [key: string]: any } = {}; +export const internalObject: Record = {}; // Register a field to internalObject for test access, // through Deno[Deno.internal][name]. diff --git a/cli/js/io.ts b/cli/js/io.ts index bf86d55b1d..2686fd3cb3 100644 --- a/cli/js/io.ts +++ b/cli/js/io.ts @@ -1,7 +1,8 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + // Interfaces 100% copied from Go. // Documentation liberally lifted from them too. -// Thank you! We love Go! +// Thank you! We love Go! <3 const DEFAULT_BUFFER_SIZE = 32 * 1024; diff --git a/cli/js/main.ts b/cli/js/main.ts index bb7a8a2dcb..4646f4cc25 100644 --- a/cli/js/main.ts +++ b/cli/js/main.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { bootstrapMainRuntime } from "./runtime_main.ts"; import { bootstrapWorkerRuntime } from "./runtime_worker.ts"; diff --git a/cli/js/net.ts b/cli/js/net.ts index b2ee7b6d3d..e5e6af7bdb 100644 --- a/cli/js/net.ts +++ b/cli/js/net.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { errors } from "./errors.ts"; import { Reader, Writer, Closer } from "./io.ts"; import { read, write } from "./ops/io.ts"; @@ -109,12 +110,11 @@ export class DatagramImpl implements DatagramConn { return [sub, remoteAddr]; } - async send(p: Uint8Array, addr: Addr): Promise { + send(p: Uint8Array, addr: Addr): Promise { const remote = { hostname: "127.0.0.1", ...addr }; const args = { ...remote, rid: this.rid }; - const byteLength = await netOps.send(args as netOps.SendRequest, p); - return byteLength; + return netOps.send(args as netOps.SendRequest, p); } close(): void { @@ -125,11 +125,11 @@ export class DatagramImpl implements DatagramConn { while (true) { try { yield await this.receive(); - } catch (error) { - if (error instanceof errors.BadResource) { + } catch (err) { + if (err instanceof errors.BadResource) { break; } - throw error; + throw err; } } } diff --git a/cli/js/net_unstable.ts b/cli/js/net_unstable.ts index 24c1d619dd..9a1d1f568b 100644 --- a/cli/js/net_unstable.ts +++ b/cli/js/net_unstable.ts @@ -1,3 +1,5 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import * as netOps from "./ops/net.ts"; import { Listener, @@ -22,6 +24,11 @@ export interface UnixListenOptions { path: string; } +export interface UnixConnectOptions { + transport: "unix"; + path: string; +} + export function listen( options: ListenOptions & { transport?: "tcp" } ): Listener; @@ -60,13 +67,6 @@ export function listenDatagram( return new DatagramImpl(res.rid, res.localAddr); } -export interface UnixConnectOptions { - transport: "unix"; - path: string; -} - -export async function connect(options: UnixConnectOptions): Promise; -export async function connect(options: ConnectOptions): Promise; export async function connect( options: ConnectOptions | UnixConnectOptions ): Promise { diff --git a/cli/js/ops/dispatch_json.ts b/cli/js/ops/dispatch_json.ts index 6a91f6a4f1..cf6f5c095a 100644 --- a/cli/js/ops/dispatch_json.ts +++ b/cli/js/ops/dispatch_json.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import * as util from "../util.ts"; import { core } from "../core.ts"; import { ErrorKind, getErrorClass } from "../errors.ts"; @@ -18,9 +19,10 @@ interface JsonResponse { } // Using an object without a prototype because `Map` was causing GC problems. -const promiseTable: { - [key: number]: util.Resolvable; -} = Object.create(null); +const promiseTable: Record< + number, + util.Resolvable +> = Object.create(null); let _nextPromiseId = 1; function nextPromiseId(): number { @@ -28,13 +30,11 @@ function nextPromiseId(): number { } function decode(ui8: Uint8Array): JsonResponse { - const s = core.decode(ui8); - return JSON.parse(s) as JsonResponse; + return JSON.parse(core.decode(ui8)); } function encode(args: object): Uint8Array { - const s = JSON.stringify(args); - return core.encode(s); + return core.encode(JSON.stringify(args)); } function unwrapResponse(res: JsonResponse): Ok { @@ -80,7 +80,7 @@ export async function sendAsync( const promise = util.createResolvable(); const argsUi8 = encode(args); const buf = core.dispatchByName(opName, argsUi8, ...zeroCopy); - if (buf) { + if (buf != null) { // Sync result. const res = decode(buf); promise.resolve(res); diff --git a/cli/js/ops/dispatch_minimal.ts b/cli/js/ops/dispatch_minimal.ts index 0d1dac44e8..ca50b00e95 100644 --- a/cli/js/ops/dispatch_minimal.ts +++ b/cli/js/ops/dispatch_minimal.ts @@ -1,13 +1,15 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import * as util from "../util.ts"; import { core } from "../core.ts"; import { TextDecoder } from "../web/text_encoding.ts"; import { ErrorKind, errors, getErrorClass } from "../errors.ts"; // Using an object without a prototype because `Map` was causing GC problems. -const promiseTableMin: { - [key: number]: util.Resolvable; -} = Object.create(null); +const promiseTableMin: Record< + number, + util.Resolvable +> = Object.create(null); // Note it's important that promiseId starts at 1 instead of 0, because sync // messages are indicated with promiseId 0. If we ever add wrap around logic for @@ -93,7 +95,7 @@ export async function sendAsyncMinimal( scratch32[2] = 0; // result const promise = util.createResolvable(); const buf = core.dispatchByName(opName, scratchBytes, zeroCopy); - if (buf) { + if (buf != null) { const record = recordFromBufMinimal(buf); // Sync result. promise.resolve(record); diff --git a/cli/js/ops/errors.ts b/cli/js/ops/errors.ts index bd3e6d8090..c6c26b8ba6 100644 --- a/cli/js/ops/errors.ts +++ b/cli/js/ops/errors.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { DiagnosticItem } from "../diagnostics.ts"; import { sendSync } from "./dispatch_json.ts"; @@ -13,12 +14,7 @@ export interface Location { } export function applySourceMap(location: Location): Location { - const { fileName, lineNumber, columnNumber } = location; - const res = sendSync("op_apply_source_map", { - fileName, - lineNumber: lineNumber, - columnNumber: columnNumber, - }); + const res = sendSync("op_apply_source_map", location); return { fileName: res.fileName, lineNumber: res.lineNumber, diff --git a/cli/js/ops/fetch.ts b/cli/js/ops/fetch.ts index 290376c860..2f881cc021 100644 --- a/cli/js/ops/fetch.ts +++ b/cli/js/ops/fetch.ts @@ -17,10 +17,10 @@ export interface FetchResponse { export function fetch( args: FetchRequest, - body: ArrayBufferView | undefined + body?: ArrayBufferView ): Promise { - let zeroCopy = undefined; - if (body) { + let zeroCopy; + if (body != null) { zeroCopy = new Uint8Array(body.buffer, body.byteOffset, body.byteLength); } diff --git a/cli/js/ops/fs/chmod.ts b/cli/js/ops/fs/chmod.ts index 76a3c8f49d..a2236935b6 100644 --- a/cli/js/ops/fs/chmod.ts +++ b/cli/js/ops/fs/chmod.ts @@ -1,13 +1,12 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; import { pathFromURL } from "../../util.ts"; export function chmodSync(path: string | URL, mode: number): void { - path = pathFromURL(path); - sendSync("op_chmod", { path, mode }); + sendSync("op_chmod", { path: pathFromURL(path), mode }); } export async function chmod(path: string | URL, mode: number): Promise { - path = pathFromURL(path); - await sendAsync("op_chmod", { path, mode }); + await sendAsync("op_chmod", { path: pathFromURL(path), mode }); } diff --git a/cli/js/ops/fs/chown.ts b/cli/js/ops/fs/chown.ts index 3afe07f16f..52735e0977 100644 --- a/cli/js/ops/fs/chown.ts +++ b/cli/js/ops/fs/chown.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; import { pathFromURL } from "../../util.ts"; @@ -7,8 +8,7 @@ export function chownSync( uid: number | null, gid: number | null ): void { - path = pathFromURL(path); - sendSync("op_chown", { path, uid, gid }); + sendSync("op_chown", { path: pathFromURL(path), uid, gid }); } export async function chown( @@ -16,6 +16,5 @@ export async function chown( uid: number | null, gid: number | null ): Promise { - path = pathFromURL(path); - await sendAsync("op_chown", { path, uid, gid }); + await sendAsync("op_chown", { path: pathFromURL(path), uid, gid }); } diff --git a/cli/js/ops/fs/copy_file.ts b/cli/js/ops/fs/copy_file.ts index 6bbb3f5994..fcb147bddc 100644 --- a/cli/js/ops/fs/copy_file.ts +++ b/cli/js/ops/fs/copy_file.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; import { pathFromURL } from "../../util.ts"; @@ -6,18 +7,18 @@ export function copyFileSync( fromPath: string | URL, toPath: string | URL ): void { - fromPath = pathFromURL(fromPath); - toPath = pathFromURL(toPath); - - sendSync("op_copy_file", { from: fromPath, to: toPath }); + sendSync("op_copy_file", { + from: pathFromURL(fromPath), + to: pathFromURL(toPath), + }); } export async function copyFile( fromPath: string | URL, toPath: string | URL ): Promise { - fromPath = pathFromURL(fromPath); - toPath = pathFromURL(toPath); - - await sendAsync("op_copy_file", { from: fromPath, to: toPath }); + await sendAsync("op_copy_file", { + from: pathFromURL(fromPath), + to: pathFromURL(toPath), + }); } diff --git a/cli/js/ops/fs/dir.ts b/cli/js/ops/fs/dir.ts index 14b6240ed2..dbf468c621 100644 --- a/cli/js/ops/fs/dir.ts +++ b/cli/js/ops/fs/dir.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync } from "../dispatch_json.ts"; export function cwd(): string { diff --git a/cli/js/ops/fs/link.ts b/cli/js/ops/fs/link.ts index 92fb58834f..05ff358efb 100644 --- a/cli/js/ops/fs/link.ts +++ b/cli/js/ops/fs/link.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; export function linkSync(oldpath: string, newpath: string): void { diff --git a/cli/js/ops/fs/make_temp.ts b/cli/js/ops/fs/make_temp.ts index 85dea5f209..3996744d1a 100644 --- a/cli/js/ops/fs/make_temp.ts +++ b/cli/js/ops/fs/make_temp.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; export interface MakeTempOptions { diff --git a/cli/js/ops/fs/mkdir.ts b/cli/js/ops/fs/mkdir.ts index 374a00d835..61ea1c2184 100644 --- a/cli/js/ops/fs/mkdir.ts +++ b/cli/js/ops/fs/mkdir.ts @@ -1,11 +1,21 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; -type MkdirArgs = { path: string; recursive: boolean; mode?: number }; +export interface MkdirOptions { + recursive?: boolean; + mode?: number; +} + +interface MkdirArgs { + path: string; + recursive: boolean; + mode?: number; +} function mkdirArgs(path: string, options?: MkdirOptions): MkdirArgs { const args: MkdirArgs = { path, recursive: false }; - if (options) { + if (options != null) { if (typeof options.recursive == "boolean") { args.recursive = options.recursive; } @@ -16,11 +26,6 @@ function mkdirArgs(path: string, options?: MkdirOptions): MkdirArgs { return args; } -export interface MkdirOptions { - recursive?: boolean; - mode?: number; -} - export function mkdirSync(path: string, options?: MkdirOptions): void { sendSync("op_mkdir", mkdirArgs(path, options)); } diff --git a/cli/js/ops/fs/open.ts b/cli/js/ops/fs/open.ts index 3742d0b52a..edd52c3767 100644 --- a/cli/js/ops/fs/open.ts +++ b/cli/js/ops/fs/open.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; import { pathFromURL } from "../../util.ts"; @@ -18,8 +19,7 @@ export interface OpenOptions { export function openSync(path: string | URL, options: OpenOptions): number { const mode: number | undefined = options?.mode; - path = pathFromURL(path); - return sendSync("op_open", { path, options, mode }); + return sendSync("op_open", { path: pathFromURL(path), options, mode }); } export function open( @@ -27,10 +27,5 @@ export function open( options: OpenOptions ): Promise { const mode: number | undefined = options?.mode; - path = pathFromURL(path); - return sendAsync("op_open", { - path, - options, - mode, - }); + return sendAsync("op_open", { path: pathFromURL(path), options, mode }); } diff --git a/cli/js/ops/fs/read_dir.ts b/cli/js/ops/fs/read_dir.ts index 09c5d1c12e..6ffe6116ed 100644 --- a/cli/js/ops/fs/read_dir.ts +++ b/cli/js/ops/fs/read_dir.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; import { pathFromURL } from "../../util.ts"; @@ -18,13 +19,13 @@ function res(response: ReadDirResponse): DirEntry[] { } export function readDirSync(path: string | URL): Iterable { - path = pathFromURL(path); - return res(sendSync("op_read_dir", { path }))[Symbol.iterator](); + return res(sendSync("op_read_dir", { path: pathFromURL(path) }))[ + Symbol.iterator + ](); } export function readDir(path: string | URL): AsyncIterable { - path = pathFromURL(path); - const array = sendAsync("op_read_dir", { path }).then(res); + const array = sendAsync("op_read_dir", { path: pathFromURL(path) }).then(res); return { async *[Symbol.asyncIterator](): AsyncIterableIterator { yield* await array; diff --git a/cli/js/ops/fs/read_link.ts b/cli/js/ops/fs/read_link.ts index bcd27ccb75..33fef7e369 100644 --- a/cli/js/ops/fs/read_link.ts +++ b/cli/js/ops/fs/read_link.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; export function readLinkSync(path: string): string { diff --git a/cli/js/ops/fs/real_path.ts b/cli/js/ops/fs/real_path.ts index ab95b95837..c424d99bc3 100644 --- a/cli/js/ops/fs/real_path.ts +++ b/cli/js/ops/fs/real_path.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; export function realPathSync(path: string): string { diff --git a/cli/js/ops/fs/remove.ts b/cli/js/ops/fs/remove.ts index d1a8702f1c..52f4cad403 100644 --- a/cli/js/ops/fs/remove.ts +++ b/cli/js/ops/fs/remove.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; import { pathFromURL } from "../../util.ts"; @@ -10,14 +11,18 @@ export function removeSync( path: string | URL, options: RemoveOptions = {} ): void { - path = pathFromURL(path); - sendSync("op_remove", { path, recursive: !!options.recursive }); + sendSync("op_remove", { + path: pathFromURL(path), + recursive: !!options.recursive, + }); } export async function remove( path: string | URL, options: RemoveOptions = {} ): Promise { - path = pathFromURL(path); - await sendAsync("op_remove", { path, recursive: !!options.recursive }); + await sendAsync("op_remove", { + path: pathFromURL(path), + recursive: !!options.recursive, + }); } diff --git a/cli/js/ops/fs/rename.ts b/cli/js/ops/fs/rename.ts index 9f02c8bc06..f0789d3ebb 100644 --- a/cli/js/ops/fs/rename.ts +++ b/cli/js/ops/fs/rename.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; export function renameSync(oldpath: string, newpath: string): void { diff --git a/cli/js/ops/fs/seek.ts b/cli/js/ops/fs/seek.ts index c7e4c9172f..2e23e084b8 100644 --- a/cli/js/ops/fs/seek.ts +++ b/cli/js/ops/fs/seek.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; import { SeekMode } from "../../io.ts"; diff --git a/cli/js/ops/fs/stat.ts b/cli/js/ops/fs/stat.ts index 402adeafc3..f444190fd7 100644 --- a/cli/js/ops/fs/stat.ts +++ b/cli/js/ops/fs/stat.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; import { build } from "../../build.ts"; import { pathFromURL } from "../../util.ts"; @@ -44,7 +45,7 @@ export interface StatResponse { // @internal export function parseFileInfo(response: StatResponse): FileInfo { - const isUnix = build.os === "darwin" || build.os === "linux"; + const unix = build.os === "darwin" || build.os === "linux"; return { isFile: response.isFile, isDirectory: response.isDirectory, @@ -54,15 +55,15 @@ export function parseFileInfo(response: StatResponse): FileInfo { atime: response.atime != null ? new Date(response.atime) : null, birthtime: response.birthtime != null ? new Date(response.birthtime) : null, // Only non-null if on Unix - dev: isUnix ? response.dev : null, - ino: isUnix ? response.ino : null, - mode: isUnix ? response.mode : null, - nlink: isUnix ? response.nlink : null, - uid: isUnix ? response.uid : null, - gid: isUnix ? response.gid : null, - rdev: isUnix ? response.rdev : null, - blksize: isUnix ? response.blksize : null, - blocks: isUnix ? response.blocks : null, + dev: unix ? response.dev : null, + ino: unix ? response.ino : null, + mode: unix ? response.mode : null, + nlink: unix ? response.nlink : null, + uid: unix ? response.uid : null, + gid: unix ? response.gid : null, + rdev: unix ? response.rdev : null, + blksize: unix ? response.blksize : null, + blocks: unix ? response.blocks : null, }; } @@ -75,37 +76,33 @@ export async function fstat(rid: number): Promise { } export async function lstat(path: string | URL): Promise { - path = pathFromURL(path); - const res = (await sendAsync("op_stat", { - path, + const res = await sendAsync("op_stat", { + path: pathFromURL(path), lstat: true, - })) as StatResponse; + }); return parseFileInfo(res); } export function lstatSync(path: string | URL): FileInfo { - path = pathFromURL(path); const res = sendSync("op_stat", { - path, + path: pathFromURL(path), lstat: true, - }) as StatResponse; + }); return parseFileInfo(res); } export async function stat(path: string | URL): Promise { - path = pathFromURL(path); - const res = (await sendAsync("op_stat", { - path, + const res = await sendAsync("op_stat", { + path: pathFromURL(path), lstat: false, - })) as StatResponse; + }); return parseFileInfo(res); } export function statSync(path: string | URL): FileInfo { - path = pathFromURL(path); const res = sendSync("op_stat", { - path, + path: pathFromURL(path), lstat: false, - }) as StatResponse; + }); return parseFileInfo(res); } diff --git a/cli/js/ops/fs/symlink.ts b/cli/js/ops/fs/symlink.ts index fde611b557..7d47419283 100644 --- a/cli/js/ops/fs/symlink.ts +++ b/cli/js/ops/fs/symlink.ts @@ -1,14 +1,15 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; -export type symlinkOptions = { +export interface SymlinkOptions { type: "file" | "dir"; -}; +} export function symlinkSync( oldpath: string, newpath: string, - options?: symlinkOptions + options?: SymlinkOptions ): void { sendSync("op_symlink", { oldpath, newpath, options }); } @@ -16,7 +17,7 @@ export function symlinkSync( export async function symlink( oldpath: string, newpath: string, - options?: symlinkOptions + options?: SymlinkOptions ): Promise { await sendAsync("op_symlink", { oldpath, newpath, options }); } diff --git a/cli/js/ops/fs/sync.ts b/cli/js/ops/fs/sync.ts index 567aab55b4..7f208b8bdd 100644 --- a/cli/js/ops/fs/sync.ts +++ b/cli/js/ops/fs/sync.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; export function fdatasyncSync(rid: number): void { diff --git a/cli/js/ops/fs/truncate.ts b/cli/js/ops/fs/truncate.ts index 2b805e5ac7..d18e5d9d9a 100644 --- a/cli/js/ops/fs/truncate.ts +++ b/cli/js/ops/fs/truncate.ts @@ -1,12 +1,9 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; function coerceLen(len?: number): number { - if (!len) { - return 0; - } - - if (len < 0) { + if (len == null || len < 0) { return 0; } diff --git a/cli/js/ops/fs/umask.ts b/cli/js/ops/fs/umask.ts index 38bf8ff6c6..fbc94091e1 100644 --- a/cli/js/ops/fs/umask.ts +++ b/cli/js/ops/fs/umask.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync } from "../dispatch_json.ts"; export function umask(mask?: number): number { diff --git a/cli/js/ops/fs/utime.ts b/cli/js/ops/fs/utime.ts index 2755a7e969..fa86038c69 100644 --- a/cli/js/ops/fs/utime.ts +++ b/cli/js/ops/fs/utime.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "../dispatch_json.ts"; function toSecondsFromEpoch(v: number | Date): number { diff --git a/cli/js/ops/fs_events.ts b/cli/js/ops/fs_events.ts index 9d72cb8984..fb78c6196d 100644 --- a/cli/js/ops/fs_events.ts +++ b/cli/js/ops/fs_events.ts @@ -1,4 +1,5 @@ -// Copyright 2019 the Deno authors. All rights reserved. MIT license. +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "./dispatch_json.ts"; import { close } from "./resources.ts"; @@ -7,10 +8,14 @@ export interface FsEvent { paths: string[]; } +interface FsWatcherOptions { + recursive: boolean; +} + class FsWatcher implements AsyncIterableIterator { readonly rid: number; - constructor(paths: string[], options: { recursive: boolean }) { + constructor(paths: string[], options: FsWatcherOptions) { const { recursive } = options; this.rid = sendSync("op_fs_events_open", { recursive, paths }); } @@ -33,7 +38,7 @@ class FsWatcher implements AsyncIterableIterator { export function watchFs( paths: string | string[], - options = { recursive: true } + options: FsWatcherOptions = { recursive: true } ): AsyncIterableIterator { return new FsWatcher(Array.isArray(paths) ? paths : [paths], options); } diff --git a/cli/js/ops/get_random_values.ts b/cli/js/ops/get_random_values.ts index 1dc56b6987..95e4602e68 100644 --- a/cli/js/ops/get_random_values.ts +++ b/cli/js/ops/get_random_values.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync } from "./dispatch_json.ts"; import { assert } from "../util.ts"; diff --git a/cli/js/ops/io.ts b/cli/js/ops/io.ts index cc3d1d1701..ecd1269d51 100644 --- a/cli/js/ops/io.ts +++ b/cli/js/ops/io.ts @@ -3,50 +3,48 @@ import { sendAsyncMinimal, sendSyncMinimal } from "./dispatch_minimal.ts"; export function readSync(rid: number, buffer: Uint8Array): number | null { - if (buffer.length == 0) { + if (buffer.length === 0) { return 0; } + const nread = sendSyncMinimal("op_read", rid, buffer); if (nread < 0) { throw new Error("read error"); - } else if (nread == 0) { - return null; - } else { - return nread; } + + return nread === 0 ? null : nread; } export async function read( rid: number, buffer: Uint8Array ): Promise { - if (buffer.length == 0) { + if (buffer.length === 0) { return 0; } + const nread = await sendAsyncMinimal("op_read", rid, buffer); if (nread < 0) { throw new Error("read error"); - } else if (nread == 0) { - return null; - } else { - return nread; } + + return nread === 0 ? null : nread; } export function writeSync(rid: number, data: Uint8Array): number { const result = sendSyncMinimal("op_write", rid, data); if (result < 0) { throw new Error("write error"); - } else { - return result; } + + return result; } export async function write(rid: number, data: Uint8Array): Promise { const result = await sendAsyncMinimal("op_write", rid, data); if (result < 0) { throw new Error("write error"); - } else { - return result; } + + return result; } diff --git a/cli/js/ops/net.ts b/cli/js/ops/net.ts index 98ee71ff8c..05b1bc2cdf 100644 --- a/cli/js/ops/net.ts +++ b/cli/js/ops/net.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "./dispatch_json.ts"; export interface NetAddr { @@ -18,7 +19,7 @@ export enum ShutdownMode { // See http://man7.org/linux/man-pages/man2/shutdown.2.html // Corresponding to SHUT_RD, SHUT_WR, SHUT_RDWR Read = 0, - Write, + Write = 1, ReadWrite, // unused } @@ -80,10 +81,6 @@ export type SendRequest = { rid: number; } & Addr; -export async function send( - args: SendRequest, - zeroCopy: Uint8Array -): Promise { - const byteLength = await sendAsync("op_datagram_send", args, zeroCopy); - return byteLength; +export function send(args: SendRequest, zeroCopy: Uint8Array): Promise { + return sendAsync("op_datagram_send", args, zeroCopy); } diff --git a/cli/js/ops/os.ts b/cli/js/ops/os.ts index 696c9f10bb..50234ee4be 100644 --- a/cli/js/ops/os.ts +++ b/cli/js/ops/os.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync } from "./dispatch_json.ts"; export function loadavg(): number[] { @@ -32,7 +33,7 @@ function deleteEnv(key: string): void { export const env = { get: getEnv, - toObject(): { [key: string]: string } { + toObject(): Record { return sendSync("op_env"); }, set: setEnv, diff --git a/cli/js/ops/permissions.ts b/cli/js/ops/permissions.ts index 783b1b297e..dfe8c48347 100644 --- a/cli/js/ops/permissions.ts +++ b/cli/js/ops/permissions.ts @@ -1,9 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { sendSync } from "./dispatch_json.ts"; -// TODO(bartlomieju): duplicated in `cli/js/permissions.ts` as -// `PermissionState -export type PermissionResponse = "granted" | "denied" | "prompt"; +import { sendSync } from "./dispatch_json.ts"; +import { PermissionState } from "../permissions.ts"; interface PermissionRequest { name: string; @@ -11,14 +9,14 @@ interface PermissionRequest { path?: string; } -export function query(desc: PermissionRequest): PermissionResponse { +export function query(desc: PermissionRequest): PermissionState { return sendSync("op_query_permission", desc).state; } -export function revoke(desc: PermissionRequest): PermissionResponse { +export function revoke(desc: PermissionRequest): PermissionState { return sendSync("op_revoke_permission", desc).state; } -export function request(desc: PermissionRequest): PermissionResponse { +export function request(desc: PermissionRequest): PermissionState { return sendSync("op_request_permission", desc).state; } diff --git a/cli/js/ops/plugins.ts b/cli/js/ops/plugins.ts index e4593afbb2..787fd799b4 100644 --- a/cli/js/ops/plugins.ts +++ b/cli/js/ops/plugins.ts @@ -1,6 +1,7 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync } from "./dispatch_json.ts"; export function openPlugin(filename: string): number { - const rid = sendSync("op_open_plugin", { filename }); - return rid; + return sendSync("op_open_plugin", { filename }); } diff --git a/cli/js/ops/process.ts b/cli/js/ops/process.ts index 39c6eb8b7c..86a0c9a712 100644 --- a/cli/js/ops/process.ts +++ b/cli/js/ops/process.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "./dispatch_json.ts"; import { assert } from "../util.ts"; diff --git a/cli/js/ops/resources.ts b/cli/js/ops/resources.ts index dacdaa6596..ffcdb553e5 100644 --- a/cli/js/ops/resources.ts +++ b/cli/js/ops/resources.ts @@ -1,9 +1,8 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync } from "./dispatch_json.ts"; -export interface ResourceMap { - [rid: number]: string; -} +export type ResourceMap = Record; export function resources(): ResourceMap { const res = sendSync("op_resources") as Array<[number, string]>; diff --git a/cli/js/ops/signal.ts b/cli/js/ops/signal.ts index 09c1781054..15093a3c43 100644 --- a/cli/js/ops/signal.ts +++ b/cli/js/ops/signal.ts @@ -1,11 +1,20 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "./dispatch_json.ts"; -export function bindSignal(signo: number): { rid: number } { +interface BindSignalResponse { + rid: number; +} + +interface PollSignalResponse { + done: boolean; +} + +export function bindSignal(signo: number): BindSignalResponse { return sendSync("op_signal_bind", { signo }); } -export function pollSignal(rid: number): Promise<{ done: boolean }> { +export function pollSignal(rid: number): Promise { return sendAsync("op_signal_poll", { rid }); } diff --git a/cli/js/ops/timers.ts b/cli/js/ops/timers.ts index 1a7081df03..2fdbd68518 100644 --- a/cli/js/ops/timers.ts +++ b/cli/js/ops/timers.ts @@ -1,6 +1,12 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync, sendAsync } from "./dispatch_json.ts"; +interface NowResponse { + seconds: number; + subsecNanos: number; +} + export function stopGlobalTimer(): void { sendSync("op_global_timer_stop"); } @@ -9,11 +15,6 @@ export async function startGlobalTimer(timeout: number): Promise { await sendAsync("op_global_timer", { timeout }); } -interface NowResponse { - seconds: number; - subsecNanos: number; -} - export function now(): NowResponse { return sendSync("op_now"); } diff --git a/cli/js/ops/tls.ts b/cli/js/ops/tls.ts index 60ec8846cf..b278c2d755 100644 --- a/cli/js/ops/tls.ts +++ b/cli/js/ops/tls.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendAsync, sendSync } from "./dispatch_json.ts"; export interface ConnectTLSRequest { diff --git a/cli/js/ops/tty.ts b/cli/js/ops/tty.ts index f848d27741..8899ca5b80 100644 --- a/cli/js/ops/tty.ts +++ b/cli/js/ops/tty.ts @@ -1,3 +1,5 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { sendSync } from "./dispatch_json.ts"; export function isatty(rid: number): boolean { @@ -5,8 +7,5 @@ export function isatty(rid: number): boolean { } export function setRaw(rid: number, mode: boolean): void { - sendSync("op_set_raw", { - rid, - mode, - }); + sendSync("op_set_raw", { rid, mode }); } diff --git a/cli/js/ops/worker_host.ts b/cli/js/ops/worker_host.ts index 11e268152b..24e6b57bad 100644 --- a/cli/js/ops/worker_host.ts +++ b/cli/js/ops/worker_host.ts @@ -1,14 +1,19 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + /* eslint-disable @typescript-eslint/no-explicit-any */ import { sendAsync, sendSync } from "./dispatch_json.ts"; +interface CreateWorkerResponse { + id: number; +} + export function createWorker( specifier: string, hasSourceCode: boolean, sourceCode: string, useDenoNamespace: boolean, name?: string -): { id: number } { +): CreateWorkerResponse { return sendSync("op_create_worker", { specifier, hasSourceCode, diff --git a/cli/js/permissions.ts b/cli/js/permissions.ts index 03c7b763d1..ab0612ad4c 100644 --- a/cli/js/permissions.ts +++ b/cli/js/permissions.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import * as permissionsOps from "./ops/permissions.ts"; export type PermissionName = diff --git a/cli/js/process.ts b/cli/js/process.ts index c7c3358f55..ff92516979 100644 --- a/cli/js/process.ts +++ b/cli/js/process.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { File } from "./files.ts"; import { close } from "./ops/resources.ts"; import { Closer, Reader, Writer } from "./io.ts"; @@ -10,7 +11,7 @@ import { kill, runStatus as runStatusOp, run as runOp } from "./ops/process.ts"; export interface RunOptions { cmd: string[]; cwd?: string; - env?: { [key: string]: string }; + env?: Record; stdout?: "inherit" | "piped" | "null" | number; stderr?: "inherit" | "piped" | "null" | number; stdin?: "inherit" | "piped" | "null" | number; @@ -100,16 +101,8 @@ export class Process { } export type ProcessStatus = - | { - success: true; - code: 0; - signal?: undefined; - } - | { - success: false; - code: number; - signal?: number; - }; + | { success: true; code: 0; signal?: undefined } + | { success: false; code: number; signal?: number }; function isRid(arg: unknown): arg is number { return !isNaN(arg as number); diff --git a/cli/js/rbtree.ts b/cli/js/rbtree.ts index 7b01024f78..fbade97b71 100644 --- a/cli/js/rbtree.ts +++ b/cli/js/rbtree.ts @@ -1,3 +1,5 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + // Derived from https://github.com/vadimg/js_bintrees. MIT Licensed. import { assert } from "./util.ts"; @@ -27,7 +29,7 @@ class RBNode { } export class RBTree { - #comparator: (a: T, b: T) => number; + readonly #comparator: (a: T, b: T) => number; #root: RBNode | null; constructor(comparator: (a: T, b: T) => number) { diff --git a/cli/js/read_file.ts b/cli/js/read_file.ts index b8d428b8c9..a90ad47fb0 100644 --- a/cli/js/read_file.ts +++ b/cli/js/read_file.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { open, openSync } from "./files.ts"; import { readAll, readAllSync } from "./buffer.ts"; diff --git a/cli/js/read_text_file.ts b/cli/js/read_text_file.ts index 154b01b0ee..02c9fe6119 100644 --- a/cli/js/read_text_file.ts +++ b/cli/js/read_text_file.ts @@ -1,18 +1,20 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { open, openSync } from "./files.ts"; import { readAll, readAllSync } from "./buffer.ts"; export function readTextFileSync(path: string | URL): string { - const decoder = new TextDecoder(); const file = openSync(path); - const content = readAllSync(file); + const contents = readAllSync(file); file.close(); - return decoder.decode(content); + const decoder = new TextDecoder(); + return decoder.decode(contents); } export async function readTextFile(path: string | URL): Promise { - const decoder = new TextDecoder(); const file = await open(path); - const content = await readAll(file); + const contents = await readAll(file); file.close(); - return decoder.decode(content); + const decoder = new TextDecoder(); + return decoder.decode(contents); } diff --git a/cli/js/repl.ts b/cli/js/repl.ts index d1cf63cd91..daa112e1ee 100644 --- a/cli/js/repl.ts +++ b/cli/js/repl.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { exit } from "./ops/os.ts"; import { core } from "./core.ts"; import { version } from "./version.ts"; diff --git a/cli/js/runtime.ts b/cli/js/runtime.ts index 39d158f715..a260dfebe9 100644 --- a/cli/js/runtime.ts +++ b/cli/js/runtime.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { core } from "./core.ts"; import * as dispatchMinimal from "./ops/dispatch_minimal.ts"; import * as dispatchJson from "./ops/dispatch_json.ts"; diff --git a/cli/js/signals.ts b/cli/js/signals.ts index 2e29528e17..64cf4106b2 100644 --- a/cli/js/signals.ts +++ b/cli/js/signals.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { bindSignal, pollSignal, unbindSignal } from "./ops/signal.ts"; import { build } from "./build.ts"; @@ -129,7 +130,7 @@ export class SignalStream implements AsyncIterableIterator, PromiseLike { #disposed = false; #pollingPromise: Promise = Promise.resolve(false); - #rid: number; + readonly #rid: number; constructor(signo: number) { this.#rid = bindSignal(signo).rid; diff --git a/cli/js/testing.ts b/cli/js/testing.ts index 64ae6f0b32..e8d42c2ebb 100644 --- a/cli/js/testing.ts +++ b/cli/js/testing.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { gray, green, italic, red, yellow } from "./colors.ts"; import { exit } from "./ops/os.ts"; import { Console, stringifyArgs } from "./web/console.ts"; @@ -11,9 +12,9 @@ import { assert } from "./util.ts"; const disabledConsole = new Console((): void => {}); -function delay(n: number): Promise { - return new Promise((resolve: () => void, _) => { - setTimeout(resolve, n); +function delay(ms: number): Promise { + return new Promise((resolve: () => void) => { + setTimeout(resolve, ms); }); } @@ -241,7 +242,7 @@ class TestRunner { passed: 0, failed: 0, }; - private usedOnly: boolean; + readonly #usedOnly: boolean; constructor( tests: TestDefinition[], @@ -249,8 +250,8 @@ class TestRunner { public failFast: boolean ) { const onlyTests = tests.filter(({ only }) => only); - this.usedOnly = onlyTests.length > 0; - const unfilteredTests = this.usedOnly ? onlyTests : tests; + this.#usedOnly = onlyTests.length > 0; + const unfilteredTests = this.#usedOnly ? onlyTests : tests; this.testsToRun = unfilteredTests.filter(filterFn); this.stats.filtered = unfilteredTests.length - this.testsToRun.length; } @@ -292,7 +293,7 @@ class TestRunner { const duration = +new Date() - suiteStart; yield { - end: { ...this.stats, usedOnly: this.usedOnly, duration, results }, + end: { ...this.stats, usedOnly: this.#usedOnly, duration, results }, }; } } diff --git a/cli/js/tls.ts b/cli/js/tls.ts index 270d724bb5..f0506898c5 100644 --- a/cli/js/tls.ts +++ b/cli/js/tls.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import * as tlsOps from "./ops/tls.ts"; import { Listener, Conn, ConnImpl, ListenerImpl } from "./net.ts"; @@ -65,7 +66,7 @@ interface StartTlsOptions { export async function startTls( conn: Conn, - { hostname = "127.0.0.1", certFile = undefined }: StartTlsOptions = {} + { hostname = "127.0.0.1", certFile }: StartTlsOptions = {} ): Promise { const res = await tlsOps.startTls({ rid: conn.rid, diff --git a/cli/js/util.ts b/cli/js/util.ts index d68a6cb51b..50a38978e0 100644 --- a/cli/js/util.ts +++ b/cli/js/util.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { build } from "./build.ts"; import { exposeForTest } from "./internals.ts"; diff --git a/cli/js/version.ts b/cli/js/version.ts index 534195ce5e..ff9b5e9723 100644 --- a/cli/js/version.ts +++ b/cli/js/version.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + interface Version { deno: string; v8: string; diff --git a/cli/js/web/README.md b/cli/js/web/README.md index f220c0da65..01672fe76c 100644 --- a/cli/js/web/README.md +++ b/cli/js/web/README.md @@ -2,10 +2,10 @@ This directory facilities Web APIs that are available in Deno. -Please note, that some of implementations might not be completely aligned with +Please note, that some implementations might not be completely aligned with specification. -Some of the Web APIs are using ops under the hood, eg. `console`, `performance`. +Some Web APIs are using ops under the hood, eg. `console`, `performance`. ## Implemented Web APIs diff --git a/cli/js/web/abort_controller.ts b/cli/js/web/abort_controller.ts index 5b0a3af3c8..376376092e 100644 --- a/cli/js/web/abort_controller.ts +++ b/cli/js/web/abort_controller.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { AbortSignalImpl, signalAbort } from "./abort_signal.ts"; export class AbortControllerImpl implements AbortController { diff --git a/cli/js/web/base64.ts b/cli/js/web/base64.ts index 4d30e00f1f..328311d030 100644 --- a/cli/js/web/base64.ts +++ b/cli/js/web/base64.ts @@ -1,3 +1,5 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + // Forked from https://github.com/beatgammit/base64-js // Copyright (c) 2014 Jameson Little. MIT License. diff --git a/cli/js/web/blob.ts b/cli/js/web/blob.ts index 899c671358..92286029f0 100644 --- a/cli/js/web/blob.ts +++ b/cli/js/web/blob.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { TextDecoder, TextEncoder } from "./text_encoding.ts"; import { build } from "../build.ts"; import { ReadableStreamImpl } from "./streams/readable_stream.ts"; diff --git a/cli/js/web/body.ts b/cli/js/web/body.ts index 35fc5ebbed..80c4b646a9 100644 --- a/cli/js/web/body.ts +++ b/cli/js/web/body.ts @@ -1,3 +1,5 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import * as blob from "./blob.ts"; import * as encoding from "./text_encoding.ts"; import * as domTypes from "./dom_types.d.ts"; diff --git a/cli/js/web/console.ts b/cli/js/web/console.ts index f6ea7a0a72..1f96bfe9d0 100644 --- a/cli/js/web/console.ts +++ b/cli/js/web/console.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { isInvalidDate, isTypedArray, TypedArray } from "./util.ts"; import { cliTable } from "./console_table.ts"; import { exposeForTest } from "../internals.ts"; @@ -381,7 +382,7 @@ function createTypedArrayString( displayName: `${typedArrayName}(${valueLength})`, delims: ["[", "]"], entryHandler: (entry, ctx, level, maxLevel): string => { - const [_, val] = entry; + const val = entry[1]; return stringifyWithQuotes(val, ctx, level + 1, maxLevel); }, group: true, @@ -400,7 +401,7 @@ function createSetString( displayName: "Set", delims: ["{", "}"], entryHandler: (entry, ctx, level, maxLevel): string => { - const [_, val] = entry; + const val = entry[1]; return stringifyWithQuotes(val, ctx, level + 1, maxLevel); }, group: false, @@ -508,7 +509,7 @@ function createRawObjectString( } ctx.add(value); - let baseString = ""; + let baseString: string; let shouldShowDisplayName = false; let displayName = (value as { [Symbol.toStringTag]: string })[ @@ -724,7 +725,7 @@ const timerMap = new Map(); const isConsoleInstance = Symbol("isConsoleInstance"); export class Console { - #printFunc: PrintFunc; + readonly #printFunc: PrintFunc; indentLevel: number; [isConsoleInstance] = false; diff --git a/cli/js/web/console_table.ts b/cli/js/web/console_table.ts index 55808cdc0c..ba2d763b7e 100644 --- a/cli/js/web/console_table.ts +++ b/cli/js/web/console_table.ts @@ -1,3 +1,5 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + // Copyright Joyent, Inc. and other Node contributors. MIT license. // Forked from Node's lib/internal/cli_table.js diff --git a/cli/js/web/custom_event.ts b/cli/js/web/custom_event.ts index ea76d2c94e..dad89f6509 100644 --- a/cli/js/web/custom_event.ts +++ b/cli/js/web/custom_event.ts @@ -1,10 +1,11 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { EventImpl as Event } from "./event.ts"; import { requiredArguments } from "./util.ts"; // eslint-disable-next-line @typescript-eslint/no-explicit-any export class CustomEventImpl extends Event implements CustomEvent { - #detail: T; + readonly #detail: T; constructor(type: string, eventInitDict: CustomEventInit = {}) { super(type, eventInitDict); diff --git a/cli/js/web/decode_utf8.ts b/cli/js/web/decode_utf8.ts index c1f879b549..d82634efee 100644 --- a/cli/js/web/decode_utf8.ts +++ b/cli/js/web/decode_utf8.ts @@ -1,3 +1,5 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + // This module is based on Bjoern Hoehrmann's DFA UTF-8 decoder. // See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. // diff --git a/cli/js/web/dom_exception.ts b/cli/js/web/dom_exception.ts index e2c77d41ca..5e7d5ee6f6 100644 --- a/cli/js/web/dom_exception.ts +++ b/cli/js/web/dom_exception.ts @@ -1,7 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. export class DOMExceptionImpl extends Error implements DOMException { - #name: string; + readonly #name: string; constructor(message = "", name = "Error") { super(message); diff --git a/cli/js/web/dom_file.ts b/cli/js/web/dom_file.ts index 792d96dd17..3d65e57688 100644 --- a/cli/js/web/dom_file.ts +++ b/cli/js/web/dom_file.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import * as blob from "./blob.ts"; export class DomFileImpl extends blob.DenoBlob implements File { diff --git a/cli/js/web/dom_iterable.ts b/cli/js/web/dom_iterable.ts index fcbca307fc..271b2f6553 100644 --- a/cli/js/web/dom_iterable.ts +++ b/cli/js/web/dom_iterable.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { requiredArguments } from "./util.ts"; import { exposeForTest } from "../internals.ts"; diff --git a/cli/js/web/error_event.ts b/cli/js/web/error_event.ts index fbdd19fb52..8e7853875f 100644 --- a/cli/js/web/error_event.ts +++ b/cli/js/web/error_event.ts @@ -4,12 +4,12 @@ import { EventImpl as Event } from "./event.ts"; import { defineEnumerableProps } from "./util.ts"; export class ErrorEventImpl extends Event implements ErrorEvent { - #message: string; - #filename: string; - #lineno: number; - #colno: number; + readonly #message: string; + readonly #filename: string; + readonly #lineno: number; + readonly #colno: number; // eslint-disable-next-line @typescript-eslint/no-explicit-any - #error: any; + readonly #error: any; get message(): string { return this.#message; diff --git a/cli/js/web/fetch.ts b/cli/js/web/fetch.ts index 0c419178ab..156c218a49 100644 --- a/cli/js/web/fetch.ts +++ b/cli/js/web/fetch.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { notImplemented } from "../util.ts"; import { isTypedArray } from "./util.ts"; import * as domTypes from "./dom_types.d.ts"; @@ -55,7 +56,6 @@ export class Response extends Body.Body implements domTypes.Response { if (!type) { type = "default"; } else { - type = type; if (type == "error") { // spec: https://fetch.spec.whatwg.org/#concept-network-error status = 0; @@ -144,12 +144,11 @@ export class Response extends Body.Body implements domTypes.Response { resBody = tees[1]; } - const cloned = new Response(resBody, { + return new Response(resBody, { status: this.status, statusText: this.statusText, headers: new Headers(headersList), }); - return cloned; } static redirect(url: URL | string, status: number): domTypes.Response { @@ -260,7 +259,7 @@ export async function fetch( } let responseBody; - let responseInit: ResponseInit = {}; + let responseInit: domTypes.ResponseInit = {}; while (remRedirectCount) { const fetchResponse = await sendFetchReq(url, method, headers, body); diff --git a/cli/js/web/fetch/multipart.ts b/cli/js/web/fetch/multipart.ts index 654d4a0ea9..a632d86002 100644 --- a/cli/js/web/fetch/multipart.ts +++ b/cli/js/web/fetch/multipart.ts @@ -19,12 +19,9 @@ interface MultipartHeaders { export class MultipartBuilder { readonly boundary: string; - readonly formData: FormData; - readonly writer: Buffer; - constructor(formData: FormData, boundary?: string) { + readonly writer = new Buffer(); + constructor(readonly formData: FormData, boundary?: string) { this.boundary = boundary ?? this.#createBoundary(); - this.formData = formData; - this.writer = new Buffer(); } getContentType(): string { diff --git a/cli/js/web/form_data.ts b/cli/js/web/form_data.ts index 155f40771a..2566943f0b 100644 --- a/cli/js/web/form_data.ts +++ b/cli/js/web/form_data.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import * as blob from "./blob.ts"; import * as domFile from "./dom_file.ts"; import { DomIterableMixin } from "./dom_iterable.ts"; @@ -96,10 +97,13 @@ class FormDataBase { if (value instanceof domFile.DomFileImpl) { this[dataSymbol][i][1] = value; } else if (value instanceof blob.DenoBlob) { - const dfile = new domFile.DomFileImpl([value], filename || "blob", { - type: value.type, - }); - this[dataSymbol][i][1] = dfile; + this[dataSymbol][i][1] = new domFile.DomFileImpl( + [value], + filename || "blob", + { + type: value.type, + } + ); } else { this[dataSymbol][i][1] = String(value); } diff --git a/cli/js/web/headers.ts b/cli/js/web/headers.ts index 9e0a70f0d4..5fd6abc44f 100644 --- a/cli/js/web/headers.ts +++ b/cli/js/web/headers.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { DomIterableMixin } from "./dom_iterable.ts"; import { requiredArguments } from "./util.ts"; import { customInspect } from "./console.ts"; diff --git a/cli/js/web/performance.ts b/cli/js/web/performance.ts index 7077b1edb1..67f8f1b6cc 100644 --- a/cli/js/web/performance.ts +++ b/cli/js/web/performance.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { now as opNow } from "../ops/timers.ts"; export class Performance { diff --git a/cli/js/web/promise.ts b/cli/js/web/promise.ts index b00c0786fe..a24e8ed51d 100644 --- a/cli/js/web/promise.ts +++ b/cli/js/web/promise.ts @@ -1,7 +1,9 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + export enum PromiseState { - Pending = 0, - Fulfilled = 1, - Rejected = 2, + Pending, + Fulfilled, + Rejected, } export type PromiseDetails = [PromiseState, T | undefined]; diff --git a/cli/js/web/request.ts b/cli/js/web/request.ts index 286aaff56e..a9dcce2de4 100644 --- a/cli/js/web/request.ts +++ b/cli/js/web/request.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import * as body from "./body.ts"; import * as domTypes from "./dom_types.d.ts"; import { ReadableStreamImpl } from "./streams/readable_stream.ts"; @@ -128,12 +129,11 @@ export class Request extends body.Body implements domTypes.Request { body2 = tees[1]; } - const cloned = new Request(this.url, { + return new Request(this.url, { body: body2, method: this.method, headers: new Headers(headersList), credentials: this.credentials, }); - return cloned; } } diff --git a/cli/js/web/streams/internals.ts b/cli/js/web/streams/internals.ts index d0d35a1c37..3fbfb77358 100644 --- a/cli/js/web/streams/internals.ts +++ b/cli/js/web/streams/internals.ts @@ -5,7 +5,6 @@ // // There are some parts that are not fully implemented, and there are some // comments which point to steps of the specification that are not implemented. -// /* eslint-disable @typescript-eslint/no-explicit-any,require-await */ import { ReadableByteStreamControllerImpl } from "./readable_byte_stream_controller.ts"; @@ -62,7 +61,7 @@ export interface ReadableStreamGenericReader export interface ReadableStreamAsyncIterator extends AsyncIterator { [sym.asyncIteratorReader]: ReadableStreamDefaultReaderImpl; [sym.preventCancel]: boolean; - return(value?: any | PromiseLike): Promise>; + return(value?: any | PromiseLike): Promise>; } export function acquireReadableStreamDefaultReader( @@ -97,6 +96,7 @@ function createAlgorithmFromUnderlyingMethod< algoArgCount: 0, ...extraArgs: any[] ): () => Promise; + function createAlgorithmFromUnderlyingMethod< O extends UnderlyingByteSource | UnderlyingSource | Transformer, P extends keyof O @@ -317,79 +317,72 @@ function isFiniteNonNegativeNumber(v: unknown): v is number { export function isReadableByteStreamController( x: unknown ): x is ReadableByteStreamControllerImpl { - return typeof x !== "object" || + return !( + typeof x !== "object" || x === null || !(sym.controlledReadableByteStream in x) - ? false - : true; + ); } export function isReadableStream(x: unknown): x is ReadableStreamImpl { - return typeof x !== "object" || + return !( + typeof x !== "object" || x === null || !(sym.readableStreamController in x) - ? false - : true; + ); } export function isReadableStreamAsyncIterator( x: unknown -): x is ReadableStreamAsyncIterator { +): x is ReadableStreamAsyncIterator { if (typeof x !== "object" || x === null) { return false; } - if (!(sym.asyncIteratorReader in x)) { - return false; - } - return true; + return sym.asyncIteratorReader in x; } export function isReadableStreamDefaultController( x: unknown ): x is ReadableStreamDefaultControllerImpl { - return typeof x !== "object" || + return !( + typeof x !== "object" || x === null || !(sym.controlledReadableStream in x) - ? false - : true; + ); } export function isReadableStreamDefaultReader( x: unknown ): x is ReadableStreamDefaultReaderImpl { - return typeof x !== "object" || x === null || !(sym.readRequests in x) - ? false - : true; + return !(typeof x !== "object" || x === null || !(sym.readRequests in x)); } export function isReadableStreamLocked(stream: ReadableStreamImpl): boolean { assert(isReadableStream(stream)); - return stream[sym.reader] ? true : false; + return !!stream[sym.reader]; } export function isReadableStreamDisturbed(stream: ReadableStream): boolean { assert(isReadableStream(stream)); - return stream[sym.disturbed] ? true : false; + return !!stream[sym.disturbed]; } -export function isTransformStream( - x: unknown -): x is TransformStreamImpl { - return typeof x !== "object" || +export function isTransformStream(x: unknown): x is TransformStreamImpl { + return !( + typeof x !== "object" || x === null || !(sym.transformStreamController in x) - ? false - : true; + ); } export function isTransformStreamDefaultController( x: unknown -): x is TransformStreamDefaultControllerImpl { - return typeof x !== "object" || +): x is TransformStreamDefaultControllerImpl { + return !( + typeof x !== "object" || x === null || !(sym.controlledTransformStream in x) - ? false - : true; + ); } export function isUnderlyingByteSource( @@ -401,37 +394,36 @@ export function isUnderlyingByteSource( } export function isWritableStream(x: unknown): x is WritableStreamImpl { - return typeof x !== "object" || + return !( + typeof x !== "object" || x === null || !(sym.writableStreamController in x) - ? false - : true; + ); } export function isWritableStreamDefaultController( x: unknown ): x is WritableStreamDefaultControllerImpl { - return typeof x !== "object" || + return !( + typeof x !== "object" || x === null || !(sym.controlledWritableStream in x) - ? false - : true; + ); } export function isWritableStreamDefaultWriter( x: unknown ): x is WritableStreamDefaultWriterImpl { - return typeof x !== "object" || x === null || !(sym.ownerWritableStream in x) - ? false - : true; + return !( + typeof x !== "object" || + x === null || + !(sym.ownerWritableStream in x) + ); } export function isWritableStreamLocked(stream: WritableStreamImpl): boolean { assert(isWritableStream(stream)); - if (stream[sym.writer] === undefined) { - return false; - } - return true; + return stream[sym.writer] !== undefined; } export function makeSizeAlgorithmFromSizeFunction( @@ -476,10 +468,7 @@ function readableByteStreamControllerShouldCallPull( // ReadableStreamGetNumReadIntoRequests(stream) > 0, return true. const desiredSize = readableByteStreamControllerGetDesiredSize(controller); assert(desiredSize !== null); - if (desiredSize > 0) { - return true; - } - return false; + return desiredSize > 0; } export function readableByteStreamControllerCallPullIfNeeded( @@ -730,10 +719,7 @@ export function readableStreamDefaultControllerCanCloseOrEnqueue( controller: ReadableStreamDefaultControllerImpl ): boolean { const state = controller[sym.controlledReadableStream][sym.state]; - if (!controller[sym.closeRequested] && state === "readable") { - return true; - } - return false; + return !controller[sym.closeRequested] && state === "readable"; } export function readableStreamDefaultControllerClearAlgorithms( @@ -813,9 +799,7 @@ export function readableStreamDefaultControllerError( function readableStreamDefaultControllerHasBackpressure( controller: ReadableStreamDefaultControllerImpl ): boolean { - return readableStreamDefaultControllerShouldCallPull(controller) - ? true - : false; + return readableStreamDefaultControllerShouldCallPull(controller); } function readableStreamDefaultControllerShouldCallPull( @@ -836,10 +820,7 @@ function readableStreamDefaultControllerShouldCallPull( } const desiredSize = readableStreamDefaultControllerGetDesiredSize(controller); assert(desiredSize !== null); - if (desiredSize > 0) { - return true; - } - return false; + return desiredSize > 0; } export function readableStreamDefaultReaderRead( @@ -914,9 +895,7 @@ export function readableStreamHasDefaultReader( stream: ReadableStreamImpl ): boolean { const reader = stream[sym.reader]; - return reader === undefined || !isReadableStreamDefaultReader(reader) - ? false - : true; + return !(reader === undefined || !isReadableStreamDefaultReader(reader)); } export function readableStreamPipeTo( @@ -1927,13 +1906,10 @@ export function writableStreamClose( export function writableStreamCloseQueuedOrInFlight( stream: WritableStreamImpl ): boolean { - if ( + return !( stream[sym.closeRequest] === undefined && stream[sym.inFlightCloseRequest] === undefined - ) { - return false; - } - return true; + ); } function writableStreamDealWithRejection( @@ -2348,13 +2324,10 @@ function writableStreamFinishInFlightWriteWithError( function writableStreamHasOperationMarkedInFlight( stream: WritableStreamImpl ): boolean { - if ( + return !( stream[sym.inFlightWriteRequest] === undefined && stream[sym.inFlightCloseRequest] === undefined - ) { - return false; - } - return true; + ); } function writableStreamMarkCloseRequestInFlight( diff --git a/cli/js/web/text_encoding.ts b/cli/js/web/text_encoding.ts index cd93d7a895..d225c69283 100644 --- a/cli/js/web/text_encoding.ts +++ b/cli/js/web/text_encoding.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + // The following code is based off of text-encoding at: // https://github.com/inexorabletash/text-encoding // @@ -151,8 +152,8 @@ interface Encoder { } class SingleByteDecoder implements Decoder { - #index: number[]; - #fatal: boolean; + readonly #index: number[]; + readonly #fatal: boolean; constructor( index: number[], @@ -422,7 +423,7 @@ function isEitherArrayBuffer(x: any): x is EitherArrayBuffer { } export class TextDecoder { - #encoding: string; + readonly #encoding: string; get encoding(): string { return this.#encoding; diff --git a/cli/js/web/timers.ts b/cli/js/web/timers.ts index 74347ee7c3..e8eacb402e 100644 --- a/cli/js/web/timers.ts +++ b/cli/js/web/timers.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { assert } from "../util.ts"; import { startGlobalTimer, stopGlobalTimer } from "../ops/timers.ts"; import { RBTree } from "../rbtree.ts"; diff --git a/cli/js/web/url.ts b/cli/js/web/url.ts index 60690d46a7..b12f6da75d 100644 --- a/cli/js/web/url.ts +++ b/cli/js/web/url.ts @@ -24,7 +24,7 @@ const searchParamsMethods: Array = [ const specialSchemes = ["ftp", "file", "http", "https", "ws", "wss"]; // https://url.spec.whatwg.org/#special-scheme -const schemePorts: { [key: string]: string } = { +const schemePorts: Record = { ftp: "21", file: "", http: "80", @@ -179,8 +179,8 @@ function resolvePathFromBase( let driveLetterPrefix = ""; if (build.os == "windows" && isFilePath) { - let driveLetter = ""; - let baseDriveLetter = ""; + let driveLetter: string; + let baseDriveLetter: string; [driveLetter, normalizedPath] = takePattern( normalizedPath, /^(\/[A-Za-z]:)(?=\/)/ @@ -214,7 +214,8 @@ function resolvePathFromBase( function isValidPort(value: string): boolean { // https://url.spec.whatwg.org/#port-state - if (value === "") true; + if (value === "") return true; + const port = Number(value); return Number.isInteger(port) && port >= 0 && port <= MAX_PORT; } @@ -409,7 +410,7 @@ export class URLImpl implements URL { let baseParts: URLParts | undefined; if (base) { baseParts = typeof base === "string" ? parse(base) : parts.get(base); - if (baseParts == undefined) { + if (baseParts === undefined) { throw new TypeError("Invalid base URL."); } } diff --git a/cli/js/web/url_search_params.ts b/cli/js/web/url_search_params.ts index 2abac3cd04..b4d199fbc9 100644 --- a/cli/js/web/url_search_params.ts +++ b/cli/js/web/url_search_params.ts @@ -6,7 +6,7 @@ import { isIterable, requiredArguments } from "./util.ts"; export const urls = new WeakMap(); export class URLSearchParamsImpl implements URLSearchParams { - #params: Array<[string, string]> = []; + readonly #params: Array<[string, string]> = []; constructor(init: string | string[][] | Record = "") { if (typeof init === "string") { diff --git a/cli/js/web/workers.ts b/cli/js/web/workers.ts index 1e0762932e..cc40f104c7 100644 --- a/cli/js/web/workers.ts +++ b/cli/js/web/workers.ts @@ -81,7 +81,7 @@ export interface WorkerOptions { export class WorkerImpl extends EventTarget implements Worker { readonly #id: number; - #name: string; + readonly #name: string; #terminated = false; public onerror?: (e: ErrorEvent) => void; diff --git a/cli/js/write_file.ts b/cli/js/write_file.ts index 3106c48ef9..6b64bc09d6 100644 --- a/cli/js/write_file.ts +++ b/cli/js/write_file.ts @@ -1,4 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { stat, statSync } from "./ops/fs/stat.ts"; import { open, openSync } from "./files.ts"; import { chmod, chmodSync } from "./ops/fs/chmod.ts"; diff --git a/cli/js/write_text_file.ts b/cli/js/write_text_file.ts index 4f111edb4b..615813460b 100644 --- a/cli/js/write_text_file.ts +++ b/cli/js/write_text_file.ts @@ -1,10 +1,12 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. + import { open, openSync } from "./files.ts"; import { writeAll, writeAllSync } from "./buffer.ts"; export function writeTextFileSync(path: string | URL, data: string): void { const file = openSync(path, { write: true, create: true, truncate: true }); - const enc = new TextEncoder(); - const contents = enc.encode(data); + const encoder = new TextEncoder(); + const contents = encoder.encode(data); writeAllSync(file, contents); file.close(); } @@ -14,8 +16,8 @@ export async function writeTextFile( data: string ): Promise { const file = await open(path, { write: true, create: true, truncate: true }); - const enc = new TextEncoder(); - const contents = enc.encode(data); + const encoder = new TextEncoder(); + const contents = encoder.encode(data); await writeAll(file, contents); file.close(); }