1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-11 00:21:05 -05:00

Update eslint and @typescript-eslint (denoland/deno_std#621)

Original: c3fe858f98
This commit is contained in:
Yoshiya Hinosawa 2019-10-06 01:02:34 +09:00 committed by Ryan Dahl
parent 2f90225c89
commit 96fe2d10a4
54 changed files with 204 additions and 188 deletions

View file

@ -1,5 +1,5 @@
steps: steps:
- bash: npm install eslint@5.16.0 typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@1.13.0 @typescript-eslint/parser@1.13.0 eslint-config-prettier - bash: npm install eslint@$(ESLINT_VERSION) typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@$(TS_ESLINT_VERSION) @typescript-eslint/parser@$(TS_ESLINT_VERSION) eslint-config-prettier
- template: ./template.unix.yml - template: ./template.unix.yml
- bash: npx eslint **/*.ts --max-warnings=0 - bash: npx eslint "**/*.ts" --max-warnings=0
- template: ./template.common.yml - template: ./template.common.yml

View file

@ -1,6 +1,8 @@
steps: steps:
- bash: npm install -g functional-red-black-tree - task: NodeTool@0
- bash: npm -g install eslint@5.16.0 typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@1.13.0 @typescript-eslint/parser@1.13.0 eslint-config-prettier inputs:
versionSpec: '10.x'
- bash: npm install eslint@$(ESLINT_VERSION) typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@$(TS_ESLINT_VERSION) @typescript-eslint/parser@$(TS_ESLINT_VERSION) eslint-config-prettier
- template: ./template.unix.yml - template: ./template.unix.yml
- bash: eslint **/*.ts --max-warnings=0 - bash: npx eslint "**/*.ts" --max-warnings=0
- template: ./template.common.yml - template: ./template.common.yml

View file

@ -1,8 +1,8 @@
steps: steps:
- bash: npm install eslint@5.16.0 typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@1.13.0 @typescript-eslint/parser@1.13.0 eslint-config-prettier - bash: npm install eslint@$(ESLINT_VERSION) typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@$(TS_ESLINT_VERSION) @typescript-eslint/parser@$(TS_ESLINT_VERSION) eslint-config-prettier
- powershell: iwr https://deno.land/x/install/install.ps1 -out install.ps1; .\install.ps1 $(DENO_VERSION) - powershell: iwr https://deno.land/x/install/install.ps1 -out install.ps1; .\install.ps1 $(DENO_VERSION)
- bash: echo "##vso[task.prependpath]C:\Users\VssAdministrator\.deno\\bin" - bash: echo "##vso[task.prependpath]C:\Users\VssAdministrator\.deno\\bin"
- bash: npx eslint **/*.ts --max-warnings=0 - bash: npx eslint "**/*.ts" --max-warnings=0
- template: ./template.common.yml - template: ./template.common.yml
parameters: parameters:
exe_suffix: ".exe" exe_suffix: ".exe"

4
.eslintignore Normal file
View file

@ -0,0 +1,4 @@
/deno.d.ts
/prettier/vendor
**/testdata/

View file

@ -2,7 +2,8 @@
"root": true, "root": true,
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"parserOptions": { "parserOptions": {
"project": "./tsconfig.json" "project": "./tsconfig.json",
"createDefaultProgram": true
}, },
"plugins": ["@typescript-eslint"], "plugins": ["@typescript-eslint"],
"extends": [ "extends": [
@ -11,7 +12,7 @@
"prettier/@typescript-eslint" "prettier/@typescript-eslint"
], ],
"rules": { "rules": {
"@typescript-eslint/array-type": ["error", "array-simple"], "@typescript-eslint/array-type": ["error", { "default": "array-simple" }],
"@typescript-eslint/explicit-member-accessibility": ["off"], "@typescript-eslint/explicit-member-accessibility": ["off"],
"@typescript-eslint/no-non-null-assertion": ["off"], "@typescript-eslint/no-non-null-assertion": ["off"],
"@typescript-eslint/no-parameter-properties": ["off"], "@typescript-eslint/no-parameter-properties": ["off"],
@ -19,6 +20,8 @@
"error", "error",
{ "argsIgnorePattern": "^_", "varsIgnorePattern": "_" } { "argsIgnorePattern": "^_", "varsIgnorePattern": "_" }
], ],
"@typescript-eslint/ban-ts-ignore": ["off"],
"@typescript-eslint/no-empty-function": ["off"],
"max-len": [ "max-len": [
"error", "error",
{ {

View file

@ -96,7 +96,7 @@ function clean(length: number): Uint8Array {
} }
function pad(num: number, bytes: number, base?: number): string { function pad(num: number, bytes: number, base?: number): string {
var numString = num.toString(base || 8); const numString = num.toString(base || 8);
return "000000000000".substr(numString.length + 12 - bytes) + numString; return "000000000000".substr(numString.length + 12 - bytes) + numString;
} }
@ -328,7 +328,7 @@ export class Tar {
// set meta data // set meta data
const info = opts.filePath && (await Deno.stat(opts.filePath)); const info = opts.filePath && (await Deno.stat(opts.filePath));
let mode = const mode =
opts.fileMode || (info && info.mode) || parseInt("777", 8) & 0xfff, opts.fileMode || (info && info.mode) || parseInt("777", 8) & 0xfff,
mtime = mtime =
opts.mtime || opts.mtime ||
@ -385,8 +385,9 @@ export class Tar {
getReader(): Deno.Reader { getReader(): Deno.Reader {
const readers: Deno.Reader[] = []; const readers: Deno.Reader[] = [];
this.data.forEach((tarData): void => { this.data.forEach((tarData): void => {
let { filePath, reader } = tarData, let { reader } = tarData;
headerArr = formatHeader(tarData); const { filePath } = tarData;
const headerArr = formatHeader(tarData);
readers.push(new Deno.Buffer(headerArr)); readers.push(new Deno.Buffer(headerArr));
if (!reader) { if (!reader) {
reader = new FileReader(filePath!); reader = new FileReader(filePath!);

View file

@ -1,6 +1,8 @@
variables: variables:
DENO_VERSION: "v0.19.0" DENO_VERSION: "v0.19.0"
TS_VERSION: "3.4.5" TS_VERSION: "3.4.5"
ESLINT_VERSION: "6.5.1"
TS_ESLINT_VERSION: "2.3.2"
# TODO Try to get eslint to run under Deno, like prettier # TODO Try to get eslint to run under Deno, like prettier
jobs: jobs:

View file

@ -12,6 +12,7 @@ import { instantiate, load, ModuleMetaData } from "./utils.ts";
/* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable @typescript-eslint/no-namespace */
declare global { declare global {
namespace globalThis { namespace globalThis {
// eslint-disable-next-line no-var
var __results: [string, string] | undefined; var __results: [string, string] | undefined;
} }
} }

View file

@ -23,6 +23,7 @@ type Define = (
/* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable @typescript-eslint/no-namespace */
declare global { declare global {
namespace globalThis { namespace globalThis {
// eslint-disable-next-line no-var
var define: Define | undefined; var define: Define | undefined;
} }
} }

View file

@ -118,7 +118,7 @@ export function currentDayOfYear(): number {
* @return IMF date formated string * @return IMF date formated string
*/ */
export function toIMF(date: Date): string { export function toIMF(date: Date): string {
function dtPad(v: string, lPad: number = 2): string { function dtPad(v: string, lPad = 2): string {
return pad(v, lPad, { char: "0" }); return pad(v, lPad, { char: "0" });
} }
const d = dtPad(date.getUTCDate().toString()); const d = dtPad(date.getUTCDate().toString());

View file

@ -56,7 +56,7 @@ async function read(
const tp = new TextProtoReader(reader); const tp = new TextProtoReader(reader);
let line: string; let line: string;
let result: string[] = []; let result: string[] = [];
let lineIndex = Startline; const lineIndex = Startline;
const r = await tp.readLine(); const r = await tp.readLine();
if (r === Deno.EOF) return Deno.EOF; if (r === Deno.EOF) return Deno.EOF;
@ -229,7 +229,7 @@ export async function parse(
throw `Error number of fields line:${i}`; throw `Error number of fields line:${i}`;
} }
i++; i++;
let out: Record<string, unknown> = {}; const out: Record<string, unknown> = {};
for (let j = 0; j < e.length; j++) { for (let j = 0; j < e.length; j++) {
const h = headers[j]; const h = headers[j];
if (h.parse) { if (h.parse) {

View file

@ -85,7 +85,7 @@ export function decode(
dst: Uint8Array, dst: Uint8Array,
src: Uint8Array src: Uint8Array
): [number, Error | void] { ): [number, Error | void] {
var i = 0; let i = 0;
for (; i < Math.floor(src.length / 2); i++) { for (; i < Math.floor(src.length / 2); i++) {
const [a, aOK] = fromHexChar(src[i * 2]); const [a, aOK] = fromHexChar(src[i * 2]);
if (!aOK) { if (!aOK) {

View file

@ -64,8 +64,8 @@ class Parser {
return line.match(/'''/) ? true : false; return line.match(/'''/) ? true : false;
} }
let merged = [], const merged = [];
acc = [], let acc = [],
isLiteral = false, isLiteral = false,
capture = false, capture = false,
captureType = "", captureType = "",
@ -123,14 +123,14 @@ class Parser {
this.tomlLines = merged; this.tomlLines = merged;
} }
_unflat(keys: string[], values: object = {}, cObj: object = {}): object { _unflat(keys: string[], values: object = {}, cObj: object = {}): object {
let out: Record<string, unknown> = {}; const out: Record<string, unknown> = {};
if (keys.length === 0) { if (keys.length === 0) {
return cObj; return cObj;
} else { } else {
if (Object.keys(cObj).length === 0) { if (Object.keys(cObj).length === 0) {
cObj = values; cObj = values;
} }
let key: string | undefined = keys.pop(); const key: string | undefined = keys.pop();
if (key) { if (key) {
out[key] = cObj; out[key] = cObj;
} }
@ -152,7 +152,7 @@ class Parser {
delete this.context.currentGroup; delete this.context.currentGroup;
} }
_split(str: string): string[] { _split(str: string): string[] {
let out = []; const out = [];
out.push(...str.split("\n")); out.push(...str.split("\n"));
return out; return out;
} }
@ -233,8 +233,8 @@ class Parser {
const reg = /([a-zA-Z0-9-_\.]*) (=)/gi; const reg = /([a-zA-Z0-9-_\.]*) (=)/gi;
let result; let result;
while ((result = reg.exec(dataString))) { while ((result = reg.exec(dataString))) {
let ogVal = result[0]; const ogVal = result[0];
let newVal = ogVal const newVal = ogVal
.replace(result[1], `"${result[1]}"`) .replace(result[1], `"${result[1]}"`)
.replace(result[2], ":"); .replace(result[2], ":");
dataString = dataString.replace(ogVal, newVal); dataString = dataString.replace(ogVal, newVal);
@ -332,9 +332,9 @@ class Parser {
} }
} }
if (this._isDeclaration(line)) { if (this._isDeclaration(line)) {
let kv = this._processDeclaration(line); const kv = this._processDeclaration(line);
let key = kv.key; const key = kv.key;
let value = kv.value; const value = kv.value;
if (!this.context.currentGroup) { if (!this.context.currentGroup) {
this.context.output[key] = value; this.context.output[key] = value;
} else { } else {
@ -360,7 +360,7 @@ class Parser {
let k = keys[i]; let k = keys[i];
if (k) { if (k) {
let v = obj[k]; let v = obj[k];
let pathDeclaration = this._parseDeclarationName(k); const pathDeclaration = this._parseDeclarationName(k);
delete obj[k]; delete obj[k];
if (pathDeclaration.length > 1) { if (pathDeclaration.length > 1) {
const shift = pathDeclaration.shift(); const shift = pathDeclaration.shift();
@ -400,7 +400,7 @@ function joinKeys(keys: string[]): string {
} }
class Dumper { class Dumper {
maxPad: number = 0; maxPad = 0;
srcObject: object; srcObject: object;
output: string[] = []; output: string[] = [];
constructor(srcObjc: object) { constructor(srcObjc: object) {
@ -507,11 +507,11 @@ class Dumper {
} }
} }
_dateDeclaration(keys: string[], value: Date): string { _dateDeclaration(keys: string[], value: Date): string {
function dtPad(v: string, lPad: number = 2): string { function dtPad(v: string, lPad = 2): string {
return pad(v, lPad, { char: "0" }); return pad(v, lPad, { char: "0" });
} }
let m = dtPad((value.getUTCMonth() + 1).toString()); const m = dtPad((value.getUTCMonth() + 1).toString());
let d = dtPad(value.getUTCDate().toString()); const d = dtPad(value.getUTCDate().toString());
const h = dtPad(value.getUTCHours().toString()); const h = dtPad(value.getUTCHours().toString());
const min = dtPad(value.getUTCMinutes().toString()); const min = dtPad(value.getUTCMinutes().toString());
const s = dtPad(value.getUTCSeconds().toString()); const s = dtPad(value.getUTCSeconds().toString());

View file

@ -1,7 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
async function cat(filenames: string[]): Promise<void> { async function cat(filenames: string[]): Promise<void> {
for (let filename of filenames) { for (const filename of filenames) {
let file = await Deno.open(filename); const file = await Deno.open(filename);
await Deno.copy(Deno.stdout, file); await Deno.copy(Deno.stdout, file);
file.close(); file.close();
} }

View file

@ -53,11 +53,11 @@ async function main(): Promise<void> {
}); });
if (res.ok) { if (res.ok) {
let resObj = await res.json(); const resObj = await res.json();
console.log("Success"); console.log("Success");
console.log(resObj["html_url"]); console.log(resObj["html_url"]);
} else { } else {
let err = await res.text(); const err = await res.text();
console.error("Failure to POST", err); console.error("Failure to POST", err);
} }
} }

View file

@ -286,7 +286,7 @@ export function parse(
argv._.push(flags.strings["_"] || !isNumber(arg) ? arg : Number(arg)); argv._.push(flags.strings["_"] || !isNumber(arg) ? arg : Number(arg));
} }
if (options.stopEarly) { if (options.stopEarly) {
argv._.push.apply(argv._, args.slice(i + 1)); argv._.push(...args.slice(i + 1));
break; break;
} }
} }

View file

@ -17,8 +17,8 @@ class Flags {
space?: boolean; space?: boolean;
zero?: boolean; zero?: boolean;
lessthan?: boolean; lessthan?: boolean;
width: number = -1; width = -1;
precision: number = -1; precision = -1;
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -44,9 +44,9 @@ class Printf {
i: number; i: number;
state: State = State.PASSTHROUGH; state: State = State.PASSTHROUGH;
verb: string = ""; verb = "";
buf: string = ""; buf = "";
argNum: number = 0; argNum = 0;
flags: Flags = new Flags(); flags: Flags = new Flags();
haveSeen: boolean[]; haveSeen: boolean[];
@ -64,7 +64,7 @@ class Printf {
doPrintf(): string { doPrintf(): string {
for (; this.i < this.format.length; ++this.i) { for (; this.i < this.format.length; ++this.i) {
let c = this.format[this.i]; const c = this.format[this.i];
switch (this.state) { switch (this.state) {
case State.PASSTHROUGH: case State.PASSTHROUGH:
if (c === "%") { if (c === "%") {
@ -104,9 +104,9 @@ class Printf {
// %[<positional>]<flag>...<verb> // %[<positional>]<flag>...<verb>
handleFormat(): void { handleFormat(): void {
this.flags = new Flags(); this.flags = new Flags();
let flags = this.flags; const flags = this.flags;
for (; this.i < this.format.length; ++this.i) { for (; this.i < this.format.length; ++this.i) {
let c = this.format[this.i]; const c = this.format[this.i];
switch (this.state) { switch (this.state) {
case State.PERCENT: case State.PERCENT:
switch (c) { switch (c) {
@ -152,7 +152,7 @@ class Printf {
break; break;
case State.POSITIONAL: // either a verb or * only verb for now, TODO case State.POSITIONAL: // either a verb or * only verb for now, TODO
if (c === "*") { if (c === "*") {
let worp = const worp =
this.flags.precision === -1 ? WorP.WIDTH : WorP.PRECISION; this.flags.precision === -1 ? WorP.WIDTH : WorP.PRECISION;
this.handleWidthOrPrecisionRef(worp); this.handleWidthOrPrecisionRef(worp);
this.state = State.PERCENT; this.state = State.PERCENT;
@ -171,7 +171,7 @@ class Printf {
// handle Positional should have already taken care of it... // handle Positional should have already taken care of it...
return; return;
} }
let arg = this.args[this.argNum]; const arg = this.args[this.argNum];
this.haveSeen[this.argNum] = true; this.haveSeen[this.argNum] = true;
if (typeof arg === "number") { if (typeof arg === "number") {
switch (wOrP) { switch (wOrP) {
@ -182,7 +182,7 @@ class Printf {
this.flags.precision = arg; this.flags.precision = arg;
} }
} else { } else {
let tmp = wOrP === WorP.WIDTH ? "WIDTH" : "PREC"; const tmp = wOrP === WorP.WIDTH ? "WIDTH" : "PREC";
this.tmpError = `%!(BAD ${tmp} '${this.args[this.argNum]}')`; this.tmpError = `%!(BAD ${tmp} '${this.args[this.argNum]}')`;
} }
this.argNum++; this.argNum++;
@ -271,7 +271,7 @@ class Printf {
return; return;
} }
handleLessThan(): string { handleLessThan(): string {
let arg = this.args[this.argNum]; const arg = this.args[this.argNum];
if ((arg || {}).constructor.name !== "Array") { if ((arg || {}).constructor.name !== "Array") {
throw new Error(`arg ${arg} is not an array. Todo better error handling`); throw new Error(`arg ${arg} is not an array. Todo better error handling`);
} }
@ -294,7 +294,7 @@ class Printf {
} else if (this.args.length <= this.argNum) { } else if (this.args.length <= this.argNum) {
this.buf += `%!(MISSING '${verb}')`; this.buf += `%!(MISSING '${verb}')`;
} else { } else {
let arg = this.args[this.argNum]; // check out of range const arg = this.args[this.argNum]; // check out of range
this.haveSeen[this.argNum] = true; // keep track of used args this.haveSeen[this.argNum] = true; // keep track of used args
if (this.flags.lessthan) { if (this.flags.lessthan) {
this.buf += this.handleLessThan(); this.buf += this.handleLessThan();
@ -404,7 +404,7 @@ class Printf {
return nStr; return nStr;
} }
fmtNumber(n: number, radix: number, upcase: boolean = false): string { fmtNumber(n: number, radix: number, upcase = false): string {
let num = Math.abs(n).toString(radix); let num = Math.abs(n).toString(radix);
const prec = this.flags.precision; const prec = this.flags.precision;
if (prec !== -1) { if (prec !== -1) {
@ -484,7 +484,7 @@ class Printf {
return fractional; return fractional;
} }
fmtFloatE(n: number, upcase: boolean = false): string { fmtFloatE(n: number, upcase = false): string {
const special = this.fmtFloatSpecial(n); const special = this.fmtFloatSpecial(n);
if (special !== "") { if (special !== "") {
return special; return special;
@ -553,7 +553,7 @@ class Printf {
return this.padNum(`${dig}.${fractional}`, n < 0); return this.padNum(`${dig}.${fractional}`, n < 0);
} }
fmtFloatG(n: number, upcase: boolean = false): string { fmtFloatG(n: number, upcase = false): string {
const special = this.fmtFloatSpecial(n); const special = this.fmtFloatSpecial(n);
if (special !== "") { if (special !== "") {
return special; return special;
@ -591,7 +591,7 @@ class Printf {
throw Error("can't happen"); throw Error("can't happen");
} }
let X = parseInt(m[F.exponent]) * (m[F.esign] === "-" ? -1 : 1); const X = parseInt(m[F.exponent]) * (m[F.esign] === "-" ? -1 : 1);
let nStr = ""; let nStr = "";
if (P > X && X >= -4) { if (P > X && X >= -4) {
this.flags.precision = P - (X + 1); this.flags.precision = P - (X + 1);
@ -616,14 +616,14 @@ class Printf {
return this.pad(s); return this.pad(s);
} }
fmtHex(val: string | number, upper: boolean = false): string { fmtHex(val: string | number, upper = false): string {
// allow others types ? // allow others types ?
switch (typeof val) { switch (typeof val) {
case "number": case "number":
return this.fmtNumber(val as number, 16, upper); return this.fmtNumber(val as number, 16, upper);
break; break;
case "string": case "string":
let sharp = this.flags.sharp && val.length !== 0; const sharp = this.flags.sharp && val.length !== 0;
let hex = sharp ? "0x" : ""; let hex = sharp ? "0x" : "";
const prec = this.flags.precision; const prec = this.flags.precision;
const end = prec !== -1 ? min(prec, val.length) : val.length; const end = prec !== -1 ? min(prec, val.length) : val.length;
@ -634,7 +634,7 @@ class Printf {
// TODO: for now only taking into account the // TODO: for now only taking into account the
// lower half of the codePoint, ie. as if a string // lower half of the codePoint, ie. as if a string
// is a list of 8bit values instead of UCS2 runes // is a list of 8bit values instead of UCS2 runes
let c = (val.charCodeAt(i) & 0xff).toString(16); const c = (val.charCodeAt(i) & 0xff).toString(16);
hex += c.length === 1 ? `0${c}` : c; hex += c.length === 1 ? `0${c}` : c;
} }
if (upper) { if (upper) {
@ -652,7 +652,7 @@ class Printf {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
fmtV(val: any): string { fmtV(val: any): string {
if (this.flags.sharp) { if (this.flags.sharp) {
let options = const options =
this.flags.precision !== -1 ? { depth: this.flags.precision } : {}; this.flags.precision !== -1 ? { depth: this.flags.precision } : {};
return this.pad(Deno.inspect(val, options)); return this.pad(Deno.inspect(val, options));
} else { } else {
@ -669,6 +669,6 @@ class Printf {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export function sprintf(format: string, ...args: any[]): string { export function sprintf(format: string, ...args: any[]): string {
let printf = new Printf(format, ...args); const printf = new Printf(format, ...args);
return printf.doPrintf(); return printf.doPrintf();
} }

View file

@ -3,7 +3,7 @@ import { sprintf } from "./sprintf.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { test, runIfMain } from "../testing/mod.ts"; import { test, runIfMain } from "../testing/mod.ts";
let S = sprintf; const S = sprintf;
test(function noVerb(): void { test(function noVerb(): void {
assertEquals(sprintf("bla"), "bla"); assertEquals(sprintf("bla"), "bla");
@ -589,8 +589,8 @@ const tests: Array<[string, any, string]> = [
test(function testThorough(): void { test(function testThorough(): void {
tests.forEach((t, i): void => { tests.forEach((t, i): void => {
// p(t) // p(t)
let is = S(t[0], t[1]); const is = S(t[0], t[1]);
let should = t[2]; const should = t[2];
assertEquals( assertEquals(
is, is,
should, should,
@ -608,7 +608,7 @@ test(function testWeirdos(): void {
}); });
test(function formatV(): void { test(function formatV(): void {
let a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } }; const a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } };
assertEquals(S("%v", a), "[object Object]"); assertEquals(S("%v", a), "[object Object]");
assertEquals(S("%#v", a), "{ a: { a: { a: { a: [Object] } } } }"); assertEquals(S("%#v", a), "{ a: { a: { a: { a: [Object] } } } }");
assertEquals( assertEquals(
@ -619,18 +619,18 @@ test(function formatV(): void {
}); });
test(function formatJ(): void { test(function formatJ(): void {
let a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } }; const a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } };
assertEquals(S("%j", a), `{"a":{"a":{"a":{"a":{"a":{"a":{"a":{}}}}}}}}`); assertEquals(S("%j", a), `{"a":{"a":{"a":{"a":{"a":{"a":{"a":{}}}}}}}}`);
}); });
test(function flagLessThan(): void { test(function flagLessThan(): void {
let a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } }; const a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } };
let aArray = [a, a, a]; const aArray = [a, a, a];
assertEquals( assertEquals(
S("%<#.1v", aArray), S("%<#.1v", aArray),
"[ { a: [Object] }, { a: [Object] }, { a: [Object] } ]" "[ { a: [Object] }, { a: [Object] }, { a: [Object] } ]"
); );
let fArray = [1.2345, 0.98765, 123456789.5678]; const fArray = [1.2345, 0.98765, 123456789.5678];
assertEquals(S("%<.2f", fArray), "[ 1.23, 0.99, 123456789.57 ]"); assertEquals(S("%<.2f", fArray), "[ 1.23, 0.99, 123456789.57 ]");
}); });

View file

@ -21,11 +21,9 @@ async function ensureValidCopy(
src: string, src: string,
dest: string, dest: string,
options: CopyOptions, options: CopyOptions,
isCopyFolder: boolean = false isCopyFolder = false
): Promise<Deno.FileInfo> { ): Promise<Deno.FileInfo> {
let destStat: Deno.FileInfo | null; const destStat: Deno.FileInfo | null = await Deno.lstat(dest).catch(
destStat = await Deno.lstat(dest).catch(
(): Promise<null> => Promise.resolve(null) (): Promise<null> => Promise.resolve(null)
); );
@ -47,7 +45,7 @@ function ensureValidCopySync(
src: string, src: string,
dest: string, dest: string,
options: CopyOptions, options: CopyOptions,
isCopyFolder: boolean = false isCopyFolder = false
): Deno.FileInfo { ): Deno.FileInfo {
let destStat: Deno.FileInfo | null; let destStat: Deno.FileInfo | null;

View file

@ -112,7 +112,7 @@ export function joinGlobs(
if (globs.length === 0) return "."; if (globs.length === 0) return ".";
let joined: string | undefined; let joined: string | undefined;
for (const glob of globs) { for (const glob of globs) {
let path = glob; const path = glob;
if (path.length > 0) { if (path.length > 0) {
if (!joined) joined = path; if (!joined) joined = path;
else joined += `${SEP}${path}`; else joined += `${SEP}${path}`;

View file

@ -127,7 +127,7 @@ export function globrex(
if (c === ")") { if (c === ")") {
if (ext.length) { if (ext.length) {
add(c); add(c);
let type: string | undefined = ext.pop(); const type: string | undefined = ext.pop();
if (type === "@") { if (type === "@") {
add("{1}"); add("{1}");
} else if (type === "!") { } else if (type === "!") {
@ -264,19 +264,19 @@ export function globrex(
} }
// Move over all consecutive "*"'s. // Move over all consecutive "*"'s.
// Also store the previous and next characters // Also store the previous and next characters
let prevChar = glob[i - 1]; const prevChar = glob[i - 1];
let starCount = 1; let starCount = 1;
while (glob[i + 1] === "*") { while (glob[i + 1] === "*") {
starCount++; starCount++;
i++; i++;
} }
let nextChar = glob[i + 1]; const nextChar = glob[i + 1];
if (!globstar) { if (!globstar) {
// globstar is disabled, so treat any number of "*" as one // globstar is disabled, so treat any number of "*" as one
add(".*"); add(".*");
} else { } else {
// globstar is enabled, so determine if this is a globstar segment // globstar is enabled, so determine if this is a globstar segment
let isGlobstar = const isGlobstar =
starCount > 1 && // multiple "*"'s starCount > 1 && // multiple "*"'s
// from the start of the segment // from the start of the segment
[SEP_RAW, "/", undefined].includes(prevChar) && [SEP_RAW, "/", undefined].includes(prevChar) &&

View file

@ -19,14 +19,14 @@ function match(
opts = strWin; opts = strWin;
strWin = ""; strWin = "";
} }
let res = globrex(glob, opts); const res = globrex(glob, opts);
return res.regex.test(isWin && strWin ? strWin : strUnix); return res.regex.test(isWin && strWin ? strWin : strUnix);
} }
test({ test({
name: "globrex: standard", name: "globrex: standard",
fn(): void { fn(): void {
let res = globrex("*.js"); const res = globrex("*.js");
t.equal(typeof globrex, "function", "constructor is a typeof function"); t.equal(typeof globrex, "function", "constructor is a typeof function");
t.equal(res instanceof Object, true, "returns object"); t.equal(res instanceof Object, true, "returns object");
t.equal(res.regex.toString(), "/^.*\\.js$/", "returns regex object"); t.equal(res.regex.toString(), "/^.*\\.js$/", "returns regex object");

View file

@ -1,5 +1,7 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
/* eslint-disable @typescript-eslint/no-explicit-any */
// TODO(kt3k): fix any types in this file
import { test } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEquals } from "../../testing/asserts.ts"; import { assertEquals } from "../../testing/asserts.ts";
@ -80,7 +82,7 @@ const unixSpecialCaseFormatTests = [
]; ];
function checkParseFormat(path: any, paths: any): void { function checkParseFormat(path: any, paths: any): void {
paths.forEach(function(p: Record<string, unknown>[]) { paths.forEach(function(p: Array<Record<string, unknown>>) {
const element = p[0]; const element = p[0];
const output = path.parse(element); const output = path.parse(element);
assertEquals(typeof output.root, "string"); assertEquals(typeof output.root, "string");
@ -96,7 +98,7 @@ function checkParseFormat(path: any, paths: any): void {
} }
function checkSpecialCaseParseFormat(path: any, testCases: any): void { function checkSpecialCaseParseFormat(path: any, testCases: any): void {
testCases.forEach(function(testCase: Record<string, unknown>[]) { testCases.forEach(function(testCase: Array<Record<string, unknown>>) {
const element = testCase[0]; const element = testCase[0];
const expect = testCase[1]; const expect = testCase[1];
const output = path.parse(element); const output = path.parse(element);

View file

@ -83,7 +83,7 @@ export function join(...paths: string[]): string {
if (paths.length === 0) return "."; if (paths.length === 0) return ".";
let joined: string | undefined; let joined: string | undefined;
for (let i = 0, len = paths.length; i < len; ++i) { for (let i = 0, len = paths.length; i < len; ++i) {
let path = paths[i]; const path = paths[i];
assertPath(path); assertPath(path);
if (path.length > 0) { if (path.length > 0) {
if (!joined) joined = path; if (!joined) joined = path;
@ -107,11 +107,11 @@ export function relative(from: string, to: string): string {
// Trim any leading backslashes // Trim any leading backslashes
let fromStart = 1; let fromStart = 1;
let fromEnd = from.length; const fromEnd = from.length;
for (; fromStart < fromEnd; ++fromStart) { for (; fromStart < fromEnd; ++fromStart) {
if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break; if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break;
} }
let fromLen = fromEnd - fromStart; const fromLen = fromEnd - fromStart;
// Trim any leading backslashes // Trim any leading backslashes
let toStart = 1; let toStart = 1;
@ -119,10 +119,10 @@ export function relative(from: string, to: string): string {
for (; toStart < toEnd; ++toStart) { for (; toStart < toEnd; ++toStart) {
if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break; if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break;
} }
let toLen = toEnd - toStart; const toLen = toEnd - toStart;
// Compare paths to find the longest common path from root // Compare paths to find the longest common path from root
let length = fromLen < toLen ? fromLen : toLen; const length = fromLen < toLen ? fromLen : toLen;
let lastCommonSep = -1; let lastCommonSep = -1;
let i = 0; let i = 0;
for (; i <= length; ++i) { for (; i <= length; ++i) {
@ -150,8 +150,8 @@ export function relative(from: string, to: string): string {
} }
break; break;
} }
let fromCode = from.charCodeAt(fromStart + i); const fromCode = from.charCodeAt(fromStart + i);
let toCode = to.charCodeAt(toStart + i); const toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode) break; if (fromCode !== toCode) break;
else if (fromCode === CHAR_FORWARD_SLASH) lastCommonSep = i; else if (fromCode === CHAR_FORWARD_SLASH) lastCommonSep = i;
} }
@ -328,6 +328,7 @@ export function extname(path: string): string {
} }
export function format(pathObject: FormatInputPathObject): string { export function format(pathObject: FormatInputPathObject): string {
/* eslint-disable max-len */
if (pathObject === null || typeof pathObject !== "object") { if (pathObject === null || typeof pathObject !== "object") {
throw new TypeError( throw new TypeError(
`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`
@ -339,9 +340,9 @@ export function format(pathObject: FormatInputPathObject): string {
export function parse(path: string): ParsedPath { export function parse(path: string): ParsedPath {
assertPath(path); assertPath(path);
let ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" }; const ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" };
if (path.length === 0) return ret; if (path.length === 0) return ret;
let isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
let start: number; let start: number;
if (isAbsolute) { if (isAbsolute) {
ret.root = "/"; ret.root = "/";

View file

@ -304,7 +304,7 @@ export function join(...paths: string[]): string {
let joined: string | undefined; let joined: string | undefined;
let firstPart: string; let firstPart: string;
for (let i = 0; i < pathsCount; ++i) { for (let i = 0; i < pathsCount; ++i) {
let path = paths[i]; const path = paths[i];
assertPath(path); assertPath(path);
if (path.length > 0) { if (path.length > 0) {
if (joined === undefined) joined = firstPart = path; if (joined === undefined) joined = firstPart = path;
@ -369,8 +369,8 @@ export function relative(from: string, to: string): string {
if (from === to) return ""; if (from === to) return "";
let fromOrig = resolve(from); const fromOrig = resolve(from);
let toOrig = resolve(to); const toOrig = resolve(to);
if (fromOrig === toOrig) return ""; if (fromOrig === toOrig) return "";
@ -389,7 +389,7 @@ export function relative(from: string, to: string): string {
for (; fromEnd - 1 > fromStart; --fromEnd) { for (; fromEnd - 1 > fromStart; --fromEnd) {
if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break; if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break;
} }
let fromLen = fromEnd - fromStart; const fromLen = fromEnd - fromStart;
// Trim any leading backslashes // Trim any leading backslashes
let toStart = 0; let toStart = 0;
@ -401,10 +401,10 @@ export function relative(from: string, to: string): string {
for (; toEnd - 1 > toStart; --toEnd) { for (; toEnd - 1 > toStart; --toEnd) {
if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break; if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break;
} }
let toLen = toEnd - toStart; const toLen = toEnd - toStart;
// Compare paths to find the longest common path from root // Compare paths to find the longest common path from root
let length = fromLen < toLen ? fromLen : toLen; const length = fromLen < toLen ? fromLen : toLen;
let lastCommonSep = -1; let lastCommonSep = -1;
let i = 0; let i = 0;
for (; i <= length; ++i) { for (; i <= length; ++i) {
@ -433,8 +433,8 @@ export function relative(from: string, to: string): string {
} }
break; break;
} }
let fromCode = from.charCodeAt(fromStart + i); const fromCode = from.charCodeAt(fromStart + i);
let toCode = to.charCodeAt(toStart + i); const toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode) break; if (fromCode !== toCode) break;
else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i; else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i;
} }
@ -737,6 +737,7 @@ export function extname(path: string): string {
} }
export function format(pathObject: FormatInputPathObject): string { export function format(pathObject: FormatInputPathObject): string {
/* eslint-disable max-len */
if (pathObject === null || typeof pathObject !== "object") { if (pathObject === null || typeof pathObject !== "object") {
throw new TypeError( throw new TypeError(
`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`
@ -748,7 +749,7 @@ export function format(pathObject: FormatInputPathObject): string {
export function parse(path: string): ParsedPath { export function parse(path: string): ParsedPath {
assertPath(path); assertPath(path);
let ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" }; const ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" };
const len = path.length; const len = path.length;
if (len === 0) return ret; if (len === 0) return ret;

View file

@ -27,7 +27,8 @@ test(function normalizeZeroLength() {
}); });
test(function isAbsoluteZeroLength() { test(function isAbsoluteZeroLength() {
// Since '' is not a valid path in any of the common environments, return false // Since '' is not a valid path in any of the common environments,
// return false
assertEquals(path.posix.isAbsolute(""), false); assertEquals(path.posix.isAbsolute(""), false);
if (path.win32) assertEquals(path.win32.isAbsolute(""), false); if (path.win32) assertEquals(path.win32.isAbsolute(""), false);
}); });
@ -40,7 +41,8 @@ test(function resolveZeroLength() {
}); });
test(function relativeZeroLength() { test(function relativeZeroLength() {
// relative, internally calls resolve. So, '' is actually the current directory // relative, internally calls resolve. So, '' is actually the current
// directory
assertEquals(path.relative("", pwd), ""); assertEquals(path.relative("", pwd), "");
assertEquals(path.relative(pwd, ""), ""); assertEquals(path.relative(pwd, ""), "");
assertEquals(path.relative(pwd, pwd), ""); assertEquals(path.relative(pwd, pwd), "");

View file

@ -22,7 +22,7 @@ function patternTest(patterns: RegExp[], path: string): boolean {
// consistent results. // consistent results.
// See: https://stackoverflow.com/a/1520853 // See: https://stackoverflow.com/a/1520853
return patterns.some((pattern): boolean => { return patterns.some((pattern): boolean => {
let r = pattern.test(path); const r = pattern.test(path);
pattern.lastIndex = 0; pattern.lastIndex = 0;
return r; return r;
}); });
@ -100,7 +100,7 @@ export async function* walk(
options.onError(err); options.onError(err);
} }
} }
for (let info of ls) { for (const info of ls) {
if (info.isSymlink()) { if (info.isSymlink()) {
if (options.followSymlinks) { if (options.followSymlinks) {
// TODO(ry) Re-enable followSymlinks. // TODO(ry) Re-enable followSymlinks.
@ -154,7 +154,7 @@ export function* walkSync(
options.onError(err); options.onError(err);
} }
} }
for (let info of ls) { for (const info of ls) {
if (info.isSymlink()) { if (info.isSymlink()) {
if (options.followSymlinks) { if (options.followSymlinks) {
unimplemented(); unimplemented();

View file

@ -59,7 +59,7 @@ function toString(cookie: Cookie): string {
out.push(`Path=${cookie.path}`); out.push(`Path=${cookie.path}`);
} }
if (cookie.expires) { if (cookie.expires) {
let dateString = toIMF(cookie.expires); const dateString = toIMF(cookie.expires);
out.push(`Expires=${dateString}`); out.push(`Expires=${dateString}`);
} }
if (cookie.unparsed) { if (cookie.unparsed) {

View file

@ -7,7 +7,7 @@ import { test } from "../testing/mod.ts";
test({ test({
name: "[HTTP] Cookie parser", name: "[HTTP] Cookie parser",
fn(): void { fn(): void {
let req = new ServerRequest(); const req = new ServerRequest();
req.headers = new Headers(); req.headers = new Headers();
assertEquals(getCookies(req), {}); assertEquals(getCookies(req), {});
req.headers = new Headers(); req.headers = new Headers();
@ -35,7 +35,7 @@ test({
test({ test({
name: "[HTTP] Cookie Delete", name: "[HTTP] Cookie Delete",
fn(): void { fn(): void {
let res: Response = {}; const res: Response = {};
delCookie(res, "deno"); delCookie(res, "deno");
assertEquals( assertEquals(
res.headers!.get("Set-Cookie"), res.headers!.get("Set-Cookie"),
@ -47,7 +47,7 @@ test({
test({ test({
name: "[HTTP] Cookie Set", name: "[HTTP] Cookie Set",
fn(): void { fn(): void {
let res: Response = {}; const res: Response = {};
res.headers = new Headers(); res.headers = new Headers();
setCookie(res, { name: "Space", value: "Cat" }); setCookie(res, { name: "Space", value: "Cat" });

View file

@ -150,7 +150,7 @@ async function serveDir(
const fileInfos = await readDir(dirPath); const fileInfos = await readDir(dirPath);
for (const fileInfo of fileInfos) { for (const fileInfo of fileInfos) {
const filePath = posix.join(dirPath, fileInfo.name); const filePath = posix.join(dirPath, fileInfo.name);
let fileUrl = posix.join(dirUrl, fileInfo.name); const fileUrl = posix.join(dirUrl, fileInfo.name);
if (fileInfo.name === "index.html" && fileInfo.isFile()) { if (fileInfo.name === "index.html" && fileInfo.isFile()) {
// in case index.html as dir... // in case index.html as dir...
return await serveFile(req, filePath); return await serveFile(req, filePath);

View file

@ -21,7 +21,7 @@ function killServer(): void {
server.stdout!.close(); server.stdout!.close();
} }
let input = `GET / HTTP/1.1 const input = `GET / HTTP/1.1
GET / HTTP/1.1 GET / HTTP/1.1
@ -31,7 +31,7 @@ GET / HTTP/1.1
`; `;
const HUGE_BODY_SIZE = 1024 * 1024; const HUGE_BODY_SIZE = 1024 * 1024;
let output = `HTTP/1.1 200 OK const output = `HTTP/1.1 200 OK
content-length: 8 content-length: 8
Hello 1 Hello 1

View file

@ -139,7 +139,7 @@ export class ServerRequest {
let line = await tp.readLine(); let line = await tp.readLine();
if (line === Deno.EOF) throw new UnexpectedEOFError(); if (line === Deno.EOF) throw new UnexpectedEOFError();
// TODO: handle chunk extension // TODO: handle chunk extension
let [chunkSizeString] = line.split(";"); const [chunkSizeString] = line.split(";");
let chunkSize = parseInt(chunkSizeString, 16); let chunkSize = parseInt(chunkSizeString, 16);
if (Number.isNaN(chunkSize) || chunkSize < 0) { if (Number.isNaN(chunkSize) || chunkSize < 0) {
throw new Error("Invalid chunk size"); throw new Error("Invalid chunk size");
@ -157,7 +157,7 @@ export class ServerRequest {
} }
const entityHeaders = await tp.readMIMEHeader(); const entityHeaders = await tp.readMIMEHeader();
if (entityHeaders !== Deno.EOF) { if (entityHeaders !== Deno.EOF) {
for (let [k, v] of entityHeaders) { for (const [k, v] of entityHeaders) {
this.headers.set(k, v); this.headers.set(k, v);
} }
} }
@ -242,8 +242,6 @@ export function parseHTTPVersion(vers: string): [number, number] {
default: { default: {
const Big = 1000000; // arbitrary upper bound const Big = 1000000; // arbitrary upper bound
const digitReg = /^\d+$/; // test if string is only digit const digitReg = /^\d+$/; // test if string is only digit
let major: number;
let minor: number;
if (!vers.startsWith("HTTP/")) { if (!vers.startsWith("HTTP/")) {
break; break;
@ -254,8 +252,8 @@ export function parseHTTPVersion(vers: string): [number, number] {
break; break;
} }
let majorStr = vers.substring(vers.indexOf("/") + 1, dot); const majorStr = vers.substring(vers.indexOf("/") + 1, dot);
major = parseInt(majorStr); const major = parseInt(majorStr);
if ( if (
!digitReg.test(majorStr) || !digitReg.test(majorStr) ||
isNaN(major) || isNaN(major) ||
@ -265,8 +263,8 @@ export function parseHTTPVersion(vers: string): [number, number] {
break; break;
} }
let minorStr = vers.substring(dot + 1); const minorStr = vers.substring(dot + 1);
minor = parseInt(minorStr); const minor = parseInt(minorStr);
if ( if (
!digitReg.test(minorStr) || !digitReg.test(minorStr) ||
isNaN(minor) || isNaN(minor) ||

View file

@ -349,7 +349,7 @@ const mockConn = {
}; };
test(async function readRequestError(): Promise<void> { test(async function readRequestError(): Promise<void> {
let input = `GET / HTTP/1.1 const input = `GET / HTTP/1.1
malformedHeader malformedHeader
`; `;
const reader = new BufReader(new StringReader(input)); const reader = new BufReader(new StringReader(input));

View file

@ -5,7 +5,7 @@ import { serve } from "../server.ts";
window.onload = async function main() { window.onload = async function main() {
const addr = "0.0.0.0:4502"; const addr = "0.0.0.0:4502";
console.log(`Simple server listening on ${addr}`); console.log(`Simple server listening on ${addr}`);
for await (let req of serve(addr)) { for await (const req of serve(addr)) {
req.respond({}); req.respond({});
} }
} }

View file

@ -79,7 +79,7 @@ function getFlagFromPermission(perm: Permission): string {
function getInstallerDir(): string { function getInstallerDir(): string {
// In Windows's Powershell $HOME environmental variable maybe null // In Windows's Powershell $HOME environmental variable maybe null
// if so use $HOMEPATH instead. // if so use $HOMEPATH instead.
let { HOME, HOMEPATH } = env(); const { HOME, HOMEPATH } = env();
const HOME_PATH = HOME || HOMEPATH; const HOME_PATH = HOME || HOMEPATH;
@ -109,7 +109,7 @@ function checkIfExistsInPath(filePath: string): boolean {
// $HOMEDRIVE is only used on Windows. // $HOMEDRIVE is only used on Windows.
const { PATH, Path, HOMEDRIVE } = env(); const { PATH, Path, HOMEDRIVE } = env();
let envPath = (PATH as string) || (Path as string) || ""; const envPath = (PATH as string) || (Path as string) || "";
const paths = envPath.split(isWindows ? ";" : ":"); const paths = envPath.split(isWindows ? ";" : ":");

View file

@ -407,7 +407,7 @@ export class BufReader implements Reader {
*/ */
export class BufWriter implements Writer { export class BufWriter implements Writer {
buf: Uint8Array; buf: Uint8Array;
n: number = 0; n = 0;
err: Error | null = null; err: Error | null = null;
/** return new BufWriter unless w is BufWriter */ /** return new BufWriter unless w is BufWriter */

View file

@ -32,7 +32,7 @@ async function readBytes(buf: BufReader): Promise<string> {
const b = new Uint8Array(1000); const b = new Uint8Array(1000);
let nb = 0; let nb = 0;
while (true) { while (true) {
let c = await buf.readByte(); const c = await buf.readByte();
if (c === Deno.EOF) { if (c === Deno.EOF) {
break; // EOF break; // EOF
} }
@ -122,10 +122,10 @@ test(async function bufioBufReader(): Promise<void> {
} }
texts[texts.length - 1] = all; texts[texts.length - 1] = all;
for (let text of texts) { for (const text of texts) {
for (let readmaker of readMakers) { for (const readmaker of readMakers) {
for (let bufreader of bufreaders) { for (const bufreader of bufreaders) {
for (let bufsize of bufsizes) { for (const bufsize of bufsizes) {
const read = readmaker.fn(stringsReader(text)); const read = readmaker.fn(stringsReader(text));
const buf = new BufReader(read, bufsize); const buf = new BufReader(read, bufsize);
const s = await bufreader.fn(buf); const s = await bufreader.fn(buf);
@ -210,8 +210,8 @@ class TestReader implements Reader {
async function testReadLine(input: Uint8Array): Promise<void> { async function testReadLine(input: Uint8Array): Promise<void> {
for (let stride = 1; stride < 2; stride++) { for (let stride = 1; stride < 2; stride++) {
let done = 0; let done = 0;
let reader = new TestReader(input, stride); const reader = new TestReader(input, stride);
let l = new BufReader(reader, input.byteLength + 1); const l = new BufReader(reader, input.byteLength + 1);
while (true) { while (true) {
const r = await l.readLine(); const r = await l.readLine();
if (r === Deno.EOF) { if (r === Deno.EOF) {
@ -220,7 +220,7 @@ async function testReadLine(input: Uint8Array): Promise<void> {
const { line, more } = r; const { line, more } = r;
assertEquals(more, false); assertEquals(more, false);
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
let want = testOutput.subarray(done, done + line.byteLength); const want = testOutput.subarray(done, done + line.byteLength);
assertEquals( assertEquals(
line, line,
want, want,
@ -244,9 +244,9 @@ test(async function bufioReadLine(): Promise<void> {
test(async function bufioPeek(): Promise<void> { test(async function bufioPeek(): Promise<void> {
const decoder = new TextDecoder(); const decoder = new TextDecoder();
let p = new Uint8Array(10); const p = new Uint8Array(10);
// string is 16 (minReadBufferSize) long. // string is 16 (minReadBufferSize) long.
let buf = new BufReader( const buf = new BufReader(
stringsReader("abcdefghijklmnop"), stringsReader("abcdefghijklmnop"),
MIN_READ_BUFFER_SIZE MIN_READ_BUFFER_SIZE
); );
@ -281,7 +281,7 @@ test(async function bufioPeek(): Promise<void> {
actual = assertNotEOF(await buf.peek(2)); actual = assertNotEOF(await buf.peek(2));
assertEquals(decoder.decode(actual), "de"); assertEquals(decoder.decode(actual), "de");
let res = await buf.read(p.subarray(0, 3)); const res = await buf.read(p.subarray(0, 3));
assertEquals(decoder.decode(p.subarray(0, 3)), "def"); assertEquals(decoder.decode(p.subarray(0, 3)), "def");
assert(res !== Deno.EOF); assert(res !== Deno.EOF);
@ -327,8 +327,8 @@ test(async function bufioWriter(): Promise<void> {
} }
const w = new Buffer(); const w = new Buffer();
for (let nwrite of bufsizes) { for (const nwrite of bufsizes) {
for (let bs of bufsizes) { for (const bs of bufsizes) {
// Write nwrite bytes using buffer size bs. // Write nwrite bytes using buffer size bs.
// Check that the right amount makes it out // Check that the right amount makes it out
// and that the data is correct. // and that the data is correct.

View file

@ -17,13 +17,13 @@ test(async function ioStringReader(): Promise<void> {
test(async function ioStringReader(): Promise<void> { test(async function ioStringReader(): Promise<void> {
const r = new StringReader("abcdef"); const r = new StringReader("abcdef");
const buf = new Uint8Array(3); const buf = new Uint8Array(3);
let res1 = await r.read(buf); const res1 = await r.read(buf);
assertEquals(res1, 3); assertEquals(res1, 3);
assertEquals(decode(buf), "abc"); assertEquals(decode(buf), "abc");
let res2 = await r.read(buf); const res2 = await r.read(buf);
assertEquals(res2, 3); assertEquals(res2, 3);
assertEquals(decode(buf), "def"); assertEquals(decode(buf), "def");
let res3 = await r.read(buf); const res3 = await r.read(buf);
assertEquals(res3, Deno.EOF); assertEquals(res3, Deno.EOF);
assertEquals(decode(buf), "def"); assertEquals(decode(buf), "def");
}); });

View file

@ -6,7 +6,7 @@ import { copyBytes, tempFile } from "./util.ts";
import * as path from "../fs/path.ts"; import * as path from "../fs/path.ts";
test(function testCopyBytes(): void { test(function testCopyBytes(): void {
let dst = new Uint8Array(4); const dst = new Uint8Array(4);
dst.fill(0); dst.fill(0);
let src = Uint8Array.of(1, 2); let src = Uint8Array.of(1, 2);

View file

@ -5,7 +5,7 @@ import { decode, encode } from "../strings/mod.ts";
/** Writer utility for buffering string chunks */ /** Writer utility for buffering string chunks */
export class StringWriter implements Writer { export class StringWriter implements Writer {
private chunks: Uint8Array[] = []; private chunks: Uint8Array[] = [];
private byteLength: number = 0; private byteLength = 0;
private cache: string | undefined; private cache: string | undefined;
constructor(private base: string = "") { constructor(private base: string = "") {

View file

@ -50,7 +50,7 @@ test(function customHandler(): void {
test(function logFunctions(): void { test(function logFunctions(): void {
const doLog = (level: string): TestHandler => { const doLog = (level: string): TestHandler => {
const handler = new TestHandler(level); const handler = new TestHandler(level);
let logger = new Logger(level, [handler]); const logger = new Logger(level, [handler]);
logger.debug("foo"); logger.debug("foo");
logger.info("bar"); logger.info("bar");
logger.warning("baz"); logger.warning("baz");

View file

@ -130,7 +130,7 @@ export function scanUntilBoundary(
class PartReader implements Reader, Closer { class PartReader implements Reader, Closer {
n: number | Deno.EOF = 0; n: number | Deno.EOF = 0;
total: number = 0; total = 0;
constructor(private mr: MultipartReader, public readonly headers: Headers) {} constructor(private mr: MultipartReader, public readonly headers: Headers) {}
@ -312,7 +312,7 @@ export class MultipartReader {
} }
private currentPart: PartReader | undefined; private currentPart: PartReader | undefined;
private partsRead: number = 0; private partsRead = 0;
private async nextPart(): Promise<PartReader | Deno.EOF> { private async nextPart(): Promise<PartReader | Deno.EOF> {
if (this.currentPart) { if (this.currentPart) {
@ -359,7 +359,7 @@ export class MultipartReader {
if (!hasPrefix(line, this.dashBoundaryDash)) { if (!hasPrefix(line, this.dashBoundaryDash)) {
return false; return false;
} }
let rest = line.slice(this.dashBoundaryDash.length, line.length); const rest = line.slice(this.dashBoundaryDash.length, line.length);
return rest.length === 0 || equal(skipLWSPChar(rest), this.newLine); return rest.length === 0 || equal(skipLWSPChar(rest), this.newLine);
} }
@ -375,7 +375,7 @@ export class MultipartReader {
class PartWriter implements Writer { class PartWriter implements Writer {
closed = false; closed = false;
private readonly partHeader: string; private readonly partHeader: string;
private headersWritten: boolean = false; private headersWritten = false;
constructor( constructor(
private writer: Writer, private writer: Writer,
@ -436,7 +436,7 @@ export class MultipartWriter {
private lastPart: PartWriter | undefined; private lastPart: PartWriter | undefined;
private bufWriter: BufWriter; private bufWriter: BufWriter;
private isClosed: boolean = false; private isClosed = false;
constructor(private readonly writer: Writer, boundary?: string) { constructor(private readonly writer: Writer, boundary?: string) {
if (boundary !== void 0) { if (boundary !== void 0) {

View file

@ -54,21 +54,21 @@ test(async function testPrettierCheckAndFormatFiles(): Promise<void> {
join(tempDir, "2.ts") join(tempDir, "2.ts")
]; ];
var { code, stdout } = await run([...cmd, "--check", ...files]); let p = await run([...cmd, "--check", ...files]);
assertEquals(code, 1); assertEquals(p.code, 1);
assertEquals(normalizeOutput(stdout), "Some files are not formatted"); assertEquals(normalizeOutput(p.stdout), "Some files are not formatted");
var { code, stdout } = await run([...cmd, "--write", ...files]); p = await run([...cmd, "--write", ...files]);
assertEquals(code, 0); assertEquals(p.code, 0);
assertEquals( assertEquals(
normalizeOutput(stdout), normalizeOutput(p.stdout),
normalizeOutput(`Formatting ${tempDir}/0.ts normalizeOutput(`Formatting ${tempDir}/0.ts
Formatting ${tempDir}/1.js`) Formatting ${tempDir}/1.js`)
); );
var { code, stdout } = await run([...cmd, "--check", ...files]); p = await run([...cmd, "--check", ...files]);
assertEquals(code, 0); assertEquals(p.code, 0);
assertEquals(normalizeOutput(stdout), "Every file is formatted"); assertEquals(normalizeOutput(p.stdout), "Every file is formatted");
emptyDir(tempDir); emptyDir(tempDir);
}); });
@ -79,23 +79,23 @@ test(async function testPrettierCheckAndFormatDirs(): Promise<void> {
const dirs = [join(tempDir, "foo"), join(tempDir, "bar")]; const dirs = [join(tempDir, "foo"), join(tempDir, "bar")];
var { code, stdout } = await run([...cmd, "--check", ...dirs]); let p = await run([...cmd, "--check", ...dirs]);
assertEquals(code, 1); assertEquals(p.code, 1);
assertEquals(normalizeOutput(stdout), "Some files are not formatted"); assertEquals(normalizeOutput(p.stdout), "Some files are not formatted");
var { code, stdout } = await run([...cmd, "--write", ...dirs]); p = await run([...cmd, "--write", ...dirs]);
assertEquals(code, 0); assertEquals(p.code, 0);
assertEquals( assertEquals(
normalizeOutput(stdout), normalizeOutput(p.stdout),
normalizeOutput(`Formatting ${tempDir}/bar/0.ts normalizeOutput(`Formatting ${tempDir}/bar/0.ts
Formatting ${tempDir}/bar/1.js Formatting ${tempDir}/bar/1.js
Formatting ${tempDir}/foo/0.ts Formatting ${tempDir}/foo/0.ts
Formatting ${tempDir}/foo/1.js`) Formatting ${tempDir}/foo/1.js`)
); );
var { code, stdout } = await run([...cmd, "--check", ...dirs]); p = await run([...cmd, "--check", ...dirs]);
assertEquals(code, 0); assertEquals(p.code, 0);
assertEquals(normalizeOutput(stdout), "Every file is formatted"); assertEquals(normalizeOutput(p.stdout), "Every file is formatted");
emptyDir(tempDir); emptyDir(tempDir);
}); });

View file

@ -60,7 +60,7 @@ export function pad(
out = out.padEnd(strLen, opts.char); out = out.padEnd(strLen, opts.char);
} }
} else if (opts.strict && outL > strLen) { } else if (opts.strict && outL > strLen) {
let addChar = opts.strictChar ? opts.strictChar : ""; const addChar = opts.strictChar ? opts.strictChar : "";
if (opts.strictSide === "left") { if (opts.strictSide === "left") {
let toDrop = outL - strLen; let toDrop = outL - strLen;
if (opts.strictChar) { if (opts.strictChar) {

View file

@ -235,7 +235,7 @@ export function assertArrayContains(
expected: unknown[], expected: unknown[],
msg?: string msg?: string
): void { ): void {
let missing: unknown[] = []; const missing: unknown[] = [];
for (let i = 0; i < expected.length; i++) { for (let i = 0; i < expected.length; i++) {
let found = false; let found = false;
for (let j = 0; j < actual.length; j++) { for (let j = 0; j < actual.length; j++) {

View file

@ -19,7 +19,7 @@ test(async function benching(): Promise<void> {
bench(async function forAwaitFetchDenolandX10(b): Promise<void> { bench(async function forAwaitFetchDenolandX10(b): Promise<void> {
b.start(); b.start();
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
let r = await fetch("https://deno.land/"); const r = await fetch("https://deno.land/");
await r.text(); await r.text();
} }
b.stop(); b.stop();
@ -31,7 +31,7 @@ test(async function benching(): Promise<void> {
await Promise.all( await Promise.all(
urls.map( urls.map(
async (denoland: string): Promise<void> => { async (denoland: string): Promise<void> => {
let r = await fetch(denoland); const r = await fetch(denoland);
await r.text(); await r.text();
} }
) )

View file

@ -271,7 +271,7 @@ function printIteratorEntries(
// Too bad, so sad that separator for ECMAScript Map has been ' => ' // Too bad, so sad that separator for ECMAScript Map has been ' => '
// What a distracting diff if you change a data structure to/from // What a distracting diff if you change a data structure to/from
// ECMAScript Object or Immutable.Map/OrderedMap which use the default. // ECMAScript Object or Immutable.Map/OrderedMap which use the default.
separator: string = ": " separator = ": "
): string { ): string {
let result = ""; let result = "";
let current = iterator.next(); let current = iterator.next();

View file

@ -13,6 +13,7 @@ import { format } from "./format.ts";
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-explicit-any
function returnArguments(...args: any[]): IArguments { function returnArguments(...args: any[]): IArguments {
// eslint-disable-next-line prefer-rest-params
return arguments; return arguments;
} }

View file

@ -62,7 +62,7 @@ function disableConsole(): void {
} }
const encoder = new TextEncoder(); const encoder = new TextEncoder();
function print(txt: string, newline: boolean = true): void { function print(txt: string, newline = true): void {
if (newline) { if (newline) {
txt += "\n"; txt += "\n";
} }
@ -172,11 +172,11 @@ function createTestResults(tests: TestDefinition[]): TestResults {
); );
} }
function formatTestTime(time: number = 0): string { function formatTestTime(time = 0): string {
return `${time.toFixed(2)}ms`; return `${time.toFixed(2)}ms`;
} }
function promptTestTime(time: number = 0, displayWarning = false): string { function promptTestTime(time = 0, displayWarning = false): string {
// if time > 5s we display a warning // if time > 5s we display a warning
// only for test time, not the full runtime // only for test time, not the full runtime
if (displayWarning && time >= 5000) { if (displayWarning && time >= 5000) {
@ -308,10 +308,9 @@ async function runTestsSerial(
print(`${yellow("RUNNING")} ${name}`, false); print(`${yellow("RUNNING")} ${name}`, false);
} }
try { try {
let start, end; const start = performance.now();
start = performance.now();
await fn(); await fn();
end = performance.now(); const end = performance.now();
if (disableLog) { if (disableLog) {
// Rewriting the current prompt line to erase `running ....` // Rewriting the current prompt line to erase `running ....`
print(CLEAR_LINE, false); print(CLEAR_LINE, false);

View file

@ -66,7 +66,7 @@ export class TextProtoReader {
* } * }
*/ */
async readMIMEHeader(): Promise<Headers | Deno.EOF> { async readMIMEHeader(): Promise<Headers | Deno.EOF> {
let m = new Headers(); const m = new Headers();
let line: Uint8Array; let line: Uint8Array;
// The first line cannot start with a leading space. // The first line cannot start with a leading space.
@ -87,7 +87,7 @@ export class TextProtoReader {
} }
while (true) { while (true) {
let kv = await this.readLineSlice(); // readContinuedLineSlice const kv = await this.readLineSlice(); // readContinuedLineSlice
if (kv === Deno.EOF) throw new UnexpectedEOFError(); if (kv === Deno.EOF) throw new UnexpectedEOFError();
if (kv.byteLength === 0) return m; if (kv.byteLength === 0) return m;
@ -104,7 +104,7 @@ export class TextProtoReader {
} }
//let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey)); //let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey));
let key = str(kv.subarray(0, endKey)); const key = str(kv.subarray(0, endKey));
// As per RFC 7230 field-name is a token, // As per RFC 7230 field-name is a token,
// tokens consist of one or more chars. // tokens consist of one or more chars.
@ -123,7 +123,7 @@ export class TextProtoReader {
) { ) {
i++; i++;
} }
let value = str(kv.subarray(i)); const value = str(kv.subarray(i));
// In case of invalid header we swallow the error // In case of invalid header we swallow the error
// example: "Audio Mode" => invalid due to space in the key // example: "Audio Mode" => invalid due to space in the key

View file

@ -1,5 +1,5 @@
{ {
"extends": "tsconfig.test.json", "extends": "./tsconfig.test.json",
"compilerOptions": { "compilerOptions": {
"allowJs": true, "allowJs": true,
"baseUrl": ".", "baseUrl": ".",

View file

@ -100,7 +100,7 @@ export async function collectUint8Arrays(
} }
const collected = new Uint8Array(length); const collected = new Uint8Array(length);
let offset = 0; let offset = 0;
for (let chunk of chunks) { for (const chunk of chunks) {
collected.set(chunk, offset); collected.set(chunk, offset);
offset += chunk.length; offset += chunk.length;
} }

View file

@ -368,7 +368,7 @@ export function createSecAccept(nonce: string): string {
const sha1 = new Sha1(); const sha1 = new Sha1();
sha1.update(nonce + kGUID); sha1.update(nonce + kGUID);
const bytes = sha1.digest(); const bytes = sha1.digest();
return btoa(String.fromCharCode.apply(String, bytes)); return btoa(String.fromCharCode(...bytes));
} }
/** Upgrade given TCP connection into websocket connection */ /** Upgrade given TCP connection into websocket connection */
@ -480,7 +480,7 @@ export async function connectWebSocket(
headers: Headers = new Headers() headers: Headers = new Headers()
): Promise<WebSocket> { ): Promise<WebSocket> {
const url = new URL(endpoint); const url = new URL(endpoint);
let { hostname } = url; const { hostname } = url;
let conn: Conn; let conn: Conn;
if (url.protocol === "http:" || url.protocol === "ws:") { if (url.protocol === "http:" || url.protocol === "ws:") {
const port = parseInt(url.port || "80"); const port = parseInt(url.port || "80");

View file

@ -70,7 +70,7 @@ async function* chunks(
let inspectIndex = 0; let inspectIndex = 0;
let matchIndex = 0; let matchIndex = 0;
while (true) { while (true) {
let result = await reader.read(inspectArr); const result = await reader.read(inspectArr);
if (result === EOF) { if (result === EOF) {
// Yield last chunk. // Yield last chunk.
const lastChunk = inputBuffer.toString(); const lastChunk = inputBuffer.toString();
@ -81,7 +81,7 @@ async function* chunks(
// Discard all remaining and silently fail. // Discard all remaining and silently fail.
return; return;
} }
let sliceRead = inspectArr.subarray(0, result as number); const sliceRead = inspectArr.subarray(0, result as number);
await writeAll(inputBuffer, sliceRead); await writeAll(inputBuffer, sliceRead);
let sliceToProcess = inputBuffer.bytes(); let sliceToProcess = inputBuffer.bytes();