0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-02-08 07:16:56 -05:00

clean up code in cli/js (#6611)

This commit is contained in:
Stanislav 2020-07-07 04:45:39 +03:00 committed by GitHub
parent ab4c574f52
commit 158ae0bfe9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
89 changed files with 395 additions and 354 deletions

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// TODO(ry) Combine this implementation with //deno_typescript/compiler_main.js // TODO(ry) Combine this implementation with //deno_typescript/compiler_main.js
// This module is the entry point for "compiler" isolate, ie. the one // This module is the entry point for "compiler" isolate, ie. the one
@ -286,8 +287,7 @@ class SourceFile {
): string | undefined { ): string | undefined {
const containingCache = RESOLVED_SPECIFIER_CACHE.get(containingFile); const containingCache = RESOLVED_SPECIFIER_CACHE.get(containingFile);
if (containingCache) { if (containingCache) {
const resolvedUrl = containingCache.get(moduleSpecifier); return containingCache.get(moduleSpecifier);
return resolvedUrl;
} }
return undefined; return undefined;
} }
@ -315,8 +315,8 @@ function getAssetInternal(filename: string): SourceFile {
class Host implements ts.CompilerHost { class Host implements ts.CompilerHost {
protected _options = DEFAULT_COMPILE_OPTIONS; protected _options = DEFAULT_COMPILE_OPTIONS;
#target: CompilerHostTarget; readonly #target: CompilerHostTarget;
#writeFile: WriteFileCallback; readonly #writeFile: WriteFileCallback;
/* Deno specific APIs */ /* Deno specific APIs */
constructor({ constructor({
@ -519,7 +519,7 @@ class Host implements ts.CompilerHost {
} }
class IncrementalCompileHost extends Host { class IncrementalCompileHost extends Host {
#buildInfo: undefined | string = undefined; readonly #buildInfo?: string;
constructor(options: IncrementalCompilerHostOptions) { constructor(options: IncrementalCompilerHostOptions) {
super(options); super(options);
@ -1123,9 +1123,7 @@ function buildBundle(
target === ts.ScriptTarget.ES3 || target === ts.ScriptTarget.ES3 ||
target === ts.ScriptTarget.ES5 || target === ts.ScriptTarget.ES5 ||
target === ts.ScriptTarget.ES2015 || target === ts.ScriptTarget.ES2015 ||
target === ts.ScriptTarget.ES2016 target === ts.ScriptTarget.ES2016;
? true
: false;
return `${ return `${
es5Bundle ? SYSTEM_LOADER_ES5 : SYSTEM_LOADER es5Bundle ? SYSTEM_LOADER_ES5 : SYSTEM_LOADER
}\n${data}\n${instantiate}`; }\n${data}\n${instantiate}`;

View file

@ -52,8 +52,8 @@ export async function compile(
const emitMap: Record<string, string> = {}; const emitMap: Record<string, string> = {};
for (const [key, emmitedSource] of Object.entries(result.emitMap)) { for (const [key, emittedSource] of Object.entries(result.emitMap)) {
emitMap[key] = emmitedSource.contents; emitMap[key] = emittedSource.contents;
} }
return [maybeDiagnostics, emitMap]; return [maybeDiagnostics, emitMap];

View file

@ -1,6 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Public deno module. // This module exports stable Deno APIs.
export { export {
Buffer, Buffer,
readAll, readAll,

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // 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 // 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 // style license available here: https://github.com/v8/v8/blob/24886f2d1c565287d33d71e4109a53bf0b54b75c/LICENSE.v8
import * as colors from "./colors.ts"; import * as colors from "./colors.ts";
@ -94,10 +95,10 @@ function getMethodCall(callSite: CallSite): string {
return result; return result;
} }
function getFileLocation(callSite: CallSite, isInternal = false): string { function getFileLocation(callSite: CallSite, internal = false): string {
const cyan = isInternal ? colors.gray : colors.cyan; const cyan = internal ? colors.gray : colors.cyan;
const yellow = isInternal ? colors.gray : colors.yellow; const yellow = internal ? colors.gray : colors.yellow;
const black = isInternal ? colors.gray : (s: string): string => s; const black = internal ? colors.gray : (s: string): string => s;
if (callSite.isNative()) { if (callSite.isNative()) {
return cyan("native"); return cyan("native");
} }
@ -130,9 +131,9 @@ function getFileLocation(callSite: CallSite, isInternal = false): string {
return result; return result;
} }
function callSiteToString(callSite: CallSite, isInternal = false): string { function callSiteToString(callSite: CallSite, internal = false): string {
const cyan = isInternal ? colors.gray : colors.cyan; const cyan = internal ? colors.gray : colors.cyan;
const black = isInternal ? colors.gray : (s: string): string => s; const black = internal ? colors.gray : (s: string): string => s;
let result = ""; let result = "";
const functionName = callSite.getFunctionName(); const functionName = callSite.getFunctionName();
@ -164,13 +165,11 @@ function callSiteToString(callSite: CallSite, isInternal = false): string {
} else if (functionName) { } else if (functionName) {
result += colors.bold(colors.italic(black(functionName))); result += colors.bold(colors.italic(black(functionName)));
} else { } else {
result += getFileLocation(callSite, isInternal); result += getFileLocation(callSite, internal);
return result; return result;
} }
result += ` ${black("(")}${getFileLocation(callSite, isInternal)}${black( result += ` ${black("(")}${getFileLocation(callSite, internal)}${black(")")}`;
")"
)}`;
return result; return result;
} }

View file

@ -26,7 +26,11 @@ export enum ErrorKind {
Busy = 23, 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) { switch (kind) {
case ErrorKind.TypeError: case ErrorKind.TypeError:
return TypeError; return TypeError;
@ -79,102 +83,119 @@ class NotFound extends Error {
this.name = "NotFound"; this.name = "NotFound";
} }
} }
class PermissionDenied extends Error { class PermissionDenied extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "PermissionDenied"; this.name = "PermissionDenied";
} }
} }
class ConnectionRefused extends Error { class ConnectionRefused extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "ConnectionRefused"; this.name = "ConnectionRefused";
} }
} }
class ConnectionReset extends Error { class ConnectionReset extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "ConnectionReset"; this.name = "ConnectionReset";
} }
} }
class ConnectionAborted extends Error { class ConnectionAborted extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "ConnectionAborted"; this.name = "ConnectionAborted";
} }
} }
class NotConnected extends Error { class NotConnected extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "NotConnected"; this.name = "NotConnected";
} }
} }
class AddrInUse extends Error { class AddrInUse extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "AddrInUse"; this.name = "AddrInUse";
} }
} }
class AddrNotAvailable extends Error { class AddrNotAvailable extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "AddrNotAvailable"; this.name = "AddrNotAvailable";
} }
} }
class BrokenPipe extends Error { class BrokenPipe extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "BrokenPipe"; this.name = "BrokenPipe";
} }
} }
class AlreadyExists extends Error { class AlreadyExists extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "AlreadyExists"; this.name = "AlreadyExists";
} }
} }
class InvalidData extends Error { class InvalidData extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "InvalidData"; this.name = "InvalidData";
} }
} }
class TimedOut extends Error { class TimedOut extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "TimedOut"; this.name = "TimedOut";
} }
} }
class Interrupted extends Error { class Interrupted extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "Interrupted"; this.name = "Interrupted";
} }
} }
class WriteZero extends Error { class WriteZero extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "WriteZero"; this.name = "WriteZero";
} }
} }
class UnexpectedEof extends Error { class UnexpectedEof extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "UnexpectedEof"; this.name = "UnexpectedEof";
} }
} }
class BadResource extends Error { class BadResource extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "BadResource"; this.name = "BadResource";
} }
} }
class Http extends Error { class Http extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
this.name = "Http"; this.name = "Http";
} }
} }
class Busy extends Error { class Busy extends Error {
constructor(msg: string) { constructor(msg: string) {
super(msg); super(msg);
@ -183,22 +204,22 @@ class Busy extends Error {
} }
export const errors = { export const errors = {
NotFound: NotFound, NotFound,
PermissionDenied: PermissionDenied, PermissionDenied,
ConnectionRefused: ConnectionRefused, ConnectionRefused,
ConnectionReset: ConnectionReset, ConnectionReset,
ConnectionAborted: ConnectionAborted, ConnectionAborted,
NotConnected: NotConnected, NotConnected,
AddrInUse: AddrInUse, AddrInUse,
AddrNotAvailable: AddrNotAvailable, AddrNotAvailable,
BrokenPipe: BrokenPipe, BrokenPipe,
AlreadyExists: AlreadyExists, AlreadyExists,
InvalidData: InvalidData, InvalidData,
TimedOut: TimedOut, TimedOut,
Interrupted: Interrupted, Interrupted,
WriteZero: WriteZero, WriteZero,
UnexpectedEof: UnexpectedEof, UnexpectedEof,
BadResource: BadResource, BadResource,
Http: Http, Http,
Busy: Busy, Busy,
}; };

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { import {
Reader, Reader,
Writer, Writer,
@ -97,10 +98,7 @@ export class File
} }
class Stdin implements Reader, ReaderSync, Closer { class Stdin implements Reader, ReaderSync, Closer {
readonly rid: number; readonly rid = 0;
constructor() {
this.rid = 0;
}
read(p: Uint8Array): Promise<number | null> { read(p: Uint8Array): Promise<number | null> {
return read(this.rid, p); return read(this.rid, p);
@ -116,10 +114,7 @@ class Stdin implements Reader, ReaderSync, Closer {
} }
class Stdout implements Writer, WriterSync, Closer { class Stdout implements Writer, WriterSync, Closer {
readonly rid: number; readonly rid = 1;
constructor() {
this.rid = 1;
}
write(p: Uint8Array): Promise<number> { write(p: Uint8Array): Promise<number> {
return write(this.rid, p); return write(this.rid, p);
@ -135,10 +130,7 @@ class Stdout implements Writer, WriterSync, Closer {
} }
export class Stderr implements Writer, WriterSync, Closer { export class Stderr implements Writer, WriterSync, Closer {
readonly rid: number; readonly rid = 2;
constructor() {
this.rid = 2;
}
write(p: Uint8Array): Promise<number> { write(p: Uint8Array): Promise<number> {
return write(this.rid, p); return write(this.rid, p);

View file

@ -1,9 +1,10 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
export const internalSymbol = Symbol("Deno.internal"); export const internalSymbol = Symbol("Deno.internal");
// The object where all the internal fields for testing will be living. // The object where all the internal fields for testing will be living.
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export const internalObject: { [key: string]: any } = {}; export const internalObject: Record<string, any> = {};
// Register a field to internalObject for test access, // Register a field to internalObject for test access,
// through Deno[Deno.internal][name]. // through Deno[Deno.internal][name].

View file

@ -1,7 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Interfaces 100% copied from Go. // Interfaces 100% copied from Go.
// Documentation liberally lifted from them too. // Documentation liberally lifted from them too.
// Thank you! We love Go! // Thank you! We love Go! <3
const DEFAULT_BUFFER_SIZE = 32 * 1024; const DEFAULT_BUFFER_SIZE = 32 * 1024;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { bootstrapMainRuntime } from "./runtime_main.ts"; import { bootstrapMainRuntime } from "./runtime_main.ts";
import { bootstrapWorkerRuntime } from "./runtime_worker.ts"; import { bootstrapWorkerRuntime } from "./runtime_worker.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { errors } from "./errors.ts"; import { errors } from "./errors.ts";
import { Reader, Writer, Closer } from "./io.ts"; import { Reader, Writer, Closer } from "./io.ts";
import { read, write } from "./ops/io.ts"; import { read, write } from "./ops/io.ts";
@ -109,12 +110,11 @@ export class DatagramImpl implements DatagramConn {
return [sub, remoteAddr]; return [sub, remoteAddr];
} }
async send(p: Uint8Array, addr: Addr): Promise<number> { send(p: Uint8Array, addr: Addr): Promise<number> {
const remote = { hostname: "127.0.0.1", ...addr }; const remote = { hostname: "127.0.0.1", ...addr };
const args = { ...remote, rid: this.rid }; const args = { ...remote, rid: this.rid };
const byteLength = await netOps.send(args as netOps.SendRequest, p); return netOps.send(args as netOps.SendRequest, p);
return byteLength;
} }
close(): void { close(): void {
@ -125,11 +125,11 @@ export class DatagramImpl implements DatagramConn {
while (true) { while (true) {
try { try {
yield await this.receive(); yield await this.receive();
} catch (error) { } catch (err) {
if (error instanceof errors.BadResource) { if (err instanceof errors.BadResource) {
break; break;
} }
throw error; throw err;
} }
} }
} }

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as netOps from "./ops/net.ts"; import * as netOps from "./ops/net.ts";
import { import {
Listener, Listener,
@ -22,6 +24,11 @@ export interface UnixListenOptions {
path: string; path: string;
} }
export interface UnixConnectOptions {
transport: "unix";
path: string;
}
export function listen( export function listen(
options: ListenOptions & { transport?: "tcp" } options: ListenOptions & { transport?: "tcp" }
): Listener; ): Listener;
@ -60,13 +67,6 @@ export function listenDatagram(
return new DatagramImpl(res.rid, res.localAddr); return new DatagramImpl(res.rid, res.localAddr);
} }
export interface UnixConnectOptions {
transport: "unix";
path: string;
}
export async function connect(options: UnixConnectOptions): Promise<Conn>;
export async function connect(options: ConnectOptions): Promise<Conn>;
export async function connect( export async function connect(
options: ConnectOptions | UnixConnectOptions options: ConnectOptions | UnixConnectOptions
): Promise<Conn> { ): Promise<Conn> {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as util from "../util.ts"; import * as util from "../util.ts";
import { core } from "../core.ts"; import { core } from "../core.ts";
import { ErrorKind, getErrorClass } from "../errors.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. // Using an object without a prototype because `Map` was causing GC problems.
const promiseTable: { const promiseTable: Record<
[key: number]: util.Resolvable<JsonResponse>; number,
} = Object.create(null); util.Resolvable<JsonResponse>
> = Object.create(null);
let _nextPromiseId = 1; let _nextPromiseId = 1;
function nextPromiseId(): number { function nextPromiseId(): number {
@ -28,13 +30,11 @@ function nextPromiseId(): number {
} }
function decode(ui8: Uint8Array): JsonResponse { function decode(ui8: Uint8Array): JsonResponse {
const s = core.decode(ui8); return JSON.parse(core.decode(ui8));
return JSON.parse(s) as JsonResponse;
} }
function encode(args: object): Uint8Array { function encode(args: object): Uint8Array {
const s = JSON.stringify(args); return core.encode(JSON.stringify(args));
return core.encode(s);
} }
function unwrapResponse(res: JsonResponse): Ok { function unwrapResponse(res: JsonResponse): Ok {
@ -80,7 +80,7 @@ export async function sendAsync(
const promise = util.createResolvable<Ok>(); const promise = util.createResolvable<Ok>();
const argsUi8 = encode(args); const argsUi8 = encode(args);
const buf = core.dispatchByName(opName, argsUi8, ...zeroCopy); const buf = core.dispatchByName(opName, argsUi8, ...zeroCopy);
if (buf) { if (buf != null) {
// Sync result. // Sync result.
const res = decode(buf); const res = decode(buf);
promise.resolve(res); promise.resolve(res);

View file

@ -1,13 +1,15 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as util from "../util.ts"; import * as util from "../util.ts";
import { core } from "../core.ts"; import { core } from "../core.ts";
import { TextDecoder } from "../web/text_encoding.ts"; import { TextDecoder } from "../web/text_encoding.ts";
import { ErrorKind, errors, getErrorClass } from "../errors.ts"; import { ErrorKind, errors, getErrorClass } from "../errors.ts";
// Using an object without a prototype because `Map` was causing GC problems. // Using an object without a prototype because `Map` was causing GC problems.
const promiseTableMin: { const promiseTableMin: Record<
[key: number]: util.Resolvable<RecordMinimal>; number,
} = Object.create(null); util.Resolvable<RecordMinimal>
> = Object.create(null);
// Note it's important that promiseId starts at 1 instead of 0, because sync // 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 // 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 scratch32[2] = 0; // result
const promise = util.createResolvable<RecordMinimal>(); const promise = util.createResolvable<RecordMinimal>();
const buf = core.dispatchByName(opName, scratchBytes, zeroCopy); const buf = core.dispatchByName(opName, scratchBytes, zeroCopy);
if (buf) { if (buf != null) {
const record = recordFromBufMinimal(buf); const record = recordFromBufMinimal(buf);
// Sync result. // Sync result.
promise.resolve(record); promise.resolve(record);

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { DiagnosticItem } from "../diagnostics.ts"; import { DiagnosticItem } from "../diagnostics.ts";
import { sendSync } from "./dispatch_json.ts"; import { sendSync } from "./dispatch_json.ts";
@ -13,12 +14,7 @@ export interface Location {
} }
export function applySourceMap(location: Location): Location { export function applySourceMap(location: Location): Location {
const { fileName, lineNumber, columnNumber } = location; const res = sendSync("op_apply_source_map", location);
const res = sendSync("op_apply_source_map", {
fileName,
lineNumber: lineNumber,
columnNumber: columnNumber,
});
return { return {
fileName: res.fileName, fileName: res.fileName,
lineNumber: res.lineNumber, lineNumber: res.lineNumber,

View file

@ -17,10 +17,10 @@ export interface FetchResponse {
export function fetch( export function fetch(
args: FetchRequest, args: FetchRequest,
body: ArrayBufferView | undefined body?: ArrayBufferView
): Promise<FetchResponse> { ): Promise<FetchResponse> {
let zeroCopy = undefined; let zeroCopy;
if (body) { if (body != null) {
zeroCopy = new Uint8Array(body.buffer, body.byteOffset, body.byteLength); zeroCopy = new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
} }

View file

@ -1,13 +1,12 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts"; import { pathFromURL } from "../../util.ts";
export function chmodSync(path: string | URL, mode: number): void { export function chmodSync(path: string | URL, mode: number): void {
path = pathFromURL(path); sendSync("op_chmod", { path: pathFromURL(path), mode });
sendSync("op_chmod", { path, mode });
} }
export async function chmod(path: string | URL, mode: number): Promise<void> { export async function chmod(path: string | URL, mode: number): Promise<void> {
path = pathFromURL(path); await sendAsync("op_chmod", { path: pathFromURL(path), mode });
await sendAsync("op_chmod", { path, mode });
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts"; import { pathFromURL } from "../../util.ts";
@ -7,8 +8,7 @@ export function chownSync(
uid: number | null, uid: number | null,
gid: number | null gid: number | null
): void { ): void {
path = pathFromURL(path); sendSync("op_chown", { path: pathFromURL(path), uid, gid });
sendSync("op_chown", { path, uid, gid });
} }
export async function chown( export async function chown(
@ -16,6 +16,5 @@ export async function chown(
uid: number | null, uid: number | null,
gid: number | null gid: number | null
): Promise<void> { ): Promise<void> {
path = pathFromURL(path); await sendAsync("op_chown", { path: pathFromURL(path), uid, gid });
await sendAsync("op_chown", { path, uid, gid });
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts"; import { pathFromURL } from "../../util.ts";
@ -6,18 +7,18 @@ export function copyFileSync(
fromPath: string | URL, fromPath: string | URL,
toPath: string | URL toPath: string | URL
): void { ): void {
fromPath = pathFromURL(fromPath); sendSync("op_copy_file", {
toPath = pathFromURL(toPath); from: pathFromURL(fromPath),
to: pathFromURL(toPath),
sendSync("op_copy_file", { from: fromPath, to: toPath }); });
} }
export async function copyFile( export async function copyFile(
fromPath: string | URL, fromPath: string | URL,
toPath: string | URL toPath: string | URL
): Promise<void> { ): Promise<void> {
fromPath = pathFromURL(fromPath); await sendAsync("op_copy_file", {
toPath = pathFromURL(toPath); from: pathFromURL(fromPath),
to: pathFromURL(toPath),
await sendAsync("op_copy_file", { from: fromPath, to: toPath }); });
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "../dispatch_json.ts"; import { sendSync } from "../dispatch_json.ts";
export function cwd(): string { export function cwd(): string {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
export function linkSync(oldpath: string, newpath: string): void { export function linkSync(oldpath: string, newpath: string): void {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
export interface MakeTempOptions { export interface MakeTempOptions {

View file

@ -1,11 +1,21 @@
// Copyright 2018-2020 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 { 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 { function mkdirArgs(path: string, options?: MkdirOptions): MkdirArgs {
const args: MkdirArgs = { path, recursive: false }; const args: MkdirArgs = { path, recursive: false };
if (options) { if (options != null) {
if (typeof options.recursive == "boolean") { if (typeof options.recursive == "boolean") {
args.recursive = options.recursive; args.recursive = options.recursive;
} }
@ -16,11 +26,6 @@ function mkdirArgs(path: string, options?: MkdirOptions): MkdirArgs {
return args; return args;
} }
export interface MkdirOptions {
recursive?: boolean;
mode?: number;
}
export function mkdirSync(path: string, options?: MkdirOptions): void { export function mkdirSync(path: string, options?: MkdirOptions): void {
sendSync("op_mkdir", mkdirArgs(path, options)); sendSync("op_mkdir", mkdirArgs(path, options));
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts"; import { pathFromURL } from "../../util.ts";
@ -18,8 +19,7 @@ export interface OpenOptions {
export function openSync(path: string | URL, options: OpenOptions): number { export function openSync(path: string | URL, options: OpenOptions): number {
const mode: number | undefined = options?.mode; const mode: number | undefined = options?.mode;
path = pathFromURL(path); return sendSync("op_open", { path: pathFromURL(path), options, mode });
return sendSync("op_open", { path, options, mode });
} }
export function open( export function open(
@ -27,10 +27,5 @@ export function open(
options: OpenOptions options: OpenOptions
): Promise<number> { ): Promise<number> {
const mode: number | undefined = options?.mode; const mode: number | undefined = options?.mode;
path = pathFromURL(path); return sendAsync("op_open", { path: pathFromURL(path), options, mode });
return sendAsync("op_open", {
path,
options,
mode,
});
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts"; import { pathFromURL } from "../../util.ts";
@ -18,13 +19,13 @@ function res(response: ReadDirResponse): DirEntry[] {
} }
export function readDirSync(path: string | URL): Iterable<DirEntry> { export function readDirSync(path: string | URL): Iterable<DirEntry> {
path = pathFromURL(path); return res(sendSync("op_read_dir", { path: pathFromURL(path) }))[
return res(sendSync("op_read_dir", { path }))[Symbol.iterator](); Symbol.iterator
]();
} }
export function readDir(path: string | URL): AsyncIterable<DirEntry> { export function readDir(path: string | URL): AsyncIterable<DirEntry> {
path = pathFromURL(path); const array = sendAsync("op_read_dir", { path: pathFromURL(path) }).then(res);
const array = sendAsync("op_read_dir", { path }).then(res);
return { return {
async *[Symbol.asyncIterator](): AsyncIterableIterator<DirEntry> { async *[Symbol.asyncIterator](): AsyncIterableIterator<DirEntry> {
yield* await array; yield* await array;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
export function readLinkSync(path: string): string { export function readLinkSync(path: string): string {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
export function realPathSync(path: string): string { export function realPathSync(path: string): string {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts"; import { pathFromURL } from "../../util.ts";
@ -10,14 +11,18 @@ export function removeSync(
path: string | URL, path: string | URL,
options: RemoveOptions = {} options: RemoveOptions = {}
): void { ): void {
path = pathFromURL(path); sendSync("op_remove", {
sendSync("op_remove", { path, recursive: !!options.recursive }); path: pathFromURL(path),
recursive: !!options.recursive,
});
} }
export async function remove( export async function remove(
path: string | URL, path: string | URL,
options: RemoveOptions = {} options: RemoveOptions = {}
): Promise<void> { ): Promise<void> {
path = pathFromURL(path); await sendAsync("op_remove", {
await sendAsync("op_remove", { path, recursive: !!options.recursive }); path: pathFromURL(path),
recursive: !!options.recursive,
});
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
export function renameSync(oldpath: string, newpath: string): void { export function renameSync(oldpath: string, newpath: string): void {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
import { SeekMode } from "../../io.ts"; import { SeekMode } from "../../io.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
import { build } from "../../build.ts"; import { build } from "../../build.ts";
import { pathFromURL } from "../../util.ts"; import { pathFromURL } from "../../util.ts";
@ -44,7 +45,7 @@ export interface StatResponse {
// @internal // @internal
export function parseFileInfo(response: StatResponse): FileInfo { export function parseFileInfo(response: StatResponse): FileInfo {
const isUnix = build.os === "darwin" || build.os === "linux"; const unix = build.os === "darwin" || build.os === "linux";
return { return {
isFile: response.isFile, isFile: response.isFile,
isDirectory: response.isDirectory, isDirectory: response.isDirectory,
@ -54,15 +55,15 @@ export function parseFileInfo(response: StatResponse): FileInfo {
atime: response.atime != null ? new Date(response.atime) : null, atime: response.atime != null ? new Date(response.atime) : null,
birthtime: response.birthtime != null ? new Date(response.birthtime) : null, birthtime: response.birthtime != null ? new Date(response.birthtime) : null,
// Only non-null if on Unix // Only non-null if on Unix
dev: isUnix ? response.dev : null, dev: unix ? response.dev : null,
ino: isUnix ? response.ino : null, ino: unix ? response.ino : null,
mode: isUnix ? response.mode : null, mode: unix ? response.mode : null,
nlink: isUnix ? response.nlink : null, nlink: unix ? response.nlink : null,
uid: isUnix ? response.uid : null, uid: unix ? response.uid : null,
gid: isUnix ? response.gid : null, gid: unix ? response.gid : null,
rdev: isUnix ? response.rdev : null, rdev: unix ? response.rdev : null,
blksize: isUnix ? response.blksize : null, blksize: unix ? response.blksize : null,
blocks: isUnix ? response.blocks : null, blocks: unix ? response.blocks : null,
}; };
} }
@ -75,37 +76,33 @@ export async function fstat(rid: number): Promise<FileInfo> {
} }
export async function lstat(path: string | URL): Promise<FileInfo> { export async function lstat(path: string | URL): Promise<FileInfo> {
path = pathFromURL(path); const res = await sendAsync("op_stat", {
const res = (await sendAsync("op_stat", { path: pathFromURL(path),
path,
lstat: true, lstat: true,
})) as StatResponse; });
return parseFileInfo(res); return parseFileInfo(res);
} }
export function lstatSync(path: string | URL): FileInfo { export function lstatSync(path: string | URL): FileInfo {
path = pathFromURL(path);
const res = sendSync("op_stat", { const res = sendSync("op_stat", {
path, path: pathFromURL(path),
lstat: true, lstat: true,
}) as StatResponse; });
return parseFileInfo(res); return parseFileInfo(res);
} }
export async function stat(path: string | URL): Promise<FileInfo> { export async function stat(path: string | URL): Promise<FileInfo> {
path = pathFromURL(path); const res = await sendAsync("op_stat", {
const res = (await sendAsync("op_stat", { path: pathFromURL(path),
path,
lstat: false, lstat: false,
})) as StatResponse; });
return parseFileInfo(res); return parseFileInfo(res);
} }
export function statSync(path: string | URL): FileInfo { export function statSync(path: string | URL): FileInfo {
path = pathFromURL(path);
const res = sendSync("op_stat", { const res = sendSync("op_stat", {
path, path: pathFromURL(path),
lstat: false, lstat: false,
}) as StatResponse; });
return parseFileInfo(res); return parseFileInfo(res);
} }

View file

@ -1,14 +1,15 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
export type symlinkOptions = { export interface SymlinkOptions {
type: "file" | "dir"; type: "file" | "dir";
}; }
export function symlinkSync( export function symlinkSync(
oldpath: string, oldpath: string,
newpath: string, newpath: string,
options?: symlinkOptions options?: SymlinkOptions
): void { ): void {
sendSync("op_symlink", { oldpath, newpath, options }); sendSync("op_symlink", { oldpath, newpath, options });
} }
@ -16,7 +17,7 @@ export function symlinkSync(
export async function symlink( export async function symlink(
oldpath: string, oldpath: string,
newpath: string, newpath: string,
options?: symlinkOptions options?: SymlinkOptions
): Promise<void> { ): Promise<void> {
await sendAsync("op_symlink", { oldpath, newpath, options }); await sendAsync("op_symlink", { oldpath, newpath, options });
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
export function fdatasyncSync(rid: number): void { export function fdatasyncSync(rid: number): void {

View file

@ -1,12 +1,9 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
function coerceLen(len?: number): number { function coerceLen(len?: number): number {
if (!len) { if (len == null || len < 0) {
return 0;
}
if (len < 0) {
return 0; return 0;
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "../dispatch_json.ts"; import { sendSync } from "../dispatch_json.ts";
export function umask(mask?: number): number { export function umask(mask?: number): number {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "../dispatch_json.ts";
function toSecondsFromEpoch(v: number | Date): number { function toSecondsFromEpoch(v: number | Date): number {

View file

@ -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 { sendSync, sendAsync } from "./dispatch_json.ts";
import { close } from "./resources.ts"; import { close } from "./resources.ts";
@ -7,10 +8,14 @@ export interface FsEvent {
paths: string[]; paths: string[];
} }
interface FsWatcherOptions {
recursive: boolean;
}
class FsWatcher implements AsyncIterableIterator<FsEvent> { class FsWatcher implements AsyncIterableIterator<FsEvent> {
readonly rid: number; readonly rid: number;
constructor(paths: string[], options: { recursive: boolean }) { constructor(paths: string[], options: FsWatcherOptions) {
const { recursive } = options; const { recursive } = options;
this.rid = sendSync("op_fs_events_open", { recursive, paths }); this.rid = sendSync("op_fs_events_open", { recursive, paths });
} }
@ -33,7 +38,7 @@ class FsWatcher implements AsyncIterableIterator<FsEvent> {
export function watchFs( export function watchFs(
paths: string | string[], paths: string | string[],
options = { recursive: true } options: FsWatcherOptions = { recursive: true }
): AsyncIterableIterator<FsEvent> { ): AsyncIterableIterator<FsEvent> {
return new FsWatcher(Array.isArray(paths) ? paths : [paths], options); return new FsWatcher(Array.isArray(paths) ? paths : [paths], options);
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts"; import { sendSync } from "./dispatch_json.ts";
import { assert } from "../util.ts"; import { assert } from "../util.ts";

View file

@ -3,50 +3,48 @@
import { sendAsyncMinimal, sendSyncMinimal } from "./dispatch_minimal.ts"; import { sendAsyncMinimal, sendSyncMinimal } from "./dispatch_minimal.ts";
export function readSync(rid: number, buffer: Uint8Array): number | null { export function readSync(rid: number, buffer: Uint8Array): number | null {
if (buffer.length == 0) { if (buffer.length === 0) {
return 0; return 0;
} }
const nread = sendSyncMinimal("op_read", rid, buffer); const nread = sendSyncMinimal("op_read", rid, buffer);
if (nread < 0) { if (nread < 0) {
throw new Error("read error"); throw new Error("read error");
} else if (nread == 0) {
return null;
} else {
return nread;
} }
return nread === 0 ? null : nread;
} }
export async function read( export async function read(
rid: number, rid: number,
buffer: Uint8Array buffer: Uint8Array
): Promise<number | null> { ): Promise<number | null> {
if (buffer.length == 0) { if (buffer.length === 0) {
return 0; return 0;
} }
const nread = await sendAsyncMinimal("op_read", rid, buffer); const nread = await sendAsyncMinimal("op_read", rid, buffer);
if (nread < 0) { if (nread < 0) {
throw new Error("read error"); 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 { export function writeSync(rid: number, data: Uint8Array): number {
const result = sendSyncMinimal("op_write", rid, data); const result = sendSyncMinimal("op_write", rid, data);
if (result < 0) { if (result < 0) {
throw new Error("write error"); throw new Error("write error");
} else {
return result;
} }
return result;
} }
export async function write(rid: number, data: Uint8Array): Promise<number> { export async function write(rid: number, data: Uint8Array): Promise<number> {
const result = await sendAsyncMinimal("op_write", rid, data); const result = await sendAsyncMinimal("op_write", rid, data);
if (result < 0) { if (result < 0) {
throw new Error("write error"); throw new Error("write error");
} else {
return result;
} }
return result;
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "./dispatch_json.ts";
export interface NetAddr { export interface NetAddr {
@ -18,7 +19,7 @@ export enum ShutdownMode {
// See http://man7.org/linux/man-pages/man2/shutdown.2.html // See http://man7.org/linux/man-pages/man2/shutdown.2.html
// Corresponding to SHUT_RD, SHUT_WR, SHUT_RDWR // Corresponding to SHUT_RD, SHUT_WR, SHUT_RDWR
Read = 0, Read = 0,
Write, Write = 1,
ReadWrite, // unused ReadWrite, // unused
} }
@ -80,10 +81,6 @@ export type SendRequest = {
rid: number; rid: number;
} & Addr; } & Addr;
export async function send( export function send(args: SendRequest, zeroCopy: Uint8Array): Promise<number> {
args: SendRequest, return sendAsync("op_datagram_send", args, zeroCopy);
zeroCopy: Uint8Array
): Promise<number> {
const byteLength = await sendAsync("op_datagram_send", args, zeroCopy);
return byteLength;
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts"; import { sendSync } from "./dispatch_json.ts";
export function loadavg(): number[] { export function loadavg(): number[] {
@ -32,7 +33,7 @@ function deleteEnv(key: string): void {
export const env = { export const env = {
get: getEnv, get: getEnv,
toObject(): { [key: string]: string } { toObject(): Record<string, string> {
return sendSync("op_env"); return sendSync("op_env");
}, },
set: setEnv, set: setEnv,

View file

@ -1,9 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // 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 import { sendSync } from "./dispatch_json.ts";
// `PermissionState import { PermissionState } from "../permissions.ts";
export type PermissionResponse = "granted" | "denied" | "prompt";
interface PermissionRequest { interface PermissionRequest {
name: string; name: string;
@ -11,14 +9,14 @@ interface PermissionRequest {
path?: string; path?: string;
} }
export function query(desc: PermissionRequest): PermissionResponse { export function query(desc: PermissionRequest): PermissionState {
return sendSync("op_query_permission", desc).state; 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; 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; return sendSync("op_request_permission", desc).state;
} }

View file

@ -1,6 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts"; import { sendSync } from "./dispatch_json.ts";
export function openPlugin(filename: string): number { export function openPlugin(filename: string): number {
const rid = sendSync("op_open_plugin", { filename }); return sendSync("op_open_plugin", { filename });
return rid;
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "./dispatch_json.ts";
import { assert } from "../util.ts"; import { assert } from "../util.ts";

View file

@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts"; import { sendSync } from "./dispatch_json.ts";
export interface ResourceMap { export type ResourceMap = Record<number, string>;
[rid: number]: string;
}
export function resources(): ResourceMap { export function resources(): ResourceMap {
const res = sendSync("op_resources") as Array<[number, string]>; const res = sendSync("op_resources") as Array<[number, string]>;

View file

@ -1,11 +1,20 @@
// Copyright 2018-2020 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 { 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 }); return sendSync("op_signal_bind", { signo });
} }
export function pollSignal(rid: number): Promise<{ done: boolean }> { export function pollSignal(rid: number): Promise<PollSignalResponse> {
return sendAsync("op_signal_poll", { rid }); return sendAsync("op_signal_poll", { rid });
} }

View file

@ -1,6 +1,12 @@
// Copyright 2018-2020 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 { sendSync, sendAsync } from "./dispatch_json.ts";
interface NowResponse {
seconds: number;
subsecNanos: number;
}
export function stopGlobalTimer(): void { export function stopGlobalTimer(): void {
sendSync("op_global_timer_stop"); sendSync("op_global_timer_stop");
} }
@ -9,11 +15,6 @@ export async function startGlobalTimer(timeout: number): Promise<void> {
await sendAsync("op_global_timer", { timeout }); await sendAsync("op_global_timer", { timeout });
} }
interface NowResponse {
seconds: number;
subsecNanos: number;
}
export function now(): NowResponse { export function now(): NowResponse {
return sendSync("op_now"); return sendSync("op_now");
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendAsync, sendSync } from "./dispatch_json.ts"; import { sendAsync, sendSync } from "./dispatch_json.ts";
export interface ConnectTLSRequest { export interface ConnectTLSRequest {

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts"; import { sendSync } from "./dispatch_json.ts";
export function isatty(rid: number): boolean { export function isatty(rid: number): boolean {
@ -5,8 +7,5 @@ export function isatty(rid: number): boolean {
} }
export function setRaw(rid: number, mode: boolean): void { export function setRaw(rid: number, mode: boolean): void {
sendSync("op_set_raw", { sendSync("op_set_raw", { rid, mode });
rid,
mode,
});
} }

View file

@ -1,14 +1,19 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
import { sendAsync, sendSync } from "./dispatch_json.ts"; import { sendAsync, sendSync } from "./dispatch_json.ts";
interface CreateWorkerResponse {
id: number;
}
export function createWorker( export function createWorker(
specifier: string, specifier: string,
hasSourceCode: boolean, hasSourceCode: boolean,
sourceCode: string, sourceCode: string,
useDenoNamespace: boolean, useDenoNamespace: boolean,
name?: string name?: string
): { id: number } { ): CreateWorkerResponse {
return sendSync("op_create_worker", { return sendSync("op_create_worker", {
specifier, specifier,
hasSourceCode, hasSourceCode,

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as permissionsOps from "./ops/permissions.ts"; import * as permissionsOps from "./ops/permissions.ts";
export type PermissionName = export type PermissionName =

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { File } from "./files.ts"; import { File } from "./files.ts";
import { close } from "./ops/resources.ts"; import { close } from "./ops/resources.ts";
import { Closer, Reader, Writer } from "./io.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 { export interface RunOptions {
cmd: string[]; cmd: string[];
cwd?: string; cwd?: string;
env?: { [key: string]: string }; env?: Record<string, string>;
stdout?: "inherit" | "piped" | "null" | number; stdout?: "inherit" | "piped" | "null" | number;
stderr?: "inherit" | "piped" | "null" | number; stderr?: "inherit" | "piped" | "null" | number;
stdin?: "inherit" | "piped" | "null" | number; stdin?: "inherit" | "piped" | "null" | number;
@ -100,16 +101,8 @@ export class Process<T extends RunOptions = RunOptions> {
} }
export type ProcessStatus = export type ProcessStatus =
| { | { success: true; code: 0; signal?: undefined }
success: true; | { success: false; code: number; signal?: number };
code: 0;
signal?: undefined;
}
| {
success: false;
code: number;
signal?: number;
};
function isRid(arg: unknown): arg is number { function isRid(arg: unknown): arg is number {
return !isNaN(arg as number); return !isNaN(arg as number);

View file

@ -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. // Derived from https://github.com/vadimg/js_bintrees. MIT Licensed.
import { assert } from "./util.ts"; import { assert } from "./util.ts";
@ -27,7 +29,7 @@ class RBNode<T> {
} }
export class RBTree<T> { export class RBTree<T> {
#comparator: (a: T, b: T) => number; readonly #comparator: (a: T, b: T) => number;
#root: RBNode<T> | null; #root: RBNode<T> | null;
constructor(comparator: (a: T, b: T) => number) { constructor(comparator: (a: T, b: T) => number) {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { open, openSync } from "./files.ts"; import { open, openSync } from "./files.ts";
import { readAll, readAllSync } from "./buffer.ts"; import { readAll, readAllSync } from "./buffer.ts";

View file

@ -1,18 +1,20 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { open, openSync } from "./files.ts"; import { open, openSync } from "./files.ts";
import { readAll, readAllSync } from "./buffer.ts"; import { readAll, readAllSync } from "./buffer.ts";
export function readTextFileSync(path: string | URL): string { export function readTextFileSync(path: string | URL): string {
const decoder = new TextDecoder();
const file = openSync(path); const file = openSync(path);
const content = readAllSync(file); const contents = readAllSync(file);
file.close(); file.close();
return decoder.decode(content); const decoder = new TextDecoder();
return decoder.decode(contents);
} }
export async function readTextFile(path: string | URL): Promise<string> { export async function readTextFile(path: string | URL): Promise<string> {
const decoder = new TextDecoder();
const file = await open(path); const file = await open(path);
const content = await readAll(file); const contents = await readAll(file);
file.close(); file.close();
return decoder.decode(content); const decoder = new TextDecoder();
return decoder.decode(contents);
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { exit } from "./ops/os.ts"; import { exit } from "./ops/os.ts";
import { core } from "./core.ts"; import { core } from "./core.ts";
import { version } from "./version.ts"; import { version } from "./version.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { core } from "./core.ts"; import { core } from "./core.ts";
import * as dispatchMinimal from "./ops/dispatch_minimal.ts"; import * as dispatchMinimal from "./ops/dispatch_minimal.ts";
import * as dispatchJson from "./ops/dispatch_json.ts"; import * as dispatchJson from "./ops/dispatch_json.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { bindSignal, pollSignal, unbindSignal } from "./ops/signal.ts"; import { bindSignal, pollSignal, unbindSignal } from "./ops/signal.ts";
import { build } from "./build.ts"; import { build } from "./build.ts";
@ -129,7 +130,7 @@ export class SignalStream
implements AsyncIterableIterator<void>, PromiseLike<void> { implements AsyncIterableIterator<void>, PromiseLike<void> {
#disposed = false; #disposed = false;
#pollingPromise: Promise<boolean> = Promise.resolve(false); #pollingPromise: Promise<boolean> = Promise.resolve(false);
#rid: number; readonly #rid: number;
constructor(signo: number) { constructor(signo: number) {
this.#rid = bindSignal(signo).rid; this.#rid = bindSignal(signo).rid;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { gray, green, italic, red, yellow } from "./colors.ts"; import { gray, green, italic, red, yellow } from "./colors.ts";
import { exit } from "./ops/os.ts"; import { exit } from "./ops/os.ts";
import { Console, stringifyArgs } from "./web/console.ts"; import { Console, stringifyArgs } from "./web/console.ts";
@ -11,9 +12,9 @@ import { assert } from "./util.ts";
const disabledConsole = new Console((): void => {}); const disabledConsole = new Console((): void => {});
function delay(n: number): Promise<void> { function delay(ms: number): Promise<void> {
return new Promise((resolve: () => void, _) => { return new Promise((resolve: () => void) => {
setTimeout(resolve, n); setTimeout(resolve, ms);
}); });
} }
@ -241,7 +242,7 @@ class TestRunner {
passed: 0, passed: 0,
failed: 0, failed: 0,
}; };
private usedOnly: boolean; readonly #usedOnly: boolean;
constructor( constructor(
tests: TestDefinition[], tests: TestDefinition[],
@ -249,8 +250,8 @@ class TestRunner {
public failFast: boolean public failFast: boolean
) { ) {
const onlyTests = tests.filter(({ only }) => only); const onlyTests = tests.filter(({ only }) => only);
this.usedOnly = onlyTests.length > 0; this.#usedOnly = onlyTests.length > 0;
const unfilteredTests = this.usedOnly ? onlyTests : tests; const unfilteredTests = this.#usedOnly ? onlyTests : tests;
this.testsToRun = unfilteredTests.filter(filterFn); this.testsToRun = unfilteredTests.filter(filterFn);
this.stats.filtered = unfilteredTests.length - this.testsToRun.length; this.stats.filtered = unfilteredTests.length - this.testsToRun.length;
} }
@ -292,7 +293,7 @@ class TestRunner {
const duration = +new Date() - suiteStart; const duration = +new Date() - suiteStart;
yield { yield {
end: { ...this.stats, usedOnly: this.usedOnly, duration, results }, end: { ...this.stats, usedOnly: this.#usedOnly, duration, results },
}; };
} }
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as tlsOps from "./ops/tls.ts"; import * as tlsOps from "./ops/tls.ts";
import { Listener, Conn, ConnImpl, ListenerImpl } from "./net.ts"; import { Listener, Conn, ConnImpl, ListenerImpl } from "./net.ts";
@ -65,7 +66,7 @@ interface StartTlsOptions {
export async function startTls( export async function startTls(
conn: Conn, conn: Conn,
{ hostname = "127.0.0.1", certFile = undefined }: StartTlsOptions = {} { hostname = "127.0.0.1", certFile }: StartTlsOptions = {}
): Promise<Conn> { ): Promise<Conn> {
const res = await tlsOps.startTls({ const res = await tlsOps.startTls({
rid: conn.rid, rid: conn.rid,

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { build } from "./build.ts"; import { build } from "./build.ts";
import { exposeForTest } from "./internals.ts"; import { exposeForTest } from "./internals.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
interface Version { interface Version {
deno: string; deno: string;
v8: string; v8: string;

View file

@ -2,10 +2,10 @@
This directory facilities Web APIs that are available in Deno. 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. 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 ## Implemented Web APIs

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { AbortSignalImpl, signalAbort } from "./abort_signal.ts"; import { AbortSignalImpl, signalAbort } from "./abort_signal.ts";
export class AbortControllerImpl implements AbortController { export class AbortControllerImpl implements AbortController {

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Forked from https://github.com/beatgammit/base64-js // Forked from https://github.com/beatgammit/base64-js
// Copyright (c) 2014 Jameson Little. MIT License. // Copyright (c) 2014 Jameson Little. MIT License.

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { TextDecoder, TextEncoder } from "./text_encoding.ts"; import { TextDecoder, TextEncoder } from "./text_encoding.ts";
import { build } from "../build.ts"; import { build } from "../build.ts";
import { ReadableStreamImpl } from "./streams/readable_stream.ts"; import { ReadableStreamImpl } from "./streams/readable_stream.ts";

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as blob from "./blob.ts"; import * as blob from "./blob.ts";
import * as encoding from "./text_encoding.ts"; import * as encoding from "./text_encoding.ts";
import * as domTypes from "./dom_types.d.ts"; import * as domTypes from "./dom_types.d.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { isInvalidDate, isTypedArray, TypedArray } from "./util.ts"; import { isInvalidDate, isTypedArray, TypedArray } from "./util.ts";
import { cliTable } from "./console_table.ts"; import { cliTable } from "./console_table.ts";
import { exposeForTest } from "../internals.ts"; import { exposeForTest } from "../internals.ts";
@ -381,7 +382,7 @@ function createTypedArrayString(
displayName: `${typedArrayName}(${valueLength})`, displayName: `${typedArrayName}(${valueLength})`,
delims: ["[", "]"], delims: ["[", "]"],
entryHandler: (entry, ctx, level, maxLevel): string => { entryHandler: (entry, ctx, level, maxLevel): string => {
const [_, val] = entry; const val = entry[1];
return stringifyWithQuotes(val, ctx, level + 1, maxLevel); return stringifyWithQuotes(val, ctx, level + 1, maxLevel);
}, },
group: true, group: true,
@ -400,7 +401,7 @@ function createSetString(
displayName: "Set", displayName: "Set",
delims: ["{", "}"], delims: ["{", "}"],
entryHandler: (entry, ctx, level, maxLevel): string => { entryHandler: (entry, ctx, level, maxLevel): string => {
const [_, val] = entry; const val = entry[1];
return stringifyWithQuotes(val, ctx, level + 1, maxLevel); return stringifyWithQuotes(val, ctx, level + 1, maxLevel);
}, },
group: false, group: false,
@ -508,7 +509,7 @@ function createRawObjectString(
} }
ctx.add(value); ctx.add(value);
let baseString = ""; let baseString: string;
let shouldShowDisplayName = false; let shouldShowDisplayName = false;
let displayName = (value as { [Symbol.toStringTag]: string })[ let displayName = (value as { [Symbol.toStringTag]: string })[
@ -724,7 +725,7 @@ const timerMap = new Map<string, number>();
const isConsoleInstance = Symbol("isConsoleInstance"); const isConsoleInstance = Symbol("isConsoleInstance");
export class Console { export class Console {
#printFunc: PrintFunc; readonly #printFunc: PrintFunc;
indentLevel: number; indentLevel: number;
[isConsoleInstance] = false; [isConsoleInstance] = false;

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Copyright Joyent, Inc. and other Node contributors. MIT license. // Copyright Joyent, Inc. and other Node contributors. MIT license.
// Forked from Node's lib/internal/cli_table.js // Forked from Node's lib/internal/cli_table.js

View file

@ -1,10 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { EventImpl as Event } from "./event.ts"; import { EventImpl as Event } from "./event.ts";
import { requiredArguments } from "./util.ts"; import { requiredArguments } from "./util.ts";
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export class CustomEventImpl<T = any> extends Event implements CustomEvent { export class CustomEventImpl<T = any> extends Event implements CustomEvent {
#detail: T; readonly #detail: T;
constructor(type: string, eventInitDict: CustomEventInit<T> = {}) { constructor(type: string, eventInitDict: CustomEventInit<T> = {}) {
super(type, eventInitDict); super(type, eventInitDict);

View file

@ -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. // This module is based on Bjoern Hoehrmann's DFA UTF-8 decoder.
// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. // See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
// //

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
export class DOMExceptionImpl extends Error implements DOMException { export class DOMExceptionImpl extends Error implements DOMException {
#name: string; readonly #name: string;
constructor(message = "", name = "Error") { constructor(message = "", name = "Error") {
super(message); super(message);

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as blob from "./blob.ts"; import * as blob from "./blob.ts";
export class DomFileImpl extends blob.DenoBlob implements File { export class DomFileImpl extends blob.DenoBlob implements File {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { requiredArguments } from "./util.ts"; import { requiredArguments } from "./util.ts";
import { exposeForTest } from "../internals.ts"; import { exposeForTest } from "../internals.ts";

View file

@ -4,12 +4,12 @@ import { EventImpl as Event } from "./event.ts";
import { defineEnumerableProps } from "./util.ts"; import { defineEnumerableProps } from "./util.ts";
export class ErrorEventImpl extends Event implements ErrorEvent { export class ErrorEventImpl extends Event implements ErrorEvent {
#message: string; readonly #message: string;
#filename: string; readonly #filename: string;
#lineno: number; readonly #lineno: number;
#colno: number; readonly #colno: number;
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
#error: any; readonly #error: any;
get message(): string { get message(): string {
return this.#message; return this.#message;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { notImplemented } from "../util.ts"; import { notImplemented } from "../util.ts";
import { isTypedArray } from "./util.ts"; import { isTypedArray } from "./util.ts";
import * as domTypes from "./dom_types.d.ts"; import * as domTypes from "./dom_types.d.ts";
@ -55,7 +56,6 @@ export class Response extends Body.Body implements domTypes.Response {
if (!type) { if (!type) {
type = "default"; type = "default";
} else { } else {
type = type;
if (type == "error") { if (type == "error") {
// spec: https://fetch.spec.whatwg.org/#concept-network-error // spec: https://fetch.spec.whatwg.org/#concept-network-error
status = 0; status = 0;
@ -144,12 +144,11 @@ export class Response extends Body.Body implements domTypes.Response {
resBody = tees[1]; resBody = tees[1];
} }
const cloned = new Response(resBody, { return new Response(resBody, {
status: this.status, status: this.status,
statusText: this.statusText, statusText: this.statusText,
headers: new Headers(headersList), headers: new Headers(headersList),
}); });
return cloned;
} }
static redirect(url: URL | string, status: number): domTypes.Response { static redirect(url: URL | string, status: number): domTypes.Response {
@ -260,7 +259,7 @@ export async function fetch(
} }
let responseBody; let responseBody;
let responseInit: ResponseInit = {}; let responseInit: domTypes.ResponseInit = {};
while (remRedirectCount) { while (remRedirectCount) {
const fetchResponse = await sendFetchReq(url, method, headers, body); const fetchResponse = await sendFetchReq(url, method, headers, body);

View file

@ -19,12 +19,9 @@ interface MultipartHeaders {
export class MultipartBuilder { export class MultipartBuilder {
readonly boundary: string; readonly boundary: string;
readonly formData: FormData; readonly writer = new Buffer();
readonly writer: Buffer; constructor(readonly formData: FormData, boundary?: string) {
constructor(formData: FormData, boundary?: string) {
this.boundary = boundary ?? this.#createBoundary(); this.boundary = boundary ?? this.#createBoundary();
this.formData = formData;
this.writer = new Buffer();
} }
getContentType(): string { getContentType(): string {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as blob from "./blob.ts"; import * as blob from "./blob.ts";
import * as domFile from "./dom_file.ts"; import * as domFile from "./dom_file.ts";
import { DomIterableMixin } from "./dom_iterable.ts"; import { DomIterableMixin } from "./dom_iterable.ts";
@ -96,10 +97,13 @@ class FormDataBase {
if (value instanceof domFile.DomFileImpl) { if (value instanceof domFile.DomFileImpl) {
this[dataSymbol][i][1] = value; this[dataSymbol][i][1] = value;
} else if (value instanceof blob.DenoBlob) { } else if (value instanceof blob.DenoBlob) {
const dfile = new domFile.DomFileImpl([value], filename || "blob", { this[dataSymbol][i][1] = new domFile.DomFileImpl(
type: value.type, [value],
}); filename || "blob",
this[dataSymbol][i][1] = dfile; {
type: value.type,
}
);
} else { } else {
this[dataSymbol][i][1] = String(value); this[dataSymbol][i][1] = String(value);
} }

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { DomIterableMixin } from "./dom_iterable.ts"; import { DomIterableMixin } from "./dom_iterable.ts";
import { requiredArguments } from "./util.ts"; import { requiredArguments } from "./util.ts";
import { customInspect } from "./console.ts"; import { customInspect } from "./console.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { now as opNow } from "../ops/timers.ts"; import { now as opNow } from "../ops/timers.ts";
export class Performance { export class Performance {

View file

@ -1,7 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
export enum PromiseState { export enum PromiseState {
Pending = 0, Pending,
Fulfilled = 1, Fulfilled,
Rejected = 2, Rejected,
} }
export type PromiseDetails<T> = [PromiseState, T | undefined]; export type PromiseDetails<T> = [PromiseState, T | undefined];

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as body from "./body.ts"; import * as body from "./body.ts";
import * as domTypes from "./dom_types.d.ts"; import * as domTypes from "./dom_types.d.ts";
import { ReadableStreamImpl } from "./streams/readable_stream.ts"; import { ReadableStreamImpl } from "./streams/readable_stream.ts";
@ -128,12 +129,11 @@ export class Request extends body.Body implements domTypes.Request {
body2 = tees[1]; body2 = tees[1];
} }
const cloned = new Request(this.url, { return new Request(this.url, {
body: body2, body: body2,
method: this.method, method: this.method,
headers: new Headers(headersList), headers: new Headers(headersList),
credentials: this.credentials, credentials: this.credentials,
}); });
return cloned;
} }
} }

View file

@ -5,7 +5,6 @@
// //
// There are some parts that are not fully implemented, and there are some // 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. // comments which point to steps of the specification that are not implemented.
//
/* eslint-disable @typescript-eslint/no-explicit-any,require-await */ /* eslint-disable @typescript-eslint/no-explicit-any,require-await */
import { ReadableByteStreamControllerImpl } from "./readable_byte_stream_controller.ts"; import { ReadableByteStreamControllerImpl } from "./readable_byte_stream_controller.ts";
@ -62,7 +61,7 @@ export interface ReadableStreamGenericReader<R = any>
export interface ReadableStreamAsyncIterator<T = any> extends AsyncIterator<T> { export interface ReadableStreamAsyncIterator<T = any> extends AsyncIterator<T> {
[sym.asyncIteratorReader]: ReadableStreamDefaultReaderImpl<T>; [sym.asyncIteratorReader]: ReadableStreamDefaultReaderImpl<T>;
[sym.preventCancel]: boolean; [sym.preventCancel]: boolean;
return(value?: any | PromiseLike<any>): Promise<IteratorResult<T, any>>; return(value?: any | PromiseLike<any>): Promise<IteratorResult<T>>;
} }
export function acquireReadableStreamDefaultReader<T>( export function acquireReadableStreamDefaultReader<T>(
@ -97,6 +96,7 @@ function createAlgorithmFromUnderlyingMethod<
algoArgCount: 0, algoArgCount: 0,
...extraArgs: any[] ...extraArgs: any[]
): () => Promise<void>; ): () => Promise<void>;
function createAlgorithmFromUnderlyingMethod< function createAlgorithmFromUnderlyingMethod<
O extends UnderlyingByteSource | UnderlyingSource | Transformer, O extends UnderlyingByteSource | UnderlyingSource | Transformer,
P extends keyof O P extends keyof O
@ -317,79 +317,72 @@ function isFiniteNonNegativeNumber(v: unknown): v is number {
export function isReadableByteStreamController( export function isReadableByteStreamController(
x: unknown x: unknown
): x is ReadableByteStreamControllerImpl { ): x is ReadableByteStreamControllerImpl {
return typeof x !== "object" || return !(
typeof x !== "object" ||
x === null || x === null ||
!(sym.controlledReadableByteStream in x) !(sym.controlledReadableByteStream in x)
? false );
: true;
} }
export function isReadableStream(x: unknown): x is ReadableStreamImpl { export function isReadableStream(x: unknown): x is ReadableStreamImpl {
return typeof x !== "object" || return !(
typeof x !== "object" ||
x === null || x === null ||
!(sym.readableStreamController in x) !(sym.readableStreamController in x)
? false );
: true;
} }
export function isReadableStreamAsyncIterator( export function isReadableStreamAsyncIterator(
x: unknown x: unknown
): x is ReadableStreamAsyncIterator<any> { ): x is ReadableStreamAsyncIterator {
if (typeof x !== "object" || x === null) { if (typeof x !== "object" || x === null) {
return false; return false;
} }
if (!(sym.asyncIteratorReader in x)) { return sym.asyncIteratorReader in x;
return false;
}
return true;
} }
export function isReadableStreamDefaultController( export function isReadableStreamDefaultController(
x: unknown x: unknown
): x is ReadableStreamDefaultControllerImpl { ): x is ReadableStreamDefaultControllerImpl {
return typeof x !== "object" || return !(
typeof x !== "object" ||
x === null || x === null ||
!(sym.controlledReadableStream in x) !(sym.controlledReadableStream in x)
? false );
: true;
} }
export function isReadableStreamDefaultReader<T>( export function isReadableStreamDefaultReader<T>(
x: unknown x: unknown
): x is ReadableStreamDefaultReaderImpl<T> { ): x is ReadableStreamDefaultReaderImpl<T> {
return typeof x !== "object" || x === null || !(sym.readRequests in x) return !(typeof x !== "object" || x === null || !(sym.readRequests in x));
? false
: true;
} }
export function isReadableStreamLocked(stream: ReadableStreamImpl): boolean { export function isReadableStreamLocked(stream: ReadableStreamImpl): boolean {
assert(isReadableStream(stream)); assert(isReadableStream(stream));
return stream[sym.reader] ? true : false; return !!stream[sym.reader];
} }
export function isReadableStreamDisturbed(stream: ReadableStream): boolean { export function isReadableStreamDisturbed(stream: ReadableStream): boolean {
assert(isReadableStream(stream)); assert(isReadableStream(stream));
return stream[sym.disturbed] ? true : false; return !!stream[sym.disturbed];
} }
export function isTransformStream( export function isTransformStream(x: unknown): x is TransformStreamImpl {
x: unknown return !(
): x is TransformStreamImpl<any, any> { typeof x !== "object" ||
return typeof x !== "object" ||
x === null || x === null ||
!(sym.transformStreamController in x) !(sym.transformStreamController in x)
? false );
: true;
} }
export function isTransformStreamDefaultController( export function isTransformStreamDefaultController(
x: unknown x: unknown
): x is TransformStreamDefaultControllerImpl<any, any> { ): x is TransformStreamDefaultControllerImpl {
return typeof x !== "object" || return !(
typeof x !== "object" ||
x === null || x === null ||
!(sym.controlledTransformStream in x) !(sym.controlledTransformStream in x)
? false );
: true;
} }
export function isUnderlyingByteSource( export function isUnderlyingByteSource(
@ -401,37 +394,36 @@ export function isUnderlyingByteSource(
} }
export function isWritableStream(x: unknown): x is WritableStreamImpl { export function isWritableStream(x: unknown): x is WritableStreamImpl {
return typeof x !== "object" || return !(
typeof x !== "object" ||
x === null || x === null ||
!(sym.writableStreamController in x) !(sym.writableStreamController in x)
? false );
: true;
} }
export function isWritableStreamDefaultController( export function isWritableStreamDefaultController(
x: unknown x: unknown
): x is WritableStreamDefaultControllerImpl<any> { ): x is WritableStreamDefaultControllerImpl<any> {
return typeof x !== "object" || return !(
typeof x !== "object" ||
x === null || x === null ||
!(sym.controlledWritableStream in x) !(sym.controlledWritableStream in x)
? false );
: true;
} }
export function isWritableStreamDefaultWriter( export function isWritableStreamDefaultWriter(
x: unknown x: unknown
): x is WritableStreamDefaultWriterImpl<any> { ): x is WritableStreamDefaultWriterImpl<any> {
return typeof x !== "object" || x === null || !(sym.ownerWritableStream in x) return !(
? false typeof x !== "object" ||
: true; x === null ||
!(sym.ownerWritableStream in x)
);
} }
export function isWritableStreamLocked(stream: WritableStreamImpl): boolean { export function isWritableStreamLocked(stream: WritableStreamImpl): boolean {
assert(isWritableStream(stream)); assert(isWritableStream(stream));
if (stream[sym.writer] === undefined) { return stream[sym.writer] !== undefined;
return false;
}
return true;
} }
export function makeSizeAlgorithmFromSizeFunction<T>( export function makeSizeAlgorithmFromSizeFunction<T>(
@ -476,10 +468,7 @@ function readableByteStreamControllerShouldCallPull(
// ReadableStreamGetNumReadIntoRequests(stream) > 0, return true. // ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
const desiredSize = readableByteStreamControllerGetDesiredSize(controller); const desiredSize = readableByteStreamControllerGetDesiredSize(controller);
assert(desiredSize !== null); assert(desiredSize !== null);
if (desiredSize > 0) { return desiredSize > 0;
return true;
}
return false;
} }
export function readableByteStreamControllerCallPullIfNeeded( export function readableByteStreamControllerCallPullIfNeeded(
@ -730,10 +719,7 @@ export function readableStreamDefaultControllerCanCloseOrEnqueue<T>(
controller: ReadableStreamDefaultControllerImpl<T> controller: ReadableStreamDefaultControllerImpl<T>
): boolean { ): boolean {
const state = controller[sym.controlledReadableStream][sym.state]; const state = controller[sym.controlledReadableStream][sym.state];
if (!controller[sym.closeRequested] && state === "readable") { return !controller[sym.closeRequested] && state === "readable";
return true;
}
return false;
} }
export function readableStreamDefaultControllerClearAlgorithms<T>( export function readableStreamDefaultControllerClearAlgorithms<T>(
@ -813,9 +799,7 @@ export function readableStreamDefaultControllerError<T>(
function readableStreamDefaultControllerHasBackpressure<T>( function readableStreamDefaultControllerHasBackpressure<T>(
controller: ReadableStreamDefaultControllerImpl<T> controller: ReadableStreamDefaultControllerImpl<T>
): boolean { ): boolean {
return readableStreamDefaultControllerShouldCallPull(controller) return readableStreamDefaultControllerShouldCallPull(controller);
? true
: false;
} }
function readableStreamDefaultControllerShouldCallPull<T>( function readableStreamDefaultControllerShouldCallPull<T>(
@ -836,10 +820,7 @@ function readableStreamDefaultControllerShouldCallPull<T>(
} }
const desiredSize = readableStreamDefaultControllerGetDesiredSize(controller); const desiredSize = readableStreamDefaultControllerGetDesiredSize(controller);
assert(desiredSize !== null); assert(desiredSize !== null);
if (desiredSize > 0) { return desiredSize > 0;
return true;
}
return false;
} }
export function readableStreamDefaultReaderRead<R>( export function readableStreamDefaultReaderRead<R>(
@ -914,9 +895,7 @@ export function readableStreamHasDefaultReader(
stream: ReadableStreamImpl stream: ReadableStreamImpl
): boolean { ): boolean {
const reader = stream[sym.reader]; const reader = stream[sym.reader];
return reader === undefined || !isReadableStreamDefaultReader(reader) return !(reader === undefined || !isReadableStreamDefaultReader(reader));
? false
: true;
} }
export function readableStreamPipeTo<T>( export function readableStreamPipeTo<T>(
@ -1927,13 +1906,10 @@ export function writableStreamClose<W>(
export function writableStreamCloseQueuedOrInFlight<W>( export function writableStreamCloseQueuedOrInFlight<W>(
stream: WritableStreamImpl<W> stream: WritableStreamImpl<W>
): boolean { ): boolean {
if ( return !(
stream[sym.closeRequest] === undefined && stream[sym.closeRequest] === undefined &&
stream[sym.inFlightCloseRequest] === undefined stream[sym.inFlightCloseRequest] === undefined
) { );
return false;
}
return true;
} }
function writableStreamDealWithRejection<W>( function writableStreamDealWithRejection<W>(
@ -2348,13 +2324,10 @@ function writableStreamFinishInFlightWriteWithError<W>(
function writableStreamHasOperationMarkedInFlight<W>( function writableStreamHasOperationMarkedInFlight<W>(
stream: WritableStreamImpl<W> stream: WritableStreamImpl<W>
): boolean { ): boolean {
if ( return !(
stream[sym.inFlightWriteRequest] === undefined && stream[sym.inFlightWriteRequest] === undefined &&
stream[sym.inFlightCloseRequest] === undefined stream[sym.inFlightCloseRequest] === undefined
) { );
return false;
}
return true;
} }
function writableStreamMarkCloseRequestInFlight<W>( function writableStreamMarkCloseRequestInFlight<W>(

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// The following code is based off of text-encoding at: // The following code is based off of text-encoding at:
// https://github.com/inexorabletash/text-encoding // https://github.com/inexorabletash/text-encoding
// //
@ -151,8 +152,8 @@ interface Encoder {
} }
class SingleByteDecoder implements Decoder { class SingleByteDecoder implements Decoder {
#index: number[]; readonly #index: number[];
#fatal: boolean; readonly #fatal: boolean;
constructor( constructor(
index: number[], index: number[],
@ -422,7 +423,7 @@ function isEitherArrayBuffer(x: any): x is EitherArrayBuffer {
} }
export class TextDecoder { export class TextDecoder {
#encoding: string; readonly #encoding: string;
get encoding(): string { get encoding(): string {
return this.#encoding; return this.#encoding;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert } from "../util.ts"; import { assert } from "../util.ts";
import { startGlobalTimer, stopGlobalTimer } from "../ops/timers.ts"; import { startGlobalTimer, stopGlobalTimer } from "../ops/timers.ts";
import { RBTree } from "../rbtree.ts"; import { RBTree } from "../rbtree.ts";

View file

@ -24,7 +24,7 @@ const searchParamsMethods: Array<keyof URLSearchParams> = [
const specialSchemes = ["ftp", "file", "http", "https", "ws", "wss"]; const specialSchemes = ["ftp", "file", "http", "https", "ws", "wss"];
// https://url.spec.whatwg.org/#special-scheme // https://url.spec.whatwg.org/#special-scheme
const schemePorts: { [key: string]: string } = { const schemePorts: Record<string, string> = {
ftp: "21", ftp: "21",
file: "", file: "",
http: "80", http: "80",
@ -179,8 +179,8 @@ function resolvePathFromBase(
let driveLetterPrefix = ""; let driveLetterPrefix = "";
if (build.os == "windows" && isFilePath) { if (build.os == "windows" && isFilePath) {
let driveLetter = ""; let driveLetter: string;
let baseDriveLetter = ""; let baseDriveLetter: string;
[driveLetter, normalizedPath] = takePattern( [driveLetter, normalizedPath] = takePattern(
normalizedPath, normalizedPath,
/^(\/[A-Za-z]:)(?=\/)/ /^(\/[A-Za-z]:)(?=\/)/
@ -214,7 +214,8 @@ function resolvePathFromBase(
function isValidPort(value: string): boolean { function isValidPort(value: string): boolean {
// https://url.spec.whatwg.org/#port-state // https://url.spec.whatwg.org/#port-state
if (value === "") true; if (value === "") return true;
const port = Number(value); const port = Number(value);
return Number.isInteger(port) && port >= 0 && port <= MAX_PORT; return Number.isInteger(port) && port >= 0 && port <= MAX_PORT;
} }
@ -409,7 +410,7 @@ export class URLImpl implements URL {
let baseParts: URLParts | undefined; let baseParts: URLParts | undefined;
if (base) { if (base) {
baseParts = typeof base === "string" ? parse(base) : parts.get(base); baseParts = typeof base === "string" ? parse(base) : parts.get(base);
if (baseParts == undefined) { if (baseParts === undefined) {
throw new TypeError("Invalid base URL."); throw new TypeError("Invalid base URL.");
} }
} }

View file

@ -6,7 +6,7 @@ import { isIterable, requiredArguments } from "./util.ts";
export const urls = new WeakMap<URLSearchParams, URL | null>(); export const urls = new WeakMap<URLSearchParams, URL | null>();
export class URLSearchParamsImpl implements URLSearchParams { export class URLSearchParamsImpl implements URLSearchParams {
#params: Array<[string, string]> = []; readonly #params: Array<[string, string]> = [];
constructor(init: string | string[][] | Record<string, string> = "") { constructor(init: string | string[][] | Record<string, string> = "") {
if (typeof init === "string") { if (typeof init === "string") {

View file

@ -81,7 +81,7 @@ export interface WorkerOptions {
export class WorkerImpl extends EventTarget implements Worker { export class WorkerImpl extends EventTarget implements Worker {
readonly #id: number; readonly #id: number;
#name: string; readonly #name: string;
#terminated = false; #terminated = false;
public onerror?: (e: ErrorEvent) => void; public onerror?: (e: ErrorEvent) => void;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { stat, statSync } from "./ops/fs/stat.ts"; import { stat, statSync } from "./ops/fs/stat.ts";
import { open, openSync } from "./files.ts"; import { open, openSync } from "./files.ts";
import { chmod, chmodSync } from "./ops/fs/chmod.ts"; import { chmod, chmodSync } from "./ops/fs/chmod.ts";

View file

@ -1,10 +1,12 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { open, openSync } from "./files.ts"; import { open, openSync } from "./files.ts";
import { writeAll, writeAllSync } from "./buffer.ts"; import { writeAll, writeAllSync } from "./buffer.ts";
export function writeTextFileSync(path: string | URL, data: string): void { export function writeTextFileSync(path: string | URL, data: string): void {
const file = openSync(path, { write: true, create: true, truncate: true }); const file = openSync(path, { write: true, create: true, truncate: true });
const enc = new TextEncoder(); const encoder = new TextEncoder();
const contents = enc.encode(data); const contents = encoder.encode(data);
writeAllSync(file, contents); writeAllSync(file, contents);
file.close(); file.close();
} }
@ -14,8 +16,8 @@ export async function writeTextFile(
data: string data: string
): Promise<void> { ): Promise<void> {
const file = await open(path, { write: true, create: true, truncate: true }); const file = await open(path, { write: true, create: true, truncate: true });
const enc = new TextEncoder(); const encoder = new TextEncoder();
const contents = enc.encode(data); const contents = encoder.encode(data);
await writeAll(file, contents); await writeAll(file, contents);
file.close(); file.close();
} }