Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v22.7.0 proposal #54452

Merged
merged 157 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
157 commits
Select commit Hold shift + click to select a range
d52f515
crypto: include NODE_EXTRA_CA_CERTS in all secure contexts by default
ebickle Sep 5, 2022
8b35f0e
tools: update eslint to 9.8.0
nodejs-github-bot Jul 30, 2024
267cd7f
path: use the correct name in `validateString`
bpasero Jul 30, 2024
019ebf0
buffer: use faster integer argument check
ronag Jul 30, 2024
037672f
url: improve resolveObject with ObjectAssign
EarlyRiser42 Jul 31, 2024
923195b
doc: clarify `useCodeCache` setting for cross-platform SEA generation
debbs061 Jul 31, 2024
826edc4
doc: expand troubleshooting section
lirantal Jul 31, 2024
33633ee
meta: add typescript team to codeowners
marco-ippolito Jul 31, 2024
b52c2ff
src: account for OpenSSL unexpected version
codebytere Jul 31, 2024
af99ba3
doc: remove unused imports from worker_threads.md
debbs061 Jul 31, 2024
2a6a12e
stream: throw TypeError when criteria fulfilled in getIterator
jakecastelli Aug 1, 2024
13cc480
module: remove outdated comment
targos Aug 1, 2024
a4aecd2
typings: add missing binding function `writeFileUtf8()`
pluris Aug 1, 2024
9f8f26e
buffer: use native copy impl
ronag Aug 2, 2024
7772b46
doc: update list of Triagers on the `README.md`
aduh95 Aug 2, 2024
98fed76
build: add `--without-amaro` build flag
aduh95 Aug 2, 2024
1cafefd
doc: fix worker threadId/destination typo
tlhunter Aug 2, 2024
5dbff81
test: add coverage for webstorage quota
jakecastelli Jul 20, 2024
9ee4b16
lib: rewrite AsyncLocalStorage without async_hooks
Qard Aug 2, 2024
db3b0df
doc: add missing new lines to custom test reporter examples
EddieAbbondanzio Aug 3, 2024
8c9a4ae
lib,permission: support Buffer to permission.has
RafaelGSS Aug 3, 2024
ab6fae9
buffer: faster type check
ronag Aug 3, 2024
1a15f3f
test: add initial pull delay and prototype pollution prevention tests
sonsurim Aug 3, 2024
670c796
test: fix typo in test
sonsurim Aug 4, 2024
db0a80a
benchmark: use assert.ok instead of assert
RafaelGSS Aug 4, 2024
11fdaa6
doc: add documentation for blob.bytes() method
jmsb02 Jul 30, 2024
20a01fc
test_runner: run after hooks even if test is aborted
cjihrig Aug 4, 2024
358fdac
doc: refresh instructions for building node from source
lirantal Aug 4, 2024
37631f8
buffer: add JSDoc to blob bytes method
RobertoSimonini1 Aug 5, 2024
425b956
lib: fix typos in comments within internal/streams
MCprotein Aug 5, 2024
5a1afb2
test_runner: remove outdated comment
cjihrig Jul 31, 2024
e218b7c
tools: add strip-types to label system
marco-ippolito Aug 5, 2024
4d8b53e
watch: reload changes in contents of --env-file
marekpiechut Aug 5, 2024
9297d29
stream: make checking pendingcb on WritableStream backward compatible
jakecastelli Aug 5, 2024
1e82591
inspector: provide detailed info to fix DevTools frontend errors
cola119 Aug 5, 2024
e619133
src: move spkac methods to ncrypto
jasnell Jul 21, 2024
144637e
doc: move release key for Myles Borins
richardlau Aug 5, 2024
7c305a4
doc, meta: replace command with link to keys
RedYetiDev Aug 5, 2024
31adeea
sea: don't set code cache flags when snapshot is used
joyeecheung Aug 5, 2024
8daeccf
src: shift more crypto impl details to ncrypto
jasnell Jul 24, 2024
5175903
doc: move `onread` option from `socket.connect()` to `new net.socket()`
sendoru Aug 5, 2024
9bbd85e
meta: bump `ossf/scorecard-action` from 2.3.3 to 2.4.0
dependabot[bot] Aug 5, 2024
6a9f168
meta: bump `github/codeql-action` from 3.25.11 to 3.25.15
dependabot[bot] Aug 6, 2024
b733854
meta: bump `actions/setup-node` from 4.0.2 to 4.0.3
dependabot[bot] Aug 6, 2024
dede30a
meta: bump `step-security/harden-runner` from 2.8.1 to 2.9.0
dependabot[bot] Aug 6, 2024
acc5b9a
meta: bump actions/setup-python from 5.1.0 to 5.1.1
dependabot[bot] Aug 1, 2024
7fa95d2
meta: bump `actions/download-artifact` from 4.1.7 to 4.1.8
dependabot[bot] Aug 6, 2024
0157ec6
meta: bump `actions/upload-artifact` from 4.3.3 to 4.3.4
dependabot[bot] Aug 6, 2024
103e4db
deps: update simdutf to 5.3.1
nodejs-github-bot Aug 6, 2024
1597a11
deps: update undici to 6.19.5
nodejs-github-bot Aug 6, 2024
350e699
build: support `lint-js-fix` in `vcbuild.bat`
RedYetiDev Aug 6, 2024
be61793
test: update wpt test for streams
Nahee-Park Aug 6, 2024
88aef5a
doc: add links to security steward companies
RedYetiDev Aug 6, 2024
dafe975
test: set test-structuredclone-jstransferable non-flaky
StefanStojanovic Aug 6, 2024
2f5309f
doc: fix sea assets example
Sadzurami Aug 6, 2024
dc46573
test_runner: make mock_loader not confuse CJS and ESM resolution
syi0808 Aug 6, 2024
8a770cf
path: fix relative on Windows
huseyinacacak-janea Aug 6, 2024
4bfa7d8
doc: add esm examples to node:console
mfdebian Aug 6, 2024
0429b1e
doc: add KevinEady as a triager
legendecas Aug 6, 2024
3835131
tools: add workflow to ensure `README` lists are in sync with gh teams
aduh95 Aug 6, 2024
a5a320c
benchmark: remove force option as force defaults to true
debbs061 Aug 6, 2024
6bcbfcd
test: add subtests to test-node-run
sungpaks Aug 6, 2024
ef9a950
deps: update acorn to 8.12.1
nodejs-github-bot Jun 16, 2024
4dd229f
benchmark: support --help in CLI
RedYetiDev Aug 6, 2024
3f0d734
meta: add module label for the lib/internal/modules folder
RedYetiDev Aug 6, 2024
e3e2f22
doc: add esm examples to node:dns
mfdebian Aug 6, 2024
783322f
lib: fix unhandled errors in webstream adapters
indutny Aug 6, 2024
112228c
fs: remove unnecessary option argument validation
JonasBa Aug 6, 2024
b85b13b
test: use assert.{s,deepS}trictEqual()
lpinca Aug 6, 2024
55f8ac3
doc: make some parameters optional in `tracingChannel.traceCallback`
deokjinkim Jul 27, 2024
581c155
meta: move one or more collaborators to emeritus
nodejs-github-bot Aug 7, 2024
b93c6d9
tools: make undici updater build wasm from src
mhdawson Jul 31, 2024
a394219
src: skip inspector wait in internal workers
legendecas Aug 7, 2024
7fad771
test_runner: fix erroneous diagnostic warning when only: false
pmarchini Aug 8, 2024
3106149
doc: warn for windows build bug
jazelly Aug 8, 2024
f5cfa44
test: refactor `test-runner-module-mocking`
aduh95 Aug 8, 2024
2f68a74
test: fix timeout not being cleared
Isaac-yz-Liu Aug 9, 2024
1ba2000
module: refactor ts parser loading
marco-ippolito Aug 9, 2024
971b9f3
doc: update `buffer.constants.MAX_LENGTH` size
samuliasmala Aug 9, 2024
a476837
typings: add util.styleText type definition
RafaelGSS Aug 9, 2024
b897057
lib: improve async_context_frame structure
Qard Aug 9, 2024
b0c768d
deps: update undici to 6.19.7
nodejs-github-bot Aug 9, 2024
37960a6
console: use validateOneOf for colorMode validation
rayark1 Aug 10, 2024
e676d98
module,win: fix long path resolve
huseyinacacak-janea Aug 10, 2024
1be0ee7
benchmark: change assert() to assert.ok()
RafaelGSS Aug 10, 2024
26c37f7
doc: remove module-based permission doc
RafaelGSS Aug 10, 2024
c8e358c
meta: add test-permission-* CODEOWNERS
RafaelGSS Aug 10, 2024
1535469
doc: explicitly mention node:fs module restriction
RafaelGSS Aug 10, 2024
c166036
benchmark: rename count to n
RafaelGSS Aug 10, 2024
e0d503a
deps: update nbytes to 0.1.1
nodejs-github-bot Aug 10, 2024
d83421f
tty: initialize winSize array with values
targos Aug 11, 2024
911de7d
inspector: support `Network.loadingFailed` event
cola119 Aug 11, 2024
869da20
deps: update c-ares to v1.33.0
nodejs-github-bot Aug 11, 2024
a2a4155
deps: fix GN build warning in ncrypto
zcbenz Aug 11, 2024
6f986e0
doc, test: simplify test README table
RedYetiDev Aug 11, 2024
6f4b5d9
doc: add esm examples to node:http2
mfdebian Aug 11, 2024
09f411e
lib: avoid for of loop and remove unnecessary variable in zlib
MCprotein Aug 12, 2024
35722b7
deps: update simdjson to 3.10.0
nodejs-github-bot Aug 12, 2024
fe7e6c9
deps: update zlib to 1.3.0.1-motley-887bb57
nodejs-github-bot Jun 16, 2024
758c9df
deps: update zlib to 1.3.0.1-motley-e432200
nodejs-github-bot Jun 23, 2024
713ae95
deps: update zlib to 1.3.0.1-motley-8b7eff8
nodejs-github-bot Jun 30, 2024
e7db639
deps: update zlib to 1.3.0.1-motley-68e57e6
nodejs-github-bot Jul 7, 2024
d0c23f3
deps: update zlib to 1.3.0.1-motley-c2469fd
nodejs-github-bot Jul 14, 2024
18bfea5
deps: update zlib to 1.3.0.1-motley-71660e1
nodejs-github-bot Aug 4, 2024
417120a
lib: replace spread operator with primordials function
MCprotein Aug 12, 2024
100225f
module: do not attempt to strip type when there's no source
aduh95 Aug 12, 2024
51b8576
benchmark: add stream.compose benchmark
jakecastelli Aug 12, 2024
94e2ea6
sqlite: ensure statement finalization on db close
cjihrig Aug 6, 2024
7f1bf1c
sqlite: split up large test file
cjihrig Jul 24, 2024
f49f1bb
test: unmark test-sqlite as flaky
cjihrig Aug 6, 2024
0bed600
url: modify pathToFileURL to handle extended UNC path
EarlyRiser42 Aug 12, 2024
8a8d1d2
doc: mark process.nextTick legacy
marco-ippolito Aug 12, 2024
b6927dd
src: move some X509Certificate stuff to ncrypto
jasnell Aug 5, 2024
0d716ad
deps: update simdutf to 5.3.4
nodejs-github-bot Aug 13, 2024
b659fc0
tools: add find pyenv path on windows
marco-ippolito Aug 13, 2024
2be78b0
src,test: ensure that V8 fast APIs are called
targos Aug 13, 2024
fe793a6
test_runner: do not expose internal loader
aduh95 Aug 13, 2024
f7f7b0c
buffer: optimize for common encodings
ronag Aug 13, 2024
6aa1d9e
build: update `ruff` to `0.5.2`
RedYetiDev Aug 13, 2024
f87aa27
src: don't match after `--` in `Dotenv::GetPathFromArgs`
RedYetiDev Aug 13, 2024
3e25be7
test: use relative paths in test-cli-permission tests
sendoru Aug 14, 2024
66dcb2a
module: unflag detect-module
GeoffreyBooth Jul 20, 2024
9aec536
path: change `posix.join` to use array
HBSPS Aug 14, 2024
1278555
buffer: optimize createFromString
ronag Aug 14, 2024
3df7938
test: make sure current run result is pushed and reset
jakecastelli Aug 14, 2024
676bbd5
test_runner: fix delete test file cause dependency file not watched
jakecastelli Aug 14, 2024
df428ad
tools: remove header from c-ares license
RedYetiDev Aug 14, 2024
c640a2f
build: always disable strict aliasing
targos Aug 14, 2024
c6544ff
benchmark: use assert.ok searchparams
RafaelGSS Aug 14, 2024
28ca678
buffer: optimize byteLength for common encodings
ronag Aug 14, 2024
409d9eb
src: shift even moar x509 to ncrypto
jasnell Aug 7, 2024
4e4d1de
src: refactor http parser binding initialization
joyeecheung Aug 14, 2024
7b641bc
buffer: optimize byteLength for short strings
ronag Aug 14, 2024
a5a60e6
buffer: use fast API for writing one-byte strings
ronag Aug 15, 2024
4b099ce
doc: fix typo in method name in the sea doc
firecraftgaming Aug 15, 2024
aa6e770
doc: correct peformance entry types
jazelly Aug 15, 2024
e3378f0
test_runner: use run() argument names in parseCommandLine()
cjihrig Aug 7, 2024
1e88045
test_runner: pass harness object as option to root test
cjihrig Aug 8, 2024
ed1ede8
test_runner: pass global options to createTestTree()
cjihrig Aug 12, 2024
69c78ca
test_runner: return setup() from parseCommandLine()
cjihrig Aug 13, 2024
961cbf0
test_runner: refactor hook creation
cjihrig Aug 13, 2024
7766c1d
test_runner: remove parseCommandLine() from test.js
cjihrig Aug 13, 2024
0b16af1
src,test: track `URL.canParse` fast API calls
targos Aug 15, 2024
8ba53ae
buffer: properly apply dst offset and src length on fast path
ronag Aug 15, 2024
33795cf
doc: replace v19 mention in Current release
RafaelGSS Aug 15, 2024
824bd58
doc: add versions when `--watch-preserve-output` was added
theoludwig Aug 16, 2024
1ca598c
cli: allow `--test-[name/skip]-pattern` in `NODE_OPTIONS`
RedYetiDev Aug 16, 2024
7f68cc0
test: make snapshot comparison more flexible
codebytere Aug 16, 2024
8883c01
doc: add note on weakness of permission model
tniessen Aug 17, 2024
f967ab3
doc: add git node security --cleanup
RafaelGSS Aug 17, 2024
9f115ba
doc: fix error description of the max header size
erm1116 Aug 18, 2024
e70711e
test_runner: report failures in filtered suites
cjihrig Aug 18, 2024
141e9fe
test_runner: use validateStringArray for `timers.enable()`
deokjinkim Aug 19, 2024
e077ff1
src: update compile cache storage structure
joyeecheung Aug 19, 2024
b6a3e61
deps: update amaro to 0.1.6
nodejs-github-bot Aug 14, 2024
240d929
module: add --experimental-transform-types flag
marco-ippolito Aug 12, 2024
65eff1e
2024-08-22, Version 22.7.0 (Current)
RafaelGSS Aug 19, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
module: add --experimental-transform-types flag
PR-URL: #54283
Reviewed-By: Benjamin Gruenbaum <[email protected]>
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Yagiz Nizipli <[email protected]>
Reviewed-By: Zeyu "Alex" Yang <[email protected]>
Reviewed-By: Chengzhong Wu <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Paolo Insogna <[email protected]>
  • Loading branch information
