1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-25 00:29:09 -05:00

Update to TypeScript 3.7 (#3275)

and update to prettier 1.19

Also, update `assert()` and remove not null assertions where possibly
in `cli`.

Closes #3273
This commit is contained in:
Kitson Kelly 2019-11-14 05:42:34 +11:00 committed by Ry Dahl
parent 279191ad94
commit 9837d324a7
80 changed files with 980 additions and 1153 deletions

View file

@ -72,41 +72,35 @@ function concatenate(...arrays: Uint8Array[]): ArrayBuffer {
} }
function bufferFromStream(stream: ReadableStreamReader): Promise<ArrayBuffer> { function bufferFromStream(stream: ReadableStreamReader): Promise<ArrayBuffer> {
return new Promise( return new Promise((resolve, reject): void => {
(resolve, reject): void => { const parts: Uint8Array[] = [];
const parts: Uint8Array[] = []; const encoder = new TextEncoder();
const encoder = new TextEncoder(); // recurse
// recurse (function pump(): void {
(function pump(): void { stream
stream .read()
.read() .then(({ done, value }): void => {
.then( if (done) {
({ done, value }): void => { return resolve(concatenate(...parts));
if (done) { }
return resolve(concatenate(...parts));
}
if (typeof value === "string") { if (typeof value === "string") {
parts.push(encoder.encode(value)); parts.push(encoder.encode(value));
} else if (value instanceof ArrayBuffer) { } else if (value instanceof ArrayBuffer) {
parts.push(new Uint8Array(value)); parts.push(new Uint8Array(value));
} else if (!value) { } else if (!value) {
// noop for undefined // noop for undefined
} else { } else {
reject("unhandled type on stream read"); reject("unhandled type on stream read");
} }
return pump(); return pump();
} })
) .catch((err): void => {
.catch( reject(err);
(err): void => { });
reject(err); })();
} });
);
})();
}
);
} }
function getHeaderValueParams(value: string): Map<string, string> { function getHeaderValueParams(value: string): Map<string, string> {
@ -275,19 +269,17 @@ export class Body implements domTypes.Body {
body body
.trim() .trim()
.split("&") .split("&")
.forEach( .forEach((bytes): void => {
(bytes): void => { if (bytes) {
if (bytes) { const split = bytes.split("=");
const split = bytes.split("="); const name = split.shift()!.replace(/\+/g, " ");
const name = split.shift()!.replace(/\+/g, " "); const value = split.join("=").replace(/\+/g, " ");
const value = split.join("=").replace(/\+/g, " "); formData.append(
formData.append( decodeURIComponent(name),
decodeURIComponent(name), decodeURIComponent(value)
decodeURIComponent(value) );
);
}
} }
); });
} catch (e) { } catch (e) {
throw new TypeError("Invalid form urlencoded format"); throw new TypeError("Invalid form urlencoded format");
} }

View file

@ -67,7 +67,8 @@ type CompilerRequest = {
| { | {
type: CompilerRequestType.Bundle; type: CompilerRequestType.Bundle;
outFile?: string; outFile?: string;
}); }
);
interface ConfigureResponse { interface ConfigureResponse {
ignoredOptions?: string[]; ignoredOptions?: string[];
@ -186,11 +187,7 @@ class SourceFile {
throw new Error("SourceFile has already been processed."); throw new Error("SourceFile has already been processed.");
} }
assert(this.sourceCode != null); assert(this.sourceCode != null);
const preProcessedFileInfo = ts.preProcessFile( const preProcessedFileInfo = ts.preProcessFile(this.sourceCode, true, true);
this.sourceCode!,
true,
true
);
this.processed = true; this.processed = true;
const files = (this.importedFiles = [] as Array<[string, string]>); const files = (this.importedFiles = [] as Array<[string, string]>);
@ -511,10 +508,10 @@ class Host implements ts.CompilerHost {
? this._getAsset(fileName) ? this._getAsset(fileName)
: SourceFile.get(fileName); : SourceFile.get(fileName);
assert(sourceFile != null); assert(sourceFile != null);
if (!sourceFile!.tsSourceFile) { if (!sourceFile.tsSourceFile) {
sourceFile!.tsSourceFile = ts.createSourceFile( sourceFile.tsSourceFile = ts.createSourceFile(
fileName, fileName,
sourceFile!.sourceCode, sourceFile.sourceCode,
languageVersion languageVersion
); );
} }
@ -577,7 +574,7 @@ class Host implements ts.CompilerHost {
emitBundle(this._rootNames, this._outFile, data, sourceFiles!); emitBundle(this._rootNames, this._outFile, data, sourceFiles!);
} else { } else {
assert(sourceFiles.length == 1); assert(sourceFiles.length == 1);
const url = sourceFiles![0].fileName; const url = sourceFiles[0].fileName;
const sourceFile = SourceFile.get(url); const sourceFile = SourceFile.get(url);
if (sourceFile) { if (sourceFile) {
@ -635,9 +632,9 @@ window.compilerMain = function compilerMain(): void {
// This will recursively analyse all the code for other imports, requesting // This will recursively analyse all the code for other imports, requesting
// those from the privileged side, populating the in memory cache which // those from the privileged side, populating the in memory cache which
// will be used by the host, before resolving. // will be used by the host, before resolving.
const resolvedRootModules = (await processImports( const resolvedRootModules = (
rootNames.map(rootName => [rootName, rootName]) await processImports(rootNames.map(rootName => [rootName, rootName]))
)).map(info => info.url); ).map(info => info.url);
const host = new Host( const host = new Host(
request.type, request.type,
@ -669,8 +666,9 @@ window.compilerMain = function compilerMain(): void {
const options = host.getCompilationSettings(); const options = host.getCompilationSettings();
const program = ts.createProgram(rootNames, options, host); const program = ts.createProgram(rootNames, options, host);
diagnostics = ts.getPreEmitDiagnostics(program).filter( diagnostics = ts
({ code }): boolean => { .getPreEmitDiagnostics(program)
.filter(({ code }): boolean => {
// TS1103: 'for-await-of' statement is only allowed within an async // TS1103: 'for-await-of' statement is only allowed within an async
// function or async generator. // function or async generator.
if (code === 1103) return false; if (code === 1103) return false;
@ -692,8 +690,7 @@ window.compilerMain = function compilerMain(): void {
// so we will ignore complaints about this compiler setting. // so we will ignore complaints about this compiler setting.
if (code === 5070) return false; if (code === 5070) return false;
return true; return true;
} });
);
// We will only proceed with the emit if there are no diagnostics. // We will only proceed with the emit if there are no diagnostics.
if (diagnostics && diagnostics.length === 0) { if (diagnostics && diagnostics.length === 0) {

View file

@ -292,20 +292,18 @@ function createRawObjectString(
shouldShowClassName = true; shouldShowClassName = true;
} }
const keys = Object.keys(value); const keys = Object.keys(value);
const entries: string[] = keys.map( const entries: string[] = keys.map((key): string => {
(key): string => { if (keys.length > OBJ_ABBREVIATE_SIZE) {
if (keys.length > OBJ_ABBREVIATE_SIZE) { return key;
return key; } else {
} else { return `${key}: ${stringifyWithQuotes(
return `${key}: ${stringifyWithQuotes( value[key],
value[key], ctx,
ctx, level + 1,
level + 1, maxLevel
maxLevel )}`;
)}`;
}
} }
); });
ctx.delete(value); ctx.delete(value);
@ -640,43 +638,39 @@ export class Console {
let idx = 0; let idx = 0;
resultData = {}; resultData = {};
data.forEach( data.forEach((v: unknown, k: unknown): void => {
(v: unknown, k: unknown): void => { resultData[idx] = { Key: k, Values: v };
resultData[idx] = { Key: k, Values: v }; idx++;
idx++; });
}
);
} else { } else {
resultData = data!; resultData = data!;
} }
Object.keys(resultData).forEach( Object.keys(resultData).forEach((k, idx): void => {
(k, idx): void => { const value: unknown = resultData[k]!;
const value: unknown = resultData[k]!;
if (value !== null && typeof value === "object") { if (value !== null && typeof value === "object") {
Object.entries(value as { [key: string]: unknown }).forEach( Object.entries(value as { [key: string]: unknown }).forEach(
([k, v]): void => { ([k, v]): void => {
if (properties && !properties.includes(k)) { if (properties && !properties.includes(k)) {
return; return;
}
if (objectValues[k]) {
objectValues[k].push(stringifyValue(v));
} else {
objectValues[k] = createColumn(v, idx);
}
} }
);
values.push(""); if (objectValues[k]) {
} else { objectValues[k].push(stringifyValue(v));
values.push(stringifyValue(value)); } else {
} objectValues[k] = createColumn(v, idx);
}
}
);
indexKeys.push(k); values.push("");
} else {
values.push(stringifyValue(value));
} }
);
indexKeys.push(k);
});
const headerKeys = Object.keys(objectValues); const headerKeys = Object.keys(objectValues);
const bodyValues = Object.values(objectValues); const bodyValues = Object.values(objectValues);

View file

@ -72,8 +72,8 @@ export function cliTable(head: string[], columns: string[][]): string {
} }
} }
const divider = columnWidths.map( const divider = columnWidths.map((i: number): string =>
(i: number): string => tableChars.middleMiddle.repeat(i + 2) tableChars.middleMiddle.repeat(i + 2)
); );
let result = let result =

View file

@ -121,7 +121,12 @@ test(function consoleTestStringifyCircular(): void {
); );
assertEquals(stringify(new Set([1, 2, 3])), "Set { 1, 2, 3 }"); assertEquals(stringify(new Set([1, 2, 3])), "Set { 1, 2, 3 }");
assertEquals( assertEquals(
stringify(new Map([[1, "one"], [2, "two"]])), stringify(
new Map([
[1, "one"],
[2, "two"]
])
),
`Map { 1 => "one", 2 => "two" }` `Map { 1 => "one", 2 => "two" }`
); );
assertEquals(stringify(new WeakSet()), "WeakSet { [items unknown] }"); assertEquals(stringify(new WeakSet()), "WeakSet { [items unknown] }");
@ -130,12 +135,18 @@ test(function consoleTestStringifyCircular(): void {
assertEquals(stringify(null), "null"); assertEquals(stringify(null), "null");
assertEquals(stringify(undefined), "undefined"); assertEquals(stringify(undefined), "undefined");
assertEquals(stringify(new Extended()), "Extended { a: 1, b: 2 }"); assertEquals(stringify(new Extended()), "Extended { a: 1, b: 2 }");
assertEquals(stringify(function f(): void {}), "[Function: f]"); assertEquals(
stringify(function f(): void {}),
"[Function: f]"
);
assertEquals( assertEquals(
stringify(async function af(): Promise<void> {}), stringify(async function af(): Promise<void> {}),
"[AsyncFunction: af]" "[AsyncFunction: af]"
); );
assertEquals(stringify(function* gf() {}), "[GeneratorFunction: gf]"); assertEquals(
stringify(function* gf() {}),
"[GeneratorFunction: gf]"
);
assertEquals( assertEquals(
stringify(async function* agf() {}), stringify(async function* agf() {}),
"[AsyncGeneratorFunction: agf]" "[AsyncGeneratorFunction: agf]"
@ -410,50 +421,47 @@ function mockConsole(f: ConsoleExamineFunc): void {
// console.group test // console.group test
test(function consoleGroup(): void { test(function consoleGroup(): void {
mockConsole( mockConsole((console, out): void => {
(console, out): void => { console.group("1");
console.group("1"); console.log("2");
console.log("2"); console.group("3");
console.group("3"); console.log("4");
console.log("4"); console.groupEnd();
console.groupEnd(); console.groupEnd();
console.groupEnd(); console.log("5");
console.log("5"); console.log("6");
console.log("6");
assertEquals( assertEquals(
out.toString(), out.toString(),
`1 `1
2 2
3 3
4 4
5 5
6 6
` `
); );
} });
);
}); });
// console.group with console.warn test // console.group with console.warn test
test(function consoleGroupWarn(): void { test(function consoleGroupWarn(): void {
mockConsole( mockConsole((console, _out, _err, both): void => {
(console, _out, _err, both): void => { console.warn("1");
console.warn("1"); console.group();
console.group(); console.warn("2");
console.warn("2"); console.group();
console.group(); console.warn("3");
console.warn("3"); console.groupEnd();
console.groupEnd(); console.warn("4");
console.warn("4"); console.groupEnd();
console.groupEnd(); console.warn("5");
console.warn("5");
console.warn("6"); console.warn("6");
console.warn("7"); console.warn("7");
assertEquals( assertEquals(
both.toString(), both.toString(),
`1 `1
2 2
3 3
4 4
@ -461,49 +469,43 @@ test(function consoleGroupWarn(): void {
6 6
7 7
` `
); );
} });
);
}); });
// console.table test // console.table test
test(function consoleTable(): void { test(function consoleTable(): void {
mockConsole( mockConsole((console, out): void => {
(console, out): void => { console.table({ a: "test", b: 1 });
console.table({ a: "test", b: 1 }); assertEquals(
assertEquals( out.toString(),
out.toString(), `┌─────────┬────────┐
`┌─────────┬────────┐
(index) Values (index) Values
a "test" a "test"
b 1 b 1
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table({ a: { b: 10 }, b: { b: 20, c: 30 } }, ["c"]);
(console, out): void => { assertEquals(
console.table({ a: { b: 10 }, b: { b: 20, c: 30 } }, ["c"]); out.toString(),
assertEquals( `┌─────────┬────┐
out.toString(),
`┌─────────┬────┐
(index) c (index) c
a a
b 30 b 30
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table([1, 2, [3, [4]], [5, 6], [[7], [8]]]);
(console, out): void => { assertEquals(
console.table([1, 2, [3, [4]], [5, 6], [[7], [8]]]); out.toString(),
assertEquals( `┌─────────┬───────┬───────┬────────┐
out.toString(),
`┌─────────┬───────┬───────┬────────┐
(index) 0 1 Values (index) 0 1 Values
0 1 0 1
@ -513,15 +515,13 @@ test(function consoleTable(): void {
4 [ 7 ] [ 8 ] 4 [ 7 ] [ 8 ]
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table(new Set([1, 2, 3, "test"]));
(console, out): void => { assertEquals(
console.table(new Set([1, 2, 3, "test"])); out.toString(),
assertEquals( `┌───────────────────┬────────┐
out.toString(),
`┌───────────────────┬────────┐
(iteration index) Values (iteration index) Values
0 1 0 1
@ -530,36 +530,37 @@ test(function consoleTable(): void {
3 "test" 3 "test"
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table(
(console, out): void => { new Map([
console.table(new Map([[1, "one"], [2, "two"]])); [1, "one"],
assertEquals( [2, "two"]
out.toString(), ])
`┌───────────────────┬─────┬────────┐ );
assertEquals(
out.toString(),
`┌───────────────────┬─────┬────────┐
(iteration index) Key Values (iteration index) Key Values
0 1 "one" 0 1 "one"
1 2 "two" 1 2 "two"
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table({
(console, out): void => { a: true,
console.table({ b: { c: { d: 10 }, e: [1, 2, [5, 6]] },
a: true, f: "test",
b: { c: { d: 10 }, e: [1, 2, [5, 6]] }, g: new Set([1, 2, 3, "test"]),
f: "test", h: new Map([[1, "one"]])
g: new Set([1, 2, 3, "test"]), });
h: new Map([[1, "one"]]) assertEquals(
}); out.toString(),
assertEquals( `┌─────────┬───────────┬───────────────────┬────────┐
out.toString(),
`┌─────────┬───────────┬───────────────────┬────────┐
(index) c e Values (index) c e Values
a true a true
@ -569,21 +570,19 @@ test(function consoleTable(): void {
h h
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table([
(console, out): void => { 1,
console.table([ "test",
1, false,
"test", { a: 10 },
false, ["test", { b: 20, c: "test" }]
{ a: 10 }, ]);
["test", { b: 20, c: "test" }] assertEquals(
]); out.toString(),
assertEquals( `┌─────────┬────────┬──────────────────────┬────┬────────┐
out.toString(),
`┌─────────┬────────┬──────────────────────┬────┬────────┐
(index) 0 1 a Values (index) 0 1 a Values
0 1 0 1
@ -593,67 +592,56 @@ test(function consoleTable(): void {
4 "test" { b: 20, c: "test" } 4 "test" { b: 20, c: "test" }
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table([]);
(console, out): void => { assertEquals(
console.table([]); out.toString(),
assertEquals( `┌─────────┐
out.toString(),
`┌─────────┐
(index) (index)
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table({});
(console, out): void => { assertEquals(
console.table({}); out.toString(),
assertEquals( `┌─────────┐
out.toString(),
`┌─────────┐
(index) (index)
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table(new Set());
(console, out): void => { assertEquals(
console.table(new Set()); out.toString(),
assertEquals( `┌───────────────────┐
out.toString(),
`┌───────────────────┐
(iteration index) (iteration index)
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table(new Map());
(console, out): void => { assertEquals(
console.table(new Map()); out.toString(),
assertEquals( `┌───────────────────┐
out.toString(),
`┌───────────────────┐
(iteration index) (iteration index)
` `
); );
} });
); mockConsole((console, out): void => {
mockConsole( console.table("test");
(console, out): void => { assertEquals(out.toString(), "test\n");
console.table("test"); });
assertEquals(out.toString(), "test\n");
}
);
}); });
// console.log(Error) test // console.log(Error) test
@ -668,52 +656,40 @@ test(function consoleLogShouldNotThrowError(): void {
assertEquals(result, 1); assertEquals(result, 1);
// output errors to the console should not include "Uncaught" // output errors to the console should not include "Uncaught"
mockConsole( mockConsole((console, out): void => {
(console, out): void => { console.log(new Error("foo"));
console.log(new Error("foo")); assertEquals(out.toString().includes("Uncaught"), false);
assertEquals(out.toString().includes("Uncaught"), false); });
}
);
}); });
// console.dir test // console.dir test
test(function consoleDir(): void { test(function consoleDir(): void {
mockConsole( mockConsole((console, out): void => {
(console, out): void => { console.dir("DIR");
console.dir("DIR"); assertEquals(out.toString(), "DIR\n");
assertEquals(out.toString(), "DIR\n"); });
} mockConsole((console, out): void => {
); console.dir("DIR", { indentLevel: 2 });
mockConsole( assertEquals(out.toString(), " DIR\n");
(console, out): void => { });
console.dir("DIR", { indentLevel: 2 });
assertEquals(out.toString(), " DIR\n");
}
);
}); });
// console.dir test // console.dir test
test(function consoleDirXml(): void { test(function consoleDirXml(): void {
mockConsole( mockConsole((console, out): void => {
(console, out): void => { console.dirxml("DIRXML");
console.dirxml("DIRXML"); assertEquals(out.toString(), "DIRXML\n");
assertEquals(out.toString(), "DIRXML\n"); });
} mockConsole((console, out): void => {
); console.dirxml("DIRXML", { indentLevel: 2 });
mockConsole( assertEquals(out.toString(), " DIRXML\n");
(console, out): void => { });
console.dirxml("DIRXML", { indentLevel: 2 });
assertEquals(out.toString(), " DIRXML\n");
}
);
}); });
// console.trace test // console.trace test
test(function consoleTrace(): void { test(function consoleTrace(): void {
mockConsole( mockConsole((console, _out, err): void => {
(console, _out, err): void => { console.trace("%s", "custom message");
console.trace("%s", "custom message"); assert(err.toString().includes("Trace: custom message"));
assert(err.toString().includes("Trace: custom message")); });
}
);
}); });

View file

@ -87,9 +87,7 @@ function fromDiagnosticCategory(
return DiagnosticCategory.Warning; return DiagnosticCategory.Warning;
default: default:
throw new Error( throw new Error(
`Unexpected DiagnosticCategory: "${category}"/"${ `Unexpected DiagnosticCategory: "${category}"/"${ts.DiagnosticCategory[category]}"`
ts.DiagnosticCategory[category]
}"`
); );
} }
} }

View file

@ -40,7 +40,7 @@ function unwrapResponse(res: JsonResponse): Ok {
throw new DenoError(res.err!.kind, res.err!.message); throw new DenoError(res.err!.kind, res.err!.message);
} }
util.assert(res.ok != null); util.assert(res.ok != null);
return res.ok!; return res.ok;
} }
export function asyncMsgFromRust(opId: number, resUi8: Uint8Array): void { export function asyncMsgFromRust(opId: number, resUi8: Uint8Array): void {
@ -50,7 +50,7 @@ export function asyncMsgFromRust(opId: number, resUi8: Uint8Array): void {
const promise = promiseTable.get(res.promiseId!); const promise = promiseTable.get(res.promiseId!);
util.assert(promise != null); util.assert(promise != null);
promiseTable.delete(res.promiseId!); promiseTable.delete(res.promiseId!);
promise!.resolve(res); promise.resolve(res);
} }
export function sendSync( export function sendSync(

View file

@ -18,11 +18,9 @@ const openErrorStackPattern = new RegExp(
testPerm({ read: true }, async function sendAsyncStackTrace(): Promise<void> { testPerm({ read: true }, async function sendAsyncStackTrace(): Promise<void> {
await Deno.open("nonexistent.txt") await Deno.open("nonexistent.txt")
.then(unreachable) .then(unreachable)
.catch( .catch((error): void => {
(error): void => { assertMatch(error.stack, openErrorStackPattern);
assertMatch(error.stack, openErrorStackPattern); });
}
);
}); });
test(async function malformedJsonControlBuffer(): Promise<void> { test(async function malformedJsonControlBuffer(): Promise<void> {

View file

@ -79,7 +79,8 @@ export function asyncMsgFromRust(opId: number, ui8: Uint8Array): void {
const { promiseId } = record; const { promiseId } = record;
const promise = promiseTableMin.get(promiseId); const promise = promiseTableMin.get(promiseId);
promiseTableMin.delete(promiseId); promiseTableMin.delete(promiseId);
promise!.resolve(record); util.assert(promise);
promise.resolve(record);
} }
export async function sendAsyncMinimal( export async function sendAsyncMinimal(

View file

@ -18,11 +18,9 @@ test(async function sendAsyncStackTrace(): Promise<void> {
const buf = new Uint8Array(10); const buf = new Uint8Array(10);
await Deno.read(10, "nonexistent.txt", buf) await Deno.read(10, "nonexistent.txt", buf)
.then(unreachable) .then(unreachable)
.catch( .catch((error): void => {
(error): void => { assertMatch(error.stack, readErrorStackPattern);
assertMatch(error.stack, readErrorStackPattern); });
}
);
}); });
test(async function malformedMinimalControlBuffer(): Promise<void> { test(async function malformedMinimalControlBuffer(): Promise<void> {
// @ts-ignore // @ts-ignore

View file

@ -27,7 +27,7 @@ export const eventTargetHasActivationBehavior: unique symbol = Symbol();
export class EventTarget implements domTypes.EventTarget { export class EventTarget implements domTypes.EventTarget {
public [domTypes.eventTargetHost]: domTypes.EventTarget | null = null; public [domTypes.eventTargetHost]: domTypes.EventTarget | null = null;
public [domTypes.eventTargetListeners]: { public [domTypes.eventTargetListeners]: {
[type in string]: domTypes.EventListener[] [type in string]: domTypes.EventListener[];
} = {}; } = {};
public [domTypes.eventTargetMode] = ""; public [domTypes.eventTargetMode] = "";
public [domTypes.eventTargetNodeType]: domTypes.NodeType = public [domTypes.eventTargetNodeType]: domTypes.NodeType =
@ -417,9 +417,7 @@ const eventTargetHelpers = {
} }
try { try {
if (listener.callback) { listener.handleEvent(eventImpl);
listener.handleEvent(eventImpl);
}
} catch (error) { } catch (error) {
throw new DenoError(ErrorKind.Interrupted, error.message); throw new DenoError(ErrorKind.Interrupted, error.message);
} }

View file

@ -188,19 +188,17 @@ class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser {
body body
.trim() .trim()
.split("&") .split("&")
.forEach( .forEach((bytes): void => {
(bytes): void => { if (bytes) {
if (bytes) { const split = bytes.split("=");
const split = bytes.split("="); const name = split.shift()!.replace(/\+/g, " ");
const name = split.shift()!.replace(/\+/g, " "); const value = split.join("=").replace(/\+/g, " ");
const value = split.join("=").replace(/\+/g, " "); formData.append(
formData.append( decodeURIComponent(name),
decodeURIComponent(name), decodeURIComponent(value)
decodeURIComponent(value) );
);
}
} }
); });
} catch (e) { } catch (e) {
throw new TypeError("Invalid form urlencoded format"); throw new TypeError("Invalid form urlencoded format");
} }

View file

@ -60,12 +60,10 @@ testPerm({ net: true }, async function fetchBlob(): Promise<void> {
testPerm({ net: true }, async function fetchBodyUsed(): Promise<void> { testPerm({ net: true }, async function fetchBodyUsed(): Promise<void> {
const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); const response = await fetch("http://localhost:4545/cli/tests/fixture.json");
assertEquals(response.bodyUsed, false); assertEquals(response.bodyUsed, false);
assertThrows( assertThrows((): void => {
(): void => { // Assigning to read-only property throws in the strict mode.
// Assigning to read-only property throws in the strict mode. response.bodyUsed = true;
response.bodyUsed = true; });
}
);
await response.blob(); await response.blob();
assertEquals(response.bodyUsed, true); assertEquals(response.bodyUsed, true);
}); });

View file

@ -82,20 +82,21 @@ test(function formDataSetEmptyBlobSuccess(): void {
}); });
test(function formDataParamsForEachSuccess(): void { test(function formDataParamsForEachSuccess(): void {
const init = [["a", "54"], ["b", "true"]]; const init = [
["a", "54"],
["b", "true"]
];
const formData = new FormData(); const formData = new FormData();
for (const [name, value] of init) { for (const [name, value] of init) {
formData.append(name, value); formData.append(name, value);
} }
let callNum = 0; let callNum = 0;
formData.forEach( formData.forEach((value, key, parent): void => {
(value, key, parent): void => { assertEquals(formData, parent);
assertEquals(formData, parent); assertEquals(value, init[callNum][1]);
assertEquals(value, init[callNum][1]); assertEquals(key, init[callNum][0]);
assertEquals(key, init[callNum][0]); callNum++;
callNum++; });
}
);
assertEquals(callNum, init.length); assertEquals(callNum, init.length);
}); });
@ -104,73 +105,69 @@ test(function formDataParamsArgumentsCheck(): void {
const methodRequireTwoParams = ["append", "set"]; const methodRequireTwoParams = ["append", "set"];
methodRequireOneParam.forEach( methodRequireOneParam.forEach((method): void => {
(method): void => { const formData = new FormData();
const formData = new FormData(); let hasThrown = 0;
let hasThrown = 0; let errMsg = "";
let errMsg = ""; try {
try { formData[method]();
formData[method](); hasThrown = 1;
hasThrown = 1; } catch (err) {
} catch (err) { errMsg = err.message;
errMsg = err.message; if (err instanceof TypeError) {
if (err instanceof TypeError) { hasThrown = 2;
hasThrown = 2; } else {
} else { hasThrown = 3;
hasThrown = 3;
}
} }
assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`FormData.${method} requires at least 1 argument, but only 0 present`
);
} }
); assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`FormData.${method} requires at least 1 argument, but only 0 present`
);
});
methodRequireTwoParams.forEach( methodRequireTwoParams.forEach((method: string): void => {
(method: string): void => { const formData = new FormData();
const formData = new FormData(); let hasThrown = 0;
let hasThrown = 0; let errMsg = "";
let errMsg = "";
try { try {
formData[method](); formData[method]();
hasThrown = 1; hasThrown = 1;
} catch (err) { } catch (err) {
errMsg = err.message; errMsg = err.message;
if (err instanceof TypeError) { if (err instanceof TypeError) {
hasThrown = 2; hasThrown = 2;
} else { } else {
hasThrown = 3; hasThrown = 3;
}
} }
assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`FormData.${method} requires at least 2 arguments, but only 0 present`
);
hasThrown = 0;
errMsg = "";
try {
formData[method]("foo");
hasThrown = 1;
} catch (err) {
errMsg = err.message;
if (err instanceof TypeError) {
hasThrown = 2;
} else {
hasThrown = 3;
}
}
assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`FormData.${method} requires at least 2 arguments, but only 1 present`
);
} }
); assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`FormData.${method} requires at least 2 arguments, but only 0 present`
);
hasThrown = 0;
errMsg = "";
try {
formData[method]("foo");
hasThrown = 1;
} catch (err) {
errMsg = err.message;
if (err instanceof TypeError) {
hasThrown = 2;
} else {
hasThrown = 3;
}
}
assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`FormData.${method} requires at least 2 arguments, but only 1 present`
);
});
}); });
test(function toStringShouldBeWebCompatibility(): void { test(function toStringShouldBeWebCompatibility(): void {

View file

@ -162,25 +162,19 @@ window.removeEventListener =
eventTarget.EventTarget.prototype.removeEventListener; eventTarget.EventTarget.prototype.removeEventListener;
// Registers the handler for window.onload function. // Registers the handler for window.onload function.
window.addEventListener( window.addEventListener("load", (e: domTypes.Event): void => {
"load", const onload = window.onload;
(e: domTypes.Event): void => { if (typeof onload === "function") {
const onload = window.onload; onload(e);
if (typeof onload === "function") {
onload(e);
}
} }
); });
// Registers the handler for window.onunload function. // Registers the handler for window.onunload function.
window.addEventListener( window.addEventListener("unload", (e: domTypes.Event): void => {
"unload", const onunload = window.onunload;
(e: domTypes.Event): void => { if (typeof onunload === "function") {
const onunload = window.onunload; onunload(e);
if (typeof onunload === "function") {
onunload(e);
}
} }
); });
// below are interfaces that are available in TypeScript but // below are interfaces that are available in TypeScript but
// have different signatures // have different signatures

View file

@ -81,22 +81,18 @@ test(async function windowQueueMicrotask(): Promise<void> {
let resolve1: () => void | undefined; let resolve1: () => void | undefined;
let resolve2: () => void | undefined; let resolve2: () => void | undefined;
let microtaskDone = false; let microtaskDone = false;
const p1 = new Promise( const p1 = new Promise((res): void => {
(res): void => { resolve1 = (): void => {
resolve1 = (): void => { microtaskDone = true;
microtaskDone = true; res();
res(); };
}; });
} const p2 = new Promise((res): void => {
); resolve2 = (): void => {
const p2 = new Promise( assert(microtaskDone);
(res): void => { res();
resolve2 = (): void => { };
assert(microtaskDone); });
res();
};
}
);
window.queueMicrotask(resolve1!); window.queueMicrotask(resolve1!);
setTimeout(resolve2!, 0); setTimeout(resolve2!, 0);
await p1; await p1;

View file

@ -145,21 +145,17 @@ const headerEntriesDict = {
test(function headerForEachSuccess(): void { test(function headerForEachSuccess(): void {
const headers = new Headers(headerEntriesDict); const headers = new Headers(headerEntriesDict);
const keys = Object.keys(headerEntriesDict); const keys = Object.keys(headerEntriesDict);
keys.forEach( keys.forEach((key): void => {
(key): void => { const value = headerEntriesDict[key];
const value = headerEntriesDict[key]; const newkey = key.toLowerCase();
const newkey = key.toLowerCase(); headerEntriesDict[newkey] = value;
headerEntriesDict[newkey] = value; });
}
);
let callNum = 0; let callNum = 0;
headers.forEach( headers.forEach((value, key, container): void => {
(value, key, container): void => { assertEquals(headers, container);
assertEquals(headers, container); assertEquals(value, headerEntriesDict[key]);
assertEquals(value, headerEntriesDict[key]); callNum++;
callNum++; });
}
);
assertEquals(callNum, keys.length); assertEquals(callNum, keys.length);
}); });
@ -260,73 +256,69 @@ test(function headerParamsArgumentsCheck(): void {
const methodRequireTwoParams = ["append", "set"]; const methodRequireTwoParams = ["append", "set"];
methodRequireOneParam.forEach( methodRequireOneParam.forEach((method): void => {
(method): void => { const headers = new Headers();
const headers = new Headers(); let hasThrown = 0;
let hasThrown = 0; let errMsg = "";
let errMsg = ""; try {
try { headers[method]();
headers[method](); hasThrown = 1;
hasThrown = 1; } catch (err) {
} catch (err) { errMsg = err.message;
errMsg = err.message; if (err instanceof TypeError) {
if (err instanceof TypeError) { hasThrown = 2;
hasThrown = 2; } else {
} else { hasThrown = 3;
hasThrown = 3;
}
} }
assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`Headers.${method} requires at least 1 argument, but only 0 present`
);
} }
); assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`Headers.${method} requires at least 1 argument, but only 0 present`
);
});
methodRequireTwoParams.forEach( methodRequireTwoParams.forEach((method): void => {
(method): void => { const headers = new Headers();
const headers = new Headers(); let hasThrown = 0;
let hasThrown = 0; let errMsg = "";
let errMsg = "";
try { try {
headers[method](); headers[method]();
hasThrown = 1; hasThrown = 1;
} catch (err) { } catch (err) {
errMsg = err.message; errMsg = err.message;
if (err instanceof TypeError) { if (err instanceof TypeError) {
hasThrown = 2; hasThrown = 2;
} else { } else {
hasThrown = 3; hasThrown = 3;
}
} }
assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`Headers.${method} requires at least 2 arguments, but only 0 present`
);
hasThrown = 0;
errMsg = "";
try {
headers[method]("foo");
hasThrown = 1;
} catch (err) {
errMsg = err.message;
if (err instanceof TypeError) {
hasThrown = 2;
} else {
hasThrown = 3;
}
}
assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`Headers.${method} requires at least 2 arguments, but only 1 present`
);
} }
); assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`Headers.${method} requires at least 2 arguments, but only 0 present`
);
hasThrown = 0;
errMsg = "";
try {
headers[method]("foo");
hasThrown = 1;
} catch (err) {
errMsg = err.message;
if (err instanceof TypeError) {
hasThrown = 2;
} else {
hasThrown = 3;
}
}
assertEquals(hasThrown, 2);
assertEquals(
errMsg,
`Headers.${method} requires at least 2 arguments, but only 1 present`
);
});
}); });
test(function toStringShouldBeWebCompatibility(): void { test(function toStringShouldBeWebCompatibility(): void {

View file

@ -2268,7 +2268,7 @@ declare namespace eventTarget {
export class EventTarget implements domTypes.EventTarget { export class EventTarget implements domTypes.EventTarget {
[domTypes.eventTargetHost]: domTypes.EventTarget | null; [domTypes.eventTargetHost]: domTypes.EventTarget | null;
[domTypes.eventTargetListeners]: { [domTypes.eventTargetListeners]: {
[type in string]: domTypes.EventListener[] [type in string]: domTypes.EventListener[];
}; };
[domTypes.eventTargetMode]: string; [domTypes.eventTargetMode]: string;
[domTypes.eventTargetNodeType]: domTypes.NodeType; [domTypes.eventTargetNodeType]: domTypes.NodeType;

View file

@ -28,7 +28,10 @@ function setup() {
test(function testDomIterable(): void { test(function testDomIterable(): void {
const { DomIterable, Base } = setup(); const { DomIterable, Base } = setup();
const fixture: Array<[string, number]> = [["foo", 1], ["bar", 2]]; const fixture: Array<[string, number]> = [
["foo", 1],
["bar", 2]
];
const domIterable = new DomIterable(fixture); const domIterable = new DomIterable(fixture);

View file

@ -39,10 +39,8 @@ testPerm({ read: true }, async function resourcesFile(): Promise<void> {
Object.keys(resourcesAfter).length, Object.keys(resourcesAfter).length,
Object.keys(resourcesBefore).length + 1 Object.keys(resourcesBefore).length + 1
); );
const newRid = Object.keys(resourcesAfter).find( const newRid = Object.keys(resourcesAfter).find((rid): boolean => {
(rid): boolean => { return !resourcesBefore.hasOwnProperty(rid);
return !resourcesBefore.hasOwnProperty(rid); });
}
);
assertEquals(resourcesAfter[newRid], "fsFile"); assertEquals(resourcesAfter[newRid], "fsFile");
}); });

View file

@ -295,14 +295,18 @@ export function readableStreamTee<OutputType>(
.then(({ value, done }) => { .then(({ value, done }) => {
if (done && !closedOrErrored) { if (done && !closedOrErrored) {
if (!canceled1) { if (!canceled1) {
rs.readableStreamDefaultControllerClose(branch1![ rs.readableStreamDefaultControllerClose(
rs.readableStreamController_ branch1![
] as ReadableStreamDefaultController<OutputType>); rs.readableStreamController_
] as ReadableStreamDefaultController<OutputType>
);
} }
if (!canceled2) { if (!canceled2) {
rs.readableStreamDefaultControllerClose(branch2![ rs.readableStreamDefaultControllerClose(
rs.readableStreamController_ branch2![
] as ReadableStreamDefaultController<OutputType>); rs.readableStreamController_
] as ReadableStreamDefaultController<OutputType>
);
} }
closedOrErrored = true; closedOrErrored = true;
} }

View file

@ -9,12 +9,10 @@ function deferred(): {
} { } {
let resolve; let resolve;
let reject; let reject;
const promise = new Promise( const promise = new Promise((res, rej): void => {
(res, rej): void => { resolve = res;
resolve = res; reject = rej;
reject = rej; });
}
);
return { return {
promise, promise,
resolve, resolve,

View file

@ -185,9 +185,6 @@ testPerm({ read: true, net: true }, async function dialAndListenTLS(): Promise<
const tpr = new TextProtoReader(r); const tpr = new TextProtoReader(r);
const statusLine = await tpr.readLine(); const statusLine = await tpr.readLine();
assert(statusLine !== Deno.EOF, `line must be read: ${String(statusLine)}`); assert(statusLine !== Deno.EOF, `line must be read: ${String(statusLine)}`);
if (statusLine === Deno.EOF) {
return;
}
const m = statusLine.match(/^(.+?) (.+?) (.+?)$/); const m = statusLine.match(/^(.+?) (.+?) (.+?)$/);
assert(m !== null, "must be matched"); assert(m !== null, "must be matched");
const [_, proto, status, ok] = m; const [_, proto, status, ok] = m;
@ -196,9 +193,6 @@ testPerm({ read: true, net: true }, async function dialAndListenTLS(): Promise<
assertEquals(ok, "OK"); assertEquals(ok, "OK");
const headers = await tpr.readMIMEHeader(); const headers = await tpr.readMIMEHeader();
assert(headers !== Deno.EOF); assert(headers !== Deno.EOF);
if (headers === Deno.EOF) {
return;
}
const contentLength = parseInt(headers.get("content-length")); const contentLength = parseInt(headers.get("content-length"));
const bodyBuf = new Uint8Array(contentLength); const bodyBuf = new Uint8Array(contentLength);
await r.readFull(bodyBuf); await r.readFull(bodyBuf);

View file

@ -15,17 +15,15 @@ interface TestResult {
function permsToCliFlags(perms: Permissions): string[] { function permsToCliFlags(perms: Permissions): string[] {
return Object.keys(perms) return Object.keys(perms)
.map( .map((key): string => {
(key): string => { if (!perms[key]) return "";
if (!perms[key]) return "";
const cliFlag = key.replace( const cliFlag = key.replace(
/\.?([A-Z])/g, /\.?([A-Z])/g,
(x, y): string => `-${y.toLowerCase()}` (x, y): string => `-${y.toLowerCase()}`
); );
return `--allow-${cliFlag}`; return `--allow-${cliFlag}`;
} })
)
.filter((e): boolean => e.length > 0); .filter((e): boolean => e.length > 0);
} }

View file

@ -29,9 +29,7 @@ const patterns = {
}; };
const urlRegExp = new RegExp( const urlRegExp = new RegExp(
`^${patterns.protocol}?${patterns.authority}?${patterns.path}${ `^${patterns.protocol}?${patterns.authority}?${patterns.path}${patterns.query}?${patterns.hash}?`
patterns.query
}?${patterns.hash}?`
); );
const authorityRegExp = new RegExp( const authorityRegExp = new RegExp(
@ -70,11 +68,9 @@ function parse(url: string): URLParts | undefined {
// Based on https://github.com/kelektiv/node-uuid // Based on https://github.com/kelektiv/node-uuid
// TODO(kevinkassimo): Use deno_std version once possible. // TODO(kevinkassimo): Use deno_std version once possible.
function generateUUID(): string { function generateUUID(): string {
return "00000000-0000-4000-8000-000000000000".replace( return "00000000-0000-4000-8000-000000000000".replace(/[0]/g, (): string =>
/[0]/g, // random integer from 0 to 15 as a hex digit.
(): string => (getRandomValues(new Uint8Array(1))[0] % 16).toString(16)
// random integer from 0 to 15 as a hex digit.
(getRandomValues(new Uint8Array(1))[0] % 16).toString(16)
); );
} }
@ -232,9 +228,7 @@ export class URL {
if (this.host || this.protocol === "file:") { if (this.host || this.protocol === "file:") {
slash = "//"; slash = "//";
} }
return `${this.protocol}${slash}${authentication}${this.host}${ return `${this.protocol}${slash}${authentication}${this.host}${this.pathname}${this.search}${this.hash}`;
this.pathname
}${this.search}${this.hash}`;
} }
set href(value: string) { set href(value: string) {

View file

@ -168,8 +168,8 @@ export class URLSearchParams {
* searchParams.sort(); * searchParams.sort();
*/ */
sort(): void { sort(): void {
this.params = this.params.sort( this.params = this.params.sort((a, b): number =>
(a, b): number => (a[0] === b[0] ? 0 : a[0] > b[0] ? 1 : -1) a[0] === b[0] ? 0 : a[0] > b[0] ? 1 : -1
); );
this.updateSteps(); this.updateSteps();
} }

View file

@ -11,7 +11,10 @@ test(function urlSearchParamsInitString(): void {
}); });
test(function urlSearchParamsInitIterable(): void { test(function urlSearchParamsInitIterable(): void {
const init = [["a", "54"], ["b", "true"]]; const init = [
["a", "54"],
["b", "true"]
];
const searchParams = new URLSearchParams(init); const searchParams = new URLSearchParams(init);
assertEquals(searchParams.toString(), "a=54&b=true"); assertEquals(searchParams.toString(), "a=54&b=true");
}); });
@ -89,17 +92,18 @@ test(function urlSearchParamsSortSuccess(): void {
}); });
test(function urlSearchParamsForEachSuccess(): void { test(function urlSearchParamsForEachSuccess(): void {
const init = [["a", "54"], ["b", "true"]]; const init = [
["a", "54"],
["b", "true"]
];
const searchParams = new URLSearchParams(init); const searchParams = new URLSearchParams(init);
let callNum = 0; let callNum = 0;
searchParams.forEach( searchParams.forEach((value, key, parent): void => {
(value, key, parent): void => { assertEquals(searchParams, parent);
assertEquals(searchParams, parent); assertEquals(value, init[callNum][1]);
assertEquals(value, init[callNum][1]); assertEquals(key, init[callNum][0]);
assertEquals(key, init[callNum][0]); callNum++;
callNum++; });
}
);
assertEquals(callNum, init.length); assertEquals(callNum, init.length);
}); });
@ -167,8 +171,9 @@ test(function urlSearchParamsAppendArgumentsCheck(): void {
const methodRequireTwoParams = ["append", "set"]; const methodRequireTwoParams = ["append", "set"];
methodRequireOneParam.concat(methodRequireTwoParams).forEach( methodRequireOneParam
(method: string): void => { .concat(methodRequireTwoParams)
.forEach((method: string): void => {
const searchParams = new URLSearchParams(); const searchParams = new URLSearchParams();
let hasThrown = 0; let hasThrown = 0;
try { try {
@ -182,26 +187,23 @@ test(function urlSearchParamsAppendArgumentsCheck(): void {
} }
} }
assertEquals(hasThrown, 2); assertEquals(hasThrown, 2);
} });
);
methodRequireTwoParams.forEach( methodRequireTwoParams.forEach((method: string): void => {
(method: string): void => { const searchParams = new URLSearchParams();
const searchParams = new URLSearchParams(); let hasThrown = 0;
let hasThrown = 0; try {
try { searchParams[method]("foo");
searchParams[method]("foo"); hasThrown = 1;
hasThrown = 1; } catch (err) {
} catch (err) { if (err instanceof TypeError) {
if (err instanceof TypeError) { hasThrown = 2;
hasThrown = 2; } else {
} else { hasThrown = 3;
hasThrown = 3;
}
} }
assertEquals(hasThrown, 2);
} }
); assertEquals(hasThrown, 2);
});
}); });
// ref: https://github.com/web-platform-tests/wpt/blob/master/url/urlsearchparams-delete.any.js // ref: https://github.com/web-platform-tests/wpt/blob/master/url/urlsearchparams-delete.any.js

View file

@ -26,7 +26,7 @@ export function log(...args: unknown[]): void {
} }
// @internal // @internal
export function assert(cond: boolean, msg = "assert"): void { export function assert(cond: unknown, msg = "assert"): asserts cond {
if (!cond) { if (!cond) {
throw Error(msg); throw Error(msg);
} }
@ -74,11 +74,9 @@ export type Resolvable<T> = Promise<T> & ResolvableMethods<T>;
// @internal // @internal
export function createResolvable<T>(): Resolvable<T> { export function createResolvable<T>(): Resolvable<T> {
let methods: ResolvableMethods<T>; let methods: ResolvableMethods<T>;
const promise = new Promise<T>( const promise = new Promise<T>((resolve, reject): void => {
(resolve, reject): void => { methods = { resolve, reject };
methods = { resolve, reject }; });
}
);
// TypeScript doesn't know that the Promise callback occurs synchronously // TypeScript doesn't know that the Promise callback occurs synchronously
// therefore use of not null assertion (`!`) // therefore use of not null assertion (`!`)
return Object.assign(promise, methods!) as Resolvable<T>; return Object.assign(promise, methods!) as Resolvable<T>;
@ -97,12 +95,9 @@ export function unreachable(): never {
// @internal // @internal
export function hexdump(u8: Uint8Array): string { export function hexdump(u8: Uint8Array): string {
return Array.prototype.map return Array.prototype.map
.call( .call(u8, (x: number): string => {
u8, return ("00" + x.toString(16)).slice(-2);
(x: number): string => { })
return ("00" + x.toString(16)).slice(-2);
}
)
.join(" "); .join(" ");
} }

View file

@ -160,11 +160,9 @@ export class WorkerImpl implements Worker {
); );
this.run(); this.run();
this.isClosedPromise = hostGetWorkerClosed(this.id); this.isClosedPromise = hostGetWorkerClosed(this.id);
this.isClosedPromise.then( this.isClosedPromise.then((): void => {
(): void => { this.isClosing = true;
this.isClosing = true; });
}
);
} }
get closed(): Promise<void> { get closed(): Promise<void> {

View file

@ -1,11 +1,9 @@
// Check that we can use the async keyword. // Check that we can use the async keyword.
async function main(): Promise<void> { async function main(): Promise<void> {
await new Promise( await new Promise((resolve): void => {
(resolve): void => { console.log("2");
console.log("2"); setTimeout(resolve, 100);
setTimeout(resolve, 100); });
}
);
console.log("3"); console.log("3");
} }

View file

@ -1,5 +1,3 @@
Deno.args.forEach( Deno.args.forEach((arg): void => {
(arg): void => { console.log(arg);
console.log(arg); });
}
);

View file

@ -1,13 +1,6 @@
[WILDCARD]error TS2322: Type '{ a: { b: { c(): { d: number; }; }; }; }' is not assignable to type '{ a: { b: { c(): { d: string; }; }; }; }'. [WILDCARD]error TS2322: Type '{ a: { b: { c(): { d: number; }; }; }; }' is not assignable to type '{ a: { b: { c(): { d: string; }; }; }; }'.
Types of property 'a' are incompatible. The types of 'a.b.c().d' are incompatible between these types.
Type '{ b: { c(): { d: number; }; }; }' is not assignable to type '{ b: { c(): { d: string; }; }; }'. Type 'number' is not assignable to type 'string'.
Types of property 'b' are incompatible.
Type '{ c(): { d: number; }; }' is not assignable to type '{ c(): { d: string; }; }'.
Types of property 'c' are incompatible.
Type '() => { d: number; }' is not assignable to type '() => { d: string; }'.
Type '{ d: number; }' is not assignable to type '{ d: string; }'.
Types of property 'd' are incompatible.
Type 'number' is not assignable to type 'string'.
[WILDCARD]/tests/error_003_typescript.ts:20:1 [WILDCARD]/tests/error_003_typescript.ts:20:1

View file

@ -362,13 +362,11 @@ itest!(lock_check_ok {
http_server: true, http_server: true,
}); });
/* TODO(ry) Re-enable this test. It is flaky and only fails occasionally.
itest!(lock_check_ok2 { itest!(lock_check_ok2 {
args: "run 019_media_types.ts --lock=lock_check_ok2.json", args: "run 019_media_types.ts --lock=lock_check_ok2.json",
output: "019_media_types.ts.out", output: "019_media_types.ts.out",
http_server: true, http_server: true,
}); });
*/
itest!(lock_check_err { itest!(lock_check_err {
args: "run --lock=lock_check_err.json http://127.0.0.1:4545/cli/tests/003_relative_import.ts", args: "run --lock=lock_check_err.json http://127.0.0.1:4545/cli/tests/003_relative_import.ts",

View file

@ -15,11 +15,9 @@ export type Resolvable<T> = Promise<T> & ResolvableMethods<T>;
export function createResolvable<T>(): Resolvable<T> { export function createResolvable<T>(): Resolvable<T> {
let methods: ResolvableMethods<T>; let methods: ResolvableMethods<T>;
const promise = new Promise<T>( const promise = new Promise<T>((resolve, reject): void => {
(resolve, reject): void => { methods = { resolve, reject };
methods = { resolve, reject }; });
}
);
// TypeScript doesn't know that the Promise callback occurs synchronously // TypeScript doesn't know that the Promise callback occurs synchronously
// therefore use of not null assertion (`!`) // therefore use of not null assertion (`!`)
return Object.assign(promise, methods!) as Resolvable<T>; return Object.assign(promise, methods!) as Resolvable<T>;
@ -40,13 +38,11 @@ async function main(): Promise<void> {
const workers: Array<[Map<number, Resolvable<string>>, Worker]> = []; const workers: Array<[Map<number, Resolvable<string>>, Worker]> = [];
for (let i = 1; i <= workerCount; ++i) { for (let i = 1; i <= workerCount; ++i) {
const worker = new Worker("./subdir/bench_worker.ts"); const worker = new Worker("./subdir/bench_worker.ts");
const promise = new Promise( const promise = new Promise((resolve): void => {
(resolve): void => { worker.onmessage = (e): void => {
worker.onmessage = (e): void => { if (e.data.cmdId === 0) resolve();
if (e.data.cmdId === 0) resolve(); };
}; });
}
);
worker.postMessage({ cmdId: 0, action: 2 }); worker.postMessage({ cmdId: 0, action: 2 });
await promise; await promise;
workers.push([new Map(), worker]); workers.push([new Map(), worker]);

View file

@ -5,13 +5,11 @@ async function bench(): Promise<void> {
const workers: Worker[] = []; const workers: Worker[] = [];
for (let i = 1; i <= workerCount; ++i) { for (let i = 1; i <= workerCount; ++i) {
const worker = new Worker("./subdir/bench_worker.ts"); const worker = new Worker("./subdir/bench_worker.ts");
const promise = new Promise( const promise = new Promise((resolve): void => {
(resolve): void => { worker.onmessage = (e): void => {
worker.onmessage = (e): void => { if (e.data.cmdId === 0) resolve();
if (e.data.cmdId === 0) resolve(); };
}; });
}
);
worker.postMessage({ cmdId: 0, action: 2 }); worker.postMessage({ cmdId: 0, action: 2 });
await promise; await promise;
workers.push(worker); workers.push(worker);

@ -1 +1 @@
Subproject commit b3fe5cb48e9399765ec103ca0c14057f77cf9fc3 Subproject commit 6af664c48ed657b89e99a9a8692dc15d7f7a6d9c

View file

@ -67,6 +67,7 @@ function unreachable() {
/** /**
* @param {unknown} cond * @param {unknown} cond
* @returns {asserts cond}
*/ */
function assert(cond) { function assert(cond) {
if (!cond) { if (!cond) {

View file

@ -257,6 +257,7 @@ pub fn get_asset(name: &str) -> Option<&'static str> {
"lib.deno_core.d.ts" => Some(include_str!("lib.deno_core.d.ts")), "lib.deno_core.d.ts" => Some(include_str!("lib.deno_core.d.ts")),
"typescript.d.ts" => inc!("typescript.d.ts"), "typescript.d.ts" => inc!("typescript.d.ts"),
"lib.esnext.d.ts" => inc!("lib.esnext.d.ts"), "lib.esnext.d.ts" => inc!("lib.esnext.d.ts"),
"lib.es2020.d.ts" => inc!("lib.es2020.d.ts"),
"lib.es2019.d.ts" => inc!("lib.es2019.d.ts"), "lib.es2019.d.ts" => inc!("lib.es2019.d.ts"),
"lib.es2018.d.ts" => inc!("lib.es2018.d.ts"), "lib.es2018.d.ts" => inc!("lib.es2018.d.ts"),
"lib.es2017.d.ts" => inc!("lib.es2017.d.ts"), "lib.es2017.d.ts" => inc!("lib.es2017.d.ts"),
@ -289,8 +290,15 @@ pub fn get_asset(name: &str) -> Option<&'static str> {
"lib.es2019.object.d.ts" => inc!("lib.es2019.object.d.ts"), "lib.es2019.object.d.ts" => inc!("lib.es2019.object.d.ts"),
"lib.es2019.string.d.ts" => inc!("lib.es2019.string.d.ts"), "lib.es2019.string.d.ts" => inc!("lib.es2019.string.d.ts"),
"lib.es2019.symbol.d.ts" => inc!("lib.es2019.symbol.d.ts"), "lib.es2019.symbol.d.ts" => inc!("lib.es2019.symbol.d.ts"),
"lib.es2020.string.d.ts" => inc!("lib.es2020.string.d.ts"),
"lib.es2020.symbol.wellknown.d.ts" => {
inc!("lib.es2020.symbol.wellknown.d.ts")
}
"lib.esnext.array.d.ts" => inc!("lib.esnext.array.d.ts"),
"lib.esnext.asynciterable.d.ts" => inc!("lib.esnext.asynciterable.d.ts"),
"lib.esnext.bigint.d.ts" => inc!("lib.esnext.bigint.d.ts"), "lib.esnext.bigint.d.ts" => inc!("lib.esnext.bigint.d.ts"),
"lib.esnext.intl.d.ts" => inc!("lib.esnext.intl.d.ts"), "lib.esnext.intl.d.ts" => inc!("lib.esnext.intl.d.ts"),
"lib.esnext.symbol.d.ts" => inc!("lib.esnext.symbol.d.ts"),
_ => None, _ => None,
} }
} }

@ -1 +1 @@
Subproject commit 26655db1dd04d93217002ac87f950aba812c53eb Subproject commit 7cf6c70d90b60e962db417d80290288eb786b5fd

View file

@ -384,28 +384,26 @@ export class Tar {
*/ */
getReader(): Deno.Reader { getReader(): Deno.Reader {
const readers: Deno.Reader[] = []; const readers: Deno.Reader[] = [];
this.data.forEach( this.data.forEach((tarData): void => {
(tarData): void => { let { reader } = tarData;
let { reader } = tarData; const { filePath } = tarData;
const { filePath } = tarData; const headerArr = formatHeader(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!);
}
readers.push(reader);
// to the nearest multiple of recordSize
readers.push(
new Deno.Buffer(
clean(
recordSize -
(parseInt(tarData.fileSize!, 8) % recordSize || recordSize)
)
)
);
} }
); readers.push(reader);
// to the nearest multiple of recordSize
readers.push(
new Deno.Buffer(
clean(
recordSize -
(parseInt(tarData.fileSize!, 8) % recordSize || recordSize)
)
)
);
});
// append 2 empty records // append 2 empty records
readers.push(new Deno.Buffer(clean(recordSize * 2))); readers.push(new Deno.Buffer(clean(recordSize * 2)));
@ -462,22 +460,18 @@ export class Untar {
"mtime", "mtime",
"uid", "uid",
"gid" "gid"
]).forEach( ]).forEach((key): void => {
(key): void => { const arr = trim(header[key]);
const arr = trim(header[key]); if (arr.byteLength > 0) {
if (arr.byteLength > 0) { meta[key] = parseInt(decoder.decode(arr), 8);
meta[key] = parseInt(decoder.decode(arr), 8);
}
} }
); });
(["owner", "group"] as ["owner", "group"]).forEach( (["owner", "group"] as ["owner", "group"]).forEach((key): void => {
(key): void => { const arr = trim(header[key]);
const arr = trim(header[key]); if (arr.byteLength > 0) {
if (arr.byteLength > 0) { meta[key] = decoder.decode(arr);
meta[key] = decoder.decode(arr);
}
} }
); });
// read the file content // read the file content
const len = parseInt(decoder.decode(header.fileSize), 8); const len = parseInt(decoder.decode(header.fileSize), 8);

View file

@ -84,25 +84,23 @@ async function read(
result = line.split(opt.comma!); result = line.split(opt.comma!);
let quoteError = false; let quoteError = false;
result = result.map( result = result.map((r): string => {
(r): string => { if (opt.trimLeadingSpace) {
if (opt.trimLeadingSpace) { r = r.trimLeft();
r = r.trimLeft();
}
if (r[0] === '"' && r[r.length - 1] === '"') {
r = r.substring(1, r.length - 1);
} else if (r[0] === '"') {
r = r.substring(1, r.length);
}
if (!opt.lazyQuotes) {
if (r[0] !== '"' && r.indexOf('"') !== -1) {
quoteError = true;
}
}
return r;
} }
); if (r[0] === '"' && r[r.length - 1] === '"') {
r = r.substring(1, r.length - 1);
} else if (r[0] === '"') {
r = r.substring(1, r.length);
}
if (!opt.lazyQuotes) {
if (r[0] !== '"' && r.indexOf('"') !== -1) {
quoteError = true;
}
}
return r;
});
if (quoteError) { if (quoteError) {
throw new ParseError(Startline, lineIndex, 'bare " in non-quoted-field'); throw new ParseError(Startline, lineIndex, 'bare " in non-quoted-field');
} }
@ -226,27 +224,25 @@ export async function parse(
); );
i++; i++;
} }
return r.map( return r.map((e): unknown => {
(e): unknown => { if (e.length !== headers.length) {
if (e.length !== headers.length) { throw `Error number of fields line:${i}`;
throw `Error number of fields line:${i}`;
}
i++;
const out: Record<string, unknown> = {};
for (let j = 0; j < e.length; j++) {
const h = headers[j];
if (h.parse) {
out[h.name] = h.parse(e[j]);
} else {
out[h.name] = e[j];
}
}
if (opt.parse) {
return opt.parse(out);
}
return out;
} }
); i++;
const out: Record<string, unknown> = {};
for (let j = 0; j < e.length; j++) {
const h = headers[j];
if (h.parse) {
out[h.name] = h.parse(e[j]);
} else {
out[h.name] = e[j];
}
}
if (opt.parse) {
return opt.parse(out);
}
return out;
});
} }
if (opt.parse) { if (opt.parse) {
return r.map((e: string[]): unknown => opt.parse!(e)); return r.map((e: string[]): unknown => opt.parse!(e));

View file

@ -20,7 +20,10 @@ const testCases = [
{ {
Name: "CRLF", Name: "CRLF",
Input: "a,b\r\nc,d\r\n", Input: "a,b\r\nc,d\r\n",
Output: [["a", "b"], ["c", "d"]] Output: [
["a", "b"],
["c", "d"]
]
}, },
{ {
Name: "BareCR", Name: "BareCR",
@ -64,12 +67,18 @@ const testCases = [
{ {
Name: "BlankLine", Name: "BlankLine",
Input: "a,b,c\n\nd,e,f\n\n", Input: "a,b,c\n\nd,e,f\n\n",
Output: [["a", "b", "c"], ["d", "e", "f"]] Output: [
["a", "b", "c"],
["d", "e", "f"]
]
}, },
{ {
Name: "BlankLineFieldCount", Name: "BlankLineFieldCount",
Input: "a,b,c\n\nd,e,f\n\n", Input: "a,b,c\n\nd,e,f\n\n",
Output: [["a", "b", "c"], ["d", "e", "f"]], Output: [
["a", "b", "c"],
["d", "e", "f"]
],
UseFieldsPerRecord: true, UseFieldsPerRecord: true,
FieldsPerRecord: 0 FieldsPerRecord: 0
}, },
@ -93,7 +102,10 @@ const testCases = [
{ {
Name: "NoComment", Name: "NoComment",
Input: "#1,2,3\na,b,c", Input: "#1,2,3\na,b,c",
Output: [["#1", "2", "3"], ["a", "b", "c"]] Output: [
["#1", "2", "3"],
["a", "b", "c"]
]
}, },
{ {
Name: "LazyQuotes", Name: "LazyQuotes",
@ -159,7 +171,10 @@ const testCases = [
{ {
Name: "FieldCount", Name: "FieldCount",
Input: "a,b,c\nd,e", Input: "a,b,c\nd,e",
Output: [["a", "b", "c"], ["d", "e"]] Output: [
["a", "b", "c"],
["d", "e"]
]
}, },
{ {
Name: "TrailingCommaEOF", Name: "TrailingCommaEOF",
@ -186,7 +201,11 @@ const testCases = [
{ {
Name: "TrailingCommaLine3", Name: "TrailingCommaLine3",
Input: "a,b,c\nd,e,f\ng,hi,", Input: "a,b,c\nd,e,f\ng,hi,",
Output: [["a", "b", "c"], ["d", "e", "f"], ["g", "hi", ""]], Output: [
["a", "b", "c"],
["d", "e", "f"],
["g", "hi", ""]
],
TrimLeadingSpace: true TrimLeadingSpace: true
}, },
{ {
@ -223,13 +242,19 @@ x,,,
{ {
Name: "TrailingCommaIneffective1", Name: "TrailingCommaIneffective1",
Input: "a,b,\nc,d,e", Input: "a,b,\nc,d,e",
Output: [["a", "b", ""], ["c", "d", "e"]], Output: [
["a", "b", ""],
["c", "d", "e"]
],
TrimLeadingSpace: true TrimLeadingSpace: true
}, },
{ {
Name: "ReadAllReuseRecord", Name: "ReadAllReuseRecord",
Input: "a,b\nc,d", Input: "a,b\nc,d",
Output: [["a", "b"], ["c", "d"]], Output: [
["a", "b"],
["c", "d"]
],
ReuseRecord: true ReuseRecord: true
}, },
// { // {
@ -496,7 +521,10 @@ const parseTestCases = [
name: "multiline", name: "multiline",
in: "a,b,c\ne,f,g\n", in: "a,b,c\ne,f,g\n",
header: false, header: false,
result: [["a", "b", "c"], ["e", "f", "g"]] result: [
["a", "b", "c"],
["e", "f", "g"]
]
}, },
{ {
name: "header mapping boolean", name: "header mapping boolean",

View file

@ -393,11 +393,9 @@ function joinKeys(keys: string[]): string {
// Dotted keys are a sequence of bare or quoted keys joined with a dot. // Dotted keys are a sequence of bare or quoted keys joined with a dot.
// This allows for grouping similar properties together: // This allows for grouping similar properties together:
return keys return keys
.map( .map((str: string): string => {
(str: string): string => { return str.match(/[^A-Za-z0-9_-]/) ? `"${str}"` : str;
return str.match(/[^A-Za-z0-9_-]/) ? `"${str}"` : str; })
}
)
.join("."); .join(".");
} }
@ -417,24 +415,20 @@ class Dumper {
_parse(obj: Record<string, unknown>, keys: string[] = []): string[] { _parse(obj: Record<string, unknown>, keys: string[] = []): string[] {
const out = []; const out = [];
const props = Object.keys(obj); const props = Object.keys(obj);
const propObj = props.filter( const propObj = props.filter((e: string): boolean => {
(e: string): boolean => { if (obj[e] instanceof Array) {
if (obj[e] instanceof Array) { const d: unknown[] = obj[e] as unknown[];
const d: unknown[] = obj[e] as unknown[]; return !this._isSimplySerializable(d[0]);
return !this._isSimplySerializable(d[0]);
}
return !this._isSimplySerializable(obj[e]);
} }
); return !this._isSimplySerializable(obj[e]);
const propPrim = props.filter( });
(e: string): boolean => { const propPrim = props.filter((e: string): boolean => {
if (obj[e] instanceof Array) { if (obj[e] instanceof Array) {
const d: unknown[] = obj[e] as unknown[]; const d: unknown[] = obj[e] as unknown[];
return this._isSimplySerializable(d[0]); return this._isSimplySerializable(d[0]);
}
return this._isSimplySerializable(obj[e]);
} }
); return this._isSimplySerializable(obj[e]);
});
const k = propPrim.concat(propObj); const k = propPrim.concat(propObj);
for (let i = 0; i < k.length; i++) { for (let i = 0; i < k.length; i++) {
const prop = k[i]; const prop = k[i];

View file

@ -112,7 +112,10 @@ test({
fn(): void { fn(): void {
const expected = { const expected = {
arrays: { arrays: {
data: [["gamma", "delta"], [1, 2]], data: [
["gamma", "delta"],
[1, 2]
],
hosts: ["alpha", "omega"] hosts: ["alpha", "omega"]
} }
}; };
@ -344,7 +347,10 @@ test({
sf4: NaN, sf4: NaN,
sf5: NaN, sf5: NaN,
sf6: NaN, sf6: NaN,
data: [["gamma", "delta"], [1, 2]], data: [
["gamma", "delta"],
[1, 2]
],
hosts: ["alpha", "omega"] hosts: ["alpha", "omega"]
}; };
const expected = `deno = "is" const expected = `deno = "is"

View file

@ -79,11 +79,9 @@ export function parse(
? [options.boolean] ? [options.boolean]
: options.boolean; : options.boolean;
booleanArgs.filter(Boolean).forEach( booleanArgs.filter(Boolean).forEach((key: string): void => {
(key: string): void => { flags.bools[key] = true;
flags.bools[key] = true; });
}
);
} }
} }
@ -114,11 +112,9 @@ export function parse(
flags.strings[key] = true; flags.strings[key] = true;
const alias = get(aliases, key); const alias = get(aliases, key);
if (alias) { if (alias) {
alias.forEach( alias.forEach((alias: string): void => {
(alias: string): void => { flags.strings[alias] = true;
flags.strings[alias] = true; });
}
);
} }
}); });
} }

View file

@ -587,18 +587,16 @@ const tests: Array<[string, any, string]> = [
]; ];
test(function testThorough(): void { test(function testThorough(): void {
tests.forEach( tests.forEach((t, i): void => {
(t, i): void => { // p(t)
// p(t) const is = S(t[0], t[1]);
const is = S(t[0], t[1]); const should = t[2];
const should = t[2]; assertEquals(
assertEquals( is,
is, should,
should, `failed case[${i}] : is >${is}< should >${should}<`
`failed case[${i}] : is >${is}< should >${should}<` );
); });
}
);
}); });
test(function testWeirdos(): void { test(function testWeirdos(): void {

View file

@ -317,11 +317,9 @@ testCopySync(
(tempDir: string): void => { (tempDir: string): void => {
const srcFile = path.join(testdataDir, "copy_file_not_exists_sync.txt"); const srcFile = path.join(testdataDir, "copy_file_not_exists_sync.txt");
const destFile = path.join(tempDir, "copy_file_not_exists_1_sync.txt"); const destFile = path.join(tempDir, "copy_file_not_exists_1_sync.txt");
assertThrows( assertThrows((): void => {
(): void => { copySync(srcFile, destFile);
copySync(srcFile, destFile); });
}
);
} }
); );
@ -367,50 +365,47 @@ testCopySync(
} }
); );
testCopySync( testCopySync("[fs] copy file synchronously", (tempDir: string): void => {
"[fs] copy file synchronously", const srcFile = path.join(testdataDir, "copy_file.txt");
(tempDir: string): void => { const destFile = path.join(tempDir, "copy_file_copy_sync.txt");
const srcFile = path.join(testdataDir, "copy_file.txt");
const destFile = path.join(tempDir, "copy_file_copy_sync.txt");
const srcContent = new TextDecoder().decode(Deno.readFileSync(srcFile)); const srcContent = new TextDecoder().decode(Deno.readFileSync(srcFile));
assertEquals(existsSync(srcFile), true); assertEquals(existsSync(srcFile), true);
assertEquals(existsSync(destFile), false); assertEquals(existsSync(destFile), false);
copySync(srcFile, destFile); copySync(srcFile, destFile);
assertEquals(existsSync(srcFile), true); assertEquals(existsSync(srcFile), true);
assertEquals(existsSync(destFile), true); assertEquals(existsSync(destFile), true);
const destContent = new TextDecoder().decode(Deno.readFileSync(destFile)); const destContent = new TextDecoder().decode(Deno.readFileSync(destFile));
assertEquals(srcContent, destContent); assertEquals(srcContent, destContent);
// Copy again without overwrite option and it should throw an error. // Copy again without overwrite option and it should throw an error.
assertThrows( assertThrows(
(): void => { (): void => {
copySync(srcFile, destFile); copySync(srcFile, destFile);
}, },
Error, Error,
`'${destFile}' already exists.` `'${destFile}' already exists.`
); );
// Modify destination file. // Modify destination file.
Deno.writeFileSync(destFile, new TextEncoder().encode("txt copy")); Deno.writeFileSync(destFile, new TextEncoder().encode("txt copy"));
assertEquals( assertEquals(
new TextDecoder().decode(Deno.readFileSync(destFile)), new TextDecoder().decode(Deno.readFileSync(destFile)),
"txt copy" "txt copy"
); );
// Copy again with overwrite option. // Copy again with overwrite option.
copySync(srcFile, destFile, { overwrite: true }); copySync(srcFile, destFile, { overwrite: true });
// Make sure the file has been overwritten. // Make sure the file has been overwritten.
assertEquals(new TextDecoder().decode(Deno.readFileSync(destFile)), "txt"); assertEquals(new TextDecoder().decode(Deno.readFileSync(destFile)), "txt");
} });
);
testCopySync( testCopySync(
"[fs] copy directory synchronously to its subdirectory", "[fs] copy directory synchronously to its subdirectory",
@ -450,57 +445,54 @@ testCopySync(
} }
); );
testCopySync( testCopySync("[fs] copy directory synchronously", (tempDir: string): void => {
"[fs] copy directory synchronously", const srcDir = path.join(testdataDir, "copy_dir");
(tempDir: string): void => { const destDir = path.join(tempDir, "copy_dir_copy_sync");
const srcDir = path.join(testdataDir, "copy_dir"); const srcFile = path.join(srcDir, "0.txt");
const destDir = path.join(tempDir, "copy_dir_copy_sync"); const destFile = path.join(destDir, "0.txt");
const srcFile = path.join(srcDir, "0.txt"); const srcNestFile = path.join(srcDir, "nest", "0.txt");
const destFile = path.join(destDir, "0.txt"); const destNestFile = path.join(destDir, "nest", "0.txt");
const srcNestFile = path.join(srcDir, "nest", "0.txt");
const destNestFile = path.join(destDir, "nest", "0.txt");
copySync(srcDir, destDir); copySync(srcDir, destDir);
assertEquals(existsSync(destFile), true); assertEquals(existsSync(destFile), true);
assertEquals(existsSync(destNestFile), true); assertEquals(existsSync(destNestFile), true);
// After copy. The source and destination should have the same content. // After copy. The source and destination should have the same content.
assertEquals( assertEquals(
new TextDecoder().decode(Deno.readFileSync(srcFile)), new TextDecoder().decode(Deno.readFileSync(srcFile)),
new TextDecoder().decode(Deno.readFileSync(destFile)) new TextDecoder().decode(Deno.readFileSync(destFile))
); );
assertEquals( assertEquals(
new TextDecoder().decode(Deno.readFileSync(srcNestFile)), new TextDecoder().decode(Deno.readFileSync(srcNestFile)),
new TextDecoder().decode(Deno.readFileSync(destNestFile)) new TextDecoder().decode(Deno.readFileSync(destNestFile))
); );
// Copy again without overwrite option and it should throw an error. // Copy again without overwrite option and it should throw an error.
assertThrows( assertThrows(
(): void => { (): void => {
copySync(srcDir, destDir); copySync(srcDir, destDir);
}, },
Error, Error,
`'${destDir}' already exists.` `'${destDir}' already exists.`
); );
// Modify the file in the destination directory. // Modify the file in the destination directory.
Deno.writeFileSync(destNestFile, new TextEncoder().encode("nest copy")); Deno.writeFileSync(destNestFile, new TextEncoder().encode("nest copy"));
assertEquals( assertEquals(
new TextDecoder().decode(Deno.readFileSync(destNestFile)), new TextDecoder().decode(Deno.readFileSync(destNestFile)),
"nest copy" "nest copy"
); );
// Copy again with overwrite option. // Copy again with overwrite option.
copySync(srcDir, destDir, { overwrite: true }); copySync(srcDir, destDir, { overwrite: true });
// Make sure the file has been overwritten. // Make sure the file has been overwritten.
assertEquals( assertEquals(
new TextDecoder().decode(Deno.readFileSync(destNestFile)), new TextDecoder().decode(Deno.readFileSync(destNestFile)),
"nest" "nest"
); );
} });
);
testCopySync( testCopySync(
"[fs] copy symlink file synchronously", "[fs] copy symlink file synchronously",

View file

@ -110,18 +110,14 @@ test(function emptyDirSyncIfItExist(): void {
assertEquals(stat.isDirectory(), true); assertEquals(stat.isDirectory(), true);
// nest directory have been remove // nest directory have been remove
assertThrows( assertThrows((): void => {
(): void => { Deno.statSync(testNestDir);
Deno.statSync(testNestDir); });
}
);
// test file have been remove // test file have been remove
assertThrows( assertThrows((): void => {
(): void => { Deno.statSync(testDirFile);
Deno.statSync(testDirFile); });
}
);
} finally { } finally {
// remote test dir // remote test dir
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });

View file

@ -15,11 +15,9 @@ test(async function ensureDirIfItNotExist(): Promise<void> {
await assertThrowsAsync( await assertThrowsAsync(
async (): Promise<void> => { async (): Promise<void> => {
await Deno.stat(testDir).then( await Deno.stat(testDir).then((): void => {
(): void => { throw new Error("test dir should exists.");
throw new Error("test dir should exists."); });
}
);
} }
); );
@ -48,11 +46,9 @@ test(async function ensureDirIfItExist(): Promise<void> {
await assertThrowsAsync( await assertThrowsAsync(
async (): Promise<void> => { async (): Promise<void> => {
await Deno.stat(testDir).then( await Deno.stat(testDir).then((): void => {
(): void => { throw new Error("test dir should still exists.");
throw new Error("test dir should still exists."); });
}
);
} }
); );
@ -68,12 +64,10 @@ test(function ensureDirSyncIfItExist(): void {
ensureDirSync(testDir); ensureDirSync(testDir);
assertThrows( assertThrows((): void => {
(): void => { Deno.statSync(testDir);
Deno.statSync(testDir); throw new Error("test dir should still exists.");
throw new Error("test dir should still exists."); });
}
);
Deno.removeSync(baseDir, { recursive: true }); Deno.removeSync(baseDir, { recursive: true });
}); });

View file

@ -14,11 +14,9 @@ test(async function ensureFileIfItNotExist(): Promise<void> {
await assertThrowsAsync( await assertThrowsAsync(
async (): Promise<void> => { async (): Promise<void> => {
await Deno.stat(testFile).then( await Deno.stat(testFile).then((): void => {
(): void => { throw new Error("test file should exists.");
throw new Error("test file should exists."); });
}
);
} }
); );
@ -31,12 +29,10 @@ test(function ensureFileSyncIfItNotExist(): void {
ensureFileSync(testFile); ensureFileSync(testFile);
assertThrows( assertThrows((): void => {
(): void => { Deno.statSync(testFile);
Deno.statSync(testFile); throw new Error("test file should exists.");
throw new Error("test file should exists."); });
}
);
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });
}); });
@ -52,11 +48,9 @@ test(async function ensureFileIfItExist(): Promise<void> {
await assertThrowsAsync( await assertThrowsAsync(
async (): Promise<void> => { async (): Promise<void> => {
await Deno.stat(testFile).then( await Deno.stat(testFile).then((): void => {
(): void => { throw new Error("test file should exists.");
throw new Error("test file should exists."); });
}
);
} }
); );
@ -72,12 +66,10 @@ test(function ensureFileSyncIfItExist(): void {
ensureFileSync(testFile); ensureFileSync(testFile);
assertThrows( assertThrows((): void => {
(): void => { Deno.statSync(testFile);
Deno.statSync(testFile); throw new Error("test file should exists.");
throw new Error("test file should exists."); });
}
);
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });
}); });

View file

@ -31,11 +31,9 @@ test(function ensureLinkSyncIfItNotExist(): void {
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
const linkFile = path.join(testDir, "link.txt"); const linkFile = path.join(testDir, "link.txt");
assertThrows( assertThrows((): void => {
(): void => { ensureLinkSync(testFile, linkFile);
ensureLinkSync(testFile, linkFile); });
}
);
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });
}); });

View file

@ -24,11 +24,9 @@ test(async function ensureSymlinkIfItNotExist(): Promise<void> {
assertThrowsAsync( assertThrowsAsync(
async (): Promise<void> => { async (): Promise<void> => {
await Deno.stat(testFile).then( await Deno.stat(testFile).then((): void => {
(): void => { throw new Error("test file should exists.");
throw new Error("test file should exists."); });
}
);
} }
); );
}); });
@ -37,18 +35,14 @@ test(function ensureSymlinkSyncIfItNotExist(): void {
const testDir = path.join(testdataDir, "link_file_2"); const testDir = path.join(testdataDir, "link_file_2");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
assertThrows( assertThrows((): void => {
(): void => { ensureSymlinkSync(testFile, path.join(testDir, "test1.txt"));
ensureSymlinkSync(testFile, path.join(testDir, "test1.txt")); });
}
);
assertThrows( assertThrows((): void => {
(): void => { Deno.statSync(testFile);
Deno.statSync(testFile); throw new Error("test file should exists.");
throw new Error("test file should exists."); });
}
);
}); });
test(async function ensureSymlinkIfItExist(): Promise<void> { test(async function ensureSymlinkIfItExist(): Promise<void> {

View file

@ -136,8 +136,8 @@ export async function* expandGlob(
); );
} }
if (hasTrailingSep) { if (hasTrailingSep) {
currentMatches = currentMatches.filter( currentMatches = currentMatches.filter(({ info }): boolean =>
({ info }): boolean => info.isDirectory() info.isDirectory()
); );
} }
if (!includeDirs) { if (!includeDirs) {
@ -238,8 +238,8 @@ export function* expandGlobSync(
); );
} }
if (hasTrailingSep) { if (hasTrailingSep) {
currentMatches = currentMatches.filter( currentMatches = currentMatches.filter(({ info }): boolean =>
({ info }): boolean => info.isDirectory() info.isDirectory()
); );
} }
if (!includeDirs) { if (!includeDirs) {

View file

@ -182,11 +182,9 @@ test(function moveSyncDirectoryIfSrcNotExists(): void {
const srcDir = path.join(testdataDir, "move_sync_test_src_1"); const srcDir = path.join(testdataDir, "move_sync_test_src_1");
const destDir = path.join(testdataDir, "move_sync_test_dest_1"); const destDir = path.join(testdataDir, "move_sync_test_dest_1");
// if src directory not exist // if src directory not exist
assertThrows( assertThrows((): void => {
(): void => { moveSync(srcDir, destDir);
moveSync(srcDir, destDir); });
}
);
}); });
test(function moveSyncDirectoryIfDestNotExists(): void { test(function moveSyncDirectoryIfDestNotExists(): void {
@ -213,11 +211,9 @@ test(function moveSyncFileIfSrcNotExists(): void {
const destFile = path.join(testdataDir, "move_sync_test_dest_3", "test.txt"); const destFile = path.join(testdataDir, "move_sync_test_dest_3", "test.txt");
// if src directory not exist // if src directory not exist
assertThrows( assertThrows((): void => {
(): void => { moveSync(srcFile, destFile);
moveSync(srcFile, destFile); });
}
);
}); });
test(function moveSyncFileIfDestExists(): void { test(function moveSyncFileIfDestExists(): void {

View file

@ -65,31 +65,25 @@ test(async function readValidObjJsonFileWithRelativePath(): Promise<void> {
test(function readJsonFileNotExistsSync(): void { test(function readJsonFileNotExistsSync(): void {
const emptyJsonFile = path.join(testdataDir, "json_not_exists.json"); const emptyJsonFile = path.join(testdataDir, "json_not_exists.json");
assertThrows( assertThrows((): void => {
(): void => { readJsonSync(emptyJsonFile);
readJsonSync(emptyJsonFile); });
}
);
}); });
test(function readEmptyJsonFileSync(): void { test(function readEmptyJsonFileSync(): void {
const emptyJsonFile = path.join(testdataDir, "json_empty.json"); const emptyJsonFile = path.join(testdataDir, "json_empty.json");
assertThrows( assertThrows((): void => {
(): void => { readJsonSync(emptyJsonFile);
readJsonSync(emptyJsonFile); });
}
);
}); });
test(function readInvalidJsonFile(): void { test(function readInvalidJsonFile(): void {
const invalidJsonFile = path.join(testdataDir, "json_invalid.json"); const invalidJsonFile = path.join(testdataDir, "json_invalid.json");
assertThrows( assertThrows((): void => {
(): void => { readJsonSync(invalidJsonFile);
readJsonSync(invalidJsonFile); });
}
);
}); });
test(function readValidArrayJsonFileSync(): void { test(function readValidArrayJsonFileSync(): void {

View file

@ -21,13 +21,11 @@ function patternTest(patterns: RegExp[], path: string): boolean {
// Forced to reset last index on regex while iterating for have // Forced to reset last index on regex while iterating for have
// consistent results. // consistent results.
// See: https://stackoverflow.com/a/1520853 // See: https://stackoverflow.com/a/1520853
return patterns.some( return patterns.some((pattern): boolean => {
(pattern): boolean => { const r = pattern.test(path);
const r = pattern.test(path); pattern.lastIndex = 0;
pattern.lastIndex = 0; return r;
return r; });
}
);
} }
function include(filename: string, options: WalkOptions): boolean { function include(filename: string, options: WalkOptions): boolean {

View file

@ -75,11 +75,9 @@ function modeToString(isDir: boolean, maybeMode: number | null): string {
.split("") .split("")
.reverse() .reverse()
.slice(0, 3) .slice(0, 3)
.forEach( .forEach((v): void => {
(v): void => { output = modeMap[+v] + output;
output = modeMap[+v] + output; });
}
);
output = `(${isDir ? "d" : "-"}${output})`; output = `(${isDir ? "d" : "-"}${output})`;
return output; return output;
} }
@ -179,9 +177,8 @@ async function serveDir(
dirViewerTemplate.replace("<%DIRNAME%>", formattedDirUrl).replace( dirViewerTemplate.replace("<%DIRNAME%>", formattedDirUrl).replace(
"<%CONTENTS%>", "<%CONTENTS%>",
listEntry listEntry
.sort( .sort((a, b): number =>
(a, b): number => a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1
a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1
) )
.map((v): string => v.template) .map((v): string => v.template)
.join("") .join("")

View file

@ -505,11 +505,9 @@ test({
let serverIsRunning = true; let serverIsRunning = true;
p.status() p.status()
.then( .then((): void => {
(): void => { serverIsRunning = false;
serverIsRunning = false; })
}
)
.catch((_): void => {}); // Ignores the error when closing the process. .catch((_): void => {}); // Ignores the error when closing the process.
await delay(100); await delay(100);
@ -551,11 +549,9 @@ test({
let serverIsRunning = true; let serverIsRunning = true;
p.status() p.status()
.then( .then((): void => {
(): void => { serverIsRunning = false;
serverIsRunning = false; })
}
)
.catch((_): void => {}); // Ignores the error when closing the process. .catch((_): void => {}); // Ignores the error when closing the process.
// Requests to the server and immediately closes the connection // Requests to the server and immediately closes the connection

View file

@ -23,6 +23,7 @@ export class BufferFullError extends Error {
export class UnexpectedEOFError extends Error { export class UnexpectedEOFError extends Error {
name = "UnexpectedEOFError"; name = "UnexpectedEOFError";
partial?: Uint8Array;
constructor() { constructor() {
super("Unexpected EOF"); super("Unexpected EOF");
} }

View file

@ -37,19 +37,16 @@ export class BaseHandler {
return this.formatter(logRecord); return this.formatter(logRecord);
} }
return this.formatter.replace( return this.formatter.replace(/{(\S+)}/g, (match, p1): string => {
/{(\S+)}/g, const value = logRecord[p1 as keyof LogRecord];
(match, p1): string => {
const value = logRecord[p1 as keyof LogRecord];
// do not interpolate missing values // do not interpolate missing values
if (!value) { if (!value) {
return match; return match;
}
return String(value);
} }
);
return String(value);
});
} }
log(_msg: string): void {} log(_msg: string): void {}

View file

@ -36,11 +36,9 @@ export class Logger {
level: level, level: level,
levelName: getLevelName(level) levelName: getLevelName(level)
}; };
this.handlers.forEach( this.handlers.forEach((handler): void => {
(handler): void => { handler.handle(record);
handler.handle(record); });
}
);
} }
debug(msg: string, ...args: unknown[]): void { debug(msg: string, ...args: unknown[]): void {

View file

@ -80,11 +80,9 @@ export async function setup(config: LogConfig): Promise<void> {
}; };
// tear down existing handlers // tear down existing handlers
state.handlers.forEach( state.handlers.forEach((handler): void => {
(handler): void => { handler.destroy();
handler.destroy(); });
}
);
state.handlers.clear(); state.handlers.clear();
// setup handlers // setup handlers
@ -106,13 +104,11 @@ export async function setup(config: LogConfig): Promise<void> {
const handlerNames = loggerConfig.handlers || []; const handlerNames = loggerConfig.handlers || [];
const handlers: BaseHandler[] = []; const handlers: BaseHandler[] = [];
handlerNames.forEach( handlerNames.forEach((handlerName): void => {
(handlerName): void => { if (state.handlers.has(handlerName)) {
if (state.handlers.has(handlerName)) { handlers.push(state.handlers.get(handlerName)!);
handlers.push(state.handlers.get(handlerName)!);
}
} }
); });
const levelName = loggerConfig.level || DEFAULT_LEVEL; const levelName = loggerConfig.level || DEFAULT_LEVEL;
const logger = new Logger(levelName, handlers); const logger = new Logger(levelName, handlers);

View file

@ -188,20 +188,18 @@ class PartReader implements Reader, Closer {
comps comps
.slice(1) .slice(1)
.map((v: string): string => v.trim()) .map((v: string): string => v.trim())
.map( .map((kv: string): void => {
(kv: string): void => { const [k, v] = kv.split("=");
const [k, v] = kv.split("="); if (v) {
if (v) { const s = v.charAt(0);
const s = v.charAt(0); const e = v.charAt(v.length - 1);
const e = v.charAt(v.length - 1); if ((s === e && s === '"') || s === "'") {
if ((s === e && s === '"') || s === "'") { params[k] = v.substr(1, v.length - 2);
params[k] = v.substr(1, v.length - 2); } else {
} else { params[k] = v;
params[k] = v;
}
} }
} }
); });
return (this.contentDispositionParams = params); return (this.contentDispositionParams = params);
} }

View file

@ -92,11 +92,9 @@ Using `assertThrows()`:
```ts ```ts
test(function doesThrow(): void { test(function doesThrow(): void {
assertThrows( assertThrows((): void => {
(): void => { throw new TypeError("hello world!");
throw new TypeError("hello world!"); });
}
);
assertThrows((): void => { assertThrows((): void => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}, TypeError); }, TypeError);
@ -111,11 +109,9 @@ test(function doesThrow(): void {
// This test will not pass // This test will not pass
test(function fails(): void { test(function fails(): void {
assertThrows( assertThrows((): void => {
(): void => { console.log("Hello world");
console.log("Hello world"); });
}
);
}); });
``` ```

View file

@ -56,12 +56,10 @@ function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] {
); );
messages.push(""); messages.push("");
messages.push(""); messages.push("");
diffResult.forEach( diffResult.forEach((result: DiffResult<string>): void => {
(result: DiffResult<string>): void => { const c = createColor(result.type);
const c = createColor(result.type); messages.push(c(`${createSign(result.type)}${result.value}`));
messages.push(c(`${createSign(result.type)}${result.value}`)); });
}
);
messages.push(""); messages.push("");
return messages; return messages;
@ -131,7 +129,7 @@ export function equal(c: unknown, d: unknown): boolean {
} }
/** Make an assertion, if not `true`, then throw. */ /** Make an assertion, if not `true`, then throw. */
export function assert(expr: boolean, msg = ""): void { export function assert(expr: unknown, msg = ""): asserts expr {
if (!expr) { if (!expr) {
throw new AssertionError(msg); throw new AssertionError(msg);
} }

View file

@ -51,8 +51,14 @@ test(function testingEqual(): void {
assert(equal(new Map(), new Map())); assert(equal(new Map(), new Map()));
assert( assert(
equal( equal(
new Map([["foo", "bar"], ["baz", "baz"]]), new Map([
new Map([["foo", "bar"], ["baz", "baz"]]) ["foo", "bar"],
["baz", "baz"]
]),
new Map([
["foo", "bar"],
["baz", "baz"]
])
) )
); );
assert( assert(
@ -69,14 +75,26 @@ test(function testingEqual(): void {
); );
assert( assert(
equal( equal(
new Map([["foo", "bar"], ["baz", "qux"]]), new Map([
new Map([["baz", "qux"], ["foo", "bar"]]) ["foo", "bar"],
["baz", "qux"]
]),
new Map([
["baz", "qux"],
["foo", "bar"]
])
) )
); );
assert(equal(new Map([["foo", ["bar"]]]), new Map([["foo", ["bar"]]]))); assert(equal(new Map([["foo", ["bar"]]]), new Map([["foo", ["bar"]]])));
assert(!equal(new Map([["foo", "bar"]]), new Map([["bar", "baz"]]))); assert(!equal(new Map([["foo", "bar"]]), new Map([["bar", "baz"]])));
assert( assert(
!equal(new Map([["foo", "bar"]]), new Map([["foo", "bar"], ["bar", "baz"]])) !equal(
new Map([["foo", "bar"]]),
new Map([
["foo", "bar"],
["bar", "baz"]
])
)
); );
assert( assert(
!equal( !equal(

View file

@ -133,7 +133,7 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> {
k: number, k: number,
M: number M: number
): FarthestPoint { ): FarthestPoint {
if (slide && slide.y === -1 && (down && down.y === -1)) if (slide && slide.y === -1 && down && down.y === -1)
return { y: 0, id: 0 }; return { y: 0, id: 0 };
if ( if (
(down && down.y === -1) || (down && down.y === -1) ||

View file

@ -360,13 +360,11 @@ const getKeysOfEnumerableProperties = (object: {}): Array<string | symbol> => {
const keys: Array<string | symbol> = Object.keys(object).sort(); const keys: Array<string | symbol> = Object.keys(object).sort();
if (Object.getOwnPropertySymbols) { if (Object.getOwnPropertySymbols) {
Object.getOwnPropertySymbols(object).forEach( Object.getOwnPropertySymbols(object).forEach((symbol): void => {
(symbol): void => { if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) {
if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) { keys.push(symbol);
keys.push(symbol);
}
} }
); });
} }
return keys; return keys;

View file

@ -203,14 +203,12 @@ function report(result: TestResult): void {
} }
function printFailedSummary(results: TestResults): void { function printFailedSummary(results: TestResults): void {
results.cases.forEach( results.cases.forEach((v): void => {
(v): void => { if (!v.ok) {
if (!v.ok) { console.error(`${RED_BG_FAIL} ${red(v.name)}`);
console.error(`${RED_BG_FAIL} ${red(v.name)}`); console.error(v.error);
console.error(v.error);
}
} }
); });
} }
function printResults( function printResults(
@ -321,14 +319,12 @@ async function runTestsSerial(
print( print(
GREEN_OK + " " + name + " " + promptTestTime(end - start, true) GREEN_OK + " " + name + " " + promptTestTime(end - start, true)
); );
results.cases.forEach( results.cases.forEach((v): void => {
(v): void => { if (v.name === name) {
if (v.name === name) { v.ok = true;
v.ok = true; v.printed = true;
v.printed = true;
}
} }
); });
} catch (err) { } catch (err) {
if (disableLog) { if (disableLog) {
print(CLEAR_LINE, false); print(CLEAR_LINE, false);
@ -336,15 +332,13 @@ async function runTestsSerial(
print(`${RED_FAILED} ${name}`); print(`${RED_FAILED} ${name}`);
print(err.stack); print(err.stack);
stats.failed++; stats.failed++;
results.cases.forEach( results.cases.forEach((v): void => {
(v): void => { if (v.name === name) {
if (v.name === name) { v.error = err;
v.error = err; v.ok = false;
v.ok = false; v.printed = true;
v.printed = true;
}
} }
); });
if (exitOnFail) { if (exitOnFail) {
break; break;
} }

View file

@ -204,8 +204,8 @@ async function main(): Promise<void> {
const include = const include =
parsedArgs._.length > 0 parsedArgs._.length > 0
? (parsedArgs._ as string[]).flatMap( ? (parsedArgs._ as string[]).flatMap((fileGlob: string): string[] =>
(fileGlob: string): string[] => fileGlob.split(",") fileGlob.split(",")
) )
: ["."]; : ["."];
const exclude = const exclude =

View file

@ -51,12 +51,10 @@ test(function testingAssertNotStrictEqual(): void {
test(function testingDoesThrow(): void { test(function testingDoesThrow(): void {
let count = 0; let count = 0;
assertThrows( assertThrows((): void => {
(): void => { count++;
count++; throw new Error();
throw new Error(); });
}
);
assert(count === 1); assert(count === 1);
}); });
@ -64,12 +62,10 @@ test(function testingDoesNotThrow(): void {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
assertThrows( assertThrows((): void => {
(): void => { count++;
count++; console.log("Hello world");
console.log("Hello world"); });
}
);
} catch (e) { } catch (e) {
assert(e.message === "Expected function to throw."); assert(e.message === "Expected function to throw.");
didThrow = true; didThrow = true;

View file

@ -114,11 +114,9 @@ test({
assertEquals(m.get("SID"), "0"); assertEquals(m.get("SID"), "0");
assertEquals(m.get("Privilege"), "127"); assertEquals(m.get("Privilege"), "127");
// Not a legal http header // Not a legal http header
assertThrows( assertThrows((): void => {
(): void => { assertEquals(m.get("Audio Mode"), "None");
assertEquals(m.get("Audio Mode"), "None"); });
}
);
} }
}); });

View file

@ -20,11 +20,9 @@ export interface Deferred<T> extends Promise<T> {
*/ */
export function deferred<T>(): Deferred<T> { export function deferred<T>(): Deferred<T> {
let methods; let methods;
const promise = new Promise<T>( const promise = new Promise<T>((resolve, reject): void => {
(resolve, reject): void => { methods = { resolve, reject };
methods = { resolve, reject }; });
}
);
return Object.assign(promise, methods)! as Deferred<T>; return Object.assign(promise, methods)! as Deferred<T>;
} }
@ -111,10 +109,9 @@ export async function collectUint8Arrays(
// Delays the given milliseconds and resolves. // Delays the given milliseconds and resolves.
export function delay(ms: number): Promise<void> { export function delay(ms: number): Promise<void> {
return new Promise( return new Promise((res): number =>
(res): number => setTimeout((): void => {
setTimeout((): void => { res();
res(); }, ms)
}, ms)
); );
} }

View file

@ -8,26 +8,24 @@ export function deepAssign(
if (!source || typeof source !== `object`) { if (!source || typeof source !== `object`) {
return; return;
} }
Object.entries(source).forEach( Object.entries(source).forEach(([key, value]: [string, unknown]): void => {
([key, value]: [string, unknown]): void => { if (value instanceof Date) {
if (value instanceof Date) { target[key] = new Date(value);
target[key] = new Date(value); return;
return;
}
if (!value || typeof value !== `object`) {
target[key] = value;
return;
}
if (Array.isArray(value)) {
target[key] = [];
}
// value is an Object
if (typeof target[key] !== `object` || !target[key]) {
target[key] = {};
}
deepAssign(target[key] as Record<string, unknown>, value!);
} }
); if (!value || typeof value !== `object`) {
target[key] = value;
return;
}
if (Array.isArray(value)) {
target[key] = [];
}
// value is an Object
if (typeof target[key] !== `object` || !target[key]) {
target[key] = {};
}
deepAssign(target[key] as Record<string, unknown>, value!);
});
} }
return target; return target;
} }

View file

@ -15,12 +15,10 @@ export default function generate(): string {
rnds[6] = (rnds[6] & 0x0f) | 0x40; // Version 4 rnds[6] = (rnds[6] & 0x0f) | 0x40; // Version 4
rnds[8] = (rnds[8] & 0x3f) | 0x80; // Variant 10 rnds[8] = (rnds[8] & 0x3f) | 0x80; // Variant 10
const bits: string[] = [...rnds].map( const bits: string[] = [...rnds].map((bit): string => {
(bit): string => { const s: string = bit.toString(16);
const s: string = bit.toString(16); return bit < 0x10 ? "0" + s : s;
return bit < 0x10 ? "0" + s : s; });
}
);
return [ return [
...bits.slice(0, 4), ...bits.slice(0, 4),
"-", "-",

View file

@ -60,11 +60,9 @@ for await (const req of serve(`:${port}`)) {
} }
} }
) )
.catch( .catch((err: Error): void => {
(err: Error): void => { console.error(`failed to accept websocket: ${err}`);
console.error(`failed to accept websocket: ${err}`); });
}
);
} }
``` ```
@ -117,11 +115,9 @@ while (true) {
} }
// FIXME: Without this, // FIXME: Without this,
// sock.receive() won't resolved though it is readable... // sock.receive() won't resolved though it is readable...
await new Promise( await new Promise((resolve): void => {
(resolve): void => { setTimeout(resolve, 0);
setTimeout(resolve, 0); });
}
);
} }
await sock.close(1000); await sock.close(1000);
// FIXME: conn.close() won't shutdown process... // FIXME: conn.close() won't shutdown process...

View file

@ -44,11 +44,9 @@ while (true) {
} }
// FIXME: Without this, // FIXME: Without this,
// sock.receive() won't resolved though it is readable... // sock.receive() won't resolved though it is readable...
await new Promise( await new Promise((resolve): void => {
(resolve): void => { setTimeout(resolve, 0);
setTimeout(resolve, 0); });
}
);
} }
await sock.close(1000); await sock.close(1000);
// FIXME: conn.close() won't shutdown process... // FIXME: conn.close() won't shutdown process...

View file

@ -52,9 +52,7 @@ for await (const req of serve(`:${port}`)) {
} }
} }
) )
.catch( .catch((err: Error): void => {
(err: Error): void => { console.error(`failed to accept websocket: ${err}`);
console.error(`failed to accept websocket: ${err}`); });
}
);
} }

@ -1 +1 @@
Subproject commit 140d1666ad04fb5ddfd5fc0d55181a9c7c067327 Subproject commit 8132faa910c498d4b52cb87fe7141058445a60b3

View file

@ -14,15 +14,9 @@ http
const proxy = http.request(options, proxyRes => { const proxy = http.request(options, proxyRes => {
res.writeHead(proxyRes.statusCode, proxyRes.headers); res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe( proxyRes.pipe(res, { end: true });
res,
{ end: true }
);
}); });
req.pipe( req.pipe(proxy, { end: true });
proxy,
{ end: true }
);
}) })
.listen(port); .listen(port);