From 82aabb657a8fbaf107e58214490fdd129db3ae6b Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Wed, 8 Jul 2020 19:26:39 +1000 Subject: [PATCH] feat: add --no-check option (#6456) This commit adds a "--no-check" option to following subcommands: - "deno cache" - "deno info" - "deno run" - "deno test" The "--no-check" options allows to skip type checking step and instead directly transpiles TS sources to JS sources. This solution uses `ts.transpileModule()` API and is just an interim solution before implementing it fully in Rust. --- cli/flags.rs | 35 +++ cli/global_state.rs | 29 +- cli/js/buffer.ts | 2 +- cli/js/compiler.ts | 254 +++++++++++++----- cli/js/compiler_api.ts | 6 +- cli/js/deno.ts | 42 +-- cli/js/deno_unstable.ts | 16 +- cli/js/files.ts | 4 +- cli/js/globals.ts | 2 +- cli/js/net.ts | 7 +- cli/js/ops/errors.ts | 2 +- cli/js/ops/fs/seek.ts | 2 +- cli/js/ops/permissions.ts | 2 +- cli/js/ops/runtime_compiler.ts | 2 +- cli/js/process.ts | 2 +- cli/js/web/body.ts | 2 +- cli/js/web/event.ts | 2 +- cli/js/web/event_target.ts | 2 +- cli/js/web/fetch.ts | 5 +- cli/js/web/request.ts | 2 +- cli/js/web/streams/internals.ts | 2 +- .../readable_byte_stream_controller.ts | 2 +- cli/js/web/streams/readable_stream.ts | 4 +- .../readable_stream_default_controller.ts | 2 +- .../streams/readable_stream_default_reader.ts | 2 +- cli/js/web/streams/transform_stream.ts | 6 +- .../transform_stream_default_controller.ts | 4 +- cli/js/web/streams/writable_stream.ts | 4 +- .../writable_stream_default_controller.ts | 2 +- .../streams/writable_stream_default_writer.ts | 2 +- cli/msg.rs | 18 +- cli/tests/error_no_check.ts | 1 + cli/tests/error_no_check.ts.out | 1 + cli/tests/integration_tests.rs | 15 ++ cli/tests/subdir/type_and_code.ts | 7 + cli/tsc.rs | 149 ++++++++++ deno_typescript/lib.rs | 5 + std/encoding/_yaml/dumper/dumper.ts | 2 +- std/encoding/_yaml/dumper/dumper_state.ts | 6 +- std/encoding/_yaml/error.ts | 2 +- std/encoding/_yaml/loader/loader.ts | 2 +- std/encoding/_yaml/loader/loader_state.ts | 8 +- std/encoding/_yaml/parse.ts | 2 +- std/encoding/_yaml/schema.ts | 4 +- std/encoding/_yaml/state.ts | 2 +- std/encoding/_yaml/stringify.ts | 2 +- std/encoding/_yaml/type.ts | 2 +- std/encoding/_yaml/type/binary.ts | 2 +- std/encoding/_yaml/type/map.ts | 2 +- std/encoding/_yaml/type/omap.ts | 2 +- std/encoding/_yaml/type/pairs.ts | 2 +- std/encoding/_yaml/type/seq.ts | 2 +- std/encoding/_yaml/type/set.ts | 2 +- std/encoding/yaml.ts | 13 +- std/hash/_wasm/hash.ts | 2 +- std/hash/mod.ts | 4 +- std/io/ioutil.ts | 2 +- std/log/handlers.ts | 2 +- std/log/logger.ts | 2 +- std/log/mod.ts | 2 +- std/node/_fs/_fs_access.ts | 2 +- std/node/_fs/_fs_chmod.ts | 2 +- std/node/_fs/_fs_chown.ts | 2 +- std/node/_fs/_fs_close.ts | 2 +- std/node/_fs/_fs_copy.ts | 2 +- std/node/_fs/_fs_dir_test.ts | 2 +- std/node/_fs/_fs_link.ts | 2 +- std/node/_fs/_fs_mkdir.ts | 8 +- std/node/_fs/_fs_writeFile_test.ts | 2 +- std/node/_fs/promises/_fs_readFile.ts | 5 +- std/node/_fs/promises/_fs_writeFile.ts | 2 +- std/node/_fs/promises/_fs_writeFile_test.ts | 2 +- std/path/_util.ts | 2 +- std/path/posix.ts | 2 +- std/path/win32.ts | 2 +- std/textproto/mod.ts | 2 +- std/tsconfig_test.json | 5 + tools/benchmark.py | 4 + 78 files changed, 567 insertions(+), 200 deletions(-) create mode 100644 cli/tests/error_no_check.ts create mode 100644 cli/tests/error_no_check.ts.out create mode 100644 cli/tests/subdir/type_and_code.ts create mode 100644 std/tsconfig_test.json diff --git a/cli/flags.rs b/cli/flags.rs index 4cacb01e4068a4..eb98c603256aeb 100644 --- a/cli/flags.rs +++ b/cli/flags.rs @@ -106,6 +106,7 @@ pub struct Flags { pub lock_write: bool, pub log_level: Option, pub net_allowlist: Vec, + pub no_check: bool, pub no_prompts: bool, pub no_remote: bool, pub read_allowlist: Vec, @@ -453,6 +454,7 @@ fn eval_parse(flags: &mut Flags, matches: &clap::ArgMatches) { fn info_parse(flags: &mut Flags, matches: &clap::ArgMatches) { ca_file_arg_parse(flags, matches); unstable_arg_parse(flags, matches); + no_check_arg_parse(flags, matches); flags.subcommand = DenoSubcommand::Info { file: matches.value_of("file").map(|f| f.to_string()), @@ -464,6 +466,7 @@ fn cache_parse(flags: &mut Flags, matches: &clap::ArgMatches) { lock_args_parse(flags, matches); importmap_arg_parse(flags, matches); config_arg_parse(flags, matches); + no_check_arg_parse(flags, matches); no_remote_arg_parse(flags, matches); ca_file_arg_parse(flags, matches); unstable_arg_parse(flags, matches); @@ -492,6 +495,7 @@ fn run_test_args_parse(flags: &mut Flags, matches: &clap::ArgMatches) { importmap_arg_parse(flags, matches); config_arg_parse(flags, matches); v8_flags_arg_parse(flags, matches); + no_check_arg_parse(flags, matches); no_remote_arg_parse(flags, matches); permission_args_parse(flags, matches); ca_file_arg_parse(flags, matches); @@ -818,6 +822,7 @@ TypeScript compiler cache: Subdirectory containing TS compiler output.", ) .arg(Arg::with_name("file").takes_value(true).required(false)) .arg(ca_file_arg()) + .arg(no_check_arg()) .arg(unstable_arg()) } @@ -829,6 +834,7 @@ fn cache_subcommand<'a, 'b>() -> App<'a, 'b> { .arg(importmap_arg()) .arg(unstable_arg()) .arg(config_arg()) + .arg(no_check_arg()) .arg(no_remote_arg()) .arg( Arg::with_name("file") @@ -1040,6 +1046,7 @@ fn run_test_args<'a, 'b>(app: App<'a, 'b>) -> App<'a, 'b> { .arg(config_arg()) .arg(lock_arg()) .arg(lock_write_arg()) + .arg(no_check_arg()) .arg(no_remote_arg()) .arg(v8_flags_arg()) .arg(ca_file_arg()) @@ -1314,6 +1321,18 @@ fn v8_flags_arg_parse(flags: &mut Flags, matches: &ArgMatches) { } } +fn no_check_arg<'a, 'b>() -> Arg<'a, 'b> { + Arg::with_name("no-check") + .long("no-check") + .help("Skip type checking modules") +} + +fn no_check_arg_parse(flags: &mut Flags, matches: &clap::ArgMatches) { + if matches.is_present("no-check") { + flags.no_check = true; + } +} + fn no_remote_arg<'a, 'b>() -> Arg<'a, 'b> { Arg::with_name("no-remote") .long("no-remote") @@ -2441,6 +2460,22 @@ mod tests { } */ + #[test] + fn no_check() { + let r = + flags_from_vec_safe(svec!["deno", "run", "--no-check", "script.ts"]); + assert_eq!( + r.unwrap(), + Flags { + subcommand: DenoSubcommand::Run { + script: "script.ts".to_string(), + }, + no_check: true, + ..Flags::default() + } + ); + } + #[test] fn no_remote() { let r = diff --git a/cli/global_state.rs b/cli/global_state.rs index cd04d03e69735c..e9988f4b57a9f1 100644 --- a/cli/global_state.rs +++ b/cli/global_state.rs @@ -170,17 +170,24 @@ impl GlobalState { let allow_js = should_allow_js(&module_graph_files); if should_compile { - self - .ts_compiler - .compile( - self.clone(), - &out, - target_lib, - permissions, - module_graph, - allow_js, - ) - .await?; + if self.flags.no_check { + self + .ts_compiler + .transpile(self.clone(), permissions, module_graph) + .await?; + } else { + self + .ts_compiler + .compile( + self.clone(), + &out, + target_lib, + permissions, + module_graph, + allow_js, + ) + .await?; + } } if let Some(ref lockfile) = self.lockfile { diff --git a/cli/js/buffer.ts b/cli/js/buffer.ts index 6a5105908e1948..5c304c127efd09 100644 --- a/cli/js/buffer.ts +++ b/cli/js/buffer.ts @@ -4,7 +4,7 @@ // Copyright 2009 The Go Authors. All rights reserved. BSD license. // https://github.com/golang/go/blob/master/LICENSE -import { Reader, Writer, ReaderSync, WriterSync } from "./io.ts"; +import type { Reader, Writer, ReaderSync, WriterSync } from "./io.ts"; import { assert } from "./util.ts"; // MIN_READ is the minimum ArrayBuffer size passed to a read call by diff --git a/cli/js/compiler.ts b/cli/js/compiler.ts index 500716a64bde53..fc75a7c102b8b0 100644 --- a/cli/js/compiler.ts +++ b/cli/js/compiler.ts @@ -14,10 +14,10 @@ import "./ts_global.d.ts"; import { bold, cyan, yellow } from "./colors.ts"; -import { CompilerOptions } from "./compiler_options.ts"; -import { Diagnostic, DiagnosticItem } from "./diagnostics.ts"; +import type { CompilerOptions } from "./compiler_options.ts"; +import type { Diagnostic, DiagnosticItem } from "./diagnostics.ts"; import { fromTypeScriptDiagnostic } from "./diagnostics_util.ts"; -import { TranspileOnlyResult } from "./ops/runtime_compiler.ts"; +import type { TranspileOnlyResult } from "./ops/runtime_compiler.ts"; import { bootstrapWorkerRuntime } from "./runtime_worker.ts"; import { assert, log, notImplemented } from "./util.ts"; import { core } from "./core.ts"; @@ -47,6 +47,8 @@ const TS_BUILD_INFO = "cache:///tsbuildinfo.json"; // TODO(Bartlomieju): this check should be done in Rust const IGNORED_COMPILER_OPTIONS: readonly string[] = [ "allowSyntheticDefaultImports", + "allowUmdGlobalAccess", + "assumeChangesOnlyAffectDirectDependencies", "baseUrl", "build", "composite", @@ -60,13 +62,13 @@ const IGNORED_COMPILER_OPTIONS: readonly string[] = [ "esModuleInterop", "extendedDiagnostics", "forceConsistentCasingInFileNames", + "generateCpuProfile", "help", "importHelpers", "incremental", "inlineSourceMap", "inlineSources", "init", - "isolatedModules", "listEmittedFiles", "listFiles", "mapRoot", @@ -139,10 +141,18 @@ const DEFAULT_COMPILE_OPTIONS: ts.CompilerOptions = { jsx: ts.JsxEmit.React, module: ts.ModuleKind.ESNext, outDir: OUT_DIR, - resolveJsonModule: true, sourceMap: true, strict: true, - stripComments: true, + removeComments: true, + target: ts.ScriptTarget.ESNext, +}; + +const DEFAULT_TRANSPILE_OPTIONS: ts.CompilerOptions = { + esModuleInterop: true, + inlineSourceMap: true, + jsx: ts.JsxEmit.React, + module: ts.ModuleKind.ESNext, + removeComments: true, target: ts.ScriptTarget.ESNext, }; @@ -172,16 +182,23 @@ interface CompilerHostOptions { incremental?: boolean; } -interface IncrementalCompilerHostOptions extends CompilerHostOptions { +type IncrementalCompilerHostOptions = Omit< + CompilerHostOptions, + "incremental" +> & { rootNames?: string[]; buildInfo?: string; -} +}; -interface ConfigureResponse { +interface HostConfigureResponse { ignoredOptions?: string[]; diagnostics?: ts.Diagnostic[]; } +interface ConfigureResponse extends HostConfigureResponse { + options: ts.CompilerOptions; +} + // Warning! The values in this enum are duplicated in `cli/msg.rs` // Update carefully! enum MediaType { @@ -238,6 +255,37 @@ const SOURCE_FILE_CACHE: Map = new Map(); */ const RESOLVED_SPECIFIER_CACHE: Map> = new Map(); +function configure( + defaultOptions: ts.CompilerOptions, + source: string, + path: string, + cwd: string +): ConfigureResponse { + const { config, error } = ts.parseConfigFileTextToJson(path, source); + if (error) { + return { diagnostics: [error], options: defaultOptions }; + } + const { options, errors } = ts.convertCompilerOptionsFromJson( + config.compilerOptions, + cwd + ); + const ignoredOptions: string[] = []; + for (const key of Object.keys(options)) { + if ( + IGNORED_COMPILER_OPTIONS.includes(key) && + (!(key in defaultOptions) || options[key] !== defaultOptions[key]) + ) { + ignoredOptions.push(key); + delete options[key]; + } + } + return { + options: Object.assign({}, defaultOptions, options), + ignoredOptions: ignoredOptions.length ? ignoredOptions : undefined, + diagnostics: errors.length ? errors : undefined, + }; +} + class SourceFile { extension!: ts.Extension; filename!: string; @@ -314,7 +362,7 @@ function getAssetInternal(filename: string): SourceFile { } class Host implements ts.CompilerHost { - protected _options = DEFAULT_COMPILE_OPTIONS; + #options = DEFAULT_COMPILE_OPTIONS; readonly #target: CompilerHostTarget; readonly #writeFile: WriteFileCallback; /* Deno specific APIs */ @@ -330,12 +378,12 @@ class Host implements ts.CompilerHost { this.#writeFile = writeFile; if (bundle) { // options we need to change when we are generating a bundle - Object.assign(this._options, DEFAULT_BUNDLER_OPTIONS); + Object.assign(this.#options, DEFAULT_BUNDLER_OPTIONS); } else if (incremental) { - Object.assign(this._options, DEFAULT_INCREMENTAL_COMPILE_OPTIONS); + Object.assign(this.#options, DEFAULT_INCREMENTAL_COMPILE_OPTIONS); } if (unstable) { - this._options.lib = [ + this.#options.lib = [ target === CompilerHostTarget.Worker ? "lib.deno.worker.d.ts" : "lib.deno.window.d.ts", @@ -345,47 +393,28 @@ class Host implements ts.CompilerHost { } get options(): ts.CompilerOptions { - return this._options; + return this.#options; } configure( cwd: string, path: string, configurationText: string - ): ConfigureResponse { + ): HostConfigureResponse { log("compiler::host.configure", path); - assert(configurationText); - const { config, error } = ts.parseConfigFileTextToJson( + const { options, ...result } = configure( + this.#options, + configurationText, path, - configurationText - ); - if (error) { - return { diagnostics: [error] }; - } - const { options, errors } = ts.convertCompilerOptionsFromJson( - config.compilerOptions, cwd ); - const ignoredOptions: string[] = []; - for (const key of Object.keys(options)) { - if ( - IGNORED_COMPILER_OPTIONS.includes(key) && - (!(key in this._options) || options[key] !== this._options[key]) - ) { - ignoredOptions.push(key); - delete options[key]; - } - } - Object.assign(this._options, options); - return { - ignoredOptions: ignoredOptions.length ? ignoredOptions : undefined, - diagnostics: errors.length ? errors : undefined, - }; + this.#options = options; + return result; } mergeOptions(...options: ts.CompilerOptions[]): ts.CompilerOptions { - Object.assign(this._options, ...options); - return Object.assign({}, this._options); + Object.assign(this.#options, ...options); + return Object.assign({}, this.#options); } /* TypeScript CompilerHost APIs */ @@ -400,7 +429,7 @@ class Host implements ts.CompilerHost { getCompilationSettings(): ts.CompilerOptions { log("compiler::host.getCompilationSettings()"); - return this._options; + return this.#options; } getCurrentDirectory(): string { @@ -522,7 +551,7 @@ class IncrementalCompileHost extends Host { readonly #buildInfo?: string; constructor(options: IncrementalCompilerHostOptions) { - super(options); + super({ ...options, incremental: true }); const { buildInfo } = options; if (buildInfo) { this.#buildInfo = buildInfo; @@ -735,10 +764,11 @@ interface BundleWriteFileState { // Update carefully! enum CompilerRequestType { Compile = 0, - Bundle = 1, - RuntimeCompile = 2, - RuntimeBundle = 3, - RuntimeTranspile = 4, + Transpile = 1, + Bundle = 2, + RuntimeCompile = 3, + RuntimeBundle = 4, + RuntimeTranspile = 5, } function createBundleWriteFile(state: BundleWriteFileState): WriteFileCallback { @@ -943,16 +973,29 @@ function performanceStart(): void { ts.performance.enable(); } -function performanceProgram(program: ts.Program | ts.BuilderProgram): void { - if ("getProgram" in program) { - program = program.getProgram(); +function performanceProgram({ + program, + fileCount, +}: { + program?: ts.Program | ts.BuilderProgram; + fileCount?: number; +}): void { + if (program) { + if ("getProgram" in program) { + program = program.getProgram(); + } + stats.push({ key: "Files", value: program.getSourceFiles().length }); + stats.push({ key: "Nodes", value: program.getNodeCount() }); + stats.push({ key: "Identifiers", value: program.getIdentifierCount() }); + stats.push({ key: "Symbols", value: program.getSymbolCount() }); + stats.push({ key: "Types", value: program.getTypeCount() }); + stats.push({ + key: "Instantiations", + value: program.getInstantiationCount(), + }); + } else if (fileCount != null) { + stats.push({ key: "Files", value: fileCount }); } - stats.push({ key: "Files", value: program.getSourceFiles().length }); - stats.push({ key: "Nodes", value: program.getNodeCount() }); - stats.push({ key: "Identifiers", value: program.getIdentifierCount() }); - stats.push({ key: "Symbols", value: program.getSymbolCount() }); - stats.push({ key: "Types", value: program.getTypeCount() }); - stats.push({ key: "Instantiations", value: program.getInstantiationCount() }); const programTime = ts.performance.getDuration("Program"); const bindTime = ts.performance.getDuration("Bind"); const checkTime = ts.performance.getDuration("Check"); @@ -976,7 +1019,7 @@ function performanceEnd(): Stats { // TODO(Bartlomieju): this check should be done in Rust; there should be no function processConfigureResponse( - configResult: ConfigureResponse, + configResult: HostConfigureResponse, configPath: string ): ts.Diagnostic[] | undefined { const { ignoredOptions, diagnostics } = configResult; @@ -1209,6 +1252,20 @@ interface CompileRequest { buildInfo?: string; } +interface TranspileRequest { + type: CompilerRequestType.Transpile; + config?: string; + configPath?: string; + cwd?: string; + performance: boolean; + sourceFiles: TranspileSourceFile[]; +} + +interface TranspileSourceFile { + sourceCode: string; + fileName: string; +} + /** Used when "deno bundle" is invoked */ interface BundleRequest { type: CompilerRequestType.Bundle; @@ -1252,6 +1309,7 @@ interface RuntimeTranspileRequest { type CompilerRequest = | CompileRequest + | TranspileRequest | BundleRequest | RuntimeCompileRequest | RuntimeBundleRequest @@ -1264,6 +1322,12 @@ interface CompileResponse { stats?: Stats; } +interface TranspileResponse { + emitMap: Record; + diagnostics: Diagnostic; + stats?: Stats; +} + interface BundleResponse { bundleOutput?: string; diagnostics: Diagnostic; @@ -1310,7 +1374,6 @@ function compile({ bundle: false, target, unstable, - incremental: true, writeFile: createCompileWriteFile(state), rootNames, buildInfo, @@ -1364,7 +1427,7 @@ function compile({ // without casting. diagnostics = emitResult.diagnostics; } - performanceProgram(program); + performanceProgram({ program }); } log("<<< compile end", { rootNames, type: CompilerRequestType[type] }); @@ -1378,21 +1441,81 @@ function compile({ }; } +function transpile({ + config: configText, + configPath, + cwd, + performance, + sourceFiles, +}: TranspileRequest): TranspileResponse { + if (performance) { + performanceStart(); + } + log(">>> transpile start"); + let compilerOptions: ts.CompilerOptions; + if (configText && configPath && cwd) { + const { options, ...response } = configure( + DEFAULT_TRANSPILE_OPTIONS, + configText, + configPath, + cwd + ); + const diagnostics = processConfigureResponse(response, configPath); + if (diagnostics && diagnostics.length) { + return { + diagnostics: fromTypeScriptDiagnostic(diagnostics), + emitMap: {}, + }; + } + compilerOptions = options; + } else { + compilerOptions = Object.assign({}, DEFAULT_TRANSPILE_OPTIONS); + } + const emitMap: Record = {}; + let diagnostics: ts.Diagnostic[] = []; + for (const { sourceCode, fileName } of sourceFiles) { + const { + outputText, + sourceMapText, + diagnostics: diags, + } = ts.transpileModule(sourceCode, { + fileName, + compilerOptions, + reportDiagnostics: true, + }); + if (diags) { + diagnostics = diagnostics.concat(...diags); + } + emitMap[`${fileName}.js`] = { filename: fileName, contents: outputText }; + // currently we inline source maps, but this is good logic to have if this + // ever changes + if (sourceMapText) { + emitMap[`${fileName}.map`] = { + filename: fileName, + contents: sourceMapText, + }; + } + } + performanceProgram({ fileCount: sourceFiles.length }); + const stats = performance ? performanceEnd() : undefined; + log("<<< transpile end"); + return { diagnostics: fromTypeScriptDiagnostic(diagnostics), emitMap, stats }; +} + function bundle({ - type, config, configPath, rootNames, target, unstable, - performance, cwd, sourceFileMap, + type, }: BundleRequest): BundleResponse { if (performance) { performanceStart(); } - log(">>> start start", { + log(">>> bundle start", { rootNames, type: CompilerRequestType[type], }); @@ -1447,7 +1570,7 @@ function bundle({ diagnostics = emitResult.diagnostics; } if (performance) { - performanceProgram(program); + performanceProgram({ program }); } } @@ -1655,6 +1778,11 @@ async function tsCompilerOnMessage({ globalThis.postMessage(result); break; } + case CompilerRequestType.Transpile: { + const result = transpile(request); + globalThis.postMessage(result); + break; + } case CompilerRequestType.Bundle: { const result = bundle(request); globalThis.postMessage(result); diff --git a/cli/js/compiler_api.ts b/cli/js/compiler_api.ts index 0f4aec88728e94..8a50e0b3de6d01 100644 --- a/cli/js/compiler_api.ts +++ b/cli/js/compiler_api.ts @@ -3,11 +3,11 @@ // This file contains the runtime APIs which will dispatch work to the internal // compiler within Deno. -import { DiagnosticItem } from "./diagnostics.ts"; +import type { DiagnosticItem } from "./diagnostics.ts"; import * as util from "./util.ts"; import * as runtimeCompilerOps from "./ops/runtime_compiler.ts"; -import { TranspileOnlyResult } from "./ops/runtime_compiler.ts"; -import { CompilerOptions } from "./compiler_options.ts"; +import type { TranspileOnlyResult } from "./ops/runtime_compiler.ts"; +import type { CompilerOptions } from "./compiler_options.ts"; function checkRelative(specifier: string): string { return specifier.match(/^([\.\/\\]|https?:\/{2}|file:\/{2})/) diff --git a/cli/js/deno.ts b/cli/js/deno.ts index 6570042af5ce14..878df8fb40ccea 100644 --- a/cli/js/deno.ts +++ b/cli/js/deno.ts @@ -27,16 +27,15 @@ export { stderr, seek, seekSync, - OpenOptions, } from "./files.ts"; +export type { OpenOptions } from "./files.ts"; export { read, readSync, write, writeSync } from "./ops/io.ts"; -export { FsEvent, watchFs } from "./ops/fs_events.ts"; +export { watchFs } from "./ops/fs_events.ts"; +export type { FsEvent } from "./ops/fs_events.ts"; export { internalSymbol as internal } from "./internals.ts"; -export { - copy, - iter, - iterSync, - SeekMode, +export { copy, iter, iterSync } from "./io.ts"; +export { SeekMode } from "./io.ts"; +export type { Reader, ReaderSync, Writer, @@ -49,30 +48,39 @@ export { makeTempDir, makeTempFileSync, makeTempFile, - MakeTempOptions, } from "./ops/fs/make_temp.ts"; -export { metrics, Metrics } from "./ops/runtime.ts"; -export { mkdirSync, mkdir, MkdirOptions } from "./ops/fs/mkdir.ts"; -export { connect, listen, Listener, Conn } from "./net.ts"; +export type { MakeTempOptions } from "./ops/fs/make_temp.ts"; +export { metrics } from "./ops/runtime.ts"; +export type { Metrics } from "./ops/runtime.ts"; +export { mkdirSync, mkdir } from "./ops/fs/mkdir.ts"; +export type { MkdirOptions } from "./ops/fs/mkdir.ts"; +export { connect, listen } from "./net.ts"; +export type { Listener, Conn } from "./net.ts"; export { env, exit, execPath } from "./ops/os.ts"; -export { run, RunOptions, Process, ProcessStatus } from "./process.ts"; -export { DirEntry, readDirSync, readDir } from "./ops/fs/read_dir.ts"; +export { Process, run } from "./process.ts"; +export type { RunOptions, ProcessStatus } from "./process.ts"; +export { readDirSync, readDir } from "./ops/fs/read_dir.ts"; +export type { DirEntry } from "./ops/fs/read_dir.ts"; export { readFileSync, readFile } from "./read_file.ts"; export { readTextFileSync, readTextFile } from "./read_text_file.ts"; export { readLinkSync, readLink } from "./ops/fs/read_link.ts"; export { realPathSync, realPath } from "./ops/fs/real_path.ts"; -export { removeSync, remove, RemoveOptions } from "./ops/fs/remove.ts"; +export { removeSync, remove } from "./ops/fs/remove.ts"; +export type { RemoveOptions } from "./ops/fs/remove.ts"; export { renameSync, rename } from "./ops/fs/rename.ts"; export { resources, close } from "./ops/resources.ts"; -export { FileInfo, statSync, lstatSync, stat, lstat } from "./ops/fs/stat.ts"; +export { statSync, lstatSync, stat, lstat } from "./ops/fs/stat.ts"; +export type { FileInfo } from "./ops/fs/stat.ts"; export { connectTls, listenTls } from "./tls.ts"; export { truncateSync, truncate } from "./ops/fs/truncate.ts"; export { isatty } from "./ops/tty.ts"; export { version } from "./version.ts"; -export { writeFileSync, writeFile, WriteFileOptions } from "./write_file.ts"; +export { writeFileSync, writeFile } from "./write_file.ts"; +export type { WriteFileOptions } from "./write_file.ts"; export { writeTextFileSync, writeTextFile } from "./write_text_file.ts"; export const args: string[] = []; -export { TestDefinition, test } from "./testing.ts"; +export { test } from "./testing.ts"; +export type { TestDefinition } from "./testing.ts"; // These are internal Deno APIs. We are marking them as internal so they do not // appear in the runtime type library. diff --git a/cli/js/deno_unstable.ts b/cli/js/deno_unstable.ts index e7a0510be849a3..8744abba46446a 100644 --- a/cli/js/deno_unstable.ts +++ b/cli/js/deno_unstable.ts @@ -15,20 +15,16 @@ export { signal, signals, Signal, SignalStream } from "./signals.ts"; export { setRaw } from "./ops/tty.ts"; export { utimeSync, utime } from "./ops/fs/utime.ts"; export { ftruncateSync, ftruncate } from "./ops/fs/truncate.ts"; -export { ShutdownMode, shutdown } from "./net.ts"; +export { shutdown, ShutdownMode } from "./net.ts"; export { listen, listenDatagram, connect } from "./net_unstable.ts"; export { startTls } from "./tls.ts"; export { kill } from "./ops/process.ts"; -export { - permissions, - PermissionName, - PermissionState, - PermissionStatus, - Permissions, -} from "./permissions.ts"; -export { +export { permissions, Permissions } from "./permissions.ts"; +export { PermissionStatus } from "./permissions.ts"; +export type { PermissionName, PermissionState } from "./permissions.ts"; +export { DiagnosticCategory } from "./diagnostics.ts"; +export type { Diagnostic, - DiagnosticCategory, DiagnosticItem, DiagnosticMessageChain, } from "./diagnostics.ts"; diff --git a/cli/js/files.ts b/cli/js/files.ts index 3dc48420d9dbca..3afcb48783f856 100644 --- a/cli/js/files.ts +++ b/cli/js/files.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { +import type { Reader, Writer, Seeker, @@ -19,7 +19,7 @@ import { openSync as opOpenSync, OpenOptions, } from "./ops/fs/open.ts"; -export { OpenOptions } from "./ops/fs/open.ts"; +export type { OpenOptions } from "./ops/fs/open.ts"; export function openSync( path: string | URL, diff --git a/cli/js/globals.ts b/cli/js/globals.ts index 5746b224f8bcd2..c73a2a6abbdec1 100644 --- a/cli/js/globals.ts +++ b/cli/js/globals.ts @@ -7,7 +7,7 @@ import * as abortSignal from "./web/abort_signal.ts"; import * as blob from "./web/blob.ts"; import * as consoleTypes from "./web/console.ts"; import * as csprng from "./ops/get_random_values.ts"; -import * as promiseTypes from "./web/promise.ts"; +import type * as promiseTypes from "./web/promise.ts"; import * as customEvent from "./web/custom_event.ts"; import * as domException from "./web/dom_exception.ts"; import * as domFile from "./web/dom_file.ts"; diff --git a/cli/js/net.ts b/cli/js/net.ts index e5e6af7bdbe24f..a4aad0254a13cb 100644 --- a/cli/js/net.ts +++ b/cli/js/net.ts @@ -1,12 +1,13 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { errors } from "./errors.ts"; -import { Reader, Writer, Closer } from "./io.ts"; +import type { Reader, Writer, Closer } from "./io.ts"; import { read, write } from "./ops/io.ts"; import { close } from "./ops/resources.ts"; import * as netOps from "./ops/net.ts"; -import { Addr } from "./ops/net.ts"; -export { ShutdownMode, shutdown, NetAddr, UnixAddr } from "./ops/net.ts"; +import type { Addr } from "./ops/net.ts"; +export type { ShutdownMode, NetAddr, UnixAddr } from "./ops/net.ts"; +export { shutdown } from "./ops/net.ts"; export interface DatagramConn extends AsyncIterable<[Uint8Array, Addr]> { receive(p?: Uint8Array): Promise<[Uint8Array, Addr]>; diff --git a/cli/js/ops/errors.ts b/cli/js/ops/errors.ts index c6c26b8ba69d1b..002ca699e87a41 100644 --- a/cli/js/ops/errors.ts +++ b/cli/js/ops/errors.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { DiagnosticItem } from "../diagnostics.ts"; +import type { DiagnosticItem } from "../diagnostics.ts"; import { sendSync } from "./dispatch_json.ts"; export function formatDiagnostics(items: DiagnosticItem[]): string { diff --git a/cli/js/ops/fs/seek.ts b/cli/js/ops/fs/seek.ts index 2e23e084b8ed5f..8fd3964fdea3e3 100644 --- a/cli/js/ops/fs/seek.ts +++ b/cli/js/ops/fs/seek.ts @@ -1,7 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { sendSync, sendAsync } from "../dispatch_json.ts"; -import { SeekMode } from "../../io.ts"; +import type { SeekMode } from "../../io.ts"; export function seekSync( rid: number, diff --git a/cli/js/ops/permissions.ts b/cli/js/ops/permissions.ts index dfe8c483471092..74b9ba0f09b412 100644 --- a/cli/js/ops/permissions.ts +++ b/cli/js/ops/permissions.ts @@ -1,7 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { sendSync } from "./dispatch_json.ts"; -import { PermissionState } from "../permissions.ts"; +import type { PermissionState } from "../permissions.ts"; interface PermissionRequest { name: string; diff --git a/cli/js/ops/runtime_compiler.ts b/cli/js/ops/runtime_compiler.ts index 5a89983ee71505..671585118df6f9 100644 --- a/cli/js/ops/runtime_compiler.ts +++ b/cli/js/ops/runtime_compiler.ts @@ -1,7 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { sendAsync } from "./dispatch_json.ts"; -import { DiagnosticItem } from "../diagnostics.ts"; +import type { DiagnosticItem } from "../diagnostics.ts"; interface CompileRequest { rootName: string; diff --git a/cli/js/process.ts b/cli/js/process.ts index 6f45081dcd61f0..ee32eac3d55de0 100644 --- a/cli/js/process.ts +++ b/cli/js/process.ts @@ -2,7 +2,7 @@ import { File } from "./files.ts"; import { close } from "./ops/resources.ts"; -import { Closer, Reader, Writer } from "./io.ts"; +import type { Closer, Reader, Writer } from "./io.ts"; import { readAll } from "./buffer.ts"; import { kill, runStatus as runStatusOp, run as runOp } from "./ops/process.ts"; diff --git a/cli/js/web/body.ts b/cli/js/web/body.ts index 3bcda063469351..69aca459f03af7 100644 --- a/cli/js/web/body.ts +++ b/cli/js/web/body.ts @@ -2,7 +2,7 @@ import * as blob from "./blob.ts"; import * as encoding from "./text_encoding.ts"; -import * as domTypes from "./dom_types.d.ts"; +import type * as domTypes from "./dom_types.d.ts"; import { ReadableStreamImpl } from "./streams/readable_stream.ts"; import { isReadableStreamDisturbed } from "./streams/internals.ts"; import { Buffer } from "../buffer.ts"; diff --git a/cli/js/web/event.ts b/cli/js/web/event.ts index b57c0f9013b8fd..556d403a6f35f9 100644 --- a/cli/js/web/event.ts +++ b/cli/js/web/event.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import * as domTypes from "./dom_types.d.ts"; +import type * as domTypes from "./dom_types.d.ts"; import { defineEnumerableProps, requiredArguments } from "./util.ts"; import { assert } from "../util.ts"; diff --git a/cli/js/web/event_target.ts b/cli/js/web/event_target.ts index 1a560dfbebd199..6f6897425a0c63 100644 --- a/cli/js/web/event_target.ts +++ b/cli/js/web/event_target.ts @@ -6,7 +6,7 @@ // and impossible logic branches based on what Deno currently supports. import { DOMExceptionImpl as DOMException } from "./dom_exception.ts"; -import * as domTypes from "./dom_types.d.ts"; +import type * as domTypes from "./dom_types.d.ts"; import { EventImpl as Event, EventPath, diff --git a/cli/js/web/fetch.ts b/cli/js/web/fetch.ts index 33cf12069966a7..543560c8d557a3 100644 --- a/cli/js/web/fetch.ts +++ b/cli/js/web/fetch.ts @@ -2,12 +2,13 @@ import { notImplemented } from "../util.ts"; import { isTypedArray } from "./util.ts"; -import * as domTypes from "./dom_types.d.ts"; +import type * as domTypes from "./dom_types.d.ts"; import { TextEncoder } from "./text_encoding.ts"; import { DenoBlob, bytesSymbol as blobBytesSymbol } from "./blob.ts"; import { read } from "../ops/io.ts"; import { close } from "../ops/resources.ts"; -import { fetch as opFetch, FetchResponse } from "../ops/fetch.ts"; +import { fetch as opFetch } from "../ops/fetch.ts"; +import type { FetchResponse } from "../ops/fetch.ts"; import * as Body from "./body.ts"; import { getHeaderValueParams } from "./util.ts"; import { ReadableStreamImpl } from "./streams/readable_stream.ts"; diff --git a/cli/js/web/request.ts b/cli/js/web/request.ts index 7ea6a9ecd1ca0d..f65b6a3637ba68 100644 --- a/cli/js/web/request.ts +++ b/cli/js/web/request.ts @@ -1,7 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import * as body from "./body.ts"; -import * as domTypes from "./dom_types.d.ts"; +import type * as domTypes from "./dom_types.d.ts"; import { ReadableStreamImpl } from "./streams/readable_stream.ts"; function byteUpperCase(s: string): string { diff --git a/cli/js/web/streams/internals.ts b/cli/js/web/streams/internals.ts index 3fbfb773586421..f6b20ccaffd2e2 100644 --- a/cli/js/web/streams/internals.ts +++ b/cli/js/web/streams/internals.ts @@ -12,7 +12,7 @@ import { ReadableStreamDefaultControllerImpl } from "./readable_stream_default_c import { ReadableStreamDefaultReaderImpl } from "./readable_stream_default_reader.ts"; import { ReadableStreamImpl } from "./readable_stream.ts"; import * as sym from "./symbols.ts"; -import { TransformStreamImpl } from "./transform_stream.ts"; +import type { TransformStreamImpl } from "./transform_stream.ts"; import { TransformStreamDefaultControllerImpl } from "./transform_stream_default_controller.ts"; import { WritableStreamDefaultControllerImpl } from "./writable_stream_default_controller.ts"; import { WritableStreamDefaultWriterImpl } from "./writable_stream_default_writer.ts"; diff --git a/cli/js/web/streams/readable_byte_stream_controller.ts b/cli/js/web/streams/readable_byte_stream_controller.ts index cbef643575bb72..65409dc1e53007 100644 --- a/cli/js/web/streams/readable_byte_stream_controller.ts +++ b/cli/js/web/streams/readable_byte_stream_controller.ts @@ -20,7 +20,7 @@ import { readableStreamCreateReadResult, setFunctionName, } from "./internals.ts"; -import { ReadableStreamImpl } from "./readable_stream.ts"; +import type { ReadableStreamImpl } from "./readable_stream.ts"; import * as sym from "./symbols.ts"; import { assert } from "../../util.ts"; import { customInspect } from "../console.ts"; diff --git a/cli/js/web/streams/readable_stream.ts b/cli/js/web/streams/readable_stream.ts index 27a733d9daa630..3191c08599f9a6 100644 --- a/cli/js/web/streams/readable_stream.ts +++ b/cli/js/web/streams/readable_stream.ts @@ -19,9 +19,9 @@ import { setUpReadableStreamDefaultControllerFromUnderlyingSource, validateAndNormalizeHighWaterMark, } from "./internals.ts"; -import { ReadableByteStreamControllerImpl } from "./readable_byte_stream_controller.ts"; +import type { ReadableByteStreamControllerImpl } from "./readable_byte_stream_controller.ts"; import { ReadableStreamAsyncIteratorPrototype } from "./readable_stream_async_iterator.ts"; -import { ReadableStreamDefaultControllerImpl } from "./readable_stream_default_controller.ts"; +import type { ReadableStreamDefaultControllerImpl } from "./readable_stream_default_controller.ts"; import * as sym from "./symbols.ts"; import { customInspect } from "../console.ts"; import { AbortSignalImpl } from "../abort_signal.ts"; diff --git a/cli/js/web/streams/readable_stream_default_controller.ts b/cli/js/web/streams/readable_stream_default_controller.ts index 0755e7765459d8..47cb719c7051ab 100644 --- a/cli/js/web/streams/readable_stream_default_controller.ts +++ b/cli/js/web/streams/readable_stream_default_controller.ts @@ -20,7 +20,7 @@ import { SizeAlgorithm, setFunctionName, } from "./internals.ts"; -import { ReadableStreamImpl } from "./readable_stream.ts"; +import type { ReadableStreamImpl } from "./readable_stream.ts"; import * as sym from "./symbols.ts"; import { customInspect } from "../console.ts"; diff --git a/cli/js/web/streams/readable_stream_default_reader.ts b/cli/js/web/streams/readable_stream_default_reader.ts index a0d5901dca6eef..01b679cd3e66d7 100644 --- a/cli/js/web/streams/readable_stream_default_reader.ts +++ b/cli/js/web/streams/readable_stream_default_reader.ts @@ -11,7 +11,7 @@ import { readableStreamReaderGenericRelease, setFunctionName, } from "./internals.ts"; -import { ReadableStreamImpl } from "./readable_stream.ts"; +import type { ReadableStreamImpl } from "./readable_stream.ts"; import * as sym from "./symbols.ts"; import { customInspect } from "../console.ts"; diff --git a/cli/js/web/streams/transform_stream.ts b/cli/js/web/streams/transform_stream.ts index ac08fea3fa9885..548a20b38d9d3c 100644 --- a/cli/js/web/streams/transform_stream.ts +++ b/cli/js/web/streams/transform_stream.ts @@ -11,10 +11,10 @@ import { setUpTransformStreamDefaultControllerFromTransformer, validateAndNormalizeHighWaterMark, } from "./internals.ts"; -import { ReadableStreamImpl } from "./readable_stream.ts"; +import type { ReadableStreamImpl } from "./readable_stream.ts"; import * as sym from "./symbols.ts"; -import { TransformStreamDefaultControllerImpl } from "./transform_stream_default_controller.ts"; -import { WritableStreamImpl } from "./writable_stream.ts"; +import type { TransformStreamDefaultControllerImpl } from "./transform_stream_default_controller.ts"; +import type { WritableStreamImpl } from "./writable_stream.ts"; import { customInspect, inspect } from "../console.ts"; // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/cli/js/web/streams/transform_stream_default_controller.ts b/cli/js/web/streams/transform_stream_default_controller.ts index 2fc8d2160081a3..78beaf8794229d 100644 --- a/cli/js/web/streams/transform_stream_default_controller.ts +++ b/cli/js/web/streams/transform_stream_default_controller.ts @@ -10,9 +10,9 @@ import { transformStreamDefaultControllerError, transformStreamDefaultControllerTerminate, } from "./internals.ts"; -import { ReadableStreamDefaultControllerImpl } from "./readable_stream_default_controller.ts"; +import type { ReadableStreamDefaultControllerImpl } from "./readable_stream_default_controller.ts"; import * as sym from "./symbols.ts"; -import { TransformStreamImpl } from "./transform_stream.ts"; +import type { TransformStreamImpl } from "./transform_stream.ts"; import { customInspect } from "../console.ts"; // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/cli/js/web/streams/writable_stream.ts b/cli/js/web/streams/writable_stream.ts index 4bbf339daefd79..8a31f512d3892d 100644 --- a/cli/js/web/streams/writable_stream.ts +++ b/cli/js/web/streams/writable_stream.ts @@ -16,8 +16,8 @@ import { validateAndNormalizeHighWaterMark, } from "./internals.ts"; import * as sym from "./symbols.ts"; -import { WritableStreamDefaultControllerImpl } from "./writable_stream_default_controller.ts"; -import { WritableStreamDefaultWriterImpl } from "./writable_stream_default_writer.ts"; +import type { WritableStreamDefaultControllerImpl } from "./writable_stream_default_controller.ts"; +import type { WritableStreamDefaultWriterImpl } from "./writable_stream_default_writer.ts"; import { customInspect } from "../console.ts"; // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/cli/js/web/streams/writable_stream_default_controller.ts b/cli/js/web/streams/writable_stream_default_controller.ts index 040d0eefcf27e8..b957c2c8f4a478 100644 --- a/cli/js/web/streams/writable_stream_default_controller.ts +++ b/cli/js/web/streams/writable_stream_default_controller.ts @@ -13,7 +13,7 @@ import { writableStreamDefaultControllerError, } from "./internals.ts"; import * as sym from "./symbols.ts"; -import { WritableStreamImpl } from "./writable_stream.ts"; +import type { WritableStreamImpl } from "./writable_stream.ts"; import { customInspect } from "../console.ts"; export class WritableStreamDefaultControllerImpl diff --git a/cli/js/web/streams/writable_stream_default_writer.ts b/cli/js/web/streams/writable_stream_default_writer.ts index 444a77aa9cd385..09b47c69fe07f4 100644 --- a/cli/js/web/streams/writable_stream_default_writer.ts +++ b/cli/js/web/streams/writable_stream_default_writer.ts @@ -16,7 +16,7 @@ import { writableStreamDefaultWriterWrite, } from "./internals.ts"; import * as sym from "./symbols.ts"; -import { WritableStreamImpl } from "./writable_stream.ts"; +import type { WritableStreamImpl } from "./writable_stream.ts"; import { customInspect } from "../console.ts"; import { assert } from "../../util.ts"; diff --git a/cli/msg.rs b/cli/msg.rs index 3e5000296ca995..5c50c96ab3e396 100644 --- a/cli/msg.rs +++ b/cli/msg.rs @@ -55,10 +55,11 @@ pub fn enum_name_media_type(mt: MediaType) -> &'static str { #[derive(Clone, Copy, PartialEq, Debug)] pub enum CompilerRequestType { Compile = 0, - Bundle = 1, - RuntimeCompile = 2, - RuntimeBundle = 3, - RuntimeTranspile = 4, + Transpile = 1, + Bundle = 2, + RuntimeCompile = 3, + RuntimeBundle = 4, + RuntimeTranspile = 5, } impl Serialize for CompilerRequestType { @@ -68,10 +69,11 @@ impl Serialize for CompilerRequestType { { let value: i32 = match self { CompilerRequestType::Compile => 0 as i32, - CompilerRequestType::Bundle => 1 as i32, - CompilerRequestType::RuntimeCompile => 2 as i32, - CompilerRequestType::RuntimeBundle => 3 as i32, - CompilerRequestType::RuntimeTranspile => 4 as i32, + CompilerRequestType::Transpile => 1 as i32, + CompilerRequestType::Bundle => 2 as i32, + CompilerRequestType::RuntimeCompile => 3 as i32, + CompilerRequestType::RuntimeBundle => 4 as i32, + CompilerRequestType::RuntimeTranspile => 5 as i32, }; Serialize::serialize(&value, serializer) } diff --git a/cli/tests/error_no_check.ts b/cli/tests/error_no_check.ts new file mode 100644 index 00000000000000..db9257a1d37621 --- /dev/null +++ b/cli/tests/error_no_check.ts @@ -0,0 +1 @@ +export { AnInterface, isAnInterface } from "./subdir/type_and_code.ts"; diff --git a/cli/tests/error_no_check.ts.out b/cli/tests/error_no_check.ts.out new file mode 100644 index 00000000000000..5890d1db8ff4f6 --- /dev/null +++ b/cli/tests/error_no_check.ts.out @@ -0,0 +1 @@ +error: Uncaught SyntaxError: The requested module './subdir/type_and_code.ts' does not provide an export named 'AnInterface' diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs index 562c25de2bcc5a..9acb4ed3f098c0 100644 --- a/cli/tests/integration_tests.rs +++ b/cli/tests/integration_tests.rs @@ -16,6 +16,7 @@ use tempfile::TempDir; fn std_tests() { let dir = TempDir::new().expect("tempdir fail"); let std_path = util::root_path().join("std"); + let std_config = std_path.join("tsconfig_test.json"); let status = util::deno_cmd() .env("DENO_DIR", dir.path()) .current_dir(std_path) // TODO(ry) change this to root_path @@ -23,6 +24,8 @@ fn std_tests() { .arg("--unstable") .arg("--seed=86") // Some tests rely on specific random numbers. .arg("-A") + .arg("--config") + .arg(std_config.to_str().unwrap()) // .arg("-Ldebug") .spawn() .unwrap() @@ -1832,6 +1835,12 @@ itest!(error_025_tab_indent { exit_code: 1, }); +itest!(error_no_check { + args: "run --reload --no-check error_no_check.ts", + output: "error_no_check.ts.out", + exit_code: 1, +}); + itest!(error_syntax { args: "run --reload error_syntax.js", exit_code: 1, @@ -1890,6 +1899,12 @@ itest!(main_module { output: "main_module.ts.out", }); +itest!(no_check { + args: "run --quiet --reload --no-check 006_url_imports.ts", + output: "006_url_imports.ts.out", + http_server: true, +}); + itest!(lib_ref { args: "run --quiet --unstable --reload lib_ref.ts", output: "lib_ref.ts.out", diff --git a/cli/tests/subdir/type_and_code.ts b/cli/tests/subdir/type_and_code.ts new file mode 100644 index 00000000000000..b1471341958765 --- /dev/null +++ b/cli/tests/subdir/type_and_code.ts @@ -0,0 +1,7 @@ +export interface AnInterface { + a: string; +} + +export function isAnInterface(value: unknown): value is AnInterface { + return value && typeof value === "object" && "a" in value; +} diff --git a/cli/tsc.rs b/cli/tsc.rs index 9f8216e52b9d6d..2a1307432651fa 100644 --- a/cli/tsc.rs +++ b/cli/tsc.rs @@ -302,6 +302,13 @@ impl CompiledFileMetadata { } } +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +struct TranspileSourceFile { + pub source_code: String, + pub file_name: String, +} + /// Emit a SHA256 hash based on source code, deno version and TS config. /// Used to check if a recompilation for source code is needed. fn source_code_version_hash( @@ -376,6 +383,13 @@ struct CompileResponse { build_info: Option, stats: Option>, } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct TranspileResponse { + diagnostics: Diagnostic, + emit_map: HashMap, + stats: Option>, +} // TODO(bartlomieju): possible deduplicate once TS refactor is stabilized #[derive(Deserialize)] @@ -704,6 +718,72 @@ impl TsCompiler { Ok(output) } + pub async fn transpile( + &self, + global_state: GlobalState, + permissions: Permissions, + module_graph: ModuleGraph, + ) -> Result<(), ErrBox> { + let mut source_files: Vec = Vec::new(); + for (_, value) in module_graph.iter() { + let url = Url::parse(&value.url).expect("Filename is not a valid url"); + if !value.url.ends_with(".d.ts") + && (!self.use_disk_cache || !self.has_compiled_source(&url)) + { + source_files.push(TranspileSourceFile { + source_code: value.source_code.clone(), + file_name: value.url.clone(), + }); + } + } + if source_files.is_empty() { + return Ok(()); + } + + let source_files_json = + serde_json::to_value(source_files).expect("Filed to serialize data"); + let compiler_config = self.config.clone(); + let cwd = std::env::current_dir().unwrap(); + let performance = match global_state.flags.log_level { + Some(Level::Debug) => true, + _ => false, + }; + let j = match (compiler_config.path, compiler_config.content) { + (Some(config_path), Some(config_data)) => json!({ + "config": str::from_utf8(&config_data).unwrap(), + "configPath": config_path, + "cwd": cwd, + "performance": performance, + "sourceFiles": source_files_json, + "type": msg::CompilerRequestType::Transpile, + }), + _ => json!({ + "performance": performance, + "sourceFiles": source_files_json, + "type": msg::CompilerRequestType::Transpile, + }), + }; + + let req_msg = j.to_string().into_boxed_str().into_boxed_bytes(); + + let msg = + execute_in_same_thread(global_state.clone(), permissions, req_msg) + .await?; + + let json_str = std::str::from_utf8(&msg).unwrap(); + + let transpile_response: TranspileResponse = serde_json::from_str(json_str)?; + + if !transpile_response.diagnostics.items.is_empty() { + return Err(ErrBox::from(transpile_response.diagnostics)); + } + + maybe_log_stats(transpile_response.stats); + + self.cache_emitted_files(transpile_response.emit_map)?; + Ok(()) + } + /// Get associated `CompiledFileMetadata` for given module if it exists. fn get_metadata(&self, url: &Url) -> Option { // Try to load cached version: @@ -1574,6 +1654,75 @@ mod tests { .starts_with("//# sourceMappingURL=data:application/json;base64")); } + #[tokio::test] + async fn test_transpile() { + let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .join("cli/tests/002_hello.ts"); + let specifier = + ModuleSpecifier::resolve_url_or_path(p.to_str().unwrap()).unwrap(); + let out = SourceFile { + url: specifier.as_url().clone(), + filename: PathBuf::from(p.to_str().unwrap().to_string()), + media_type: msg::MediaType::TypeScript, + source_code: include_bytes!("./tests/002_hello.ts").to_vec(), + types_header: None, + }; + let dir = + deno_dir::DenoDir::new(Some(test_util::new_deno_dir().path().to_owned())) + .unwrap(); + let http_cache = http_cache::HttpCache::new(&dir.root.join("deps")); + let mock_state = GlobalState::mock( + vec![String::from("deno"), String::from("hello.ts")], + None, + ); + let file_fetcher = SourceFileFetcher::new( + http_cache, + true, + mock_state.flags.cache_blocklist.clone(), + false, + false, + None, + ) + .unwrap(); + + let mut module_graph_loader = ModuleGraphLoader::new( + file_fetcher.clone(), + None, + Permissions::allow_all(), + false, + false, + ); + module_graph_loader + .add_to_graph(&specifier, None) + .await + .expect("Failed to create graph"); + let module_graph = module_graph_loader.get_graph(); + + let ts_compiler = TsCompiler::new( + file_fetcher, + mock_state.flags.clone(), + dir.gen_cache.clone(), + ) + .unwrap(); + + let result = ts_compiler + .transpile(mock_state.clone(), Permissions::allow_all(), module_graph) + .await; + assert!(result.is_ok()); + let compiled_file = ts_compiler.get_compiled_module(&out.url).unwrap(); + let source_code = compiled_file.code; + assert!(source_code + .as_bytes() + .starts_with(b"console.log(\"Hello World\");")); + let mut lines: Vec = + source_code.split('\n').map(|s| s.to_string()).collect(); + let last_line = lines.pop().unwrap(); + assert!(last_line + .starts_with("//# sourceMappingURL=data:application/json;base64")); + } + #[tokio::test] async fn test_bundle() { let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) diff --git a/deno_typescript/lib.rs b/deno_typescript/lib.rs index 25e5a7fd03d59e..54d9b1d3bb0af3 100644 --- a/deno_typescript/lib.rs +++ b/deno_typescript/lib.rs @@ -148,6 +148,11 @@ pub fn compile_bundle( let config_json = serde_json::json!({ "compilerOptions": { "declaration": true, + // In order to help ensure there are no type directed emits in the code + // which interferes with transpiling only, the setting + // `"importsNotUsedAsValues"` set to `"error"` will help ensure that items + // that are written as `import type` are caught and are treated as errors. + "importsNotUsedAsValues": "error", // Emit the source alongside the sourcemaps within a single file; // requires --inlineSourceMap or --sourceMap to be set. // "inlineSources": true, diff --git a/std/encoding/_yaml/dumper/dumper.ts b/std/encoding/_yaml/dumper/dumper.ts index 1280ee75729379..2b23d475813d19 100644 --- a/std/encoding/_yaml/dumper/dumper.ts +++ b/std/encoding/_yaml/dumper/dumper.ts @@ -6,7 +6,7 @@ /* eslint-disable max-len */ import { YAMLError } from "../error.ts"; -import { RepresentFn, StyleVariant, Type } from "../type.ts"; +import type { RepresentFn, StyleVariant, Type } from "../type.ts"; import * as common from "../utils.ts"; import { DumperState, DumperStateOptions } from "./dumper_state.ts"; diff --git a/std/encoding/_yaml/dumper/dumper_state.ts b/std/encoding/_yaml/dumper/dumper_state.ts index 3c1de0e0e86e80..2124ecb9857fd6 100644 --- a/std/encoding/_yaml/dumper/dumper_state.ts +++ b/std/encoding/_yaml/dumper/dumper_state.ts @@ -3,10 +3,10 @@ // Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { Schema, SchemaDefinition } from "../schema.ts"; +import type { Schema, SchemaDefinition } from "../schema.ts"; import { State } from "../state.ts"; -import { StyleVariant, Type } from "../type.ts"; -import { ArrayObject, Any } from "../utils.ts"; +import type { StyleVariant, Type } from "../type.ts"; +import type { ArrayObject, Any } from "../utils.ts"; const _hasOwnProperty = Object.prototype.hasOwnProperty; diff --git a/std/encoding/_yaml/error.ts b/std/encoding/_yaml/error.ts index 7f305ccf2c5d3a..a96ab11d6cc717 100644 --- a/std/encoding/_yaml/error.ts +++ b/std/encoding/_yaml/error.ts @@ -3,7 +3,7 @@ // Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { Mark } from "./mark.ts"; +import type { Mark } from "./mark.ts"; export class YAMLError extends Error { constructor( diff --git a/std/encoding/_yaml/loader/loader.ts b/std/encoding/_yaml/loader/loader.ts index 39954c280342bc..4ab3e9adc78d2c 100644 --- a/std/encoding/_yaml/loader/loader.ts +++ b/std/encoding/_yaml/loader/loader.ts @@ -7,7 +7,7 @@ import { YAMLError } from "../error.ts"; import { Mark } from "../mark.ts"; -import { Type } from "../type.ts"; +import type { Type } from "../type.ts"; import * as common from "../utils.ts"; import { LoaderState, LoaderStateOptions, ResultType } from "./loader_state.ts"; diff --git a/std/encoding/_yaml/loader/loader_state.ts b/std/encoding/_yaml/loader/loader_state.ts index ca50fcaf1dbd97..781a4a08633b4b 100644 --- a/std/encoding/_yaml/loader/loader_state.ts +++ b/std/encoding/_yaml/loader/loader_state.ts @@ -3,11 +3,11 @@ // Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { YAMLError } from "../error.ts"; -import { Schema, SchemaDefinition, TypeMap } from "../schema.ts"; +import type { YAMLError } from "../error.ts"; +import type { Schema, SchemaDefinition, TypeMap } from "../schema.ts"; import { State } from "../state.ts"; -import { Type } from "../type.ts"; -import { Any, ArrayObject } from "../utils.ts"; +import type { Type } from "../type.ts"; +import type { Any, ArrayObject } from "../utils.ts"; export interface LoaderStateOptions { legacy?: boolean; diff --git a/std/encoding/_yaml/parse.ts b/std/encoding/_yaml/parse.ts index 2aa0042bdd5f93..9a6f325f24190b 100644 --- a/std/encoding/_yaml/parse.ts +++ b/std/encoding/_yaml/parse.ts @@ -4,7 +4,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { CbFunction, load, loadAll } from "./loader/loader.ts"; -import { LoaderStateOptions } from "./loader/loader_state.ts"; +import type { LoaderStateOptions } from "./loader/loader_state.ts"; export type ParseOptions = LoaderStateOptions; diff --git a/std/encoding/_yaml/schema.ts b/std/encoding/_yaml/schema.ts index 579644dbb7c775..98b49203cc3470 100644 --- a/std/encoding/_yaml/schema.ts +++ b/std/encoding/_yaml/schema.ts @@ -4,8 +4,8 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { YAMLError } from "./error.ts"; -import { KindType, Type } from "./type.ts"; -import { ArrayObject, Any } from "./utils.ts"; +import type { KindType, Type } from "./type.ts"; +import type { ArrayObject, Any } from "./utils.ts"; function compileList( schema: Schema, diff --git a/std/encoding/_yaml/state.ts b/std/encoding/_yaml/state.ts index 6df6dc04766e25..67a105d39ef0be 100644 --- a/std/encoding/_yaml/state.ts +++ b/std/encoding/_yaml/state.ts @@ -3,7 +3,7 @@ // Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { SchemaDefinition } from "./schema.ts"; +import type { SchemaDefinition } from "./schema.ts"; import { DEFAULT_SCHEMA } from "./schema/mod.ts"; export abstract class State { diff --git a/std/encoding/_yaml/stringify.ts b/std/encoding/_yaml/stringify.ts index f037631d9c8565..9b3b5a80ec0cc0 100644 --- a/std/encoding/_yaml/stringify.ts +++ b/std/encoding/_yaml/stringify.ts @@ -4,7 +4,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { dump } from "./dumper/dumper.ts"; -import { DumperStateOptions } from "./dumper/dumper_state.ts"; +import type { DumperStateOptions } from "./dumper/dumper_state.ts"; export type DumpOptions = DumperStateOptions; diff --git a/std/encoding/_yaml/type.ts b/std/encoding/_yaml/type.ts index 4a2c6bbacf2806..18dee338c3d877 100644 --- a/std/encoding/_yaml/type.ts +++ b/std/encoding/_yaml/type.ts @@ -3,7 +3,7 @@ // Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { ArrayObject, Any } from "./utils.ts"; +import type { ArrayObject, Any } from "./utils.ts"; export type KindType = "sequence" | "scalar" | "mapping"; export type StyleVariant = "lowercase" | "uppercase" | "camelcase" | "decimal"; diff --git a/std/encoding/_yaml/type/binary.ts b/std/encoding/_yaml/type/binary.ts index 1a321afe83b13e..2433960dcc98be 100644 --- a/std/encoding/_yaml/type/binary.ts +++ b/std/encoding/_yaml/type/binary.ts @@ -3,7 +3,7 @@ // https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { Type } from "../type.ts"; -import { Any } from "../utils.ts"; +import type { Any } from "../utils.ts"; // [ 64, 65, 66 ] -> [ padding, CR, LF ] const BASE64_MAP = diff --git a/std/encoding/_yaml/type/map.ts b/std/encoding/_yaml/type/map.ts index dcd99abcac9711..c0c8b04b722b10 100644 --- a/std/encoding/_yaml/type/map.ts +++ b/std/encoding/_yaml/type/map.ts @@ -4,7 +4,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { Type } from "../type.ts"; -import { Any } from "../utils.ts"; +import type { Any } from "../utils.ts"; export const map = new Type("tag:yaml.org,2002:map", { construct(data): Any { diff --git a/std/encoding/_yaml/type/omap.ts b/std/encoding/_yaml/type/omap.ts index d6d7515058196b..785846dea90089 100644 --- a/std/encoding/_yaml/type/omap.ts +++ b/std/encoding/_yaml/type/omap.ts @@ -4,7 +4,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { Type } from "../type.ts"; -import { Any } from "../utils.ts"; +import type { Any } from "../utils.ts"; const _hasOwnProperty = Object.prototype.hasOwnProperty; const _toString = Object.prototype.toString; diff --git a/std/encoding/_yaml/type/pairs.ts b/std/encoding/_yaml/type/pairs.ts index e999748ae73559..5e3eac5ced8677 100644 --- a/std/encoding/_yaml/type/pairs.ts +++ b/std/encoding/_yaml/type/pairs.ts @@ -4,7 +4,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { Type } from "../type.ts"; -import { Any } from "../utils.ts"; +import type { Any } from "../utils.ts"; const _toString = Object.prototype.toString; diff --git a/std/encoding/_yaml/type/seq.ts b/std/encoding/_yaml/type/seq.ts index b19565dbca8dfd..df2caaece6e7bd 100644 --- a/std/encoding/_yaml/type/seq.ts +++ b/std/encoding/_yaml/type/seq.ts @@ -4,7 +4,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { Type } from "../type.ts"; -import { Any } from "../utils.ts"; +import type { Any } from "../utils.ts"; export const seq = new Type("tag:yaml.org,2002:seq", { construct(data): Any { diff --git a/std/encoding/_yaml/type/set.ts b/std/encoding/_yaml/type/set.ts index 0bfe1c8db4e458..8fe04e6f0c6988 100644 --- a/std/encoding/_yaml/type/set.ts +++ b/std/encoding/_yaml/type/set.ts @@ -4,7 +4,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { Type } from "../type.ts"; -import { Any } from "../utils.ts"; +import type { Any } from "../utils.ts"; const _hasOwnProperty = Object.prototype.hasOwnProperty; diff --git a/std/encoding/yaml.ts b/std/encoding/yaml.ts index 78866ed2a6f959..19245b2fccf42a 100644 --- a/std/encoding/yaml.ts +++ b/std/encoding/yaml.ts @@ -3,13 +3,12 @@ // Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -export { ParseOptions, parse, parseAll } from "./_yaml/parse.ts"; -export { - DumpOptions as StringifyOptions, - stringify, -} from "./_yaml/stringify.ts"; -export { SchemaDefinition } from "./_yaml/schema.ts"; -export { StyleVariant } from "./_yaml/type.ts"; +export type { ParseOptions } from "./_yaml/parse.ts"; +export { parse, parseAll } from "./_yaml/parse.ts"; +export type { DumpOptions as StringifyOptions } from "./_yaml/stringify.ts"; +export { stringify } from "./_yaml/stringify.ts"; +export type { SchemaDefinition } from "./_yaml/schema.ts"; +export type { StyleVariant } from "./_yaml/type.ts"; export { CORE_SCHEMA, DEFAULT_SCHEMA, diff --git a/std/hash/_wasm/hash.ts b/std/hash/_wasm/hash.ts index d04a4d4a02b99f..43ddf77f3c57f8 100644 --- a/std/hash/_wasm/hash.ts +++ b/std/hash/_wasm/hash.ts @@ -10,7 +10,7 @@ import init, { import * as hex from "../../encoding/hex.ts"; import * as base64 from "../../encoding/base64.ts"; -import { Hasher, Message, OutputFormat } from "../hasher.ts"; +import type { Hasher, Message, OutputFormat } from "../hasher.ts"; await init(source); diff --git a/std/hash/mod.ts b/std/hash/mod.ts index 946769f039ce03..06c9ce4395b668 100644 --- a/std/hash/mod.ts +++ b/std/hash/mod.ts @@ -1,9 +1,9 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { Hash } from "./_wasm/hash.ts"; -import { Hasher } from "./hasher.ts"; +import type { Hasher } from "./hasher.ts"; -export { Hasher } from "./hasher.ts"; +export type { Hasher } from "./hasher.ts"; export type SupportedAlgorithm = | "md2" | "md4" diff --git a/std/io/ioutil.ts b/std/io/ioutil.ts index 3d9e72b569ebe1..ac6d103a3aa707 100644 --- a/std/io/ioutil.ts +++ b/std/io/ioutil.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { BufReader } from "./bufio.ts"; +import type { BufReader } from "./bufio.ts"; type Reader = Deno.Reader; type Writer = Deno.Writer; import { assert } from "../_util/assert.ts"; diff --git a/std/log/handlers.ts b/std/log/handlers.ts index 0efa7cc269d1f7..e09dc648c2e5e1 100644 --- a/std/log/handlers.ts +++ b/std/log/handlers.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { getLevelByName, LevelName, LogLevels } from "./levels.ts"; -import { LogRecord } from "./logger.ts"; +import type { LogRecord } from "./logger.ts"; import { red, yellow, blue, bold } from "../fmt/colors.ts"; import { existsSync, exists } from "../fs/exists.ts"; import { BufWriterSync } from "../io/bufio.ts"; diff --git a/std/log/logger.ts b/std/log/logger.ts index 05e83dc772d270..482047f2ac8bb7 100644 --- a/std/log/logger.ts +++ b/std/log/logger.ts @@ -5,7 +5,7 @@ import { getLevelName, LevelName, } from "./levels.ts"; -import { BaseHandler } from "./handlers.ts"; +import type { BaseHandler } from "./handlers.ts"; export interface LogRecordOptions { msg: string; diff --git a/std/log/mod.ts b/std/log/mod.ts index ed94725c4915c7..9565749aacd786 100644 --- a/std/log/mod.ts +++ b/std/log/mod.ts @@ -8,7 +8,7 @@ import { RotatingFileHandler, } from "./handlers.ts"; import { assert } from "../_util/assert.ts"; -import { LevelName } from "./levels.ts"; +import type { LevelName } from "./levels.ts"; export { LogLevels, LevelName } from "./levels.ts"; export { Logger } from "./logger.ts"; diff --git a/std/node/_fs/_fs_access.ts b/std/node/_fs/_fs_access.ts index ee93c4c7f03992..79e4ca96db5ecb 100644 --- a/std/node/_fs/_fs_access.ts +++ b/std/node/_fs/_fs_access.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { CallbackWithError } from "./_fs_common.ts"; +import type { CallbackWithError } from "./_fs_common.ts"; import { notImplemented } from "../_utils.ts"; /** Revist once https://github.com/denoland/deno/issues/4017 lands */ diff --git a/std/node/_fs/_fs_chmod.ts b/std/node/_fs/_fs_chmod.ts index b1079e0a14f24f..844afd21df180c 100644 --- a/std/node/_fs/_fs_chmod.ts +++ b/std/node/_fs/_fs_chmod.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { CallbackWithError } from "./_fs_common.ts"; +import type { CallbackWithError } from "./_fs_common.ts"; import { fromFileUrl } from "../path.ts"; const allowedModes = /^[0-7]{3}/; diff --git a/std/node/_fs/_fs_chown.ts b/std/node/_fs/_fs_chown.ts index cd1973b1f78b07..56068ef738f3cd 100644 --- a/std/node/_fs/_fs_chown.ts +++ b/std/node/_fs/_fs_chown.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { CallbackWithError } from "./_fs_common.ts"; +import type { CallbackWithError } from "./_fs_common.ts"; import { fromFileUrl } from "../path.ts"; /** diff --git a/std/node/_fs/_fs_close.ts b/std/node/_fs/_fs_close.ts index cdd815ad9dede6..add6f6663eaecc 100644 --- a/std/node/_fs/_fs_close.ts +++ b/std/node/_fs/_fs_close.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { CallbackWithError } from "./_fs_common.ts"; +import type { CallbackWithError } from "./_fs_common.ts"; export function close(fd: number, callback: CallbackWithError): void { queueMicrotask(() => { diff --git a/std/node/_fs/_fs_copy.ts b/std/node/_fs/_fs_copy.ts index 26d9a8c9a26d1a..72f43d18fc5151 100644 --- a/std/node/_fs/_fs_copy.ts +++ b/std/node/_fs/_fs_copy.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { CallbackWithError } from "./_fs_common.ts"; +import type { CallbackWithError } from "./_fs_common.ts"; import { fromFileUrl } from "../path.ts"; export function copyFile( diff --git a/std/node/_fs/_fs_dir_test.ts b/std/node/_fs/_fs_dir_test.ts index e8991277269e07..2d2d5f5857decc 100644 --- a/std/node/_fs/_fs_dir_test.ts +++ b/std/node/_fs/_fs_dir_test.ts @@ -1,6 +1,6 @@ import { assert, assertEquals, fail } from "../../testing/asserts.ts"; import Dir from "./_fs_dir.ts"; -import Dirent from "./_fs_dirent.ts"; +import type Dirent from "./_fs_dirent.ts"; Deno.test({ name: "Closing current directory with callback is successful", diff --git a/std/node/_fs/_fs_link.ts b/std/node/_fs/_fs_link.ts index 50916a7ba0d7ef..df08e13b1b6f67 100644 --- a/std/node/_fs/_fs_link.ts +++ b/std/node/_fs/_fs_link.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { CallbackWithError } from "./_fs_common.ts"; +import type { CallbackWithError } from "./_fs_common.ts"; import { fromFileUrl } from "../path.ts"; /** diff --git a/std/node/_fs/_fs_mkdir.ts b/std/node/_fs/_fs_mkdir.ts index a65db8dba3d868..8578f465373bf0 100644 --- a/std/node/_fs/_fs_mkdir.ts +++ b/std/node/_fs/_fs_mkdir.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { CallbackWithError } from "./_fs_common.ts"; +import type { CallbackWithError } from "./_fs_common.ts"; import { fromFileUrl } from "../path.ts"; /** @@ -31,10 +31,11 @@ export function mkdir( if (options.recursive !== undefined) recursive = options.recursive; if (options.mode !== undefined) mode = options.mode; } - if (typeof recursive !== "boolean") + if (typeof recursive !== "boolean") { throw new Deno.errors.InvalidData( "invalid recursive option , must be a boolean" ); + } Deno.mkdir(path, { recursive, mode }) .then(() => { if (typeof callback === "function") { @@ -61,10 +62,11 @@ export function mkdirSync(path: string | URL, options?: MkdirOptions): void { if (options.recursive !== undefined) recursive = options.recursive; if (options.mode !== undefined) mode = options.mode; } - if (typeof recursive !== "boolean") + if (typeof recursive !== "boolean") { throw new Deno.errors.InvalidData( "invalid recursive option , must be a boolean" ); + } Deno.mkdirSync(path, { recursive, mode }); } diff --git a/std/node/_fs/_fs_writeFile_test.ts b/std/node/_fs/_fs_writeFile_test.ts index 3959ad219193a7..015ed65538c19b 100644 --- a/std/node/_fs/_fs_writeFile_test.ts +++ b/std/node/_fs/_fs_writeFile_test.ts @@ -6,7 +6,7 @@ import { assertThrows, } from "../../testing/asserts.ts"; import { writeFile, writeFileSync } from "./_fs_writeFile.ts"; -import { TextEncodings } from "./_fs_common.ts"; +import type { TextEncodings } from "./_fs_common.ts"; import * as path from "../../path/mod.ts"; const testDataDir = path.resolve(path.join("node", "_fs", "testdata")); diff --git a/std/node/_fs/promises/_fs_readFile.ts b/std/node/_fs/promises/_fs_readFile.ts index 83ef9ac50d09cb..8677e05cd493d4 100644 --- a/std/node/_fs/promises/_fs_readFile.ts +++ b/std/node/_fs/promises/_fs_readFile.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { +import type { FileOptionsArgument, BinaryOptionsArgument, TextOptionsArgument, @@ -21,8 +21,9 @@ export function readFile( return new Promise((resolve, reject) => { readFileCallback(path, options, (err, data): void => { if (err) return reject(err); - if (data == null) + if (data == null) { return reject(new Error("Invalid state: data missing, but no error")); + } resolve(data); }); }); diff --git a/std/node/_fs/promises/_fs_writeFile.ts b/std/node/_fs/promises/_fs_writeFile.ts index 4f7c39a6a205c6..48b9bf0eaf2fc9 100644 --- a/std/node/_fs/promises/_fs_writeFile.ts +++ b/std/node/_fs/promises/_fs_writeFile.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { Encodings, WriteFileOptions } from "../_fs_common.ts"; +import type { Encodings, WriteFileOptions } from "../_fs_common.ts"; import { writeFile as writeFileCallback } from "../_fs_writeFile.ts"; diff --git a/std/node/_fs/promises/_fs_writeFile_test.ts b/std/node/_fs/promises/_fs_writeFile_test.ts index 8f6ef0842d5cba..6901fff22e0df9 100644 --- a/std/node/_fs/promises/_fs_writeFile_test.ts +++ b/std/node/_fs/promises/_fs_writeFile_test.ts @@ -6,7 +6,7 @@ import { assertThrowsAsync, } from "../../../testing/asserts.ts"; import { writeFile } from "./_fs_writeFile.ts"; -import { TextEncodings } from "../_fs_common.ts"; +import type { TextEncodings } from "../_fs_common.ts"; const decoder = new TextDecoder("utf-8"); diff --git a/std/path/_util.ts b/std/path/_util.ts index 8ae40373b21971..0c325304520e97 100644 --- a/std/path/_util.ts +++ b/std/path/_util.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ /** This module is browser compatible. */ -import { FormatInputPathObject } from "./_interface.ts"; +import type { FormatInputPathObject } from "./_interface.ts"; import { CHAR_UPPERCASE_A, CHAR_LOWERCASE_A, diff --git a/std/path/posix.ts b/std/path/posix.ts index 1e78d1cfe9ae84..351ceb06ea224e 100644 --- a/std/path/posix.ts +++ b/std/path/posix.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ /** This module is browser compatible. */ -import { FormatInputPathObject, ParsedPath } from "./_interface.ts"; +import type { FormatInputPathObject, ParsedPath } from "./_interface.ts"; import { CHAR_DOT, CHAR_FORWARD_SLASH } from "./_constants.ts"; import { diff --git a/std/path/win32.ts b/std/path/win32.ts index bac43a61a9a719..30482e45365443 100644 --- a/std/path/win32.ts +++ b/std/path/win32.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ /** This module is browser compatible. */ -import { FormatInputPathObject, ParsedPath } from "./_interface.ts"; +import type { FormatInputPathObject, ParsedPath } from "./_interface.ts"; import { CHAR_DOT, CHAR_BACKWARD_SLASH, diff --git a/std/textproto/mod.ts b/std/textproto/mod.ts index f440ba5d50a057..1d0d22715a25b0 100644 --- a/std/textproto/mod.ts +++ b/std/textproto/mod.ts @@ -3,7 +3,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -import { BufReader } from "../io/bufio.ts"; +import type { BufReader } from "../io/bufio.ts"; import { concat } from "../bytes/mod.ts"; import { decode } from "../encoding/utf8.ts"; diff --git a/std/tsconfig_test.json b/std/tsconfig_test.json new file mode 100644 index 00000000000000..1dbf69fb2ec2d6 --- /dev/null +++ b/std/tsconfig_test.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "importsNotUsedAsValues": "error" + } +} diff --git a/tools/benchmark.py b/tools/benchmark.py index 369aa6fcaa72cf..b79f35ac83acdb 100755 --- a/tools/benchmark.py +++ b/tools/benchmark.py @@ -31,6 +31,10 @@ ["run", "--allow-read", "cli/tests/workers_round_robin_bench.ts"], None), ("text_decoder", ["run", "cli/tests/text_decoder_perf.js"], None), ("text_encoder", ["run", "cli/tests/text_encoder_perf.js"], None), + ("check", ["cache", "--reload", "std/examples/chat/server_test.ts"], None), + ("no_check", + ["cache", "--reload", "--no-check", + "std/examples/chat/server_test.ts"], None), ]