marco-ippolito authored and RafaelGSS committed Aug 21, 2024
commit 240d9296c1d3a0b122393000c2a1aa039bb7d948
12 changes: 12 additions & 0 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,17 @@ files with no extension will be treated as WebAssembly if they begin with the
WebAssembly magic number (`\0asm`); otherwise they will be treated as ES module
JavaScript.

### `--experimental-transform-types`

<!-- YAML
added: REPLACEME
-->

> Stability: 1.0 - Early development

Enables the transformation of TypeScript-only syntax into JavaScript code.
Implies `--experimental-strip-types` and `--enable-source-maps`.

### `--experimental-eventsource`

<!-- YAML
Expand Down Expand Up @@ -2961,6 +2972,7 @@ one is included in the list below.
* `--experimental-sqlite`
* `--experimental-strip-types`
* `--experimental-top-level-await`
* `--experimental-transform-types`
* `--experimental-vm-modules`
* `--experimental-wasi-unstable-preview1`
* `--experimental-wasm-modules`
Expand Down
45 changes: 31 additions & 14 deletions doc/api/typescript.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Modules: TypeScript

<!-- YAML
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/54283
description: Added `--experimental-transform-types` flag.
-->

> Stability: 1.0 - Early development

## Enabling

There are two ways to enable runtime TypeScript support in Node.js:
Expand Down Expand Up @@ -44,13 +53,15 @@ added: v22.6.0
> Stability: 1.0 - Early development

The flag [`--experimental-strip-types`][] enables Node.js to run TypeScript
files that contain only type annotations. Such files contain no TypeScript
features that require transformation, such as enums or namespaces. Node.js will
replace inline type annotations with whitespace, and no type checking is
performed. TypeScript features that depend on settings within `tsconfig.json`,
files. By default Node.js will execute only files that contain no
TypeScript features that require transformation, such as enums or namespaces.
Node.js will replace inline type annotations with whitespace,
and no type checking is performed.
To enable the transformation of such features
use the flag [`--experimental-transform-types`][].
TypeScript features that depend on settings within `tsconfig.json`,
such as paths or converting newer JavaScript syntax to older standards, are
intentionally unsupported. To get fuller TypeScript support, including support
for enums and namespaces and paths, see [Full TypeScript support][].
intentionally unsupported. To get full TypeScript support, see [Full TypeScript support][].

The type stripping feature is designed to be lightweight.
By intentionally not supporting syntaxes that require JavaScript code
Expand Down Expand Up @@ -82,20 +93,24 @@ The `tsconfig.json` option `allowImportingTsExtensions` will allow the
TypeScript compiler `tsc` to type-check files with `import` specifiers that
include the `.ts` extension.

### Unsupported TypeScript features
### TypeScript features

Since Node.js is only removing inline types, any TypeScript features that
involve _replacing_ TypeScript syntax with new JavaScript syntax will error.
This is by design. To run TypeScript with such features, see
[Full TypeScript support][].
involve _replacing_ TypeScript syntax with new JavaScript syntax will error,
unless the flag [`--experimental-transform-types`][] is passed.

The most prominent unsupported features that require transformation are:
The most prominent features that require transformation are:

* `Enum`
* `experimentalDecorators`
* `namespaces`
* `legacy module`
* parameter properties

Since Decorators are currently a [TC39 Stage 3 proposal](https://github.com/tc39/proposal-decorators)
and will soon be supported by the JavaScript engine,
they are not transformed and will result in a parser error.
This is a temporary limitation and will be resolved in the future.

In addition, Node.js does not read `tsconfig.json` files and does not support
features that depend on settings within `tsconfig.json`, such as paths or
converting newer JavaScript syntax into older standards.
Expand Down Expand Up @@ -132,8 +147,9 @@ TypeScript syntax is unsupported in the REPL, STDIN input, `--print`, `--check`,
### Source maps

Since inline types are replaced by whitespace, source maps are unnecessary for
correct line numbers in stack traces; and Node.js does not generate them. For
source maps support, see [Full TypeScript support][].
correct line numbers in stack traces; and Node.js does not generate them.
When [`--experimental-transform-types`][] is enabled, source-maps
are enabled by default.

### Type stripping in dependencies

Expand All @@ -145,6 +161,7 @@ a `node_modules` path.
[ES Modules]: esm.md
[Full TypeScript support]: #full-typescript-support
[`--experimental-strip-types`]: cli.md#--experimental-strip-types
[`--experimental-transform-types`]: cli.md#--experimental-transform-types
[`tsx`]: https://tsx.is/
[`verbatimModuleSyntax`]: https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax
[file extensions are mandatory]: esm.md#mandatory-file-extensions
Expand Down
3 changes: 3 additions & 0 deletions doc/node.1
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ Enable snapshot testing in the test runner.
.It Fl -experimental-strip-types
Enable experimental type-stripping for TypeScript files.
.
.It Fl -experimental-transform-types
Enable transformation of TypeScript-only syntax into JavaScript code.
.
.It Fl -experimental-eventsource
Enable experimental support for the EventSource Web API.
.
Expand Down
4 changes: 2 additions & 2 deletions lib/internal/main/eval_string.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const {
markBootstrapComplete,
} = require('internal/process/pre_execution');
const { evalModuleEntryPoint, evalScript } = require('internal/process/execution');
const { addBuiltinLibsToObject, tsParse } = require('internal/modules/helpers');
const { addBuiltinLibsToObject, stripTypeScriptTypes } = require('internal/modules/helpers');

const { getOptionValue } = require('internal/options');

Expand All @@ -24,7 +24,7 @@ markBootstrapComplete();

const code = getOptionValue('--eval');
const source = getOptionValue('--experimental-strip-types') ?
tsParse(code) :
stripTypeScriptTypes(code) :
code;

const print = getOptionValue('--print');
Expand Down
16 changes: 8 additions & 8 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -1362,8 +1362,8 @@ function loadESMFromCJS(mod, filename) {
if (isUnderNodeModules(filename)) {
throw new ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING(filename);
}
const { tsParse } = require('internal/modules/helpers');
source = tsParse(source);
const { stripTypeScriptTypes } = require('internal/modules/helpers');
source = stripTypeScriptTypes(source, filename);
}
const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader();
const isMain = mod[kIsMainSymbol];
Expand Down Expand Up @@ -1576,9 +1576,9 @@ function loadCTS(module, filename) {
throw new ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING(filename);
}
const source = getMaybeCachedSource(module, filename);
const { tsParse } = require('internal/modules/helpers');
const content = tsParse(source);
module._compile(content, filename, 'commonjs');
const { stripTypeScriptTypes } = require('internal/modules/helpers');
const code = stripTypeScriptTypes(source, filename);
module._compile(code, filename, 'commonjs');
}

/**
Expand All @@ -1592,8 +1592,8 @@ function loadTS(module, filename) {
}
// If already analyzed the source, then it will be cached.
const source = getMaybeCachedSource(module, filename);
const { tsParse } = require('internal/modules/helpers');
const content = tsParse(source);
const { stripTypeScriptTypes } = require('internal/modules/helpers');
const content = stripTypeScriptTypes(source, filename);
let format;
const pkg = packageJsonReader.getNearestParentPackageJSON(filename);
// Function require shouldn't be used in ES modules.
Expand All @@ -1613,7 +1613,7 @@ function loadTS(module, filename) {
if (Module._cache[parentPath]) {
let parentSource;
try {
parentSource = tsParse(fs.readFileSync(parentPath, 'utf8'));
parentSource = stripTypeScriptTypes(fs.readFileSync(parentPath, 'utf8'), parentPath);
} catch {
// Continue regardless of error.
}
Expand Down
5 changes: 2 additions & 3 deletions lib/internal/modules/esm/get_format.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,8 @@ function getFileProtocolModuleFormat(url, context = { __proto__: null }, ignoreE
// but this gets called again from `defaultLoad`/`defaultLoadSync`.
let parsedSource;
if (source) {
// We do the type stripping only if `source` is not falsy.
const { tsParse } = require('internal/modules/helpers');
parsedSource = tsParse(source);
const { stripTypeScriptTypes } = require('internal/modules/helpers');
parsedSource = stripTypeScriptTypes(source, url);
}
const detectedFormat = detectModuleFormat(parsedSource, url);
// When source is undefined, default to module-typescript.
Expand Down
8 changes: 4 additions & 4 deletions lib/internal/modules/esm/translators.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const { readFileSync } = require('fs');
const { dirname, extname, isAbsolute } = require('path');
const {
loadBuiltinModule,
tsParse,
stripTypeScriptTypes,
stripBOM,
urlToFilename,
} = require('internal/modules/helpers');
Expand Down Expand Up @@ -309,7 +309,7 @@ translators.set('require-commonjs', (url, source, isMain) => {
translators.set('require-commonjs-typescript', (url, source, isMain) => {
emitExperimentalWarning('Type Stripping');
assert(cjsParse);
const code = tsParse(stringify(source));
const code = stripTypeScriptTypes(stringify(source), url);
return createCJSModuleWrap(url, code);
});

Expand Down Expand Up @@ -526,7 +526,7 @@ translators.set('wasm', async function(url, source) {
translators.set('commonjs-typescript', function(url, source) {
emitExperimentalWarning('Type Stripping');
assertBufferSource(source, false, 'load');
const code = tsParse(stringify(source));
const code = stripTypeScriptTypes(stringify(source), url);
debug(`Translating TypeScript ${url}`);
return FunctionPrototypeCall(translators.get('commonjs'), this, url, code, false);
});
Expand All @@ -535,7 +535,7 @@ translators.set('commonjs-typescript', function(url, source) {
translators.set('module-typescript', function(url, source) {
emitExperimentalWarning('Type Stripping');
assertBufferSource(source, false, 'load');
const code = tsParse(stringify(source));
const code = stripTypeScriptTypes(stringify(source), url);
debug(`Translating TypeScript ${url}`);
return FunctionPrototypeCall(translators.get('module'), this, url, code, false);
});
49 changes: 43 additions & 6 deletions lib/internal/modules/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const path = require('path');
const { pathToFileURL, fileURLToPath } = require('internal/url');
const assert = require('internal/assert');

const { Buffer } = require('buffer');
const { getOptionValue } = require('internal/options');
const { setOwnProperty } = require('internal/util');
const { inspect } = require('internal/util/inspect');
Expand Down Expand Up @@ -300,7 +301,21 @@ function getBuiltinModule(id) {
return normalizedId ? require(normalizedId) : undefined;
}

/**
* TypeScript parsing function, by default Amaro.transformSync.
* @type {Function}
*/
let typeScriptParser;
/**
* The TypeScript parsing mode, either 'strip-only' or 'transform'.
* @type {string}
*/
let typeScriptParsingMode;
/**
* Whether source maps are enabled for TypeScript parsing.
* @type {boolean}
*/
let sourceMapEnabled;

/**
* Load the TypeScript parser.
Expand All @@ -318,22 +333,44 @@ function loadTypeScriptParser(parser) {
} else {
const amaro = require('internal/deps/amaro/dist/index');
// Default option for Amaro is to perform Type Stripping only.
const defaultOptions = { __proto__: null, mode: 'strip-only' };
typeScriptParsingMode = getOptionValue('--experimental-transform-types') ? 'transform' : 'strip-only';
sourceMapEnabled = getOptionValue('--enable-source-maps');
// Curry the transformSync function with the default options.
typeScriptParser = (source) => amaro.transformSync(source, defaultOptions);
typeScriptParser = amaro.transformSync;
}
return typeScriptParser;
}

/**
* @typedef {object} TransformOutput
* @property {string} code The compiled code.
* @property {string} [map] The source maps (optional).
*
* Performs type-stripping to TypeScript source code.
* @param {string} source TypeScript code to parse.
* @returns {string} JavaScript code.
* @param {string} filename The filename of the source code.
* @returns {TransformOutput} The stripped TypeScript code.
*/
function tsParse(source) {
function stripTypeScriptTypes(source, filename) {
assert(typeof source === 'string');
const parse = loadTypeScriptParser();
const { code } = parse(source);
const options = {
__proto__: null,
mode: typeScriptParsingMode,
sourceMap: sourceMapEnabled,
filename,
// Transform option is only applied in transform mode.
transform: {
verbatimModuleSyntax: true,
},
};
const { code, map } = parse(source, options);
if (map) {
// TODO(@marco-ippolito) When Buffer.transcode supports utf8 to
// base64 transformation, we should change this line.
const base64SourceMap = Buffer.from(map).toString('base64');
return `${code}\n\n//# sourceMappingURL=data:application/json;base64,${base64SourceMap}`;
}
return code;
}

Expand All @@ -353,7 +390,7 @@ module.exports = {
loadBuiltinModule,
makeRequireFunction,
normalizeReferrerURL,
tsParse,
stripTypeScriptTypes,
stripBOM,
toRealPath,
hasStartedUserCJSExecution() {
Expand Down
8 changes: 8 additions & 0 deletions src/node_options.cc
Original file line number Diff line number Diff line change
Expand Up @@ -808,6 +808,14 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
&EnvironmentOptions::experimental_strip_types,
kAllowedInEnvvar);
Implies("--experimental-strip-types", "--experimental-detect-module");

AddOption("--experimental-transform-types",
"enable transformation of TypeScript-only"
"syntax into JavaScript code",
&EnvironmentOptions::experimental_transform_types,
kAllowedInEnvvar);
Implies("--experimental-transform-types", "--experimental-strip-types");
Implies("--experimental-transform-types", "--enable-source-maps");
AddOption("--interactive",
"always enter the REPL even if stdin does not appear "
"to be a terminal",
Expand Down
1 change: 1 addition & 0 deletions src/node_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ class EnvironmentOptions : public Options {
std::vector<std::string> preload_esm_modules;

bool experimental_strip_types = false;
bool experimental_transform_types = false;

std::vector<std::string> user_argv;

Expand Down
Loading
Loading