From 2ad4108acaaad4d41d8290db8035aa7510e97289 Mon Sep 17 00:00:00 2001 From: Ved Chaudhari <84765263+vedchaudhari@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:45:53 +0530 Subject: [PATCH 001/253] fs: restore stack traces of fs/promises readFile and writeFile errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Errors from readFile(), writeFile() and appendFile() have had no stack frames since they started using a single thread pool round trip, as the stack was captured from a C++ callback with no JS frames on it. Capture it after the await instead, like the rest of fs/promises. Refs: https://github.com/nodejs/node/pull/65327 Refs: https://github.com/nodejs/node/pull/65489 Assisted-by: claude:opus-5.5 Signed-off-by: vedchaudhari PR-URL: https://github.com/nodejs/node/pull/66757 Reviewed-By: Christian Aurich Zanettini Martins Reviewed-By: Gürgün Dayıoğlu --- lib/internal/fs/promises.js | 58 +++++++++++++------ test/parallel/test-fs-promises.js | 25 ++++++++ ...test-permission-fs-promises-stack-trace.js | 42 ++++++++++++++ 3 files changed, 106 insertions(+), 19 deletions(-) create mode 100644 test/parallel/test-permission-fs-promises-stack-trace.js diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index b79e807fe6c4..5f9765d0cf35 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -2226,8 +2226,14 @@ async function writeFile(path, data, options) { if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) { path = getValidatedPath(path); - await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'), - parseFileMode(options.mode, 'mode', 0o666), data); + const flagsNumber = stringToFlags(flag, 'options.flag'); + const mode = parseFileMode(options.mode, 'mode', 0o666); + try { + await writeFileInOneRoundTrip(path, flagsNumber, mode, data); + } catch (err) { + ErrorCaptureStackTrace(err); + throw err; + } checkAborted(options.signal); // An abort during the write still wins. return; } @@ -2244,6 +2250,10 @@ async function writeFile(path, data, options) { /** * Open + write + close as one thread pool round trip. + * Throws synchronously if the permission model denies access, while the + * caller's frames are still on the stack. The caller is responsible for + * capturing the stack trace of a rejection, as no JS frames are on the stack + * when the job completes. * @param {string|Buffer} path Validated path * @param {number} flagsNumber * @param {number} mode @@ -2251,22 +2261,21 @@ async function writeFile(path, data, options) { * @returns {Promise} */ function writeFileInOneRoundTrip(path, flagsNumber, mode, data) { - return new Promise((resolve, reject) => { - const job = new binding.WriteFileJob(path, flagsNumber, mode, data); + const job = new binding.WriteFileJob(path, flagsNumber, mode, data); + const promise = new Promise((resolve, reject) => { job.ondone = (err) => { if (err != null) { - ErrorCaptureStackTrace(err, writeFileInOneRoundTrip); reject(err); } else { resolve(); } }; - const accessError = job.run(path); - if (accessError !== undefined) { - ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip); - reject(accessError); - } }); + const accessError = job.run(path); + if (accessError !== undefined) { + throw accessError; + } + return promise; } function isCustomIterable(obj) { @@ -2309,7 +2318,15 @@ async function readFile(path, options) { // files of up to one chunk; larger and non-regular files (size 0) come // back as an open fd + size and are read by readFileHandle() as before. path = getValidatedPath(path); - const { 0: buffer, 1: fd, 2: size } = await readFileInOneRoundTrip(path, stringToFlags(flag)); + const flagsNumber = stringToFlags(flag); + let result; + try { + result = await readFileInOneRoundTrip(path, flagsNumber); + } catch (err) { + ErrorCaptureStackTrace(err); + throw err; + } + const { 0: buffer, 1: fd, 2: size } = result; if (fd === -1) { checkAborted(options.signal); // An abort during the read still wins. return options.encoding ? buffer.toString(options.encoding) : buffer; @@ -2323,28 +2340,31 @@ async function readFile(path, options) { } /** + * Throws synchronously if the permission model denies access, while the + * caller's frames are still on the stack. The caller is responsible for + * capturing the stack trace of a rejection, as no JS frames are on the stack + * when the job completes. * @param {string|Buffer} path Validated path * @param {number} flagsNumber * @returns {Promise<[Buffer|undefined, number, number|undefined]>} [buffer, -1] or [undefined, fd, size] */ function readFileInOneRoundTrip(path, flagsNumber) { - return new Promise((resolve, reject) => { - const job = new binding.ReadFileJob(path, flagsNumber, kReadFileBufferLength); + const job = new binding.ReadFileJob(path, flagsNumber, kReadFileBufferLength); + const promise = new Promise((resolve, reject) => { job.ondone = (err, buffer, fd, size, closeErr) => { const error = err ?? closeErr; if (error != null) { - ErrorCaptureStackTrace(error, readFileInOneRoundTrip); reject(error); } else { resolve([buffer, fd, size]); } }; - const accessError = job.run(path); - if (accessError !== undefined) { - ErrorCaptureStackTrace(accessError, readFileInOneRoundTrip); - reject(accessError); - } }); + const accessError = job.run(path); + if (accessError !== undefined) { + throw accessError; + } + return promise; } async function* _watch(filename, options = kEmptyObject) { diff --git a/test/parallel/test-fs-promises.js b/test/parallel/test-fs-promises.js index 07f01187e89b..6ddc4cd3cb36 100644 --- a/test/parallel/test-fs-promises.js +++ b/test/parallel/test-fs-promises.js @@ -9,6 +9,7 @@ const fs = require('fs'); const fsPromises = fs.promises; const { access, + appendFile, chmod, chown, copyFile, @@ -62,6 +63,30 @@ assert.strictEqual( } ).then(common.mustCall()); + assert.rejects( + readFile('this file does not exist'), + { + code: 'ENOENT', + stack: /at async assert\.rejects/ + } + ).then(common.mustCall()); + + assert.rejects( + writeFile(path.join('this dir does not exist', 'file'), 'data'), + { + code: 'ENOENT', + stack: /at async assert\.rejects/ + } + ).then(common.mustCall()); + + assert.rejects( + appendFile(path.join('this dir does not exist', 'file'), 'data'), + { + code: 'ENOENT', + stack: /at async assert\.rejects/ + } + ).then(common.mustCall()); + assert.rejects( access(__filename, 8), { diff --git a/test/parallel/test-permission-fs-promises-stack-trace.js b/test/parallel/test-permission-fs-promises-stack-trace.js new file mode 100644 index 000000000000..7160473173ea --- /dev/null +++ b/test/parallel/test-permission-fs-promises-stack-trace.js @@ -0,0 +1,42 @@ +'use strict'; + +require('../common'); +const assert = require('assert'); +const { spawnSync } = require('child_process'); +const tmpdir = require('../common/tmpdir'); + +tmpdir.refresh(); + +// The permission model denies access before the first await, so the stack +// still has the frames of a caller that does not await the promise. +const { status, stderr } = spawnSync( + process.execPath, + [ + '--permission', + '-e', + ` + const assert = require('assert'); + const { readFile, writeFile, appendFile } = require('fs/promises'); + const target = ${JSON.stringify(tmpdir.resolve('file'))}; + + function readCaller() { return readFile(target); } + function writeCaller() { return writeFile(target, 'data'); } + function appendCaller() { return appendFile(target, 'data'); } + async function awaitAppendCaller() { await appendFile(target, 'data'); } + + const cases = [ + [readCaller, /at readCaller /], + [writeCaller, /at writeCaller /], + [appendCaller, /at appendCaller /], + [awaitAppendCaller, /at awaitAppendCaller /], + ]; + let checked = 0; + for (const [caller, stack] of cases) { + assert.rejects(caller(), { code: 'ERR_ACCESS_DENIED', stack }) + .then(() => checked++); + } + process.on('exit', () => assert.strictEqual(checked, cases.length)); + `, + ], +); +assert.strictEqual(status, 0, stderr.toString()); From 28cb3cbcc93a7b979e1101e3bb1b08afd9dddf64 Mon Sep 17 00:00:00 2001 From: fatih Date: Thu, 12 Nov 2026 22:15:20 +0300 Subject: [PATCH 002/253] inspector: disconnect handles before releasing interfaces MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Disconnect the thread handle while NodeInspectorClient still owns the interface. This prevents cross-thread posts from calling shared_from_this() after the interface's last strong reference has been released. Add a regression test verifying handle expiration during owner teardown. Fixes: https://github.com/nodejs/node/issues/67079 Signed-off-by: Fatih Güzel PR-URL: https://github.com/nodejs/node/pull/67281 Reviewed-By: Chengzhong Wu --- node.gyp | 1 + src/inspector/main_thread_interface.cc | 4 ++ src/inspector/main_thread_interface.h | 1 + src/inspector_agent.cc | 5 ++ .../inspector/test_main_thread_interface.cc | 54 +++++++++++++++++++ 5 files changed, 65 insertions(+) create mode 100644 test/cctest/inspector/test_main_thread_interface.cc diff --git a/node.gyp b/node.gyp index 9c0b270ea5fe..a462a9e9f2e4 100644 --- a/node.gyp +++ b/node.gyp @@ -492,6 +492,7 @@ 'test/cctest/test_quic_tokens.cc', ], 'node_cctest_inspector_sources': [ + 'test/cctest/inspector/test_main_thread_interface.cc', 'test/cctest/inspector/test_network_requests_buffer.cc', 'test/cctest/inspector/test_node_protocol.cc', 'test/cctest/test_inspector_socket.cc', diff --git a/src/inspector/main_thread_interface.cc b/src/inspector/main_thread_interface.cc index 0fca7483e95c..d4822598e17b 100644 --- a/src/inspector/main_thread_interface.cc +++ b/src/inspector/main_thread_interface.cc @@ -200,6 +200,10 @@ class ThreadSafeDelegate : public InspectorSessionDelegate { MainThreadInterface::MainThreadInterface(Agent* agent) : agent_(agent) {} MainThreadInterface::~MainThreadInterface() { + Disconnect(); +} + +void MainThreadInterface::Disconnect() { if (handle_) handle_->Reset(); } diff --git a/src/inspector/main_thread_interface.h b/src/inspector/main_thread_interface.h index 3311f9df014a..99fee99596c6 100644 --- a/src/inspector/main_thread_interface.h +++ b/src/inspector/main_thread_interface.h @@ -80,6 +80,7 @@ class MainThreadInterface : explicit MainThreadInterface(Agent* agent); ~MainThreadInterface(); + void Disconnect(); void DispatchMessages(); void Post(std::unique_ptr request); bool WaitForFrontendEvent(); diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index cfa2f2adb9d1..408c754e3e98 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -535,6 +535,11 @@ class NodeInspectorClient : public V8InspectorClient { } } + ~NodeInspectorClient() override { + // Close the handle before the interface can lose its last strong reference. + if (interface_) interface_->Disconnect(); + } + void runMessageLoopOnPause(int context_group_id) override { waiting_for_resume_ = true; runMessageLoop(); diff --git a/test/cctest/inspector/test_main_thread_interface.cc b/test/cctest/inspector/test_main_thread_interface.cc new file mode 100644 index 000000000000..edb8dd57f976 --- /dev/null +++ b/test/cctest/inspector/test_main_thread_interface.cc @@ -0,0 +1,54 @@ +#include "gtest/gtest.h" +#include "inspector/main_thread_interface.h" +#include "inspector/worker_inspector.h" +#include "node_test_fixture.h" + +#include + +namespace node { +namespace inspector { +namespace { + +class MainThreadInterfaceTest : public EnvironmentTestFixture {}; + +class RetainInterfaceRequest : public Request { + public: + explicit RetainInterfaceRequest( + std::shared_ptr* retained_interface) + : retained_interface_(retained_interface) {} + + void Call(MainThreadInterface* thread) override { + *retained_interface_ = thread->shared_from_this(); + } + + private: + std::shared_ptr* retained_interface_; +}; + +TEST_F(MainThreadInterfaceTest, ClosesHandleBeforeReleasingInterface) { + const v8::HandleScope handle_scope(isolate_); + const Argv argv; + std::shared_ptr retained_interface; + std::shared_ptr handle; + { + Env env{handle_scope, argv}; + handle = (*env)->inspector_agent()->GetWorkerManager()->MainThread(); + ASSERT_FALSE(handle->Expired()); + ASSERT_TRUE(handle->Post( + std::make_unique(&retained_interface))); + (*env)->RunAndClearInterrupts(); + ASSERT_NE(retained_interface, nullptr); + + // Keep the interface alive after its inspector owner is destroyed, so + // closing the handle cannot depend on the interface's destructor. + } + + ASSERT_TRUE(handle->Expired()); + EXPECT_FALSE(handle->Post( + std::make_unique(&retained_interface))); + retained_interface.reset(); +} + +} // namespace +} // namespace inspector +} // namespace node From c15d48a58fd42f51b0c7cbb85775470d6a35d6ad Mon Sep 17 00:00:00 2001 From: Emerson Gomes Date: Thu, 12 Nov 2026 15:07:37 -0600 Subject: [PATCH 003/253] http2: flush final GOAWAY after pending writes Keep the native close pending when an active socket write prevents the terminal GOAWAY from being serialized. Finish the close after the outgoing buffers become available, preserving the requested error code. Handle synchronous completion and transport errors without retrying writes to a failed transport or losing the socket close notification. Add a deterministic regression for default and custom GOAWAY codes, both inside and outside the receive callback. Fixes: https://github.com/nodejs/node/issues/66832 Assisted-by: Codex Signed-off-by: Emerson Gomes PR-URL: https://github.com/nodejs/node/pull/66834 Reviewed-By: Matteo Collina Reviewed-By: Tim Perry --- src/node_http2.cc | 40 +++++--- src/node_http2.h | 8 +- ...est-http2-session-destroy-pending-write.js | 91 +++++++++++++++++++ 3 files changed, 124 insertions(+), 15 deletions(-) create mode 100644 test/parallel/test-http2-session-destroy-pending-write.js diff --git a/src/node_http2.cc b/src/node_http2.cc index 3505d96eba6e..2792199b449d 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -848,19 +848,22 @@ void Http2Session::Close(uint32_t code, bool socket_closed) { return; set_closing(); + pending_close_code_ = code; + pending_close_socket_closed_ = socket_closed; + // Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks. // ConsumeHTTP2Data() finishes the close once mem_recv returns. if (is_receiving()) { set_close_pending(); - pending_close_code_ = code; - pending_close_socket_closed_ = socket_closed; return; } FinishClose(code, socket_closed); } -void Http2Session::FinishClose(uint32_t code, bool socket_closed) { +void Http2Session::FinishClose(uint32_t code, + bool socket_closed, + int write_status) { CHECK(is_closing()); // Stop reading on the i/o stream @@ -869,15 +872,20 @@ void Http2Session::FinishClose(uint32_t code, bool socket_closed) { stream_->ReadStop(); } - // If the socket is not closed, then attempt to send a closing GOAWAY + // If the socket is still writable, attempt to send a closing GOAWAY // frame. There is no guarantee that this GOAWAY will be received by // the peer but the HTTP/2 spec recommends sending it anyway. We'll // make a best effort. - if (!socket_closed) { + if (!socket_closed && write_status == 0) { Debug(this, "terminating session with code %d", code); CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0); - SendPendingData(); - } else if (stream_ != nullptr) { + if (SendPendingData() != 0) { + // An earlier write still owns the outgoing buffers. Keep the session + // alive until its completion lets us flush the terminal GOAWAY. + set_close_pending(); + return; + } + } else if (socket_closed && stream_ != nullptr) { // so that the previous listener of the socket, typically, JS code of a // (tls) socket will be notified of any activity later stream_->RemoveStreamListener(this); @@ -912,10 +920,12 @@ void Http2Session::FinishClose(uint32_t code, bool socket_closed) { EmitStatistics(); } -void Http2Session::MaybeFinishPendingClose() { - if (!is_close_pending() || is_destroyed()) return; +void Http2Session::MaybeFinishPendingClose(int status) { + if (!is_close_pending() || is_destroyed() || is_receiving() || is_sending()) { + return; + } set_close_pending(false); - FinishClose(pending_close_code_, pending_close_socket_closed_); + FinishClose(pending_close_code_, pending_close_socket_closed_, status); } // Locates an existing known stream by ID. nghttp2 has a similar method @@ -1890,9 +1900,16 @@ void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) { CHECK(is_write_in_progress()); set_write_in_progress(false); + // ClearOutgoing() may synchronously finish a pending close. + const bool close_pending = is_close_pending(); // Inform all pending writes about their completion. ClearOutgoing(status); + if (close_pending || is_close_pending()) { + MaybeFinishPendingClose(status); + return; + } + if (is_reading_stopped() && !is_write_in_progress() && nghttp2_session_want_read(session_.get())) { @@ -2007,7 +2024,7 @@ void Http2Session::ClearOutgoing(int status) { // Now that we've finished sending queued data, if there are any pending // RstStreams we should try sending again and then flush them one by one. - if (!pending_rst_streams_.empty()) { + if (status == 0 && !pending_rst_streams_.empty()) { std::vector current_pending_rst_streams; pending_rst_streams_.swap(current_pending_rst_streams); @@ -2129,6 +2146,7 @@ uint8_t Http2Session::SendPendingData() { set_write_in_progress(false); ClearOutgoing(res.err); MaybeNotifyGracefulCloseComplete(); + MaybeFinishPendingClose(res.err); } MaybeStopReading(); diff --git a/src/node_http2.h b/src/node_http2.h index 48dab9537707..5016cb98ad5f 100644 --- a/src/node_http2.h +++ b/src/node_http2.h @@ -1071,8 +1071,8 @@ class Http2Session : public AsyncWrap, std::vector outgoing_storage_; size_t outgoing_length_ = 0; std::vector pending_rst_streams_; - // Saved arguments for Close() deferred while nghttp2_session_mem_recv() - // callbacks are active. + // Saved arguments for Close() deferred while receiving data or waiting for + // an outgoing write to finish. uint32_t pending_close_code_ = NGHTTP2_NO_ERROR; bool pending_close_socket_closed_ = false; // Count streams that have been rejected while being opened. Exceeding a fixed @@ -1089,8 +1089,8 @@ class Http2Session : public AsyncWrap, void CopyDataIntoOutgoing(const uint8_t* src, size_t src_length); void ClearOutgoing(int status); - void FinishClose(uint32_t code, bool socket_closed); - void MaybeFinishPendingClose(); + void FinishClose(uint32_t code, bool socket_closed, int write_status = 0); + void MaybeFinishPendingClose(int status = 0); void MaybeNotifyGracefulCloseComplete(); diff --git a/test/parallel/test-http2-session-destroy-pending-write.js b/test/parallel/test-http2-session-destroy-pending-write.js new file mode 100644 index 000000000000..7ff3941a0724 --- /dev/null +++ b/test/parallel/test-http2-session-destroy-pending-write.js @@ -0,0 +1,91 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +// Destroying a session while a socket write is pending must flush the final +// GOAWAY before ending the socket, including when called from a stream handler. +const assert = require('assert'); +const http2 = require('http2'); +const { Duplex } = require('stream'); +const { + HeadersFrame, + SettingsFrame, + kClientMagic, + kFakeRequestHeaders, +} = require('../common/http2'); + +for (const [code, deferDestroy] of [ + [0, false], + [http2.constants.NGHTTP2_REFUSED_STREAM, false], + [0, true], + [http2.constants.NGHTTP2_REFUSED_STREAM, true], +]) { + const output = []; + let pendingWrite; + const socket = new Duplex({ + read() {}, + write(chunk, encoding, callback) { + output.push(Buffer.from(chunk)); + if (pendingWrite === undefined) { + // Hold the initial SETTINGS write until the stream handler destroys + // the session. No timers or large response bodies are needed. + pendingWrite = callback; + setImmediate(() => { + socket.push(new HeadersFrame(1, kFakeRequestHeaders, 0, true).data); + }); + } else { + callback(); + } + }, + }); + + const session = http2.performServerHandshake(socket); + session.on('stream', common.mustCall((stream) => { + assert.strictEqual(typeof pendingWrite, 'function'); + stream.on('close', common.mustCall()); + if (code !== 0) { + stream.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_HTTP2_SESSION_ERROR'); + })); + } + const destroy = common.mustCall(() => { + session.destroy(code); + assert.strictEqual(session.destroyed, true); + setImmediate(common.mustCall(() => { + const callback = pendingWrite; + pendingWrite = null; + callback(); + })); + }); + if (deferDestroy) + setImmediate(destroy); + else + destroy(); + })); + session.on('close', common.mustCall()); + if (code !== 0) { + session.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_HTTP2_SESSION_ERROR'); + })); + } + + socket.on('finish', common.mustCall(() => { + const data = Buffer.concat(output); + let goaways = 0; + for (let offset = 0; offset < data.length;) { + const length = data.readUIntBE(offset, 3); + assert(data.length >= offset + 9 + length); + if (data[offset + 3] === 7) { + goaways++; + assert.strictEqual(data.readUInt32BE(offset + 9), 1); + assert.strictEqual(data.readUInt32BE(offset + 13), code); + } + offset += 9 + length; + } + assert.strictEqual(goaways, 1); + })); + + socket.push(Buffer.concat([kClientMagic, new SettingsFrame().data])); +} From d15f18b4988b70f330dd820efc72bfe1666ab0e7 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 11 Oct 2026 16:54:28 +0000 Subject: [PATCH 004/253] lib: update node:bench reporters to include sys info Signed-off-by: James M Snell Assisted-by: Opencode PR-URL: https://github.com/nodejs/node/pull/66664 Reviewed-By: Matteo Collina --- doc/api/bench.md | 42 ++++++++++++--- lib/internal/bench_runner/environment.js | 61 ++++++++++++++++++++++ lib/internal/bench_runner/reporter/json.js | 12 +++++ lib/internal/bench_runner/reporter/spec.js | 51 +++++++++++++++++- test/parallel/test-bench-cli-reporters.js | 11 ++-- test/parallel/test-bench-reporters.js | 42 +++++++++++++-- 6 files changed, 202 insertions(+), 17 deletions(-) create mode 100644 lib/internal/bench_runner/environment.js diff --git a/doc/api/bench.md b/doc/api/bench.md index 866449165530..5f23df07f01c 100644 --- a/doc/api/bench.md +++ b/doc/api/bench.md @@ -260,13 +260,36 @@ bench('example', (b) => { run().compose(spec).pipe(process.stdout); ``` -The `spec` reporter buffers results and outputs a concise table containing the -sample count, mean rate, 95% confidence interval for the mean, median rate, and -warnings. A coefficient of variation above 5% is reported as `noisy`, and an -absolute skewness above 1 is reported as `skewed`. The exact human-readable -format is subject to change. - -The `json` reporter emits every lifecycle record as newline-delimited JSON. +The built-in reporters collect a snapshot of the reporting process's +environment when they receive their first record. The snapshot contains: + +* `node` {string} The value of `process.version`. +* `v8` {string} The value of `process.versions.v8`. +* `platform` {string} The value of `process.platform`. +* `arch` {string} The value of `process.arch`. +* `os` {Object} The operating system `type`, `release`, and `machine`, as + returned by the corresponding [`os`][] functions. +* `cpus` {Object\[]} The logical CPUs grouped by `model`, with the `count` of + each model. +* `availableParallelism` {number} The value of `os.availableParallelism()`. +* `memory` {Object} The `total` and `free` system memory in bytes, and the + `constrained` memory limit in bytes, or `null` when the process is not + constrained below the total system memory. +* `loadavg` {number\[]} The value of `os.loadavg()`. +* `execArgv` {string\[]} The value of `process.execArgv`. + +With process isolation, reporters run in the parent process. Benchmark children +are started from the same executable, but their `execArgv` can differ. + +The `spec` reporter buffers results and outputs a summary of the environment +followed by a concise table containing the sample count, mean rate, 95% +confidence interval for the mean, median rate, and warnings. A coefficient of +variation above 5% is reported as `noisy`, and an absolute skewness above 1 is +reported as `skewed`. The exact human-readable format is subject to change. + +The `json` reporter emits a `'bench:environment'` record containing the +environment snapshot before the first lifecycle record, and then emits every +lifecycle record as newline-delimited JSON. BigInt values, including `duration_ns`, are encoded as decimal strings. Errors are represented using their `name`, `message`, `stack`, `code`, `cause`, and `errors` properties. As required by JSON, non-finite numbers are encoded as @@ -798,7 +821,8 @@ tags, and parameters described in [benchmark result][], together with: The plan contains execution settings known to the runner. Runtime version, operating system, processor, and other environment metadata are intentionally -left for reporters and higher-level tools to collect. +left for reporters and higher-level tools to collect. The built-in reporters +include an [environment snapshot][benchmark reporters]. `'bench:complete'` data contains a [benchmark result][]. A failed result has an additional `error` property and may contain samples recorded before the error. @@ -856,6 +880,8 @@ A completed benchmark result contains: [`context.record()`]: #contextrecordsample [`createRunner()`]: #createrunneroptions +[`os`]: os.md [`run()`]: #runoptions +[benchmark reporters]: #benchmark-reporters [benchmark result]: #benchmark-result [command-line options documentation]: cli.md#--bench diff --git a/lib/internal/bench_runner/environment.js b/lib/internal/bench_runner/environment.js new file mode 100644 index 000000000000..17e349c342a3 --- /dev/null +++ b/lib/internal/bench_runner/environment.js @@ -0,0 +1,61 @@ +'use strict'; + +const { + ArrayPrototypePush, + ArrayPrototypeSlice, +} = primordials; + +function groupCpus(cpus) { + const groups = []; + for (let i = 0; i < cpus.length; i++) { + // The reported speed is the current core frequency, which fluctuates + // with frequency scaling, so only the model is used for grouping. + const { model } = cpus[i]; + let group; + for (let j = 0; j < groups.length; j++) { + if (groups[j].model === model) { + group = groups[j]; + break; + } + } + if (group === undefined) { + group = { __proto__: null, model, count: 0 }; + ArrayPrototypePush(groups, group); + } + group.count++; + } + return groups; +} + +function collectEnvironment() { + const os = require('os'); + const total = os.totalmem(); + const constrained = process.constrainedMemory(); + return { + __proto__: null, + node: process.version, + v8: process.versions.v8, + platform: process.platform, + arch: process.arch, + os: { + __proto__: null, + type: os.type(), + release: os.release(), + machine: os.machine(), + }, + cpus: groupCpus(os.cpus()), + availableParallelism: os.availableParallelism(), + memory: { + __proto__: null, + total, + free: os.freemem(), + constrained: constrained > 0 && constrained < total ? constrained : null, + }, + loadavg: os.loadavg(), + execArgv: ArrayPrototypeSlice(process.execArgv), + }; +} + +module.exports = { + collectEnvironment, +}; diff --git a/lib/internal/bench_runner/reporter/json.js b/lib/internal/bench_runner/reporter/json.js index 3237a3e1b26c..4a46b83c5f84 100644 --- a/lib/internal/bench_runner/reporter/json.js +++ b/lib/internal/bench_runner/reporter/json.js @@ -9,6 +9,9 @@ const { String, } = primordials; const { isError } = require('internal/util'); +const { + collectEnvironment, +} = require('internal/bench_runner/environment'); function toJSONValue(value, seen) { if (typeof value === 'bigint') return String(value); @@ -56,7 +59,16 @@ function stringify(record) { } async function* jsonReporter(source) { + let environmentReported = false; for await (const record of source) { + if (!environmentReported) { + environmentReported = true; + yield `${stringify({ + __proto__: null, + type: 'bench:environment', + data: collectEnvironment(), + })}\n`; + } yield `${stringify(record)}\n`; } } diff --git a/lib/internal/bench_runner/reporter/spec.js b/lib/internal/bench_runner/reporter/spec.js index 34f5831553f3..6663360f5925 100644 --- a/lib/internal/bench_runner/reporter/spec.js +++ b/lib/internal/bench_runner/reporter/spec.js @@ -13,6 +13,9 @@ const { StringPrototypeReplaceAll, } = primordials; const Transform = require('internal/streams/transform'); +const { + collectEnvironment, +} = require('internal/bench_runner/environment'); const kHeader = 'benchmark | samples | mean rate | 95% CI | median rate | warning\n'; @@ -62,6 +65,50 @@ function formatRate(rate) { return `${formatted}${prefix} ops/s`; } +function formatBytes(bytes) { + const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']; + let unit = 0; + while (bytes >= 1024 && unit < units.length - 1) { + bytes /= 1024; + unit++; + } + return `${NumberPrototypeToFixed(bytes, unit === 0 ? 0 : 1)} ${units[unit]}`; +} + +function formatEnvironment(environment) { + const { cpus, memory, os } = environment; + let output = `node: ${environment.node} (V8 ${environment.v8}), ` + + `${environment.platform} ${environment.arch} ` + + `(${os.type} ${os.release})\n`; + + const groups = []; + for (let i = 0; i < cpus.length; i++) { + ArrayPrototypePush(groups, `${cpus[i].count} x ${cpus[i].model}`); + } + if (groups.length === 0) ArrayPrototypePush(groups, 'unknown'); + output += `cpu: ${ArrayPrototypeJoin(groups, ', ')} ` + + `(available parallelism: ${environment.availableParallelism})\n`; + + output += `memory: ${formatBytes(memory.total)} total, ` + + `${formatBytes(memory.free)} free`; + if (memory.constrained !== null) { + output += `, ${formatBytes(memory.constrained)} constrained`; + } + output += '\n'; + + const loadavg = []; + for (let i = 0; i < environment.loadavg.length; i++) { + ArrayPrototypePush( + loadavg, NumberPrototypeToFixed(environment.loadavg[i], 2)); + } + output += `load average: ${ArrayPrototypeJoin(loadavg, ', ')}\n`; + + if (environment.execArgv.length > 0) { + output += `exec argv: ${ArrayPrototypeJoin(environment.execArgv, ' ')}\n`; + } + return `${output}\n`; +} + function formatWarning(summary) { const warnings = []; if (NumberIsFinite(summary.coefficientOfVariation) && @@ -97,6 +144,7 @@ function formatResult(data) { class SpecReporter extends Transform { #diagnostics = []; + #environment; #reported = false; #results = []; @@ -105,7 +153,7 @@ class SpecReporter extends Transform { } #format(summary = undefined) { - let output = kHeader; + let output = formatEnvironment(this.#environment) + kHeader; for (let i = 0; i < this.#results.length; i++) { output += formatResult(this.#results[i]); } @@ -121,6 +169,7 @@ class SpecReporter extends Transform { } _transform({ type, data }, _encoding, callback) { + this.#environment ??= collectEnvironment(); switch (type) { case 'bench:complete': ArrayPrototypePush(this.#results, data); diff --git a/test/parallel/test-bench-cli-reporters.js b/test/parallel/test-bench-cli-reporters.js index 31cee67aaa12..9bc775c7c472 100644 --- a/test/parallel/test-bench-cli-reporters.js +++ b/test/parallel/test-bench-cli-reporters.js @@ -125,16 +125,19 @@ for (const { file, status } of [ fixtures.path('bench-runner/a.cjs'), ]); assert.strictEqual(result.status, 0); - parseRecords(result); - assert.match(fs.readFileSync(destination, 'utf8'), - /^benchmark \| samples \| mean rate/); + const records = parseRecords(result); + assert.strictEqual(records[0].type, 'bench:environment'); + const output = fs.readFileSync(destination, 'utf8'); + assert.match(output, /^node: v\d+/); + assert.match(output, /^benchmark \| samples \| mean rate/m); } { const result = spawnBench([fixtures.path('bench-runner/a.cjs')]); assert.strictEqual(result.status, 0); assert.strictEqual(result.stderr, ''); - assert.match(result.stdout, /^benchmark \| samples \| mean rate/); + assert.match(result.stdout, /^node: v\d+/); + assert.match(result.stdout, /^benchmark \| samples \| mean rate/m); assert.match(result.stdout, /1 completed, 0 failed, 0 skipped/); } diff --git a/test/parallel/test-bench-reporters.js b/test/parallel/test-bench-reporters.js index b5078a40de6b..09cde1d46b11 100644 --- a/test/parallel/test-bench-reporters.js +++ b/test/parallel/test-bench-reporters.js @@ -4,6 +4,7 @@ const common = require('../common'); const { completeSample } = require('../common/bench'); const assert = require('assert'); +const os = require('os'); const { Readable } = require('stream'); const { bench, run } = require('node:bench'); const { json, spec } = require('node:bench/reporters'); @@ -26,7 +27,25 @@ bench('json failed', { samples: 1 }, () => { const lines = chunks.join('').trim().split('\n'); const records = lines.map((line) => JSON.parse(line)); - assert.strictEqual(records.length, 8); + assert.strictEqual(records.length, 9); + const { type: environmentType, data: environment } = records[0]; + assert.strictEqual(environmentType, 'bench:environment'); + assert.strictEqual(environment.node, process.version); + assert.strictEqual(environment.v8, process.versions.v8); + assert.strictEqual(environment.platform, process.platform); + assert.strictEqual(environment.arch, process.arch); + assert.strictEqual(environment.os.type, os.type()); + assert.strictEqual(environment.os.release, os.release()); + assert.strictEqual(environment.os.machine, os.machine()); + assert.strictEqual( + environment.cpus.reduce((total, { count }) => total + count, 0), + os.cpus().length); + assert.strictEqual(environment.availableParallelism, + os.availableParallelism()); + assert.strictEqual(environment.memory.total, os.totalmem()); + assert.strictEqual(typeof environment.memory.free, 'number'); + assert.strictEqual(environment.loadavg.length, 3); + assert.deepStrictEqual(environment.execArgv, process.execArgv); const plans = records.filter(({ type }) => type === 'bench:plan'); assert.deepStrictEqual(plans.map(({ data }) => data.selected), [true, true]); const sample = records.find(({ type }) => type === 'bench:sample'); @@ -105,7 +124,18 @@ bench('json failed', { samples: 1 }, () => { }, ]; const specChunks = await Readable.from(synthetic).compose(spec).toArray(); - assert.strictEqual(specChunks.join(''), + const specOutput = specChunks.join(''); + const specHeaderEnd = specOutput.indexOf('\n\n') + 2; + const specHeader = specOutput.slice(0, specHeaderEnd); + assert.match(specHeader, + new RegExp(`^node: ${RegExp.escape(process.version)} ` + + `\\(V8 ${RegExp.escape(process.versions.v8)}\\), ` + + `${process.platform} ${process.arch} `)); + assert.match(specHeader, /^cpu: .*\(available parallelism: \d+\)$/m); + assert.match(specHeader, /^memory: [\d.]+ \w+ total, [\d.]+ \w+ free/m); + assert.match(specHeader, /^load average: [\d.]+, [\d.]+, [\d.]+$/m); + assert.match(specHeader, /^exec argv: --experimental-bench --no-warnings$/m); + assert.strictEqual(specOutput.slice(specHeaderEnd), 'benchmark | samples | mean rate | 95% CI | ' + 'median rate | warning\n' + 'fast [size="small"] | 2 | 1.50k ops/s | ' + @@ -123,7 +153,8 @@ bench('json failed', { samples: 1 }, () => { type: 'bench:diagnostic', data: { aggregate, circular }, }]).compose(json).toArray(); - const jsonEdge = JSON.parse(jsonEdgeChunks.join('')); + assert.strictEqual(jsonEdgeChunks.length, 2); + const jsonEdge = JSON.parse(jsonEdgeChunks[1]); assert.deepStrictEqual(jsonEdge.data.aggregate.errors, ['1']); assert.strictEqual(jsonEdge.data.circular.self, '[Circular]'); @@ -134,7 +165,10 @@ bench('json failed', { samples: 1 }, () => { for await (const chunk of json(undefinedRecord())) { undefinedChunks.push(chunk); } - assert.strictEqual(undefinedChunks.join(''), 'null\n'); + assert.strictEqual(undefinedChunks.length, 2); + assert.strictEqual(JSON.parse(undefinedChunks[0]).type, + 'bench:environment'); + assert.strictEqual(undefinedChunks[1], 'null\n'); function result(name, rate) { return { From 76b8e83ec5c5df1d6b3b66b541403bcd158e62ea Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 11 Oct 2026 17:07:02 +0000 Subject: [PATCH 005/253] lib: default bench operations to 1 b.end(N) ... N defaults to 1 b.report(...) operations defaults to 1 Signed-off-by: James M Snell Assisted-by: Opencode PR-URL: https://github.com/nodejs/node/pull/66664 Reviewed-By: Matteo Collina --- doc/api/bench.md | 8 +- lib/internal/bench_runner/benchmark.js | 4 +- test/parallel/test-bench-end-operations.js | 91 ++++++++++++++++++++++ 3 files changed, 97 insertions(+), 6 deletions(-) create mode 100644 test/parallel/test-bench-end-operations.js diff --git a/doc/api/bench.md b/doc/api/bench.md index 5f23df07f01c..b457cff50c4e 100644 --- a/doc/api/bench.md +++ b/doc/api/bench.md @@ -71,7 +71,7 @@ to their caller. Each warmup and measured sample invokes the benchmark function once with a fresh {BenchContext}. The function must either call `context.start()` and -`context.end(operations)` exactly once, or call `context.record(sample)` exactly +`context.end([operations])` exactly once, or call `context.record(sample)` exactly once to provide an externally measured sample. Setup before `start()` and cleanup after `end()` are outside the measured region. Promise-returning functions are awaited. @@ -665,14 +665,14 @@ added: v26.9.0 Starts the measured region using `process.hrtime.bigint()`. Calling `start()` more than once is an error. -### `context.end(operations[, options])` +### `context.end([operations[, options]])` * `operations` {number} The number of completed operations. Must be a positive - safe integer. + safe integer. **Default:** `1`. * `options` {Object} * `detail` {any} Additional structured-cloneable sample data. With CLI process isolation, it must also be supported by advanced child process @@ -694,7 +694,7 @@ added: v26.9.0 * `sample` {Object} * `operations` {number} The number of completed operations. Must be a positive - safe integer. + safe integer. **Default:** `1`. * `duration_ns` {bigint} An externally measured positive duration in nanoseconds no greater than `Number.MAX_SAFE_INTEGER`. * `detail` {any} Additional structured-cloneable sample data. With CLI process diff --git a/lib/internal/bench_runner/benchmark.js b/lib/internal/bench_runner/benchmark.js index cea0abc71e52..ea47696489ab 100644 --- a/lib/internal/bench_runner/benchmark.js +++ b/lib/internal/bench_runner/benchmark.js @@ -349,7 +349,7 @@ class BenchContext { this.#startTime = hrtime(); } - end(operations, options = kEmptyObject) { + end(operations = 1, options = kEmptyObject) { const endTime = hrtime(); if (this.#closed) { this.#invalid = true; @@ -415,7 +415,7 @@ class BenchContext { try { validateObject(sample, 'sample'); - const { detail, duration_ns, operations } = sample; + const { detail, duration_ns, operations = 1 } = sample; validateInteger( operations, 'sample.operations', 1, NumberMAX_SAFE_INTEGER); if (typeof duration_ns !== 'bigint') { diff --git a/test/parallel/test-bench-end-operations.js b/test/parallel/test-bench-end-operations.js new file mode 100644 index 000000000000..83a51512e1b7 --- /dev/null +++ b/test/parallel/test-bench-end-operations.js @@ -0,0 +1,91 @@ +// Flags: --experimental-bench --no-warnings +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { createRunner } = require('node:bench'); + +function waitForTick() { + const started = process.hrtime.bigint(); + while (process.hrtime.bigint() === started); +} + +const runner = createRunner({ yieldBetweenSamples: false }); + +runner.bench('default operations', { samples: 1, warmup: 0 }, + common.mustCall((b) => { + b.start(); + waitForTick(); + const sample = b.end(); + assert.strictEqual(sample.operations, 1); + })); + +runner.bench('undefined operations with options', { samples: 1, warmup: 0 }, + common.mustCall((b) => { + b.start(); + waitForTick(); + const sample = b.end(undefined, { detail: 'value' }); + assert.strictEqual(sample.operations, 1); + assert.strictEqual(sample.detail, 'value'); + })); + +const invalid = [0, -1, 0.5, NaN, Infinity, null, '1']; +for (const operations of invalid) { + runner.bench(`invalid ${String(operations)}`, { samples: 1, warmup: 0 }, + (b) => { + b.start(); + waitForTick(); + b.end(operations); + }); +} + +runner.bench('record default operations', { samples: 1, warmup: 0 }, + common.mustCall((b) => { + const sample = b.record({ duration_ns: 10n }); + assert.strictEqual(sample.operations, 1); + assert.strictEqual(sample.rate, 100_000_000); + })); + +runner.bench('record undefined operations', { samples: 1, warmup: 0 }, + common.mustCall((b) => { + const sample = b.record({ duration_ns: 10n, operations: undefined }); + assert.strictEqual(sample.operations, 1); + })); + +for (const operations of invalid) { + runner.bench(`record invalid ${String(operations)}`, + { samples: 1, warmup: 0 }, + (b) => b.record({ duration_ns: 10n, operations })); +} + +(async () => { + const records = await runner.run().toArray(); + const byName = new Map(records + .filter(({ type }) => type === 'bench:complete') + .map(({ data }) => [data.name, data])); + + assert.deepStrictEqual( + byName.get('default operations').samples.map(({ operations }) => operations), + [1]); + assert.deepStrictEqual( + byName.get('undefined operations with options').samples + .map(({ operations }) => operations), + [1]); + + for (const name of ['record default operations', + 'record undefined operations']) { + assert.deepStrictEqual( + byName.get(name).samples.map(({ operations }) => operations), [1]); + } + + for (const operations of invalid) { + const code = typeof operations === 'number' ? + 'ERR_OUT_OF_RANGE' : 'ERR_INVALID_ARG_TYPE'; + for (const prefix of ['invalid', 'record invalid']) { + const { error, samples } = + byName.get(`${prefix} ${String(operations)}`); + assert.strictEqual(error.code, code); + assert.strictEqual(samples.length, 0); + } + } +})().then(common.mustCall()); From 426c7589f7bfd1b15d0fdcf1abb72120b6a48504 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 11 Oct 2026 17:38:31 +0000 Subject: [PATCH 006/253] lib: add gc options to node:bench Adds option post-warmup and pre-sample gc options to node:bench Signed-off-by: James M Snell Assisted-by: Opencode PR-URL: https://github.com/nodejs/node/pull/66664 Reviewed-By: Matteo Collina --- doc/api/bench.md | 49 +++++++++- doc/api/cli.md | 20 ++++ doc/node-config-schema.json | 8 ++ doc/node.1 | 13 +++ lib/internal/bench_runner/benchmark.js | 6 ++ lib/internal/bench_runner/cli.js | 12 +++ lib/internal/bench_runner/harness.js | 40 ++++++++ src/node_options.cc | 10 ++ src/node_options.h | 1 + test/fixtures/bench-runner/gc.cjs | 10 ++ test/parallel/test-bench-gc.js | 126 +++++++++++++++++++++++++ 11 files changed, 290 insertions(+), 5 deletions(-) create mode 100644 test/fixtures/bench-runner/gc.cjs create mode 100644 test/parallel/test-bench-gc.js diff --git a/doc/api/bench.md b/doc/api/bench.md index b457cff50c4e..8118a928d0f5 100644 --- a/doc/api/bench.md +++ b/doc/api/bench.md @@ -90,6 +90,32 @@ system load can all affect results. Keep raw samples when comparing results and investigate noisy or skewed distributions rather than treating a confidence interval as a pass/fail threshold. +### Garbage collection + +Warmup invocations can leave garbage on the heap that is collected during the +first measured samples, charging warmup allocations to measured work. The `gc` +option forces a full garbage collection outside the measured region: + +* `'none'`: No garbage collection is forced. This is the default. +* `'once'`: A full garbage collection runs after warmup, before the first + measured sample. Garbage produced by measured samples is still collected + during measurement, so its cost remains part of the results. +* `'sample'`: A full garbage collection runs before every measured sample. This + reduces variance between samples, but samples that are too short to trigger a + collection on their own exclude the cost of collecting their garbage, which + can make allocation-heavy code appear faster than it is in practice. + +Forced collection runs after `beforeEach` hooks and any event loop turn between +samples, and is excluded from benchmark timeout accounting. The effective mode +is reported as `gc` in `'bench:plan'` events. The mode can be overridden for +every benchmark through `createRunner()`, [`run()`][], or [`--bench-gc`][]. + +Forcing garbage collection requires the `--expose-gc` flag, which also makes +`globalThis.gc()` available to benchmark code. A benchmark whose effective mode +is `'once'` or `'sample'` fails when the flag is not set. When `--bench-gc` +selects one of these modes, the command-line runner adds `--expose-gc` to +benchmark child processes automatically. + ### Measurement integrity A statistically consistent result does not prove that a benchmark measured the @@ -221,9 +247,10 @@ arbitrary functions or closures to move them between isolates, because closures cannot be reconstructed with their original lexical environment. Benchmark files passed to `--bench` should declare benchmarks but must not call -`run()`. The CLI supports `--bench-name-pattern`, `--bench-samples`, -`--bench-warmup`, `--bench-reporter`, and `--bench-reporter-destination`. See -the [command-line options documentation][] for details. +`run()`. The CLI supports `--bench-gc`, `--bench-name-pattern`, +`--bench-samples`, `--bench-warmup`, `--bench-reporter`, and +`--bench-reporter-destination`. See the [command-line options documentation][] +for details. Preload modules passed through `--require` or `--import` should not declare benchmarks. Such declarations are not associated with an entry file and have @@ -321,6 +348,9 @@ added: v26.9.0 --> * `options` {Object} + * `gc` {string} Overrides the [garbage collection][] mode for every + benchmark declared through this runner. One of `'none'`, `'once'`, or + `'sample'`. * `yieldBetweenSamples` {boolean} Schedule an event loop turn between sample callbacks. Disabling this also prevents timer-based abort signals from firing between synchronous callbacks. Benchmark timeouts continue to be @@ -334,8 +364,8 @@ the module-level functions. Call the returned `run()` function to start the runner and obtain its {BenchmarksStream}. Each runner can be started once. Its `run()` function accepts the same options -as the module-level [`run()`][]. `run({ yieldBetweenSamples })` overrides the -value passed to `createRunner()`. Unlike the module-level runner, a failed +as the module-level [`run()`][]. `run({ gc })` and `run({ yieldBetweenSamples })` +override the values passed to `createRunner()`. Unlike the module-level runner, a failed benchmark in an explicit runner does not change the process exit code. ## `bench([name][, options], fn)` @@ -350,6 +380,8 @@ added: v26.9.0 * `diagnosticChannels` {Array} String diagnostics channel names, deduplicated and inherited from containing suites by union. Symbol values in the array are silently ignored. **Default:** `[]`. + * `gc` {string} The [garbage collection][] mode. One of `'none'`, `'once'`, + or `'sample'`. **Default:** `'none'`. * `only` {boolean} When any benchmark or containing suite has `only` set, benchmarks without `only` in their hierarchy are skipped. **Default:** `false`. @@ -511,6 +543,9 @@ added: v26.9.0 --> * `options` {Object} + * `gc` {string} Overrides the [garbage collection][] mode for every + benchmark. One of `'none'`, `'once'`, or `'sample'`. **Default:** the value + passed to `createRunner()` for an explicit runner. * `namePattern` {string|RegExp} Only runs benchmarks whose full hierarchical name matches the pattern. String values are interpreted as JavaScript regular expressions. @@ -803,6 +838,8 @@ isolation, all files share one runner and their plans are emitted before any benchmark executes. Plan data contains the benchmark-scoped identity, location, tags, and parameters described in [benchmark result][], together with: +* `gc` {string} The effective [garbage collection][] mode after run-level + overrides. * `diagnosticChannels` {string\[]} The inherited string channel names subscribed to during each callback. * `samples` {number} The effective maximum number of measured callback @@ -878,6 +915,7 @@ A completed benchmark result contains: interval for the median rate, with `lower` and `upper` properties. * `skewness` {number} The skewness of the scaled rate histogram. +[`--bench-gc`]: cli.md#--bench-gcmode [`context.record()`]: #contextrecordsample [`createRunner()`]: #createrunneroptions [`os`]: os.md @@ -885,3 +923,4 @@ A completed benchmark result contains: [benchmark reporters]: #benchmark-reporters [benchmark result]: #benchmark-result [command-line options documentation]: cli.md#--bench +[garbage collection]: #garbage-collection diff --git a/doc/api/cli.md b/doc/api/cli.md index 70c5743afc98..66b43036528f 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -554,6 +554,25 @@ details. This flag cannot be combined with `--test`, `--watch`, `--watch-path`, `--check`, `--eval`, or `--interactive`. +### `--bench-gc=mode` + + + +> Stability: 1 - Experimental + +Overrides the garbage collection mode for every selected benchmark. When `mode` +is `'once'`, a full garbage collection runs before the first measured sample. +When `mode` is `'sample'`, a full garbage collection runs before every measured +sample. When `mode` is `'none'`, no garbage collection is forced. Without this +option, each benchmark uses its own `gc` value, which defaults to `'none'`. + +Forcing garbage collection requires the `--expose-gc` flag. With process +isolation, `--expose-gc` is added to benchmark child processes automatically +when `mode` is `'once'` or `'sample'`. With `--bench-isolation=none`, +`--expose-gc` must be passed explicitly. + ### `--bench-isolation=mode` + +* `value` {any} A value produced by measured work. +* Returns: {any} `value`. + +Stores `value` where the optimizing compiler cannot prove it is unused, so the +computation that produced it is not eliminated as dead code. Returning `value` +allows the call to wrap an expression. + +```mjs +import { bench, doNotOptimize } from 'node:bench'; + +bench('Math.sqrt', (b) => { + const n = 1_000_000; + b.start(); + for (let i = 0; i < n; i++) { + doNotOptimize(Math.sqrt(i)); + } + b.end(n); +}); +``` + +```cjs +const { bench, doNotOptimize } = require('node:bench'); + +bench('Math.sqrt', (b) => { + const n = 1_000_000; + b.start(); + for (let i = 0; i < n; i++) { + doNotOptimize(Math.sqrt(i)); + } + b.end(n); +}); +``` + +The call adds a small, constant cost to every invocation, so it is best suited +to work that takes longer than a few nanoseconds per call. For cheaper +operations, accumulate results into a value that is passed to +`doNotOptimize()` once after the measured region. + +`doNotOptimize()` only prevents the result from being discarded. It does not +prevent the compiler from hoisting loop-invariant work or folding constant +inputs; vary inputs between iterations when the work would otherwise be +invariant. + +`doNotOptimize()` is intended to be called only from benchmark functions while +a runner is executing them. Non-number values are retained until the current +sample finishes, after which the runner releases them. When called outside a +benchmark function, the most recent non-number value remains reachable until +`doNotOptimize()` is called again. + ## `before(fn)` - -> This flag is discouraged and may be removed in a future version of Node.js. -> Please use -> [`--import` with `register()`][preloading asynchronous module customization hooks] instead. - -Specify the `module` containing exported [asynchronous module customization hooks][]. -`module` may be any string accepted as an [`import` specifier][]. - -This feature requires `--allow-worker` if used with the [Permission Model][]. - ### `--experimental-network-inspection` -Type: Runtime +Type: End-of-Life -[`module.register()`][] is deprecated. Use [`module.registerHooks()`][] -instead. +The `module.register()` API and the `--experimental-loader` and `--loader` +flags have been removed. Use [`module.registerHooks()`][] instead. -The `module.register()` API provides off-thread async hooks for customizing ES modules; -the `module.registerHooks()` API provides similar hooks that are synchronous, in-thread, and -work for all types of modules. -Supporting async hooks has proven to be complex, involving worker threads orchestration, and there are issues -that have proven unresolvable. See [caveats of asynchronous customization hooks][]. Please migrate to -`module.registerHooks()` as soon as possible as `module.register()` will be -removed in a future version of Node.js. +The `module.register()` API provided off-thread async module customization +hooks for customizing ES modules. The `module.registerHooks()` API provides +similar hooks that are synchronous, in-thread and work for all types of modules. +To continue running async module customization off-thread, users can spawn their +own threads to run the async customizations, communicate from the in-thread +synchronous hooks and block for the results on the main thread, similar to how +`module.register()` worked internally. ### DEP0206: Calling `digest()` on an already-finalized `Hmac` instance @@ -4935,7 +4938,6 @@ Type: Documentation-only [`message.trailersDistinct`]: http.md#messagetrailersdistinct [`message.trailers`]: http.md#messagetrailers [`module.createRequire()`]: module.md#modulecreaterequirefilename -[`module.register()`]: module.md#moduleregisterspecifier-parenturl-options [`module.registerHooks()`]: module.md#moduleregisterhooksoptions [`os.networkInterfaces()`]: os.md#osnetworkinterfaces [`os.tmpdir()`]: os.md#ostmpdir @@ -4991,7 +4993,6 @@ Type: Documentation-only [`zlib.bytesWritten`]: zlib.md#zlibbyteswritten [alloc]: buffer.md#static-method-bufferallocsize-fill-encoding [alloc_unsafe_size]: buffer.md#static-method-bufferallocunsafesize-alignment -[caveats of asynchronous customization hooks]: module.md#caveats-of-asynchronous-customization-hooks [from_arraybuffer]: buffer.md#static-method-bufferfromarraybuffer-byteoffset-length [from_string_encoding]: buffer.md#static-method-bufferfromstring-encoding [legacy URL API]: url.md#legacy-url-api diff --git a/doc/api/errors.md b/doc/api/errors.md index 8020ec838c88..e6ab55bab058 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -733,13 +733,6 @@ by the `node:assert` module. An attempt was made to register something that is not a function as an `AsyncHooks` callback. - - -### `ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED` - -An operation related to module loading is customized by an asynchronous loader -hook that never settled the promise before the loader thread exits. - ### `ERR_ASYNC_RESOURCE_DOMAIN_REMOVED` @@ -2364,19 +2357,6 @@ for more information. IP is blocked by `net.BlockList`. - - -### `ERR_LOADER_CHAIN_INCOMPLETE` - - - -An ESM loader hook returned without calling `next()` and without explicitly -signaling a short circuit. - ### `ERR_LOAD_SQLITE_EXTENSION` @@ -3936,6 +3916,17 @@ attempting a [`require()`][] operation or when loading the program entry point. > Stability: 0 - Deprecated. These error codes are either inconsistent, or have > been removed. + + +### `ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED` + + + +An operation related to module loading is customized by an asynchronous loader +hook that never settled the promise before the loader thread exits. + ### `ERR_CANNOT_TRANSFER_OBJECT` @@ -4174,6 +4165,20 @@ changes: An invalid transfer object was passed to `postMessage()`. + + +### `ERR_LOADER_CHAIN_INCOMPLETE` + + + +An ESM loader hook returned without calling `next()` and without explicitly +signaling a short circuit. + ### `ERR_MANIFEST_ASSERT_INTEGRITY` diff --git a/doc/api/esm.md b/doc/api/esm.md index ef15a51dcfe5..bc4af89045f7 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -199,8 +199,7 @@ ES modules are resolved and cached as URLs. This means that special characters must be [percent-encoded][], such as `#` with `%23` and `?` with `%3F`. `file:`, `node:`, and `data:` URL schemes are supported. A specifier like -`'https://example.com/app.js'` is not supported natively in Node.js unless using -a [custom HTTPS loader][]. +`'https://example.com/app.js'` is not supported natively in Node.js. #### `file:` URLs @@ -493,8 +492,6 @@ resolutions are subject to the permitted exports resolutions within the package. * This can result in synchronous file-system operations, which can impact performance similarly to `require.resolve`. -* This feature is not available within custom loaders (it would - create a deadlock). **Non-standard API**: @@ -1316,8 +1313,8 @@ _isImports_, _conditions_) ### Customizing ESM specifier resolution algorithm [Module customization hooks][] provide a mechanism for customizing the ESM -specifier resolution algorithm. An example that provides CommonJS-style -resolution for ESM specifiers is [commonjs-extension-resolution-loader][]. +specifier resolution algorithm, for example to provide CommonJS-style +resolution for ESM specifiers. @@ -1360,8 +1357,6 @@ resolution for ESM specifiers is [commonjs-extension-resolution-loader][]. [`process.dlopen`]: process.md#processdlopenmodule-filename-flags [`require(esm)`]: modules.md#loading-ecmascript-modules-using-require [`url.fileURLToPath()`]: url.md#urlfileurltopathurl-options -[commonjs-extension-resolution-loader]: https://github.com/nodejs/loaders-test/tree/main/commonjs-extension-resolution-loader -[custom https loader]: module.md#import-from-https [import.meta.resolve]: #importmetaresolvespecifier [merve]: https://github.com/anonrig/merve/tree/v1.0.0 [percent-encoded]: url.md#percent-encoding-in-urls diff --git a/doc/api/module.md b/doc/api/module.md index f86167e8d44f..309114f9468c 100644 --- a/doc/api/module.md +++ b/doc/api/module.md @@ -176,56 +176,6 @@ isBuiltin('fs'); // true isBuiltin('wss'); // false ``` -## `module.register(specifier[, parentURL][, options])` - - - -> Stability: 0 - Deprecated: Use [`module.registerHooks()`][] instead. - -* `specifier` {string|URL} Customization hooks to be registered; this should be - the same string that would be passed to `import()`, except that if it is - relative, it is resolved relative to `parentURL`. -* `parentURL` {string|URL} If you want to resolve `specifier` relative to a base - URL, such as `import.meta.url`, you can pass that URL here. **Default:** - `'data:'` -* `options` {Object} - * `parentURL` {string|URL} If you want to resolve `specifier` relative to a - base URL, such as `import.meta.url`, you can pass that URL here. This - property is ignored if the `parentURL` is supplied as the second argument. - **Default:** `'data:'` - * `data` {any} Any arbitrary, cloneable JavaScript value to pass into the - [`initialize`][] hook. - * `transferList` {Object\[]} [transferable objects][] to be passed into the - `initialize` hook. - -Register a module that exports [hooks][] that customize Node.js module -resolution and loading behavior. See [Customization hooks][]. - -This feature requires `--allow-worker` if used with the [Permission Model][]. - ## `module.registerHooks(options)` -Node.js currently supports two types of module customization hooks: - -1. [`module.registerHooks(options)`][`module.registerHooks()`]: takes synchronous hook - functions that are run directly on the thread where the modules are loaded. -2. [`module.register(specifier[, parentURL][, options])`][`register`]: takes specifier to a - module that exports asynchronous hook functions. The functions are run on a - separate loader thread. - -The asynchronous hooks incur extra overhead from inter-thread communication, -and have [several caveats][caveats of asynchronous customization hooks] especially -when customizing CommonJS modules in the module graph. -In most cases, it's recommended to use synchronous hooks via `module.registerHooks()` -for simplicity. - -### Synchronous customization hooks +Node.js supports module customization hooks registered with +[`module.registerHooks()`][]. > Stability: 1.2 - Release candidate -#### Registration of synchronous customization hooks +### Registration of customization hooks -To register synchronous customization hooks, use [`module.registerHooks()`][], which -takes [synchronous hook functions][] directly in-line. +To register customization hooks, use [`module.registerHooks()`][], which +takes [hook functions][] directly in-line. ```mjs // register-hooks.js @@ -711,7 +648,7 @@ registerHooks({ }); ``` -##### Registering hooks before application code runs with flags +#### Registering hooks before application code runs with flags The hooks can be registered before the application code is run by using the [`--import`][] or [`--require`][] flag: @@ -736,7 +673,7 @@ Using `--import` or `--require` ensures that the hooks are registered before any application code is loaded, including the entry point of the application and for any worker threads by default as well. -##### Registering hooks before application code runs programmatically +#### Registering hooks before application code runs programmatically Alternatively, `registerHooks()` can be called from the entry point. @@ -751,7 +688,7 @@ module. ```mjs import { registerHooks } from 'node:module'; -registerHooks({ /* implementation of synchronous hooks */ }); +registerHooks({ /* implementation of hooks */ }); // If loaded using static import, the hooks would not be applied when loading // my-app.mjs, because statically imported modules are all executed before its @@ -765,7 +702,7 @@ await import('./my-app.mjs'); ```cjs const { registerHooks } = require('node:module'); -registerHooks({ /* implementation of synchronous hooks */ }); +registerHooks({ /* implementation of hooks */ }); import('./my-app.mjs'); // Or, if my-app.mjs does not have top-level await or it's a CommonJS module, @@ -773,7 +710,7 @@ import('./my-app.mjs'); // require('./my-app.mjs'); ``` -##### Registering hooks before application code runs with a `data:` URL +#### Registering hooks before application code runs with a `data:` URL Alternatively, inline JavaScript code can be embedded in `data:` URLs to register the hooks before the application code runs. For example, @@ -782,7 +719,7 @@ the hooks before the application code runs. For example, node --import 'data:text/javascript,import {registerHooks} from "node:module"; registerHooks(/* hooks code */);' ./my-app.js ``` -#### Convention of hooks and chaining +### Convention of hooks and chaining Hooks are part of a chain, even if that chain consists of only one custom (user-provided) hook and the default hook, which is always present. @@ -833,14 +770,13 @@ hook to signal that the chain is intentionally ending at your hook. If a hook should be applied when loading other hook modules, the other hook modules should be loaded after the hook is registered. -#### Deregistration of synchronous customization hooks +### Deregistration of customization hooks The object returned by `registerHooks()` has a `deregister()` method that can be used to remove the hooks from the chain. Once `deregister()` is called, the hooks will no longer be invoked during module resolution or loading. -This is currently only available for synchronous hooks registered via `registerHooks()`, not for asynchronous -hooks registered via `module.register()`. +This is available for hooks registered via `registerHooks()`. ```mjs import { registerHooks } from 'node:module'; @@ -890,7 +826,7 @@ hooks.deregister(); require('./another-module.cjs'); ``` -#### Hook functions accepted by `module.registerHooks()` +### Hook functions accepted by `module.registerHooks()` -The `module.registerHooks()` method accepts the following synchronous hook functions. +The `module.registerHooks()` method accepts the following hook functions. ```mjs function resolve(specifier, context, nextResolve) { @@ -910,16 +846,16 @@ function load(url, context, nextLoad) { } ``` -Synchronous hooks are run in the same thread and the same [realm][] where the modules -are loaded, the code in the hook function can pass values to the modules being referenced -directly via global variables or other shared states. +Hooks are run in the same [realm][] as the modules being loaded, so the code in the +hook function can pass values to the modules being referenced directly via global +variables or other shared states. -Unlike the asynchronous hooks, the synchronous hooks are not inherited into child worker -threads by default, though if the hooks are registered using a file preloaded by -[`--import`][] or [`--require`][], child worker threads can inherit the preloaded scripts -via `process.execArgv` inheritance. See [the documentation of `Worker`][] for details. +Hooks are not inherited into child worker threads by default. If the hooks are +registered using a file preloaded by [`--import`][] or [`--require`][], child worker threads +can inherit the preloaded scripts via `process.execArgv` inheritance. See +[the documentation of `Worker`][] for details. -#### Synchronous `resolve(specifier, context, nextResolve)` +### `resolve(specifier, context, nextResolve)` - -The [`register`][] method can be used to register a module that exports a set of -hooks. The hooks are functions that are called by Node.js to customize the -module resolution and loading process. The exported functions must have specific -names and signatures, and they must be exported as named exports. - -```mjs -export async function initialize({ number, port }) { - // Receives data from `register`. -} - -export async function resolve(specifier, context, nextResolve) { - // Take an `import` or `require` specifier and resolve it to a URL. -} - -export async function load(url, context, nextLoad) { - // Take a resolved URL and return the source code to be evaluated. -} -``` - -Asynchronous hooks are run in a separate thread, isolated from the main thread where -application code runs. That means it is a different [realm][]. The hooks thread -may be terminated by the main thread at any time, so do not depend on -asynchronous operations (like `console.log`) to complete. They are inherited into -child workers by default. - -#### `initialize()` - - - -* `data` {any} The data from `register(loader, import.meta.url, { data })`. - -The `initialize` hook is only accepted by [`register`][]. `registerHooks()` does -not support nor need it since initialization done for synchronous hooks can be run -directly before the call to `registerHooks()`. - -The `initialize` hook provides a way to define a custom function that runs in -the hooks thread when the hooks module is initialized. Initialization happens -when the hooks module is registered via [`register`][]. - -This hook can receive data from a [`register`][] invocation, including -ports and other transferable objects. The return value of `initialize` can be a -{Promise}, in which case it will be awaited before the main application thread -execution resumes. - -Module customization code: - -```mjs -// path-to-my-hooks.js - -export async function initialize({ number, port }) { - port.postMessage(`increment: ${number + 1}`); -} -``` - -Caller code: - -```mjs -import assert from 'node:assert'; -import { register } from 'node:module'; -import { MessageChannel } from 'node:worker_threads'; - -// This example showcases how a message channel can be used to communicate -// between the main (application) thread and the hooks running on the hooks -// thread, by sending `port2` to the `initialize` hook. -const { port1, port2 } = new MessageChannel(); - -port1.on('message', (msg) => { - assert.strictEqual(msg, 'increment: 2'); -}); -port1.unref(); - -register('./path-to-my-hooks.js', { - parentURL: import.meta.url, - data: { number: 1, port: port2 }, - transferList: [port2], -}); -``` - -```cjs -const assert = require('node:assert'); -const { register } = require('node:module'); -const { pathToFileURL } = require('node:url'); -const { MessageChannel } = require('node:worker_threads'); - -// This example showcases how a message channel can be used to communicate -// between the main (application) thread and the hooks running on the hooks -// thread, by sending `port2` to the `initialize` hook. -const { port1, port2 } = new MessageChannel(); - -port1.on('message', (msg) => { - assert.strictEqual(msg, 'increment: 2'); -}); -port1.unref(); - -register('./path-to-my-hooks.js', { - parentURL: pathToFileURL(__filename), - data: { number: 1, port: port2 }, - transferList: [port2], -}); -``` - -#### Asynchronous `resolve(specifier, context, nextResolve)` - - - -* `specifier` {string} -* `context` {Object} - * `conditions` {string\[]} Export conditions of the relevant `package.json` - * `importAttributes` {Object} An object whose key-value pairs represent the - attributes for the module to import - * `parentURL` {string|undefined} The module importing this one, or undefined - if this is the Node.js entry point -* `nextResolve` {Function} The subsequent `resolve` hook in the chain, or the - Node.js default `resolve` hook after the last user-supplied `resolve` hook - * `specifier` {string} - * `context` {Object|undefined} When omitted, the defaults are provided. When provided, defaults - are merged in with preference to the provided properties. -* Returns: {Object|Promise} The asynchronous version takes either an object containing the - following properties, or a `Promise` that will resolve to such an object. - * `format` {string|null|undefined} A hint to the `load` hook (it might be ignored). It can be a - module format (such as `'commonjs'` or `'module'`) or an arbitrary value like `'css'` or - `'yaml'`. - * `importAttributes` {Object|undefined} The import attributes to use when - caching the module (optional; if excluded the input will be used) - * `shortCircuit` {undefined|boolean} A signal that this hook intends to - terminate the chain of `resolve` hooks. **Default:** `false` - * `url` {string} The absolute URL to which this input resolves - -The asynchronous version works similarly to the synchronous version, only that the -`nextResolve` function returns a `Promise`, and the `resolve` hook itself can return a `Promise`. - -> **Warning** In the case of the asynchronous version, despite support for returning -> promises and async functions, calls to `resolve` may still block the main thread which -> can impact performance. - -> **Warning** The `resolve` hook invoked for `require()` calls inside CommonJS modules -> customized by asynchronous hooks does not receive the original specifier passed to -> `require()`. Instead, it receives a URL already fully resolved using the default -> CommonJS resolution. - -> **Warning** In the CommonJS modules that are customized by the asynchronous customization hooks, -> `require.resolve()` and `require()` will use `"import"` export condition instead of -> `"require"`, which may cause unexpected behaviors when loading dual packages. - -```mjs -export async function resolve(specifier, context, nextResolve) { - // When calling `defaultResolve`, the arguments can be modified. For example, - // to change the specifier or add conditions. - if (specifier.includes('foo')) { - specifier = specifier.replace('foo', 'bar'); - return nextResolve(specifier, { - ...context, - conditions: [...context.conditions, 'another-condition'], - }); - } - - // The hook can also skips default resolution and provide a custom URL. - if (specifier === 'special-module') { - return { - url: 'file:///path/to/special-module.mjs', - format: 'module', - shortCircuit: true, // This is mandatory if not calling nextResolve(). - }; - } - - // If no customization is needed, defer to the next hook in the chain which would be the - // Node.js default resolve if this is the last user-specified loader. - return nextResolve(specifier); -} -``` - -#### Asynchronous `load(url, context, nextLoad)` - - - -* `url` {string} The URL returned by the `resolve` chain -* `context` {Object} - * `conditions` {string\[]} Export conditions of the relevant `package.json` - * `format` {string|null|undefined} The format optionally supplied by the - `resolve` hook chain. This can be any string value as an input; input values do not need to - conform to the list of acceptable return values described below. - * `importAttributes` {Object} -* `nextLoad` {Function} The subsequent `load` hook in the chain, or the - Node.js default `load` hook after the last user-supplied `load` hook - * `url` {string} - * `context` {Object|undefined} When omitted, defaults are provided. When provided, defaults are - merged in with preference to the provided properties. In the default `nextLoad`, if - the module pointed to by `url` does not have explicit module type information, - `context.format` is mandatory. - -* Returns: {Promise} The asynchronous version takes either an object containing the - following properties, or a `Promise` that will resolve to such an object. - * `format` {string} - * `shortCircuit` {undefined|boolean} A signal that this hook intends to - terminate the chain of `load` hooks. **Default:** `false` - * `source` {string|ArrayBuffer|TypedArray} The source for Node.js to evaluate - -> **Warning**: The asynchronous `load` hook and namespaced exports from CommonJS -> modules are incompatible. Attempting to use them together will result in an empty -> object from the import. This may be addressed in the future. This does not apply -> to the synchronous `load` hook, in which case exports can be used as usual. - -The asynchronous version works similarly to the synchronous version, though -when using the asynchronous `load` hook, omitting vs providing a `source` for -`'commonjs'` has very different effects: - -* When a `source` is provided, all `require` calls from this module will be - processed by the ESM loader with registered `resolve` and `load` hooks; all - `require.resolve` calls from this module will be processed by the ESM loader - with registered `resolve` hooks; only a subset of the CommonJS API will be - available (e.g. no `require.extensions`, no `require.cache`, no - `require.resolve.paths`) and monkey-patching on the CommonJS module loader - will not apply. -* If `source` is undefined or `null`, it will be handled by the CommonJS module - loader and `require`/`require.resolve` calls will not go through the - registered hooks. This behavior for nullish `source` is temporary — in the - future, nullish `source` will not be supported. - -These caveats do not apply to the synchronous `load` hook, in which case -the complete set of CommonJS APIs available to the customized CommonJS -modules, and `require`/`require.resolve` always go through the registered -hooks. - -The Node.js internal asynchronous `load` implementation, which is the value of `next` for the -last hook in the `load` chain, returns `null` for `source` when `format` is -`'commonjs'` for backward compatibility. Here is an example hook that would -opt-in to using the non-default behavior: - -```mjs -import { readFile } from 'node:fs/promises'; - -// Asynchronous version accepted by module.register(). This fix is not needed -// for the synchronous version accepted by module.registerHooks(). -export async function load(url, context, nextLoad) { - const result = await nextLoad(url, context); - if (result.format === 'commonjs') { - result.source ??= await readFile(new URL(result.responseURL ?? url)); - } - return result; -} -``` - -This doesn't apply to the synchronous `load` hook either, in which case the -`source` returned contains source code loaded by the next hook, regardless -of module format. - ### Examples The various module customization hooks can be used together to accomplish wide-ranging customizations of the Node.js code loading and evaluation behaviors. -#### Import from HTTPS - -The hook below registers hooks to enable rudimentary support for such -specifiers. While this may seem like a significant improvement to Node.js core -functionality, there are substantial downsides to actually using these hooks: -performance is much slower than loading files from disk, there is no caching, -and there is no security. - -```mjs -// https-hooks.mjs -import { get } from 'node:https'; - -export function load(url, context, nextLoad) { - // For JavaScript to be loaded over the network, we need to fetch and - // return it. - if (url.startsWith('https://')) { - return new Promise((resolve, reject) => { - get(url, (res) => { - let data = ''; - res.setEncoding('utf8'); - res.on('data', (chunk) => data += chunk); - res.on('end', () => resolve({ - // This example assumes all network-provided JavaScript is ES module - // code. - format: 'module', - shortCircuit: true, - source: data, - })); - }).on('error', (err) => reject(err)); - }); - } - - // Let Node.js handle all other URLs. - return nextLoad(url); -} -``` - -```mjs -// main.mjs -import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js'; - -console.log(VERSION); -``` - -With the preceding hooks module, running -`node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs` -prints the current version of CoffeeScript per the module at the URL in -`main.mjs`. - - - #### Transpilation Sources that are in formats Node.js doesn't understand can be converted into @@ -1685,58 +1052,6 @@ JavaScript using the [`load` hook][load hook]. This is less performant than transpiling source files before running Node.js; transpiler hooks should only be used for development and testing purposes. -##### Asynchronous version - -```mjs -// coffeescript-hooks.mjs -import { readFile } from 'node:fs/promises'; -import { findPackageJSON } from 'node:module'; -import coffeescript from 'coffeescript'; - -const extensionsRegex = /\.(coffee|litcoffee|coffee\.md)$/; - -export async function load(url, context, nextLoad) { - if (extensionsRegex.test(url)) { - // CoffeeScript files can be either CommonJS or ES modules. Use a custom format - // to tell Node.js not to detect its module type. - const { source: rawSource } = await nextLoad(url, { ...context, format: 'coffee' }); - // This hook converts CoffeeScript source code into JavaScript source code - // for all imported CoffeeScript files. - const transformedSource = coffeescript.compile(rawSource.toString(), url); - - // To determine how Node.js would interpret the transpilation result, - // search up the file system for the nearest parent package.json file - // and read its "type" field. - return { - format: await getPackageType(url), - shortCircuit: true, - source: transformedSource, - }; - } - - // Let Node.js handle all other URLs. - return nextLoad(url, context); -} - -async function getPackageType(url) { - // `url` is only a file path during the first iteration when passed the - // resolved url from the load() hook - // an actual file path from load() will contain a file extension as it's - // required by the spec - // this simple truthy check for whether `url` contains a file extension will - // work for most projects but does not cover some edge-cases (such as - // extensionless files or a url ending in a trailing space) - const pJson = findPackageJSON(url); - - return readFile(pJson, 'utf8') - .then(JSON.parse) - .then((json) => json?.type) - .catch(() => undefined); -} -``` - -##### Synchronous version - ```mjs // coffeescript-sync-hooks.mjs import { readFileSync } from 'node:fs'; @@ -1807,9 +1122,8 @@ able to return an `format` known to Node.js even in the absence of an explicit t (if undefined) or `ERR_UNKNOWN_MODULE_FORMAT` (if it's not a known format listed in the [load hook][] documentation). -With the preceding hooks modules, running -`node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee` -or `node --import ./coffeescript-sync-hooks.mjs ./main.coffee` +With the preceding hooks module, running +`node --import ./coffeescript-sync-hooks.mjs ./main.coffee` causes `main.coffee` to be turned into JavaScript after its source code is loaded from disk but before Node.js executes it; and so on for any `.coffee`, `.litcoffee` or `.coffee.md` files referenced via `import` statements of any @@ -1822,25 +1136,6 @@ The previous two examples defined `load` hooks. This is an example of a which specifiers to override to other URLs (this is a very simplistic implementation of a small subset of the "import maps" specification). -##### Asynchronous version - -```mjs -// import-map-hooks.js -import fs from 'node:fs/promises'; - -const { imports } = JSON.parse(await fs.readFile('import-map.json')); - -export async function resolve(specifier, context, nextResolve) { - if (Object.hasOwn(imports, specifier)) { - return nextResolve(imports[specifier], context); - } - - return nextResolve(specifier, context); -} -``` - -##### Synchronous version - ```mjs // import-map-sync-hooks.js import fs from 'node:fs/promises'; @@ -1882,8 +1177,7 @@ import 'a-module'; console.log('some module!'); ``` -Running `node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js` -or `node --import ./import-map-sync-hooks.js main.js` +Running `node --import ./import-map-sync-hooks.js main.js` should print `some module!`. ## Source Map Support @@ -2104,7 +1398,6 @@ returned object contains the following keys: [Conditional exports]: packages.md#conditional-exports [Customization hooks]: #customization-hooks [ES Modules]: esm.md -[Permission Model]: permissions.md#permission-model [Source Map]: https://tc39.es/ecma426/ [Source map format]: https://tc39.es/ecma426/#sec-source-map-format [V8 JavaScript code coverage]: https://v8project.blogspot.com/2017/12/javascript-code-coverage.html @@ -2120,7 +1413,6 @@ returned object contains the following keys: [`NODE_V8_COVERAGE=dir`]: cli.md#node_v8_coveragedir [`Object.freeze()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze [`SourceMap`]: #class-modulesourcemap -[`initialize`]: #initialize [`module.constants.compileCacheStatus`]: #moduleconstantscompilecachestatus [`module.enableCompileCache()`]: #moduleenablecompilecacheoptions [`module.flushCompileCache()`]: #moduleflushcompilecache @@ -2129,22 +1421,16 @@ returned object contains the following keys: [`module.registerHooks()`]: #moduleregisterhooksoptions [`module.setSourceMapsSupport()`]: #modulesetsourcemapssupportenabled-options [`os.tmpdir()`]: os.md#ostmpdir -[`register`]: #moduleregisterspecifier-parenturl-options [`util.TextDecoder`]: util.md#class-utiltextdecoder [accepted final formats]: #accepted-final-formats-returned-by-load -[asynchronous `load` hook]: #asynchronous-loadurl-context-nextload -[asynchronous `resolve` hook]: #asynchronous-resolvespecifier-context-nextresolve -[asynchronous hook functions]: #asynchronous-hooks-accepted-by-moduleregister -[caveats of asynchronous customization hooks]: #caveats-of-asynchronous-customization-hooks -[deregistration of synchronous customization hooks]: #deregistration-of-synchronous-customization-hooks +[deregistration of customization hooks]: #deregistration-of-customization-hooks +[hook functions]: #hook-functions-accepted-by-moduleregisterhooks [hooks]: #customization-hooks -[load hook]: #synchronous-loadurl-context-nextload +[load hook]: #loadurl-context-nextload [module compile cache]: #module-compile-cache [realm]: https://tc39.es/ecma262/#realm -[resolve hook]: #synchronous-resolvespecifier-context-nextresolve +[resolve hook]: #resolvespecifier-context-nextresolve [source map include directives]: https://tc39.es/ecma426/#sec-linking-generated-code -[synchronous hook functions]: #hook-functions-accepted-by-moduleregisterhooks [the `module` object]: modules.md#the-module-object [the documentation of `Worker`]: worker_threads.md#new-workerfilename-options -[transferable objects]: worker_threads.md#portpostmessagevalue-transferlist [type-stripping]: typescript.md#type-stripping diff --git a/doc/api/test.md b/doc/api/test.md index db530c609add..01703227f8cf 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -2883,10 +2883,8 @@ Node.js builtin modules. Any references to the original module prior to mocking order to enable module mocking, Node.js must be started with the [`--experimental-test-module-mocks`][] command-line flag. -**Note**: [module customization hooks][] registered via the **synchronous** API effect resolution of -the `specifier` provided to `mock.module`. Customization hooks registered via the **asynchronous** -API are currently ignored (because the test runner's loader is synchronous, and node does not -support multi-chain / cross-chain loading). +**Note**: [module customization hooks][] registered with `module.registerHooks()` affect resolution of +the `specifier` provided to `mock.module`. The following example demonstrates how a mock is created for a module. diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 08da7b35f152..af572039c8ac 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -169,27 +169,16 @@ if (isMainThread) { added: - v23.7.0 - v22.14.0 +changes: + - version: REPLACEME + pr-url: https://github.com/nodejs/node/pull/67090 + description: Always `false`, as Node.js no longer runs code in internal threads. --> * Type: {boolean} -Is `true` if this code is running inside of an internal [`Worker`][] thread (e.g the loader thread). - -```bash -node --experimental-loader ./loader.js main.js -``` - -```mjs -// loader.js -import { isInternalThread } from 'node:worker_threads'; -console.log(isInternalThread); // true -``` - -```cjs -// loader.js -const { isInternalThread } = require('node:worker_threads'); -console.log(isInternalThread); // true -``` +Always `false`. Node.js no longer runs user-visible code in internal [`Worker`][] +threads, so this is retained only for backward compatibility. ```mjs // main.js diff --git a/doc/node-config-schema.json b/doc/node-config-schema.json index 9b9c0f835d02..8453ca49e7da 100644 --- a/doc/node-config-schema.json +++ b/doc/node-config-schema.json @@ -367,21 +367,6 @@ "type": "boolean", "description": "experimental support for importing source as text with import attributes" }, - "experimental-loader": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "array", - "minItems": 1, - "items": { - "type": "string" - } - } - ], - "description": "use the specified module as a custom loader" - }, "experimental-package-map": { "type": "string", "description": "use the specified file for package map resolution" diff --git a/doc/node.1 b/doc/node.1 index ad7120516787..6f1feb9e99ef 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -885,11 +885,6 @@ Enable experimental support for importing modules with .It Fl -experimental-inspector-network-resource Enable experimental support for inspector network resources. . -.It Fl -experimental-loader Ns = Ns Ar module -Specify the \fBmodule\fR containing exported asynchronous module customization hooks. -\fBmodule\fR may be any string accepted as an \fBimport\fR specifier. -This feature requires \fB--allow-worker\fR if used with the Permission Model. -. .It Fl -experimental-network-inspection Enable experimental support for the network inspection with Chrome DevTools. . @@ -2290,8 +2285,6 @@ one is included in the list below. .It \fB--experimental-json-modules\fR .It -\fB--experimental-loader\fR -.It \fB--experimental-modules\fR .It \fB--experimental-package-map\fR diff --git a/lib/internal/bench_runner/cli.js b/lib/internal/bench_runner/cli.js index 4993b44face4..f0b6f84adb14 100644 --- a/lib/internal/bench_runner/cli.js +++ b/lib/internal/bench_runner/cli.js @@ -719,7 +719,6 @@ function runFileOptionRequiresValue(arg) { } const kOptionAliases = new SafeMap([ - ['--loader', '--experimental-loader'], ['-C', '--conditions'], ['-r', '--require'], ]); diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 786fc7e275eb..88518563bc6b 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1143,8 +1143,6 @@ E('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); E('ERR_ARG_NOT_ITERABLE', '%s must be iterable', TypeError); E('ERR_ASSERTION', '%s', Error); E('ERR_ASYNC_CALLBACK', '%s must be a function', TypeError); -E('ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED', - 'Async loader request never settled', Error); E('ERR_ASYNC_RESOURCE_DOMAIN_REMOVED', 'The domain property on AsyncResource has been removed. ' + 'Use AsyncLocalStorage instead.', Error); @@ -1605,13 +1603,6 @@ E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks', Error); E('ERR_IP_BLOCKED', function(ip) { return `IP(${ip}) is blocked by net.BlockList`; }, Error); -E( - 'ERR_LOADER_CHAIN_INCOMPLETE', - '"%s" did not call the next hook in its chain and did not' + - ' explicitly signal a short circuit. If this is intentional, include' + - ' `shortCircuit: true` in the hook\'s return.', - Error, -); E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error); E('ERR_MISSING_ARGS', (...args) => { @@ -1789,13 +1780,14 @@ E('ERR_REQUIRE_ESM', 'all ES modules instead).\n'; return msg; }, Error); -E('ERR_REQUIRE_ESM_RACE_CONDITION', (filename, parentFilename, isForAsyncLoaderHookWorker) => { +E('ERR_REQUIRE_ESM_RACE_CONDITION', (filename, parentFilename) => { let raceMessage = `Cannot require() ES Module ${filename} because it is not yet fully loaded.\n`; raceMessage += 'This may be caused by a race condition if the module is simultaneously dynamically '; raceMessage += 'import()-ed via Promise.all().\n'; - raceMessage += 'Try await-ing the import() sequentially in a loop instead.\n'; - raceMessage += ` (From ${parentFilename ? `${parentFilename} in ` : ' '}`; - raceMessage += `${isForAsyncLoaderHookWorker ? 'loader hook worker thread' : 'non-loader-hook thread'})`; + raceMessage += 'Try await-ing the import() sequentially in a loop instead.'; + if (parentFilename) { + raceMessage += `\n (From ${parentFilename})`; + } return raceMessage; }, Error); E('ERR_SCRIPT_EXECUTION_INTERRUPTED', diff --git a/lib/internal/main/eval_string.js b/lib/internal/main/eval_string.js index 998c3fb4ada5..c662b8c2c267 100644 --- a/lib/internal/main/eval_string.js +++ b/lib/internal/main/eval_string.js @@ -30,7 +30,7 @@ markBootstrapComplete(); const code = getOptionValue('--eval'); const print = getOptionValue('--print'); -const shouldLoadESM = getOptionValue('--import').length > 0 || getOptionValue('--experimental-loader').length > 0; +const shouldLoadESM = getOptionValue('--import').length > 0; const inputType = getOptionValue('--input-type'); const tsEnabled = getOptionValue('--strip-types'); if (inputType === 'module') { diff --git a/lib/internal/main/worker_thread.js b/lib/internal/main/worker_thread.js index ed12eb946789..9895b86dbb4d 100644 --- a/lib/internal/main/worker_thread.js +++ b/lib/internal/main/worker_thread.js @@ -106,16 +106,14 @@ port.on('message', (message) => { mainThreadPort, } = message; - if (doEval !== 'internal') { - if (argv !== undefined) { - ArrayPrototypePushApply(process.argv, argv); - } - - const publicWorker = require('worker_threads'); - publicWorker.parentPort = publicPort; - publicWorker.workerData = workerData; + if (argv !== undefined) { + ArrayPrototypePushApply(process.argv, argv); } + const publicWorker = require('worker_threads'); + publicWorker.parentPort = publicPort; + publicWorker.workerData = workerData; + require('internal/worker').assignEnvironmentData(environmentData); setupMainThreadPort(mainThreadPort); @@ -141,24 +139,18 @@ port.on('message', (message) => { }; workerIo.sharedCwdCounter = cwdCounter; - const isLoaderHookWorker = (filename === 'internal/modules/esm/worker' && doEval === 'internal'); - if (!isLoaderHookWorker) { - // If we are in the loader hook worker, delay the module loader initializations until - // initializeAsyncLoaderHooksOnLoaderHookWorker() which needs to run preloads - // after the asynchronous loader hooks are registered. - initializeModuleLoaders({ shouldSpawnLoaderHookWorker: true, shouldPreloadModules: true }); - // Re-mount the inherited --vfs-load source so its reserved path (which a - // worker filename may point into) resolves in this thread too. With - // --import, mounting is deferred to after that loop in run_main, matching - // the main thread; finishVfsMounts() is idempotent so it runs once. - if (getOptionValue('--import').length === 0) { - finishVfsMounts(); - } - // Unlike the --vfs-load source, the SEA VFS needs no provider that a - // preload could register, so its mount is never deferred. - if (getOptionValue('[sea_vfs]')) { - require('internal/vfs/sea').initSeaVfsInWorker(); - } + initializeModuleLoaders({ shouldPreloadModules: true }); + // Re-mount the inherited --vfs-load source so its reserved path (which a + // worker filename may point into) resolves in this thread too. With + // --import, mounting is deferred to after that loop in run_main, matching + // the main thread; finishVfsMounts() is idempotent so it runs once. + if (getOptionValue('--import').length === 0) { + finishVfsMounts(); + } + // Unlike the --vfs-load source, the SEA VFS needs no provider that a + // preload could register, so its mount is never deferred. + if (getOptionValue('[sea_vfs]')) { + require('internal/vfs/sea').initSeaVfsInWorker(); } if (!hasStdin) @@ -168,14 +160,6 @@ port.on('message', (message) => { `(eval = ${doEval}) at cwd = ${process.cwd()}`); port.postMessage({ type: UP_AND_RUNNING }); switch (doEval) { - case 'internal': { - // Currently the only user of internal eval is the async loader hook thread. - assert(isLoaderHookWorker, `Unexpected internal eval ${filename}`); - const setupModuleWorker = require('internal/modules/esm/worker'); - setupModuleWorker(workerData, publicPort); - break; - } - case 'classic': if (webWorkerData?.source !== undefined) { // The source of a web Worker script loaded from a blob: or data: // URL. diff --git a/lib/internal/modules/customization_hooks.js b/lib/internal/modules/customization_hooks.js index c3d1970243fd..5ce0ab4418a0 100644 --- a/lib/internal/modules/customization_hooks.js +++ b/lib/internal/modules/customization_hooks.js @@ -282,7 +282,7 @@ function validateLoadSloppy(url, context, result) { function validateSourceStrict(url, context, result) { const { source, format } = result; - // To align with module.register(), the load hooks are still invoked for + // To align with the legacy module.register(), the load hooks are still invoked for // the builtins even though the default load step only provides null as source, // and any source content for builtins provided by the user hooks are ignored. if (!StringPrototypeStartsWith(url, 'node:') && @@ -302,7 +302,7 @@ function validateSourceStrict(url, context, result) { function validateSourcePermissive(url, context, result) { const { source, format } = result; if (format === 'commonjs' && source == null) { - // Accommodate the quirk in defaultLoad used by asynchronous loader hooks + // To retain the legacy behavior from the quirk in defaultLoad used by asynchronous loader hooks // which sets source to null for commonjs. // See: https://github.com/nodejs/node/issues/57327#issuecomment-2701382020 return; diff --git a/lib/internal/modules/esm/hooks.js b/lib/internal/modules/esm/hooks.js deleted file mode 100644 index 220dcd33754e..000000000000 --- a/lib/internal/modules/esm/hooks.js +++ /dev/null @@ -1,870 +0,0 @@ -'use strict'; - -const { - ArrayPrototypePush, - ArrayPrototypePushApply, - AtomicsLoad, - AtomicsWait, - AtomicsWaitAsync, - Int32Array, - ObjectAssign, - ObjectDefineProperty, - ObjectSetPrototypeOf, - Promise, - ReflectSet, - SafeSet, - StringPrototypeSlice, - StringPrototypeToUpperCase, -} = primordials; - -const { - ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED, - ERR_INTERNAL_ASSERTION, - ERR_INVALID_ARG_TYPE, - ERR_INVALID_ARG_VALUE, - ERR_INVALID_RETURN_PROPERTY_VALUE, - ERR_INVALID_RETURN_VALUE, - ERR_LOADER_CHAIN_INCOMPLETE, - ERR_WORKER_UNSERIALIZABLE_ERROR, -} = require('internal/errors').codes; -const { URLParse } = require('internal/url'); -const { canParse: URLCanParse } = internalBinding('url'); -const { receiveMessageOnPort } = require('worker_threads'); -const { - isAnyArrayBuffer, - isArrayBufferView, -} = require('internal/util/types'); -const { - validateObject, - validateString, -} = require('internal/validators'); -const { - constructSharedArrayBuffer, - kEmptyObject, -} = require('internal/util'); - -const { - defaultResolve, - throwIfInvalidParentURL, -} = require('internal/modules/esm/resolve'); -const { - getDefaultConditions, -} = require('internal/modules/esm/utils'); -const { hasWorkerCondition } = require('internal/modules/helpers'); -const { deserializeError } = require('internal/error_serdes'); -const { - SHARED_MEMORY_BYTE_LENGTH, - WORKER_TO_MAIN_THREAD_NOTIFICATION, -} = require('internal/modules/esm/shared_constants'); -let debug = require('internal/util/debuglog').debuglog('async_loader_worker', (fn) => { - debug = fn; -}); - -let importAssertionAlreadyWarned = false; - -function emitImportAssertionWarning() { - if (!importAssertionAlreadyWarned) { - importAssertionAlreadyWarned = true; - process.emitWarning('Use `importAttributes` instead of `importAssertions`', 'ExperimentalWarning'); - } -} - -function defineImportAssertionAlias(context) { - return ObjectDefineProperty(context, 'importAssertions', { - __proto__: null, - configurable: true, - get() { - emitImportAssertionWarning(); - return this.importAttributes; - }, - set(value) { - emitImportAssertionWarning(); - return ReflectSet(this, 'importAttributes', value); - }, - }); -} - -/** - * @typedef {object} ExportedHooks - * @property {Function} resolve Resolve hook. - * @property {Function} load Load hook. - */ - -/** - * @typedef {object} KeyedHook - * @property {Function} fn The hook function. - * @property {URL['href']} url The URL of the module. - * @property {KeyedHook?} next The next hook in the chain. - */ - -// [2] `validate...()`s throw the wrong error - -/** - * @typedef {{ format: ModuleFormat, source: ModuleSource }} LoadResult - */ - -/** - * @typedef {{ format: ModuleFormat, url: string, importAttributes: Record }} ResolveResult - */ - -/** - * Interface for classes that implement asynchronous loader hooks that can be attached to the ModuleLoader - * via `ModuleLoader.#setAsyncLoaderHooks()`. - * @typedef {object} AsyncLoaderHooks - * @property {boolean} isForAsyncLoaderHookWorker Whether the instance is running on the loader hook worker thread. - * @property {(url: string, context: object, defaultLoad: Function) => Promise} load - * Calling the asynchronous `load` hook asynchronously. - * @property {(url: string, context: object, defaultLoad: Function) => LoadResult} [loadSync] - * Calling the asynchronous `load` hook synchronously. - * @property {(originalSpecifier: string, parentURL: string, - * importAttributes: Record) => Promise} resolve - * Calling the asynchronous `resolve` hook asynchronously. - * @property {(originalSpecifier: string, parentURL: string, - * importAttributes: Record) => ResolveResult} [resolveSync] - * Calling the asynchronous `resolve` hook synchronously. - * @property {(specifier: string, parentURL: string) => any} register Register asynchronous loader hooks - * @property {() => void} waitForLoaderHookInitialization Force loading of hooks. - */ - -/** - * @implements {AsyncLoaderHooks} - * Instances of this class run directly on the loader hook worker thread and customize the module - * loading of the hooks worker itself. - */ -class AsyncLoaderHooksOnLoaderHookWorker { - #chains = { - /** - * Phase 1 of 2 in ESM loading. - * The output of the `resolve` chain of hooks is passed into the `load` chain of hooks. - * @private - * @property {KeyedHook[]} resolve Last-in-first-out collection of resolve hooks. - */ - resolve: [ - { - fn: defaultResolve, - url: 'node:internal/modules/esm/resolve', - }, - ], - - /** - * Phase 2 of 2 in ESM loading. - * @private - * @property {KeyedHook[]} load Last-in-first-out collection of loader hooks. - */ - load: [ - { - fn: require('internal/modules/esm/load').defaultLoad, - url: 'node:internal/modules/esm/load', - }, - ], - }; - - // Cache URLs we've already validated to avoid repeated validation - #validatedUrls = new SafeSet(); - - isForAsyncLoaderHookWorker = true; - - /** - * Import and register custom/user-defined module loader hook(s). - * @param {string} urlOrSpecifier - * @param {string} parentURL - * @param {any} [data] Arbitrary data to be passed from the custom - * loader (user-land) to the worker. - */ - async register(urlOrSpecifier, parentURL, data, isInternal) { - const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); - const keyedExports = isInternal ? - require(urlOrSpecifier) : - await cascadedLoader.import( - urlOrSpecifier, - parentURL, - kEmptyObject, - ); - await this.addCustomLoader(urlOrSpecifier, keyedExports, data); - } - - /** - * Collect custom/user-defined module loader hook(s). - * @param {string} url Custom loader specifier - * @param {Record} exports - * @param {any} [data] Arbitrary data to be passed from the custom loader (user-land) - * to the worker. - * @returns {any | Promise} User data, ignored unless it's a promise, in which case it will be awaited. - */ - addCustomLoader(url, exports, data) { - const { - initialize, - resolve, - load, - } = pluckHooks(exports); - - if (resolve) { - const next = this.#chains.resolve[this.#chains.resolve.length - 1]; - ArrayPrototypePush(this.#chains.resolve, { __proto__: null, fn: resolve, url, next }); - } - if (load) { - const next = this.#chains.load[this.#chains.load.length - 1]; - ArrayPrototypePush(this.#chains.load, { __proto__: null, fn: load, url, next }); - } - return initialize?.(data); - } - - /** - * Resolve the location of the module. - * - * Internally, this behaves like a backwards iterator, wherein the stack of - * hooks starts at the top and each call to `nextResolve()` moves down 1 step - * until it reaches the bottom or short-circuits. - * @param {string} originalSpecifier The specified URL path of the module to - * be resolved. - * @param {string} [parentURL] The URL path of the module's parent. - * @param {ImportAttributes} [importAttributes] Attributes from the import - * statement or expression. - * @returns {Promise<{ format: string, url: URL['href'] }>} - */ - async resolve( - originalSpecifier, - parentURL, - importAttributes = { __proto__: null }, - ) { - throwIfInvalidParentURL(parentURL); - - const chain = this.#chains.resolve; - const context = { - conditions: getDefaultConditions(), - importAttributes, - parentURL, - }; - const meta = { - chainFinished: null, - context, - hookErrIdentifier: '', - hookName: 'resolve', - shortCircuited: false, - }; - - const validateArgs = (hookErrIdentifier, suppliedSpecifier, ctx) => { - validateString( - suppliedSpecifier, - `${hookErrIdentifier} specifier`, - ); // non-strings can be coerced to a URL string - - if (ctx) { validateObject(ctx, `${hookErrIdentifier} context`); } - }; - const validateOutput = (hookErrIdentifier, output) => { - if (typeof output !== 'object' || output === null) { // [2] - throw new ERR_INVALID_RETURN_VALUE( - 'an object', - hookErrIdentifier, - output, - ); - } - }; - - const nextResolve = nextHookFactory(chain[chain.length - 1], meta, { validateArgs, validateOutput }); - - const resolution = await nextResolve(originalSpecifier, defineImportAssertionAlias(context)); - const { hookErrIdentifier } = meta; // Retrieve the value after all settled - - validateOutput(hookErrIdentifier, resolution); - - if (resolution?.shortCircuit === true) { meta.shortCircuited = true; } - - if (!meta.chainFinished && !meta.shortCircuited) { - throw new ERR_LOADER_CHAIN_INCOMPLETE(hookErrIdentifier); - } - - let resolvedImportAttributes; - const { - format, - url, - } = resolution; - - if (typeof url !== 'string') { - // non-strings can be coerced to a URL string - // validateString() throws a less-specific error - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a URL string', - hookErrIdentifier, - 'url', - url, - ); - } - - // Avoid expensive URL instantiation for known-good URLs - if (!this.#validatedUrls.has(url)) { - // No need to convert to string, since the type is already validated - if (!URLCanParse(url)) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a URL string', - hookErrIdentifier, - 'url', - url, - ); - } - - this.#validatedUrls.add(url); - } - - if (!('importAttributes' in resolution) && ('importAssertions' in resolution)) { - emitImportAssertionWarning(); - resolvedImportAttributes = resolution.importAssertions; - } else { - resolvedImportAttributes = resolution.importAttributes; - } - - if ( - resolvedImportAttributes != null && - typeof resolvedImportAttributes !== 'object' - ) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'an object', - hookErrIdentifier, - 'importAttributes', - resolvedImportAttributes, - ); - } - - if ( - format != null && - typeof format !== 'string' // [2] - ) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a string', - hookErrIdentifier, - 'format', - format, - ); - } - - return { - __proto__: null, - format, - importAttributes: resolvedImportAttributes, - url, - }; - } - - /** - * Provide source that is understood by one of Node's translators. - * - * Internally, this behaves like a backwards iterator, wherein the stack of - * hooks starts at the top and each call to `nextLoad()` moves down 1 step - * until it reaches the bottom or short-circuits. - * @param {URL['href']} url The URL/path of the module to be loaded - * @param {object} context Metadata about the module - * @returns {Promise<{ format: ModuleFormat, source: ModuleSource }>} - */ - async load(url, context = kEmptyObject) { - const chain = this.#chains.load; - const meta = { - chainFinished: null, - context, - hookErrIdentifier: '', - hookName: 'load', - shortCircuited: false, - }; - - const validateArgs = (hookErrIdentifier, nextUrl, ctx) => { - if (typeof nextUrl !== 'string') { - // Non-strings can be coerced to a URL string - // validateString() throws a less-specific error - throw new ERR_INVALID_ARG_TYPE( - `${hookErrIdentifier} url`, - 'a URL string', - nextUrl, - ); - } - - // Avoid expensive URL instantiation for known-good URLs - if (!this.#validatedUrls.has(nextUrl)) { - // No need to convert to string, since the type is already validated - if (!URLCanParse(nextUrl)) { - throw new ERR_INVALID_ARG_VALUE( - `${hookErrIdentifier} url`, - nextUrl, - 'should be a URL string', - ); - } - - this.#validatedUrls.add(nextUrl); - } - - if (ctx) { validateObject(ctx, `${hookErrIdentifier} context`); } - }; - const validateOutput = (hookErrIdentifier, output) => { - if (typeof output !== 'object' || output === null) { // [2] - throw new ERR_INVALID_RETURN_VALUE( - 'an object', - hookErrIdentifier, - output, - ); - } - }; - - const nextLoad = nextHookFactory(chain[chain.length - 1], meta, { validateArgs, validateOutput }); - - const loaded = await nextLoad(url, defineImportAssertionAlias(context)); - const { hookErrIdentifier } = meta; // Retrieve the value after all settled - - validateOutput(hookErrIdentifier, loaded); - - if (loaded?.shortCircuit === true) { meta.shortCircuited = true; } - - if (!meta.chainFinished && !meta.shortCircuited) { - throw new ERR_LOADER_CHAIN_INCOMPLETE(hookErrIdentifier); - } - - const { - format, - source, - } = loaded; - let responseURL = loaded.responseURL; - - if (responseURL === undefined) { - responseURL = url; - } - - let responseURLObj; - if (typeof responseURL === 'string') { - responseURLObj = URLParse(responseURL); - } - - if (responseURLObj?.href !== responseURL) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'undefined or a fully resolved URL string', - hookErrIdentifier, - 'responseURL', - responseURL, - ); - } - - if (format == null) { - require('internal/modules/esm/load').throwUnknownModuleFormat(url, format); - } - - if (typeof format !== 'string') { // [2] - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a string', - hookErrIdentifier, - 'format', - format, - ); - } - - if ( - source != null && - typeof source !== 'string' && - !isAnyArrayBuffer(source) && - !isArrayBufferView(source) - ) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a string, an ArrayBuffer, or a TypedArray', - hookErrIdentifier, - 'source', - source, - ); - } - - return { - __proto__: null, - format, - responseURL, - source, - }; - } - - waitForLoaderHookInitialization() { - // No-op - } -} -ObjectSetPrototypeOf(AsyncLoaderHooksOnLoaderHookWorker.prototype, null); - -/** - * There is only one loader hook thread for each non-loader-hook worker thread - * (i.e. the non-loader-hook thread and any worker threads that are not loader hook workers themselves), - * so there is only 1 MessageChannel. - */ -let MessageChannel; - -/** - * Abstraction over a worker thread that runs the asynchronous module loader hooks. - * Instances of this class run on the non-loader-hook thread and communicate with the loader hooks worker thread. - */ -class AsyncLoaderHookWorker { - /** - * Shared memory. Always use Atomics method to read or write to it. - * @type {Int32Array} - */ - #lock; - /** - * The InternalWorker instance, which lets us communicate with the loader thread. - */ - #worker; - - /** - * The last notification ID received from the worker. This is used to detect - * if the worker has already sent a notification before putting the main - * thread to sleep, to avoid a race condition. - * @type {number} - */ - #workerNotificationLastId = 0; - - /** - * Track how many async responses the main thread should expect. - * @type {number} - */ - #numberOfPendingAsyncResponses = 0; - - #isReady = false; - - constructor() { - const { InternalWorker } = require('internal/worker'); - MessageChannel ??= require('internal/worker/io').MessageChannel; - - const lock = constructSharedArrayBuffer(SHARED_MEMORY_BYTE_LENGTH); - this.#lock = new Int32Array(lock); - - this.#worker = new InternalWorker('internal/modules/esm/worker', { - stderr: false, - stdin: false, - stdout: false, - trackUnmanagedFds: false, - workerData: { - lock, - workerCondition: hasWorkerCondition(), - }, - }); - this.#worker.unref(); // ! Allows the process to eventually exit. - this.#worker.on('exit', process.exit); - } - - waitForWorker() { - if (!this.#isReady) { - const { kIsOnline } = require('internal/worker'); - if (!this.#worker[kIsOnline]) { - debug('wait for signal from worker'); - AtomicsWait(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 0); - const response = this.#worker.receiveMessageSync(); - if (response == null) { return; } - if (response.message.status === 'exit') { - process.exit(response.message.body); - } - - // ! This line catches initialization errors in the worker thread. - this.#unwrapMessage(response); - } - - this.#isReady = true; - } - } - - /** - * Invoke a remote method asynchronously. - * @param {string} method Method to invoke - * @param {any[]} [transferList] Objects in `args` to be transferred - * @param {any[]} args Arguments to pass to `method` - * @returns {Promise} - */ - async makeAsyncRequest(method, transferList, ...args) { - this.waitForWorker(); - - MessageChannel ??= require('internal/worker/io').MessageChannel; - const asyncCommChannel = new MessageChannel(); - - // Pass work to the worker. - debug('post async message to worker', { method, args, transferList }); - const finalTransferList = [asyncCommChannel.port2]; - if (transferList) { - ArrayPrototypePushApply(finalTransferList, transferList); - } - this.#worker.postMessage({ - __proto__: null, - method, args, - port: asyncCommChannel.port2, - }, finalTransferList); - - if (this.#numberOfPendingAsyncResponses++ === 0) { - // On the next lines, the main thread will await a response from the worker thread that might - // come AFTER the last task in the event loop has run its course and there would be nothing - // left keeping the thread alive (and once the main thread dies, the whole process stops). - // However we want to keep the process alive until the worker thread responds (or until the - // event loop of the worker thread is also empty), so we ref the worker until we get all the - // responses back. - this.#worker.ref(); - } - - let response; - do { - debug('wait for async response from worker', { method, args }); - await AtomicsWaitAsync(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, this.#workerNotificationLastId).value; - this.#workerNotificationLastId = AtomicsLoad(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - - response = receiveMessageOnPort(asyncCommChannel.port1); - } while (response == null); - debug('got async response from worker', { method, args }, this.#lock); - - if (--this.#numberOfPendingAsyncResponses === 0) { - // We got all the responses from the worker, its job is done (until next time). - this.#worker.unref(); - } - - const body = this.#unwrapMessage(response); - asyncCommChannel.port1.close(); - return body; - } - - /** - * Invoke a remote method synchronously. - * @param {string} method Method to invoke - * @param {any[]} [transferList] Objects in `args` to be transferred - * @param {any[]} args Arguments to pass to `method` - * @returns {any} - */ - makeSyncRequest(method, transferList, ...args) { - this.waitForWorker(); - - // Pass work to the worker. - debug('post sync message to worker', { method, args, transferList }); - this.#worker.postMessage({ __proto__: null, method, args }, transferList); - - let response; - do { - debug('wait for sync response from worker', { method, args }); - // Sleep until worker responds. - AtomicsWait(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, this.#workerNotificationLastId); - this.#workerNotificationLastId = AtomicsLoad(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - - response = this.#worker.receiveMessageSync(); - debug('got sync message from worker', { method, args, response }); - } while (response == null); - - if (response.message.status === 'never-settle') { - const error = new ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED(); - error.details = { method, args }; - throw error; - } else if (response.message.status === 'exit') { - process.exit(response.message.body); - } - return this.#unwrapMessage(response); - } - - #unwrapMessage(response) { - if (response.message.status === 'never-settle') { - return new Promise(() => {}); - } - const { status, body } = response.message; - if (status === 'error') { - if (body == null || typeof body !== 'object') { throw body; } - if (body.serializationFailed || body.serialized == null) { - throw new ERR_WORKER_UNSERIALIZABLE_ERROR(); - } - - // eslint-disable-next-line no-restricted-syntax - throw deserializeError(body.serialized); - } else { - return body; - } - } -} -ObjectSetPrototypeOf(AsyncLoaderHookWorker.prototype, null); - -// TODO(JakobJingleheimer): Remove this when loaders go "stable". -let globalPreloadWarningWasEmitted = false; - -/** - * A utility function to pluck the hooks from a user-defined loader. - * @param {import('./loader.js').ModuleExports} exports - * @returns {ExportedHooks} - */ -function pluckHooks({ - globalPreload, - initialize, - resolve, - load, -}) { - const acceptedHooks = { __proto__: null }; - - if (resolve) { - acceptedHooks.resolve = resolve; - } - if (load) { - acceptedHooks.load = load; - } - - if (initialize) { - acceptedHooks.initialize = initialize; - } else if (globalPreload && !globalPreloadWarningWasEmitted) { - process.emitWarning( - '`globalPreload` has been removed; use `initialize` instead.', - 'UnsupportedWarning', - ); - globalPreloadWarningWasEmitted = true; - } - - return acceptedHooks; -} - - -/** - * A utility function to iterate through a hook chain, track advancement in the - * chain, and generate and supply the `next` argument to the custom - * hook. - * @param {KeyedHook} current The (currently) first hook in the chain (this shifts - * on every call). - * @param {object} meta Properties that change as the current hook advances - * along the chain. - * @param {boolean} meta.chainFinished Whether the end of the chain has been - * reached AND invoked. - * @param {string} meta.hookErrIdentifier A user-facing identifier to help - * pinpoint where an error occurred. Ex "file:///foo.mjs 'resolve'". - * @param {string} meta.hookName The kind of hook the chain is (ex 'resolve') - * @param {boolean} meta.shortCircuited Whether a hook signaled a short-circuit. - * @param {function(string, unknown): void} validate A wrapper function - * containing all validation of a custom loader hook's intermediary output. Any - * validation within MUST throw. - * @returns {Function} The next hook in the chain. - */ -function nextHookFactory(current, meta, { validateArgs, validateOutput }) { - // First, prepare the current - const { hookName } = meta; - const { - fn: hook, - url: hookFilePath, - next, - } = current; - - // ex 'nextResolve' - const nextHookName = `next${ - StringPrototypeToUpperCase(hookName[0]) + - StringPrototypeSlice(hookName, 1) - }`; - - let nextNextHook; - if (next) { - nextNextHook = nextHookFactory(next, meta, { validateArgs, validateOutput }); - } else { - // eslint-disable-next-line node-core/func-name-matching - nextNextHook = function chainAdvancedTooFar() { - throw new ERR_INTERNAL_ASSERTION( - `ESM custom loader '${hookName}' advanced beyond the end of the chain.`, - ); - }; - } - - return ObjectDefineProperty( - async (arg0 = undefined, context) => { - // Update only when hook is invoked to avoid fingering the wrong filePath - meta.hookErrIdentifier = `${hookFilePath} '${hookName}'`; - - validateArgs(`${meta.hookErrIdentifier} hook's ${nextHookName}()`, arg0, context); - - const outputErrIdentifier = `${hookFilePath} '${hookName}' hook's ${nextHookName}()`; - - // Set when next is actually called, not just generated. - if (!next) { meta.chainFinished = true; } - - if (context) { // `context` has already been validated, so no fancy check needed. - ObjectAssign(meta.context, context); - } - - const output = await hook(arg0, meta.context, nextNextHook); - validateOutput(outputErrIdentifier, output); - - if (output?.shortCircuit === true) { meta.shortCircuited = true; } - - return output; - }, - 'name', - { __proto__: null, value: nextHookName }, - ); -} - -/** - * @type {AsyncLoaderHookWorker} - * Worker instance used to run async loader hooks in a separate thread. This is a singleton for each - * non-loader-hook worker thread (i.e. the main thread and any worker threads that are not - * loader hook workers themselves). - */ -let asyncLoaderHookWorker; -/** - * Get the AsyncLoaderHookWorker instance. If it is not defined, then create a new one. - * @returns {AsyncLoaderHookWorker} - */ -function getAsyncLoaderHookWorker() { - asyncLoaderHookWorker ??= new AsyncLoaderHookWorker(); - return asyncLoaderHookWorker; -} - -/** - * @implements {AsyncLoaderHooks} - * Instances of this class are created in the non-loader-hook thread and communicate with the worker thread - * spawned to run the async loader hooks. - */ -class AsyncLoaderHooksProxiedToLoaderHookWorker { - - isForAsyncLoaderHookWorker = false; - - /** - * Instantiate a module loader that uses user-provided custom loader hooks. - */ - constructor() { - getAsyncLoaderHookWorker(); - } - - /** - * Register some loader specifier. - * @param {string} originalSpecifier The specified URL path of the loader to - * be registered. - * @param {string} parentURL The parent URL from where the loader will be - * registered if using it package name as specifier - * @param {any} [data] Arbitrary data to be passed from the custom loader - * (user-land) to the worker. - * @param {any[]} [transferList] Objects in `data` that are changing ownership - * @param {boolean} [isInternal] For internal loaders that should not be publicly exposed. - * @returns {{ format: string, url: URL['href'] }} - */ - register(originalSpecifier, parentURL, data, transferList, isInternal) { - return asyncLoaderHookWorker.makeSyncRequest('register', transferList, originalSpecifier, parentURL, - data, isInternal); - } - - /** - * Resolve the location of the module. - * @param {string} originalSpecifier The specified URL path of the module to - * be resolved. - * @param {string} [parentURL] The URL path of the module's parent. - * @param {ImportAttributes} importAttributes Attributes from the import - * statement or expression. - * @returns {{ format: string, url: URL['href'] }} - */ - resolve(originalSpecifier, parentURL, importAttributes) { - return asyncLoaderHookWorker.makeAsyncRequest('resolve', undefined, originalSpecifier, parentURL, importAttributes); - } - - resolveSync(originalSpecifier, parentURL, importAttributes) { - // This happens only as a result of `import.meta.resolve` calls, which must be sync per spec. - return asyncLoaderHookWorker.makeSyncRequest('resolve', undefined, originalSpecifier, parentURL, importAttributes); - } - - /** - * Provide source that is understood by one of Node's translators. - * @param {URL['href']} url The URL/path of the module to be loaded - * @param {object} [context] Metadata about the module - * @returns {Promise<{ format: ModuleFormat, source: ModuleSource }>} - */ - load(url, context) { - return asyncLoaderHookWorker.makeAsyncRequest('load', undefined, url, context); - } - loadSync(url, context) { - return asyncLoaderHookWorker.makeSyncRequest('load', undefined, url, context); - } - - waitForLoaderHookInitialization() { - asyncLoaderHookWorker.waitForWorker(); - } -} - -exports.AsyncLoaderHooksProxiedToLoaderHookWorker = AsyncLoaderHooksProxiedToLoaderHookWorker; -exports.AsyncLoaderHooksOnLoaderHookWorker = AsyncLoaderHooksOnLoaderHookWorker; -exports.AsyncLoaderHookWorker = AsyncLoaderHookWorker; diff --git a/lib/internal/modules/esm/load.js b/lib/internal/modules/esm/load.js index 06f60f9f6725..66e7eb6d5ecf 100644 --- a/lib/internal/modules/esm/load.js +++ b/lib/internal/modules/esm/load.js @@ -8,7 +8,7 @@ const { } = require('internal/util'); const { defaultGetFormat } = require('internal/modules/esm/get_format'); -const { validateAttributes, emitImportAssertionWarning } = require('internal/modules/esm/assert'); +const { validateAttributes } = require('internal/modules/esm/assert'); const { loaderMethods } = require('internal/modules/helpers'); const { Buffer: { from: BufferFrom } } = require('buffer'); @@ -51,67 +51,6 @@ function getSourceSync(url, context) { } -/** - * Node.js default load hook. - * @param {string} url - * @param {LoadContext} context - * @returns {LoadReturn} - */ -function defaultLoad(url, context = kEmptyObject) { - let responseURL = url; - let { - importAttributes, - format, - source, - } = context; - - if (importAttributes == null && !('importAttributes' in context) && 'importAssertions' in context) { - emitImportAssertionWarning(); - importAttributes = context.importAssertions; - // Alias `importAssertions` to `importAttributes` - context = { - ...context, - importAttributes, - }; - } - - const urlInstance = new URL(url); - - throwIfUnsupportedURLScheme(urlInstance); - - if (urlInstance.protocol === 'node:') { - source = null; - format ??= 'builtin'; - } else if (format === 'addon') { - // Skip loading addon file content. It must be loaded with dlopen from file system. - source = null; - } else if (format !== 'commonjs') { - if (source == null) { - ({ responseURL, source } = getSourceSync(urlInstance, context)); - context = { __proto__: context, source }; - } - - if (format == null) { - // Now that we have the source for the module, run `defaultGetFormat` to detect its format. - format = defaultGetFormat(urlInstance, context); - - if (format === 'commonjs') { - // For backward compatibility reasons, we need to discard the source in - // order for the CJS loader to re-fetch it. - source = null; - } - } - } - - validateAttributes(url, format, importAttributes); - - return { - __proto__: null, - format, - responseURL, - source, - }; -} /** * @typedef LoadContext * @property {string} [format] A hint (possibly returned from `resolve`) @@ -212,7 +151,6 @@ function throwUnknownModuleFormat(url, format) { module.exports = { - defaultLoad, defaultLoadSync, getSourceSync, throwUnknownModuleFormat, diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index 2e0b0fef8e9d..f8e68e7996cb 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -1,18 +1,9 @@ 'use strict'; const { - ArrayPrototypeJoin, - ArrayPrototypeMap, - ArrayPrototypeReduce, FunctionPrototypeCall, - JSONStringify, ObjectSetPrototypeOf, - Promise, - PromisePrototypeThen, - RegExpPrototypeSymbolReplace, - encodeURIComponent, globalThis, - hardenRegExp, } = primordials; const { LoadCache, ResolveCache } = require('internal/modules/esm/module_map'); @@ -37,17 +28,15 @@ const { ERR_UNKNOWN_MODULE_FORMAT, } = require('internal/errors').codes; const { getOptionValue } = require('internal/options'); -const { isURL, pathToFileURL } = require('internal/url'); +const { pathToFileURL } = require('internal/url'); const { - getDeprecationWarningEmitter, kEmptyObject, } = require('internal/util'); const { compileSourceTextModule, SourceTextModuleTypes: { kUser }, getDefaultConditions, - shouldSpawnLoaderHookWorker, - requestTypes: { kImportInRequiredESM, kRequireInImportedCJS, kImportInImportedESM }, + requestTypes: { kImportInRequiredESM, kImportInImportedESM }, } = require('internal/modules/esm/utils'); /** * @typedef {import('./utils.js').ModuleRequestType} ModuleRequestType @@ -62,7 +51,6 @@ const { kUninstantiated, kErrored, kSourcePhase, - throwIfPromiseRejected, setImportMetaResolveInitializer, } = internalBinding('module_wrap'); const { @@ -83,10 +71,7 @@ let debug = require('internal/util/debuglog').debuglog('esm', (fn) => { debug = fn; }); -const { isPromise } = require('internal/util/types'); - /** - * @typedef {import('./hooks.js').AsyncLoaderHookWorker} AsyncLoaderHookWorker * @typedef {import('./module_job.js').ModuleJobBase} ModuleJobBase * @typedef {import('url').URL} URL */ @@ -123,22 +108,12 @@ const { defaultLoadSync, throwUnknownModuleFormat } = require('internal/modules/ * responseURL?: string, * translatorKey: string, * isResolvedBySyncHooks: boolean, - * isSourceLoadedSynchronously: boolean, * }} TranslateContext */ /** - * @typedef {import('./hooks.js').AsyncLoaderHooks} AsyncLoaderHooks - * @typedef {import('./hooks.js').AsyncLoaderHooksOnLoaderHookWorker} AsyncLoaderHooksOnLoaderHookWorker - * @typedef {import('./hooks.js').AsyncLoaderHooksProxiedToLoaderHookWorker} AsyncLoaderHooksProxiedToLoaderHookWorker - */ - -/** - * This class covers the base machinery of module loading. There are two types of loader hooks: - * 1. Asynchronous loader hooks, which are run in a separate loader hook worker thread. - * This is configured in #asyncLoaderHooks. - * 2. Synchronous loader hooks, which are run in-thread. This is shared with the CJS loader and is - * stored in the cross-module syncResolveHooks and syncLoadHooks arrays. + * This class covers the base machinery of module loading. The `module.registerHooks()` hooks are + * shared with the CJS loader and stored in the cross-module syncResolveHooks and syncLoadHooks arrays. */ class ModuleLoader { /** @@ -156,57 +131,6 @@ class ModuleLoader { */ loadCache = new LoadCache(); - /** - * @see {AsyncLoaderHooks.isForAsyncLoaderHookWorker} - * Shortcut to this.#asyncLoaderHooks.isForAsyncLoaderHookWorker. - */ - isForAsyncLoaderHookWorker = false; - - /** - * Asynchronous loader hooks to pass requests to. - * - * Note that this value _MUST_ be set with `#setAsyncLoaderHooks` - * because it needs to copy `#asyncLoaderHooks.isForAsyncLoaderHookWorker` - * to this property. - * TODO(joyeecheung): this was a legacy of the previous setup of import.meta.resolve - * configuration; put this information in the environment directly instead. - * - * When the ModuleLoader is created on a loader hook thread, this is - * {@link AsyncLoaderHooksOnLoaderHookWorker}, and its methods directly call out - * to loader methods. Otherwise, this is {@link AsyncLoaderHooksProxiedToLoaderHookWorker}, - * and its methods post messages to the loader thread and possibly block on it. - * @see {ModuleLoader.#setAsyncLoaderHooks} - * @type {AsyncLoaderHooks} - */ - #asyncLoaderHooks; - - constructor(asyncLoaderHooks) { - this.#setAsyncLoaderHooks(asyncLoaderHooks); - } - - /** - * Change the currently activate async loader hooks for this module - * loader to be the provided `AsyncLoaderHooks`. - * - * If present, this class customizes its core functionality to the - * `AsyncLoaderHooks` object, including registration, loading, and resolving. - * There are some responsibilities that this class _always_ takes - * care of, like validating outputs, so that the AsyncLoaderHooks object - * does not have to do so. - * - * Calling this function alters how modules are loaded and should be - * invoked with care. - * @param {AsyncLoaderHooks} asyncLoaderHooks - */ - #setAsyncLoaderHooks(asyncLoaderHooks) { - this.#asyncLoaderHooks = asyncLoaderHooks; - if (asyncLoaderHooks) { - this.isForAsyncLoaderHookWorker = asyncLoaderHooks.isForAsyncLoaderHookWorker; - } else { - this.isForAsyncLoaderHookWorker = false; - } - } - /** * * @param {string} source Source code of the module. @@ -290,10 +214,6 @@ class ModuleLoader { if (job !== undefined) { mod[kRequiredModuleSymbol] = job.module; const parentFilename = urlToFilename(parent?.filename); - // This race should only be possible on the loader hook thread. See https://github.com/nodejs/node/issues/59666 - if (!job.module) { - throw new ERR_REQUIRE_ESM_RACE_CONDITION(filename, parentFilename, this.isForAsyncLoaderHookWorker); - } const status = job.module.getStatus(); debug('Module status', job, status); // hasAsyncGraph is available after module been instantiated. @@ -303,13 +223,10 @@ class ModuleLoader { if (status === kEvaluated) { return { wrap: job.module, namespace: job.module.getNamespace() }; } else if (status === kInstantiated) { - // When it's an async job cached by another import request, - // which has finished linking but has not started its - // evaluation because the async run() task would be later - // in line. Then start the evaluation now with runSync(), which - // is guaranteed to finish by the time the other run() get to it, - // and the other task would just get the cached evaluation results, - // similar to what would happen when both are async. + // The job was created by an earlier import() that has finished linking but has + // not started its evaluation, which is deferred to a later microtask. Evaluate + // it now with runSync(); the pending run() will then just find it already + // evaluated, similar to what would happen when both are async. mod[kRequiredModuleSymbol] = job.module; const { namespace } = job.runSync(parent); return { wrap: job.module, namespace: namespace || job.module.getNamespace() }; @@ -317,21 +234,14 @@ class ModuleLoader { // If the module was previously imported and errored, throw the error. throw job.module.getError(); } - // When the cached async job have already encountered a linking - // error that gets wrapped into a rejection, but is still later - // in line to throw on it, just unwrap and throw the linking error - // from require(). - if (job.instantiated) { - throwIfPromiseRejected(job.instantiated); - } if (status !== kEvaluating) { assert(status === kUninstantiated, `Unexpected module status ${status}`); - // If we get here, either there's a race where the job is still being instantiated - // by an in-flight import(), or the cached module previously encountered an + // If we get here, either the job was created by an in-flight import() that has not + // instantiated it yet, or the cached module previously encountered an // instantiation error during a prior load (e.g. due to a mismatched import). // TODO(joyeecheung): the current check is too broad. We should attempt to // get the potential instantiation error and throw it. - throw new ERR_REQUIRE_ESM_RACE_CONDITION(filename, parentFilename, false); + throw new ERR_REQUIRE_ESM_RACE_CONDITION(filename, parentFilename); } let message = `Cannot require() ES Module ${filename} in a cycle.`; if (parentFilename) { @@ -397,10 +307,6 @@ class ModuleLoader { * @param {ModuleJobBase} job The cached module job. */ #checkCachedJobForRequireESM(specifier, url, parentURL, job) { - // This race should only be possible on the loader hook thread. See https://github.com/nodejs/node/issues/59666 - if (!job.module) { - throw new ERR_REQUIRE_ESM_RACE_CONDITION(url, parentURL, this.isForAsyncLoaderHookWorker); - } // This module is being evaluated, which means it's imported in a previous link // in a cycle. if (job.module.getStatus() === kEvaluating) { @@ -422,7 +328,7 @@ class ModuleLoader { * Load a module and translate it into a ModuleWrap for require(esm). * This is run synchronously, and the translator always return a ModuleWrap synchronously. * @param {ResolveResult} resolveResult Result from the resolve step. - * @param {object} loadContext See {@link load} + * @param {{ format: string, importAttributes: object }} loadContext Context for the load step. * @param {string|undefined} parentURL URL of the parent module. Undefined if it's the entry point. * @param {ModuleRequest} request Module request. * @returns {ModuleWrap} @@ -460,8 +366,7 @@ class ModuleLoader { } /** - * Translate a loaded module source into a ModuleWrap. This is run synchronously, - * but the translator may return the ModuleWrap in a Promise. + * Translate a loaded module source into a ModuleWrap synchronously. * @param {string} url URL of the module to be translated. * @param {TranslateContext} translateContext Context for the translator * @param {string|undefined} parentURL URL of the module initiating the module loading for the first time. @@ -479,98 +384,47 @@ class ModuleLoader { const result = FunctionPrototypeCall(translator, this, url, translateContext, parentURL); assert(result instanceof ModuleWrap, `The ${format} module returned is not a ModuleWrap`); - if (format === 'commonjs' || format === 'commonjs-sync' || format === 'require-commonjs') { + if (format === 'commonjs' || format === 'commonjs-sync') { result.isCommonJS = true; } return result; } /** - * Load a module and translate it into a ModuleWrap for require() in imported CJS. - * This is run synchronously, and the translator always return a ModuleWrap synchronously. + * Load a module and translate it into a ModuleWrap for ordinary imported ESM. + * Loading and translation are synchronous; evaluation may be asynchronous. * @param {ResolveResult} resolveResult Result from the resolve step. - * @param {object} loadContext See {@link load} + * @param {{ format: string, importAttributes: object }} loadContext Context for the load step. * @param {string|undefined} parentURL URL of the parent module. Undefined if it's the entry point. * @returns {ModuleWrap} */ - loadAndTranslateForRequireInImportedCJS(resolveResult, loadContext, parentURL) { + loadAndTranslate(resolveResult, loadContext, parentURL) { const { url } = resolveResult; const loadResult = this.#loadSync(url, loadContext); - const formatFromLoad = loadResult.format; - - if (formatFromLoad === 'wasm') { // require(wasm) is not supported. - throw new ERR_UNKNOWN_MODULE_FORMAT(formatFromLoad, url); - } - - if (formatFromLoad === 'module' || formatFromLoad === 'module-typescript') { - if (!getOptionValue('--require-module')) { - throw new ERR_REQUIRE_ESM(url, true); - } - } - - let translatorKey = formatFromLoad; - if (formatFromLoad === 'commonjs') { - translatorKey = 'require-commonjs'; - } - if (formatFromLoad === 'commonjs-typescript') { - translatorKey = 'require-commonjs-typescript'; - } - const translateContext = { ...resolveResult, ...loadResult, - translatorKey, + translatorKey: loadResult.format, __proto__: null, }; - const wrap = this.#translate(url, translateContext, parentURL); - assert(wrap instanceof ModuleWrap, `Translator used for require(${url}) should not be async`); - return wrap; - } - - /** - * Load a module and translate it into a ModuleWrap for ordinary imported ESM. - * This may be run asynchronously if there are asynchronous module loader hooks registered. - * @param {ResolveResult} resolveResult Result from the resolve step. - * @param {object} loadContext See {@link load} - * @param {string|undefined} parentURL URL of the parent module. Undefined if it's the entry point. - * @returns {Promise|ModuleWrap} - */ - loadAndTranslate(resolveResult, loadContext, parentURL) { - const { url } = resolveResult; - const maybePromise = this.load(url, loadContext); - const afterLoad = (loadResult) => { - const translateContext = { - ...resolveResult, - ...loadResult, - translatorKey: loadResult.format, - __proto__: null, - }; - return this.#translate(url, translateContext, parentURL); - }; - if (isPromise(maybePromise)) { - return PromisePrototypeThen(maybePromise, afterLoad); - } - return afterLoad(maybePromise); + return this.#translate(url, translateContext, parentURL); } /** * Given a resolved module request, obtain a ModuleJobBase from it - if it's already cached, * return the cached ModuleJobBase. Otherwise, load its source and translate it into a ModuleWrap first. - * This runs synchronously. On any thread that is not an async loader hook worker thread, - * the module should be linked by the time this returns. Otherwise it may still have - * pending module requests. + * This runs synchronously, so the module should be linked by the time this returns. * @param {string} parentURL See {@link getOrCreateModuleJob} * @param {ResolveResult} resolveResult * @param {ModuleRequest} request Module request. * @param {ModuleRequestType} requestType Type of the module request. - * @returns {ModuleJobBase} The (possibly pending) module job + * @returns {ModuleJobBase} The module job */ #getOrCreateModuleJobAfterResolve(parentURL, resolveResult, request, requestType) { const { url, format } = resolveResult; if (process.env.WATCH_REPORT_DEPENDENCIES && process.send) { - const type = requestType === kRequireInImportedCJS ? 'require' : 'import'; - process.send({ [`watch:${type}`]: [url] }); + process.send({ 'watch:import': [url] }); } // Relay Events from worker to main thread if (process.env.WATCH_REPORT_DEPENDENCIES && !process.send) { @@ -597,34 +451,19 @@ class ModuleLoader { const context = { format, importAttributes, __proto__: null }; - let moduleOrModulePromise; - if (requestType === kRequireInImportedCJS) { - moduleOrModulePromise = this.loadAndTranslateForRequireInImportedCJS(resolveResult, context, parentURL); - } else if (requestType === kImportInRequiredESM) { - moduleOrModulePromise = this.loadAndTranslateForImportInRequiredESM(resolveResult, context, parentURL, request); - } else { - moduleOrModulePromise = this.loadAndTranslate(resolveResult, context, parentURL); - } + const module = requestType === kImportInRequiredESM ? + this.loadAndTranslateForImportInRequiredESM(resolveResult, context, parentURL, request) : + this.loadAndTranslate(resolveResult, context, parentURL); - if (requestType === kImportInRequiredESM || requestType === kRequireInImportedCJS || - !this.isForAsyncLoaderHookWorker) { - assert(moduleOrModulePromise instanceof ModuleWrap, `Expected ModuleWrap for loading ${url}`); - } + assert(module instanceof ModuleWrap, `Expected ModuleWrap for loading ${url}`); const isMain = (parentURL === undefined); const inspectBrk = (isMain && getOptionValue('--inspect-brk')); - // Use ModuleJobSync for kImportInRequiredESM, which must always be linked synchronously, - // and whenever we're on the main thread (not the async loader hook worker), - // except for kRequireInImportedCJS (TODO: consolidate that case too). - // TODO(joyeecheung): use ModuleJobSync for kRequireInImportedCJS too. - const ModuleJobCtor = (requestType === kImportInRequiredESM || - (!this.isForAsyncLoaderHookWorker && requestType !== kRequireInImportedCJS)) ? - ModuleJobSync : ModuleJob; - job = new ModuleJobCtor( + job = new ModuleJobSync( this, url, importAttributes, - moduleOrModulePromise, + module, request.phase, isMain, inspectBrk, @@ -637,35 +476,16 @@ class ModuleLoader { } /** - * Get a (possibly not yet fully linked) module job from the cache, or create one and return its Promise. + * Get a module job from the cache, or create one. Loading and linking are synchronous. * @param {string} [parentURL] The URL of the module where the module request is initiated. * It's undefined if it's from the root module. * @param {ModuleRequest} request Module request. * @param {ModuleRequestType} requestType Type of the module request. - * @returns {Promise|ModuleJobBase} + * @returns {ModuleJobBase} */ getOrCreateModuleJob(parentURL, request, requestType) { - let maybePromise; - if (!this.isForAsyncLoaderHookWorker || - requestType === kRequireInImportedCJS || requestType === kImportInRequiredESM) { - // On the main thread, always resolve synchronously; - // `resolveSync` coordinates with the async loader hook worker if needed. - // On the async loader hook worker, require(esm) and require() in imported CJS - // must still be resolved synchronously. - maybePromise = this.resolveSync(parentURL, request); - assert(!isPromise(maybePromise)); - } else { - maybePromise = this.#resolve(parentURL, request); - } - - const afterResolve = (resolveResult) => { - return this.#getOrCreateModuleJobAfterResolve(parentURL, resolveResult, request, requestType); - }; - - if (isPromise(maybePromise)) { - return PromisePrototypeThen(maybePromise, afterResolve); - } - return afterResolve(maybePromise); + const resolveResult = this.resolveSync(parentURL, request); + return this.#getOrCreateModuleJobAfterResolve(parentURL, resolveResult, request, requestType); } /** @@ -682,15 +502,10 @@ class ModuleLoader { async import(specifier, parentURL, importAttributes, phase = kEvaluationPhase, isEntryPoint = false) { return onImport.tracePromise(async () => { const request = { specifier, phase, attributes: importAttributes, __proto__: null }; - let moduleJob; - try { - moduleJob = await this.getOrCreateModuleJob(parentURL, request); - } catch (e) { - if (e?.code === 'ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED') { - return new Promise(() => {}); - } - throw e; - } + const moduleJob = this.getOrCreateModuleJob(parentURL, request); + // Loading and linking are synchronous, but import() must still never evaluate the + // module before returning to its caller, so yield once before running the job. + await null; if (phase === kSourcePhase) { const module = await moduleJob.modulePromise; return module.getModuleSourceObject(); @@ -704,44 +519,10 @@ class ModuleLoader { }); } - /** - * @see {@link AsyncLoaderHooks.register} - * @returns {any} - */ - register(specifier, parentURL, data, transferList, isInternal) { - if (!this.#asyncLoaderHooks) { - // On the loader hook worker thread, the #asyncLoaderHooks must already have been initialized - // to be an instance of AsyncLoaderHooksOnLoaderHookWorker, so this branch can only ever - // be hit on a non-loader-hook thread that will talk to the loader hook worker thread. - const { AsyncLoaderHooksProxiedToLoaderHookWorker } = require('internal/modules/esm/hooks'); - this.#setAsyncLoaderHooks(new AsyncLoaderHooksProxiedToLoaderHookWorker()); - } - return this.#asyncLoaderHooks.register(`${specifier}`, `${parentURL}`, data, transferList, isInternal); - } - - /** - * Resolve a module request to a URL identifying the location of the module. Handles customization hooks, - * if any. - * @param {string} [parentURL] The URL of the module where the module request is initiated. - * It's undefined if it's from the root module. - * @param {ModuleRequest} request Module request. - * @returns {Promise|ResolveResult} - */ - #resolve(parentURL, request) { - if (this.isForAsyncLoaderHookWorker) { - const specifier = `${request.specifier}`; - const importAttributes = request.attributes ?? kEmptyObject; - // TODO(joyeecheung): invoke the synchronous hooks in the default step on loader thread. - return this.#asyncLoaderHooks.resolve(specifier, parentURL, importAttributes); - } - - return this.resolveSync(parentURL, request); - } - /** * Either return a cached resolution, or perform the default resolution which is synchronous, and * cache the result. - * @param {string} specifier See {@link resolve}. + * @param {string} specifier The module specifier. * @param {{ parentURL?: string, importAttributes: ImportAttributes, conditions?: string[]}} context * @returns {{ format: string, url: string }} */ @@ -759,37 +540,28 @@ class ModuleLoader { } /** - * This is the default resolve step for module.registerHooks(), which incorporates asynchronous hooks - * from module.register() which are run in a blocking fashion for it to be synchronous. + * This is the default resolve step for module.registerHooks(). * @param {{isResolvedByDefaultResolve: boolean}} out Output object to track whether the default resolve was used * without polluting the user-visible resolve result. - * @param {string|URL} specifier See {@link resolveSync}. + * @param {string|URL} specifier The module specifier. * @param {{ parentURL?: string, importAttributes: ImportAttributes, conditions?: string[]}} context - * See {@link resolveSync}. + * Resolution context. * @returns {{ format: string, url: string }} */ - #resolveAndMaybeBlockOnLoaderThread(out, specifier, context) { - if (this.#asyncLoaderHooks?.resolveSync) { - return this.#asyncLoaderHooks.resolveSync(specifier, context.parentURL, context.importAttributes); - } + #defaultResolve(out, specifier, context) { out.isResolvedByDefaultResolve = true; return this.#cachedDefaultResolve(specifier, context); } /** - * Similar to {@link resolve}, but the results are always synchronously returned. If there are any - * asynchronous resolve hooks from module.register(), it will block until the results are returned - * from the loader thread for this to be synchronous. - * This is here to support `import.meta.resolve()`, `require()` in imported CJS, and - * `module.registerHooks()` hooks. - * @param {string} [parentURL] See {@link resolve}. - * @param {ModuleRequest} request See {@link resolve}. - * @param {boolean} [shouldSkipSyncHooks] Whether to skip the synchronous hooks registered by module.registerHooks(). - * This is used to maintain compatibility for the re-invented require.resolve (in imported CJS customized - * by module.register()`) which invokes the CJS resolution separately from the hook chain. + * Resolve a module request to a URL identifying the location of the module. Handles + * `module.registerHooks()` hooks, if any. + * @param {string} [parentURL] The URL of the module where the module request is initiated. + * It's undefined if it's from the root module. + * @param {ModuleRequest} request Module request. * @returns {ResolveResult} */ - resolveSync(parentURL, request, shouldSkipSyncHooks = false) { + resolveSync(parentURL, request) { const specifier = `${request.specifier}`; const importAttributes = request.attributes ?? kEmptyObject; // Use an output parameter to track the state and avoid polluting the user-visible resolve results. @@ -797,10 +569,10 @@ class ModuleLoader { let result; let isResolvedBySyncHooks = false; - if (!shouldSkipSyncHooks && syncResolveHooks.length) { - // Has module.registerHooks() hooks, chain the asynchronous hooks in the default step. + if (syncResolveHooks.length) { + // Has module.registerHooks() hooks, chain the default resolver in the default step. result = resolveWithSyncHooks(specifier, parentURL, importAttributes, this.#defaultConditions, - this.#resolveAndMaybeBlockOnLoaderThread.bind(this, out)); + this.#defaultResolve.bind(this, out)); // If the default step ran, sync hooks did not short-circuit the resolution. isResolvedBySyncHooks = !out.isResolvedByDefaultResolve; } else { @@ -811,85 +583,34 @@ class ModuleLoader { importAttributes, __proto__: null, }; - result = this.#resolveAndMaybeBlockOnLoaderThread(out, specifier, context); + result = this.#defaultResolve(out, specifier, context); } result.isResolvedBySyncHooks = isResolvedBySyncHooks; return result; } /** - * Provide source that is understood by one of Node's translators. Handles customization hooks, - * if any. - * @typedef {{ - * format: ModuleFormat, - * source: ModuleSource, - * responseURL?: string, - * isSourceLoadedSynchronously: boolean, - * }} LoadResult + * Provide source that is understood by one of Node's translators. Handles + * `module.registerHooks()` hooks, if any. * @param {string} url The URL of the module to be loaded. - * @param {object} context Metadata about the module - * @returns {Promise | LoadResult}} - */ - load(url, context) { - if (this.isForAsyncLoaderHookWorker) { - // TODO(joyeecheung): invoke the synchronous hooks in the default step on loader thread. - return this.#asyncLoaderHooks.load(url, context); - } - return this.#loadSync(url, context); - } - - /** - * This is the default load step for module.registerHooks(), which incorporates asynchronous hooks - * from module.register() which are run in a blocking fashion for it to be synchronous. - * @param {{isSourceLoadedSynchronously: boolean}} out - * Output object to track whether the source was loaded synchronously without polluting - * the user-visible load result. - * @param {string} url See {@link load} - * @param {object} context See {@link load} - * @returns {{ format: ModuleFormat, source: ModuleSource }} - */ - #loadAndMaybeBlockOnLoaderThread(out, url, context) { - if (this.#asyncLoaderHooks?.loadSync) { - out.isSourceLoadedSynchronously = false; - return this.#asyncLoaderHooks.loadSync(url, context); - } - out.isSourceLoadedSynchronously = true; - return defaultLoadSync(url, context); - } - - /** - * Similar to {@link load} but this is always run synchronously. If there are asynchronous hooks - * from module.register(), this blocks on the loader thread for it to return synchronously. - * - * This is here to support `require()` in imported CJS and `module.registerHooks()` hooks. - * @param {string} url See {@link load} - * @param {object} [context] See {@link load} - * @returns {LoadResult} + * @param {{ format: string, importAttributes: object }} context Metadata about the module + * @returns {{ format: ModuleFormat, source: ModuleSource, responseURL?: string }} */ #loadSync(url, context) { - // Use an output parameter to track the state and avoid polluting the user-visible resolve results. - const out = { - isSourceLoadedSynchronously: true, - __proto__: null, - }; - let result; if (syncLoadHooks.length) { - // Has module.registerHooks() hooks, chain the asynchronous hooks in the default step. + // Has module.registerHooks() hooks, chain the default loader in the default step. // TODO(joyeecheung): construct the ModuleLoadContext in the loaders directly instead // of converting them from plain objects in the hooks. - result = loadWithSyncHooks( + return loadWithSyncHooks( url, context.format, context.importAttributes, this.#defaultConditions, - this.#loadAndMaybeBlockOnLoaderThread.bind(this, out), + defaultLoadSync, validateLoadSloppy, ); - } else { - result = this.#loadAndMaybeBlockOnLoaderThread(out, url, context); } - result.isSourceLoadedSynchronously = out.isSourceLoadedSynchronously; - return result; + return defaultLoadSync(url, context); } validateLoadResult(url, format) { @@ -897,60 +618,9 @@ class ModuleLoader { throwUnknownModuleFormat(url, format); } } - - /** - * Block until the async loader hooks have been initialized. - * - * No-op when no hooks have been supplied. - */ - waitForAsyncLoaderHookInitialization() { - this.#asyncLoaderHooks?.waitForLoaderHookInitialization(); - } } ObjectSetPrototypeOf(ModuleLoader.prototype, null); -let emittedLoaderFlagWarning = false; -/** - * A loader instance is used as the main entry point for loading ES modules. Currently, this is a singleton; there is - * only one used for loading the main module and everything in its dependency graph, though separate instances of this - * class might be instantiated as part of bootstrap for other purposes. - * @param {AsyncLoaderHooksOnLoaderHookWorker|undefined} [asyncLoaderHooks] - * Only provided when run on the loader hook thread. - * @returns {ModuleLoader} - */ -function createModuleLoader(asyncLoaderHooks) { - // Don't spawn a new loader hook worker if we are already in a loader hook worker to avoid infinite recursion. - if (shouldSpawnLoaderHookWorker()) { - assert(asyncLoaderHooks === undefined, 'asyncLoaderHooks should only be provided on the loader hook thread itself'); - const userLoaderPaths = getOptionValue('--experimental-loader'); - if (userLoaderPaths.length > 0) { - if (!emittedLoaderFlagWarning) { - const readableURIEncode = (string) => ArrayPrototypeReduce( - [ - [/'/g, '%27'], // We need to URL-encode the single quote as it's the delimiter for the --import flag. - [/%22/g, '"'], // We can decode the double quotes to improve readability. - [/%2F/ig, '/'], // We can decode the slashes to improve readability. - ], - (str, { 0: regex, 1: replacement }) => RegExpPrototypeSymbolReplace(hardenRegExp(regex), str, replacement), - encodeURIComponent(string)); - process.emitWarning( - '`--experimental-loader` may be removed in the future; instead use `register()`:\n' + - `--import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; ${ArrayPrototypeJoin( - ArrayPrototypeMap(userLoaderPaths, (loader) => `register(${readableURIEncode(JSONStringify(loader))}, pathToFileURL("./"))`), - '; ', - )};'`, - 'ExperimentalWarning', - ); - emittedLoaderFlagWarning = true; - } - const { AsyncLoaderHooksProxiedToLoaderHookWorker } = require('internal/modules/esm/hooks'); - asyncLoaderHooks = new AsyncLoaderHooksProxiedToLoaderHookWorker(); - } - } - - return new ModuleLoader(asyncLoaderHooks); -} - let allowImportMetaResolveParentURL; /** * This is only called from the native ImportMetaObjectInitialize function to set up import.meta.resolve @@ -1000,20 +670,12 @@ let cascadedLoader; * require('internal/module/esm/loader').getOrInitializeCascadedLoader() * lazily only right before the loader is actually needed, and don't do it * in the top-level, to avoid circular dependencies. - * @param {AsyncLoaderHooksOnLoaderHookWorker|undefined} [asyncLoaderHooks] - * Only provided when run on the loader hook thread. * @returns {ModuleLoader} */ -function getOrInitializeCascadedLoader(asyncLoaderHooks) { +function getOrInitializeCascadedLoader() { if (!cascadedLoader) { - cascadedLoader = createModuleLoader(asyncLoaderHooks); - // import.meta.resolve is not allowed in the async loader hook worker thread. - // So only set up the import.meta.resolve initializer when we are initializing - // the non-loader-hook-thread cascaded loader. When the native land doesn't see it, - // it knows the loader is running on the loader hook thread. - if (!(asyncLoaderHooks?.isForAsyncLoaderHookWorker)) { - setImportMetaResolveInitializer(createImportMetaResolve.bind(null, cascadedLoader)); - } + cascadedLoader = new ModuleLoader(); + setImportMetaResolveInitializer(createImportMetaResolve.bind(null, cascadedLoader)); } return cascadedLoader; } @@ -1022,60 +684,8 @@ function isCascadedLoaderInitialized() { return cascadedLoader !== undefined; } -/** - * Register a single loader programmatically. - * @param {string|URL} specifier - * @param {string|URL} [parentURL] Base to use when resolving `specifier`; optional if - * `specifier` is absolute. Same as `options.parentUrl`, just inline - * @param {object} [options] Additional options to apply, described below. - * @param {string|URL} [options.parentURL] Base to use when resolving `specifier` - * @param {any} [options.data] Arbitrary data passed to the loader's `initialize` hook - * @param {any[]} [options.transferList] Objects in `data` that are changing ownership - * @returns {void} We want to reserve the return value for potential future extension of the API. - * @example - * ```js - * register('./myLoader.js'); - * register('ts-node/esm', { parentURL: import.meta.url }); - * register('./myLoader.js', { parentURL: import.meta.url }); - * register('ts-node/esm', import.meta.url); - * register('./myLoader.js', import.meta.url); - * register(new URL('./myLoader.js', import.meta.url)); - * register('./myLoader.js', { - * parentURL: import.meta.url, - * data: { banana: 'tasty' }, - * }); - * register('./myLoader.js', { - * parentURL: import.meta.url, - * data: someArrayBuffer, - * transferList: [someArrayBuffer], - * }); - * ``` - */ -const emitRegisterDeprecation = getDeprecationWarningEmitter( - 'DEP0205', - '`module.register()` is deprecated. Use `module.registerHooks()` instead.', - undefined, - false, -); - -function register(specifier, parentURL = undefined, options) { - emitRegisterDeprecation(); - - if (parentURL != null && typeof parentURL === 'object' && !isURL(parentURL)) { - options = parentURL; - parentURL = options.parentURL; - } - getOrInitializeCascadedLoader().register( - specifier, - parentURL ?? 'data:', - options?.data, - options?.transferList, - ); -} - module.exports = { - createModuleLoader, + ModuleLoader, getOrInitializeCascadedLoader, isCascadedLoaderInitialized, - register, }; diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js index c8506b42ff3f..ba300785c9eb 100644 --- a/lib/internal/modules/esm/module_job.js +++ b/lib/internal/modules/esm/module_job.js @@ -11,12 +11,10 @@ const { FunctionPrototype, ObjectAssign, ObjectSetPrototypeOf, - PromisePrototypeThen, PromiseResolve, RegExpPrototypeExec, RegExpPrototypeSymbolReplace, RegExpPrototypeSymbolSplit, - SafePromiseAllReturnArrayLike, SafePromiseAllReturnVoid, SafeSet, StringPrototypeIncludes, @@ -31,15 +29,11 @@ let debug = require('internal/util/debuglog').debuglog('esm', (fn) => { const { ModuleWrap, kErrored, - kEvaluated, - kEvaluating, kDeferPhase, kEvaluationPhase, kInstantiated, - kUninstantiated, } = internalBinding('module_wrap'); const { - getPromiseDetails, privateSymbols: { entry_point_module_private_symbol, module_source_private_symbol: kModuleSource, @@ -49,7 +43,6 @@ const { * @typedef {import('./utils.js').ModuleRequestType} ModuleRequestType */ const { decorateErrorStack } = require('internal/util'); -const { isPromise } = require('internal/util/types'); const { getSourceMapsSupport, } = require('internal/source_map/source_map_cache'); @@ -63,7 +56,6 @@ const { getOptionValue } = require('internal/options'); const noop = FunctionPrototype; const { ERR_REQUIRE_ASYNC_MODULE, - ERR_REQUIRE_ESM_RACE_CONDITION, } = require('internal/errors').codes; const CJSGlobalLike = [ @@ -193,14 +185,7 @@ function findModulesWithTopLevelAwait(root) { if (job.module?.hasTopLevelAwait) { ArrayPrototypePush(found, job.module); } - let linked = job.linked; - if (isPromise(linked)) { - linked = getPromiseDetails(linked)?.[1]; - } - // If `require(esm)` comes from the deprecated async loader hook worker thread, - // linked may be pending at this point. In that case, this branch would be skipped - - // we just allow lossy reporting of TLA locations in an edge case when a deprecated - // feature is used in combination with another experimental flag. + const { linked } = job; if (ArrayIsArray(linked)) { for (let i = 0; i < linked.length; i++) { ArrayPrototypePush(stack, linked[i]); @@ -309,7 +294,7 @@ class ModuleJobBase { * @param {ModuleRequestType} requestType Type of the module request. * @returns {ModuleJobBase[]} */ - syncLink(requestType) { + link(requestType) { // Store itself into the cache first before linking in case there are circular // references in the linking. Track whether we're overwriting an existing entry // so we know whether to remove the temporary entry in the finally block. @@ -323,11 +308,8 @@ class ModuleJobBase { try { for (let idx = 0; idx < moduleRequests.length; idx++) { const request = moduleRequests[idx]; - // TODO(joyeecheung): split this into two iterators, one for resolving and one for loading so - // that hooks can pre-fetch sources off-thread. const job = this.loader.getOrCreateModuleJob(this.url, request, requestType); - debug(`ModuleJobBase.syncLink() ${this.url} -> ${request.specifier}`, job); - assert(!isPromise(job)); + debug(`ModuleJobBase.link() ${this.url} -> ${request.specifier}`, job); assert(job.module instanceof ModuleWrap); if (this.shouldRunModule(request.phase)) { ArrayPrototypePush(evaluationDepJobs, job); @@ -374,9 +356,6 @@ class ModuleJobBase { if (this.phase < phase) { this.phase = phase; this.linked = this.link(requestType); - if (isPromise(this.linked)) { - PromisePrototypeThen(this.linked, undefined, noop); - } } } @@ -395,33 +374,23 @@ class ModuleJob extends ModuleJobBase { * @param {ModuleLoader} loader The ESM loader. * @param {string} url URL of the module to be wrapped in ModuleJob. * @param {ImportAttributes} importAttributes Import attributes from the import statement. - * @param {ModuleWrap|Promise} moduleOrModulePromise Translated ModuleWrap for the module. + * @param {ModuleWrap} module Translated ModuleWrap for the module. * @param {number} phase The phase to load the module to. * @param {boolean} isMain Whether the module is the entry point. * @param {boolean} inspectBrk Whether this module should be evaluated with the * first line paused in the debugger (because --inspect-brk is passed). * @param {ModuleRequestType} requestType Type of the module request. */ - constructor(loader, url, importAttributes = { __proto__: null }, moduleOrModulePromise, + constructor(loader, url, importAttributes = { __proto__: null }, module, phase = kEvaluationPhase, isMain, inspectBrk, requestType) { super(loader, url, importAttributes, phase, isMain, inspectBrk); - // Expose the promise to the ModuleWrap directly for linking below. - if (isPromise(moduleOrModulePromise)) { - this.modulePromise = moduleOrModulePromise; - } else { - this.module = moduleOrModulePromise; - this.modulePromise = PromiseResolve(moduleOrModulePromise); - } + this.module = module; + this.modulePromise = PromiseResolve(module); if (this.shouldLinkModule(this.phase)) { - // Promise for the list of all dependencyJobs. + // The list of all dependencyJobs. this.linked = this.link(requestType); - // This promise is awaited later anyway, so silence - // 'unhandled rejection' warnings. - if (isPromise(this.linked)) { - PromisePrototypeThen(this.linked, undefined, noop); - } } // instantiated == deep dependency jobs wrappers are instantiated, @@ -429,59 +398,6 @@ class ModuleJob extends ModuleJobBase { this.instantiated = undefined; } - /** - * @param {ModuleRequestType} requestType Type of the module request. - * @returns {ModuleJobBase[]|Promise} - */ - link(requestType) { - if (this.loader.isForAsyncLoaderHookWorker) { - return this.#asyncLink(requestType); - } - return this.syncLink(requestType); - } - - /** - * @param {ModuleRequestType} requestType Type of the module request. - * @returns {Promise} - */ - async #asyncLink(requestType) { - assert(this.loader.isForAsyncLoaderHookWorker); - this.module = await this.modulePromise; - assert(this.module instanceof ModuleWrap); - const moduleRequests = this.module.getModuleRequests(); - // Create an ArrayLike to avoid calling into userspace with `.then` - // when returned from the async function. - // Modules should be aligned with the moduleRequests array in order. - const modulePromises = Array(moduleRequests.length); - const evaluationDepJobs = []; - this.commonJsDeps = Array(moduleRequests.length); - for (let idx = 0; idx < moduleRequests.length; idx++) { - const request = moduleRequests[idx]; - // Explicitly keeping track of dependency jobs is needed in order - // to flatten out the dependency graph below in `asyncInstantiate()`, - // so that circular dependencies can't cause a deadlock by two of - // these `link` callbacks depending on each other. - // TODO(joyeecheung): split this into two iterators, one for resolving and one for loading so - // that hooks can pre-fetch sources off-thread. - const dependencyJobPromise = this.loader.getOrCreateModuleJob(this.url, request, requestType); - const modulePromise = PromisePrototypeThen(dependencyJobPromise, (job) => { - debug(`ModuleJob.asyncLink() ${this.url} -> ${request.specifier}`, job); - if (this.shouldRunModule(request.phase)) { - ArrayPrototypePush(evaluationDepJobs, job); - } - return job.modulePromise; - }); - modulePromises[idx] = modulePromise; - } - const modules = await SafePromiseAllReturnArrayLike(modulePromises); - for (let idx = 0; idx < moduleRequests.length; idx++) { - this.commonJsDeps[idx] = modules[idx].isCommonJS; - } - - this.module.link(modules); - return evaluationDepJobs; - } - #instantiate() { if (this.instantiated === undefined) { this.instantiated = this.#asyncInstantiate(); @@ -491,8 +407,6 @@ class ModuleJob extends ModuleJobBase { async #asyncInstantiate() { const jobsInGraph = new SafeSet(); - // TODO(joyeecheung): if it's not on the async loader thread, consider this already - // linked. const addJobsToDependencyGraph = async (moduleJob) => { debug(`async addJobsToDependencyGraph() ${this.url}`, moduleJob); @@ -500,8 +414,7 @@ class ModuleJob extends ModuleJobBase { return; } jobsInGraph.add(moduleJob); - const dependencyJobs = isPromise(moduleJob.linked) ? await moduleJob.linked : moduleJob.linked; - return SafePromiseAllReturnVoid(dependencyJobs, addJobsToDependencyGraph); + return SafePromiseAllReturnVoid(moduleJob.linked, addJobsToDependencyGraph); }; await addJobsToDependencyGraph(this); @@ -520,46 +433,6 @@ class ModuleJob extends ModuleJobBase { } } - runSync(parent) { - assert(this.shouldRunModule(this.phase)); - assert(this.module instanceof ModuleWrap); - let status = this.module.getStatus(); - - debug('ModuleJob.runSync()', status, this.module); - if (status === kUninstantiated) { - // TODO(joyeecheung): Reject graphs with top-level await _before_ instantiation, so that - // the async graph error supersedes instantiation (mismatch export) errors in the graph. - // FIXME(joyeecheung): this cannot fully handle < kInstantiated. Make the linking - // fully synchronous instead. - if (this.module.getModuleRequests().length === 0) { - this.module.link([]); - } - this.module.instantiate(); - status = this.module.getStatus(); - } - if (status === kInstantiated || status === kErrored) { - this.throwIfAsyncGraph(parent); - if (status === kInstantiated) { - setHasStartedUserESMExecution(); - const namespace = this.module.evaluateSync(); - return { __proto__: null, module: this.module, namespace }; - } - throw this.module.getError(); - } else if (status === kEvaluating || status === kEvaluated) { - this.throwIfAsyncGraph(parent); - // kEvaluating can show up when this is being used to deal with CJS <-> CJS cycles. - // Allow it for now, since we only need to ban ESM <-> CJS cycles which would be - // detected earlier during the linking phase, though the CJS handling in the ESM - // loader won't be able to emit warnings on pending circular exports like what - // the CJS loader does. - // TODO(joyeecheung): remove the re-invented require() in the ESM loader and - // always handle CJS using the CJS loader to eliminate the quirks. - return { __proto__: null, module: this.module, namespace: this.module.getNamespace() }; - } - assert(status === kUninstantiated, `Unexpected module status ${status}.`); - throw new ERR_REQUIRE_ESM_RACE_CONDITION(); - } - async run(isEntryPoint = false) { debug('ModuleJob.run()', this.module); assert(this.shouldRunModule(this.phase)); @@ -581,16 +454,12 @@ class ModuleJob extends ModuleJobBase { } /** - * This is a fully synchronous job and does not spawn additional threads in any way. * Loading and linking are always synchronous. Evaluation via runSync() throws on an * asynchronous graph; evaluation via run() falls back to async for top-level await. * It also disallows CJS <-> ESM cycles. * - * Used for all ES module imports on the main thread, regardless of how the import was - * triggered (entry point, import(), require(esm), --import, etc.). - * Modules loaded by require() in imported CJS are handled by ModuleJob with the - * isForRequireInImportedCJS set to true instead. The two currently have different caching behaviors. - * TODO(joyeecheung): consolidate this with the isForRequireInImportedCJS variant of ModuleJob. + * Used for all ES module imports regardless of how the import was triggered + * (entry point, import(), require(esm), --import, etc.). */ class ModuleJobSync extends ModuleJobBase { /** @@ -617,15 +486,6 @@ class ModuleJobSync extends ModuleJobBase { } } - /** - * @param {ModuleRequestType} requestType Type of the module request. - * @returns {ModuleJobBase[]} - */ - link(requestType) { - // Synchronous linking is always used for ModuleJobSync. - return this.syncLink(requestType); - } - get modulePromise() { return PromiseResolve(this.module); } @@ -708,9 +568,6 @@ class ModuleJobSync extends ModuleJobBase { // TODO(joyeecheung): Reject graphs with top-level await _before_ instantiation, so that the // async graph error supersedes instantiation (mismatch export) errors in the graph. this.instantiateSync(); - // On the deprecated async loader hook worker thread, dependencies linked by an - // earlier import may not be walkable synchronously, so double-check with - // V8 now that the graph is instantiated. this.throwIfAsyncGraph(parent); setHasStartedUserESMExecution(); try { diff --git a/lib/internal/modules/esm/module_map.js b/lib/internal/modules/esm/module_map.js index 207515573c79..05a6c3082d28 100644 --- a/lib/internal/modules/esm/module_map.js +++ b/lib/internal/modules/esm/module_map.js @@ -20,7 +20,8 @@ const { validateString } = require('internal/validators'); * Future resolutions of the same input (specifier, parent URL and import attributes) * must return the same result if the first attempt was successful, per * https://tc39.es/ecma262/#sec-HostLoadImportedModule. - * This cache is *not* used when custom loaders are registered. + * Only results of the default resolver are cached; results returned by + * `module.registerHooks()` resolve hooks are not. */ class ResolveCache extends SafeMap { /** diff --git a/lib/internal/modules/esm/shared_constants.js b/lib/internal/modules/esm/shared_constants.js deleted file mode 100644 index 4200bc87367d..000000000000 --- a/lib/internal/modules/esm/shared_constants.js +++ /dev/null @@ -1,25 +0,0 @@ -// This file contains the definition for the constant values that must be -// available to both the main thread and the loader thread. - -'use strict'; - -/* -The shared memory area is divided in 1 32-bit long section. It has to be 32-bit long as -`Atomics.notify` only works with `Int32Array` objects. - ---32-bits-- - ^ - | - | -WORKER_TO_MAIN_THREAD_NOTIFICATION - -WORKER_TO_MAIN_THREAD_NOTIFICATION is only used to send notifications, its value is going to -increase every time the worker sends a notification to the main thread. - -*/ - -module.exports = { - WORKER_TO_MAIN_THREAD_NOTIFICATION: 0, - - SHARED_MEMORY_BYTE_LENGTH: 1 * 4, -}; diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js index 583b6d1fe91d..100f791b98ee 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -17,13 +17,9 @@ const { globalThis, } = primordials; -const { - compileFunctionForCJSLoader, -} = internalBinding('contextify'); - const { BuiltinModule } = require('internal/bootstrap/realm'); const assert = require('internal/assert'); -const { dirname, extname } = require('path'); +const { dirname } = require('path'); const { assertBufferSource, loadBuiltinModule, @@ -45,22 +41,20 @@ const { findLongestRegisteredExtension, resolveForCJSWithHooks, loadSourceForCJSWithHooks, - populateCJSExportsFromESM, } = require('internal/modules/cjs/loader'); -const { fileURLToPath, pathToFileURL, URL } = require('internal/url'); +const { fileURLToPath, URL } = require('internal/url'); const { isAnyArrayBuffer } = require('internal/util/types'); let debug = require('internal/util/debuglog').debuglog('esm', (fn) => { debug = fn; }); -const { emitExperimentalWarning, kEmptyObject, setOwnProperty, isWindows } = require('internal/util'); +const { emitExperimentalWarning, setOwnProperty, isWindows } = require('internal/util'); const { ERR_INVALID_RETURN_PROPERTY_VALUE, ERR_UNKNOWN_BUILTIN_MODULE, ERR_WEBASSEMBLY_NOT_SUPPORTED, } = require('internal/errors').codes; -const { maybeCacheSourceMap } = require('internal/source_map/source_map_cache'); const moduleWrap = internalBinding('module_wrap'); -const { ModuleWrap, kEvaluationPhase } = moduleWrap; +const { ModuleWrap } = moduleWrap; const { getSourceSync } = require('internal/modules/esm/load'); @@ -101,108 +95,9 @@ translators.set('module', function moduleStrategy(url, translateContext, parentU return module; }); -const { requestTypes: { kRequireInImportedCJS } } = require('internal/modules/esm/utils'); const kShouldSkipModuleHooks = { __proto__: null, shouldSkipModuleHooks: true }; const kShouldNotSkipModuleHooks = { __proto__: null, shouldSkipModuleHooks: false }; -/** - * This may be eventually removed when module.register() reaches end-of-life. - * - * Loads a CommonJS module via the ESM Loader sync CommonJS translator. - * This translator creates its own version of the `require` function passed into CommonJS modules. - * Any monkey patches applied to the CommonJS Loader will not affect this module. - * Any `require` calls in this module will load all children in the same way. - * @param {import('internal/modules/cjs/loader').Module} module - The module to load. - * @param {string} source - The source code of the module. - * @param {string} url - The URL of the module. - * @param {string} filename - The filename of the module. - * @param {boolean} isMain - Whether the module is the entrypoint - * @param {TranslateContext} translateContext Context for the translator - */ -function loadCJSModuleWithSpecialRequire(module, source, url, filename, isMain, translateContext) { - // Use the full URL as the V8 resource name so that any search params - // (e.g. ?node-test-mock) are preserved in coverage reports. - const compileResult = compileFunctionForCJSLoader(source, url, false /* is_sea_main */, false); - - const { function: compiledWrapper, sourceMapURL, sourceURL } = compileResult; - // Cache the source map for the cjs module if present. - if (sourceMapURL) { - maybeCacheSourceMap(url, source, module, false, sourceURL, sourceMapURL); - } - const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); - const __dirname = dirname(filename); - // eslint-disable-next-line node-core/func-name-matching,func-style - const requireFn = function require(specifier) { - let importAttributes = kEmptyObject; - if (!StringPrototypeStartsWith(specifier, 'node:') && !BuiltinModule.normalizeRequirableId(specifier)) { - // TODO: do not depend on the monkey-patchable CJS loader here. - const path = CJSModule._resolveFilename(specifier, module); - switch (extname(path)) { - case '.json': - importAttributes = { __proto__: null, type: 'json' }; - break; - case '.node': - // If it gets here in the translators, the hooks must have already been invoked - // in the loader. Skip them in the synthetic module evaluation step. - return wrapModuleLoad(specifier, module, false, kShouldSkipModuleHooks); - default: - // fall through - } - specifier = `${pathToFileURL(path)}`; - } - - // NOTE: This re-invented require() is only used on the loader-hook worker thread. - // On the main thread, the authentic require() is used instead (fixed by #60380). - const request = { specifier, attributes: importAttributes, phase: kEvaluationPhase, __proto__: null }; - const job = cascadedLoader.getOrCreateModuleJob(url, request, kRequireInImportedCJS); - job.runSync(module); - let mod = cjsCache.get(job.url); - assert(job.module, `Imported CJS module ${url} failed to load module ${job.url} using require() due to race condition`); - - if (job.module.synthetic) { - assert(mod, `Imported CJS module ${url} failed to load module ${job.url} using require() due to missed cache`); - return mod.exports; - } - - // The module being required is a source text module. - if (!mod) { - mod = cjsEmplaceModuleCacheEntry(job.url); - cjsCache.set(job.url, mod); - } - // The module has been cached by the re-invented require. Update the exports object - // from the namespace object and return the evaluated exports. - if (!mod.loaded) { - debug('populateCJSExportsFromESM from require(esm) in imported CJS', url, mod, job.module); - populateCJSExportsFromESM(mod, job.module, job.module.getNamespace()); - mod.loaded = true; - } - return mod.exports; - }; - setOwnProperty(requireFn, 'resolve', function resolve(specifier) { - if (!StringPrototypeStartsWith(specifier, 'node:')) { - const { - filename, url: resolvedURL, - } = resolveForCJSWithHooks(specifier, module, false, kShouldNotSkipModuleHooks); - if (specifier !== filename) { - specifier = resolvedURL ?? `${pathToFileURL(filename)}`; - } - } - - const request = { specifier, __proto__: null, attributes: kEmptyObject }; - // Skip sync hooks in resolveSync since resolveForCJSWithHooks already ran them above. - const { url: resolvedURL } = cascadedLoader.resolveSync(url, request, /* shouldSkipSyncHooks */ true); - return urlToFilename(resolvedURL); - }); - setOwnProperty(requireFn, 'main', process.mainModule); - - FunctionPrototypeCall(compiledWrapper, module.exports, - module.exports, requireFn, module, filename, __dirname); - setOwnProperty(module, 'loaded', true); -} - -// TODO: can we use a weak map instead? -const cjsCache = new SafeMap(); - /** * Creates a ModuleWrap object for a CommonJS module. * @param {string} url - The URL of the module. @@ -226,7 +121,6 @@ function createCJSModuleWrap(url, translateContext, parentURL) { } const { exportNames, module } = cjsPreparseModuleExports(filename, source, sourceFormat); - cjsCache.set(url, module); const wrapperNames = [...exportNames]; if (!exportNames.has('default')) { @@ -244,19 +138,7 @@ function createCJSModuleWrap(url, translateContext, parentURL) { debug(`Loading CJSModule ${url}`); if (!module.loaded) { - // For backward-compatibility, it's possible for async hooks to return a nullish value for - // CJS source associated with a `file:` URL - that usually means the source is not - // customized (is loaded by default load) or the hook author wants it to be reloaded - // through CJS routine. In this case, the source is obtained by calling the - // Module._load(). - if (translateContext.translatorKey === 'commonjs-sync' || - translateContext.isSourceLoadedSynchronously || - translateContext.source == null) { - loadCJSModuleWithModuleLoad(module, source, url, filename, !!isMain, translateContext); - } else { // CommonJS with source customized by async hooks - // This may be eventually removed when module.register() reaches end-of-life. - loadCJSModuleWithSpecialRequire(module, source, url, filename, !!isMain, translateContext); - } + loadCJSModuleWithModuleLoad(module, source, url, filename, !!isMain, translateContext); } let exports; @@ -298,7 +180,6 @@ function createCJSNoSourceModuleWrap(url, parentURL) { const filename = urlToFilename(url); const module = cjsEmplaceModuleCacheEntry(filename); - cjsCache.set(url, module); if (isMain) { setOwnProperty(process, 'mainModule', module); @@ -333,25 +214,10 @@ translators.set('commonjs-sync', function requireCommonJS(url, translateContext, return createCJSModuleWrap(url, translateContext, parentURL); }); -// Handle CommonJS modules referenced by `require` calls using re-invented require. -// This path is only used by require() from imported CJS customized by the *async* -// loader hooks. -translators.set('require-commonjs', (url, translateContext, parentURL) => { - return createCJSModuleWrap(url, translateContext, parentURL); -}); - -// Handle TypeScript CommonJS modules referenced by `require` calls using re-invented require. -// This path is only used by require() from imported CJS customized by the *async* -// loader hooks. -translators.set('require-commonjs-typescript', (url, translateContext, parentURL) => { - translateContext.source = stripTypeScriptModuleTypes(stringify(translateContext.source), url); - return createCJSModuleWrap(url, translateContext, parentURL); -}); - // This goes through Module._load to accommodate monkey-patchers. /** * Loads a CommonJS module through Module._load to accommodate monkey-patchers. - * If the module was resolved by synchronous hooks (i.e. not by the default resolver), + * If the module was resolved by hooks (i.e. not by the default resolver), * passes the pre-resolved information and source to Module._load to avoid * re-resolving and re-loading. * @param {import('internal/modules/cjs/loader').Module} module - The module to load. @@ -483,7 +349,6 @@ translators.set('builtin', function builtinStrategy(url, translateContext) { // Slice 'node:' scheme const id = StringPrototypeSlice(url, 5); const module = loadBuiltinModule(id, url); - cjsCache.set(url, module); if (!StringPrototypeStartsWith(url, 'node:') || !module) { throw new ERR_UNKNOWN_BUILTIN_MODULE(url); } @@ -545,7 +410,6 @@ translators.set('json', function jsonStrategy(url, translateContext) { if (shouldCheckAndPopulateCJSModuleCache) { CJSModule._cache[modulePath] = module; } - cjsCache.set(url, module); return new ModuleWrap(url, undefined, ['default'], function() { debug(`Parsing JSONModule ${url}`); this.setExport('default', module.exports); diff --git a/lib/internal/modules/esm/utils.js b/lib/internal/modules/esm/utils.js index 8937b8a61298..b8c8b10d3867 100644 --- a/lib/internal/modules/esm/utils.js +++ b/lib/internal/modules/esm/utils.js @@ -296,14 +296,10 @@ async function importModuleDynamicallyCallback(referrerSymbol, specifier, phase, throw new ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING(); } -let _shouldSpawnLoaderHookWorker = true; /** * Initializes handling of ES modules. - * @param {boolean} [shouldSpawnLoaderHookWorker] Whether the custom loader worker - * should be spawned later. */ -function initializeESM(shouldSpawnLoaderHookWorker = true) { - _shouldSpawnLoaderHookWorker = shouldSpawnLoaderHookWorker; +function initializeESM() { initializeDefaultConditions(); // Setup per-realm callbacks that locate data or callbacks that we keep // track of for different ESM modules. @@ -311,15 +307,6 @@ function initializeESM(shouldSpawnLoaderHookWorker = true) { setImportModuleDynamicallyCallback(importModuleDynamicallyCallback); } -/** - * Determine whether the custom loader worker should be spawned when initializing - * the singleton ESM loader. - * @returns {boolean} - */ -function shouldSpawnLoaderHookWorker() { - return _shouldSpawnLoaderHookWorker; -} - const SourceTextModuleTypes = { kInternal: 'internal', // TODO(joyeecheung): support internal ESM. kEmbedder: 'embedder', // Embedder ESM, also used by SEA @@ -391,12 +378,11 @@ function compileSourceTextModule(url, source, type, context = kEmptyObject) { const kImportInImportedESM = Symbol('kImportInImportedESM'); const kImportInRequiredESM = Symbol('kImportInRequiredESM'); -const kRequireInImportedCJS = Symbol('kRequireInImportedCJS'); /** - * @typedef {kImportInImportedESM | kImportInRequiredESM | kRequireInImportedCJS} ModuleRequestType + * @typedef {kImportInImportedESM | kImportInRequiredESM} ModuleRequestType */ -const requestTypes = { kImportInImportedESM, kImportInRequiredESM, kRequireInImportedCJS }; +const requestTypes = { kImportInImportedESM, kImportInRequiredESM }; module.exports = { embedder_module_hdo, @@ -404,7 +390,6 @@ module.exports = { initializeESM, getDefaultConditions, getConditionsSet, - shouldSpawnLoaderHookWorker, compileSourceTextModule, SourceTextModuleTypes, requestTypes, diff --git a/lib/internal/modules/esm/worker.js b/lib/internal/modules/esm/worker.js deleted file mode 100644 index 7d023059a4b0..000000000000 --- a/lib/internal/modules/esm/worker.js +++ /dev/null @@ -1,324 +0,0 @@ -'use strict'; - -const { - AtomicsAdd, - AtomicsNotify, - DataViewPrototypeGetBuffer, - Int32Array, - PromisePrototypeThen, - ReflectApply, - SafeSet, - TypedArrayPrototypeGetBuffer, -} = primordials; -const assert = require('internal/assert'); -const { clearImmediate, setImmediate } = require('timers'); -const { - hasUncaughtExceptionCaptureCallback, -} = require('internal/process/execution'); -const { - isArrayBuffer, - isDataView, - isTypedArray, -} = require('util/types'); - -const { getOptionValue } = require('internal/options'); -const { - loadPreloadModules, - initializeModuleLoaders, - initializeFrozenIntrinsics, -} = require('internal/process/pre_execution'); -const { receiveMessageOnPort } = require('internal/worker/io'); -const { - WORKER_TO_MAIN_THREAD_NOTIFICATION, -} = require('internal/modules/esm/shared_constants'); -const { isMarkedAsUntransferable } = require('internal/buffer'); -const { getCWDURL } = require('internal/util'); -const { isCascadedLoaderInitialized, getOrInitializeCascadedLoader } = require('internal/modules/esm/loader'); -const { AsyncLoaderHooksOnLoaderHookWorker } = require('internal/modules/esm/hooks'); -const { enableWorkerCondition } = require('internal/modules/helpers'); - -/** - * Register asynchronous module loader customization hooks. This should only be run in the loader - * hooks worker. In a non-loader-hooks thread, if any asynchronous loader hook is registered, the - * ModuleLoader#asyncLoaderHooks are initialized to be AsyncLoaderHooksProxiedToLoaderHookWorker - * which posts the messages to the async loader hook worker thread. - * When no asynchronous loader hook is registered, the loader hook worker is not spawned and module - * loading is entiredly done in-thread. - * @returns {Promise} - */ -async function initializeAsyncLoaderHooksOnLoaderHookWorker() { - const customLoaderURLs = getOptionValue('--experimental-loader'); - - // The worker thread spawned for handling asynchronous loader hooks should not - // further spawn other hook threads or there will be an infinite recursion. - const shouldSpawnLoaderHookWorker = false; - // The worker thread for async loader hooks will preload user modules itself in - // initializeAsyncLoaderHooksOnLoaderHookWorker(). - const shouldPreloadModules = false; - initializeModuleLoaders({ shouldSpawnLoaderHookWorker, shouldPreloadModules }); - - assert(!isCascadedLoaderInitialized(), - 'ModuleLoader should be initialized in initializeAsyncLoaderHooksOnLoaderHookWorker()'); - const asyncLoaderHooks = new AsyncLoaderHooksOnLoaderHookWorker(); - getOrInitializeCascadedLoader(asyncLoaderHooks); - - // We need the async loader hooks to be set _before_ we start invoking - // `--require`, otherwise loops can happen because a `--require` script - // might call `register(...)` before we've installed ourselves. These - // global values are magically set in `initializeModuleLoaders` just for us and - // we call them in the correct order. - // N.B. This block appears here specifically in order to ensure that - // `--require` calls occur before `--loader` ones do. - loadPreloadModules(); - initializeFrozenIntrinsics(); - - const parentURL = getCWDURL().href; - for (let i = 0; i < customLoaderURLs.length; i++) { - await asyncLoaderHooks.register(customLoaderURLs[i], parentURL); - } - - return asyncLoaderHooks; -} - -/** - * Transfers an ArrayBuffer, TypedArray, or DataView to a worker thread. - * @param {boolean} hasError - Whether an error occurred during transfer. - * @param {ArrayBuffer[] | TypedArray | DataView} source - The data to transfer. - * @returns {ArrayBuffer[]|undefined} - */ -function transferArrayBuffer(hasError, source) { - if (hasError || source == null) { return; } - let arrayBuffer; - if (isArrayBuffer(source)) { - arrayBuffer = source; - } else if (isTypedArray(source)) { - arrayBuffer = TypedArrayPrototypeGetBuffer(source); - } else if (isDataView(source)) { - arrayBuffer = DataViewPrototypeGetBuffer(source); - } - if (arrayBuffer && !isMarkedAsUntransferable(arrayBuffer)) { - return [arrayBuffer]; - } -} - -/** - * Wraps a message with a status and body, and serializes the body if necessary. - * @param {string} status - The status of the message. - * @param {any} body - The body of the message. - * @returns {{status: string, body: any}} - */ -function wrapMessage(status, body) { - if (status === 'success' || body === null || - (typeof body !== 'object' && - typeof body !== 'function' && - typeof body !== 'symbol')) { - return { status, body }; - } - - let serialized; - let serializationFailed; - try { - const { serializeError } = require('internal/error_serdes'); - serialized = serializeError(body); - } catch { - serializationFailed = true; - } - - return { - status, - body: { - serialized, - serializationFailed, - }, - }; -} - -/** - * Initializes the loader hooks worker thread with customized asynchronous module loading hooks. - * @param {SharedArrayBuffer} lock - The lock used to synchronize communication between the worker and the main thread. - * @param {MessagePort} syncCommPort - The message port used for synchronous communication between the worker and the - * main thread. - * @param {(err: Error, origin?: string) => void} errorHandler - The function to use for uncaught exceptions. - * @returns {Promise} A promise that resolves when the worker thread has been initialized. - */ -async function customizedModuleWorker(lock, syncCommPort, errorHandler) { - let asyncLoaderHooks; - let initializationError; - let hasInitializationError = false; - - { - // If a custom hook is calling `process.exit`, we should wake up the main thread - // so it can detect the exit event. - const { exit } = process; - process.exit = function(code) { - syncCommPort.postMessage(wrapMessage('exit', code ?? process.exitCode)); - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - return ReflectApply(exit, this, arguments); - }; - } - - try { - asyncLoaderHooks = await initializeAsyncLoaderHooksOnLoaderHookWorker(); - } catch (exception) { - // If there was an error while parsing and executing a user loader, for example if because a - // loader contained a syntax error, then we need to send the error to the main thread so it can - // be thrown and printed. - hasInitializationError = true; - initializationError = exception; - } - - syncCommPort.on('message', handleMessage); - - if (hasInitializationError) { - syncCommPort.postMessage(wrapMessage('error', initializationError)); - } else { - syncCommPort.postMessage(wrapMessage('success')); - } - - // We're ready, so unlock the main thread. - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - - let immediate; - /** - * Checks for messages on the syncCommPort and handles them asynchronously. - */ - function checkForMessages() { - immediate = setImmediate(checkForMessages).unref(); - // We need to let the event loop tick a few times to give the main thread a chance to send - // follow-up messages. - const response = receiveMessageOnPort(syncCommPort); - - if (response !== undefined) { - PromisePrototypeThen(handleMessage(response.message), undefined, errorHandler); - } - } - - const unsettledResponsePorts = new SafeSet(); - - process.on('beforeExit', () => { - for (const port of unsettledResponsePorts) { - port.postMessage(wrapMessage('never-settle')); - } - unsettledResponsePorts.clear(); - - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - - // Attach back the event handler. - syncCommPort.on('message', handleMessage); - // Also check synchronously for a message, in case it's already there. - clearImmediate(immediate); - checkForMessages(); - // We don't need the sync check after this tick, as we already have added the event handler. - clearImmediate(immediate); - // Add some work for next tick so the worker cannot exit. - setImmediate(() => {}); - }); - - /** - * Handles incoming messages from the main thread or other workers. - * @param {object} options - The options object. - * @param {string} options.method - The name of the hook. - * @param {Array} options.args - The arguments to pass to the method. - * @param {MessagePort} options.port - The message port to use for communication. - */ - async function handleMessage({ method, args, port }) { - // Each potential exception needs to be caught individually so that the correct error is sent to - // the main thread. - let hasError = false; - let shouldRemoveGlobalErrorHandler = false; - assert(typeof asyncLoaderHooks[method] === 'function', `${method} is not implemented in the loader worker`); - if (port == null && !hasUncaughtExceptionCaptureCallback()) { - // When receiving sync messages, we want to unlock the main thread when there's an exception. - process.on('uncaughtException', errorHandler); - shouldRemoveGlobalErrorHandler = true; - } - - // We are about to yield the execution with `await ReflectApply` below. In case the code - // following the `await` never runs, we remove the message handler so the `beforeExit` event - // can be triggered. - syncCommPort.off('message', handleMessage); - - // We keep checking for new messages to not miss any. - clearImmediate(immediate); - immediate = setImmediate(checkForMessages).unref(); - - unsettledResponsePorts.add(port ?? syncCommPort); - - let response; - try { - response = await ReflectApply(asyncLoaderHooks[method], asyncLoaderHooks, args); - } catch (exception) { - hasError = true; - response = exception; - } - - unsettledResponsePorts.delete(port ?? syncCommPort); - - // Send the method response (or exception) to the main thread. - try { - (port ?? syncCommPort).postMessage( - wrapMessage(hasError ? 'error' : 'success', response), - transferArrayBuffer(hasError, response?.source), - ); - } catch (exception) { - // Or send the exception thrown when trying to send the response. - (port ?? syncCommPort).postMessage(wrapMessage('error', exception)); - } - - if (shouldRemoveGlobalErrorHandler) { - process.off('uncaughtException', errorHandler); - } - - syncCommPort.off('message', handleMessage); - // We keep checking for new messages to not miss any. - clearImmediate(immediate); - immediate = setImmediate(checkForMessages).unref(); - // To prevent the main thread from terminating before this function completes after unlocking, - // the following process is executed at the end of the function. - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - } -} - -/** - * Initializes a worker thread for a module with customized hooks. - * ! Run everything possible within this function so errors get reported. - * @param {{lock: SharedArrayBuffer, workerCondition: boolean}} workerData - The lock used to - * synchronize with the main thread, and whether the spawning thread is a Web Worker. - * @param {MessagePort} syncCommPort - The communication port used to communicate with the main thread. - * @returns {object} - */ -module.exports = function setupModuleWorker(workerData, syncCommPort) { - const lock = new Int32Array(workerData.lock); - if (workerData.workerCondition) { - enableWorkerCondition(); - } - - /** - * Handles errors that occur in the worker thread. - * @param {Error} err - The error that occurred. - * @param {string} [origin] - The origin of the error. - */ - function errorHandler(err, origin = 'unhandledRejection') { - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - process.off('uncaughtException', errorHandler); - if (hasUncaughtExceptionCaptureCallback()) { - process._fatalException(err); - return; - } - internalBinding('errors').triggerUncaughtException( - err, - origin === 'unhandledRejection', - ); - } - - return PromisePrototypeThen( - customizedModuleWorker(lock, syncCommPort, errorHandler), - undefined, - errorHandler, - ); -}; diff --git a/lib/internal/modules/package_json_reader.js b/lib/internal/modules/package_json_reader.js index 71612c27cc5c..d043694c8c04 100644 --- a/lib/internal/modules/package_json_reader.js +++ b/lib/internal/modules/package_json_reader.js @@ -411,11 +411,9 @@ function findPackageJSON(specifier, base = 'data:') { defaultResolve ??= require('internal/modules/esm/resolve').defaultResolve; try { - // TODO(@JakobJingleheimer): Detect whether findPackageJSON is being used within a loader - // (possibly piggyback on `isForAsyncLoaderHookWorker` from the loader?) and if so: - // - When inside, use the default resolve - // - (I think it's impossible to use the chain because of re-entry & a deadlock from atomics). - // - When outside, use cascadedLoader.resolveSync (not implemented yet, but the pieces exist). + // TODO(@JakobJingleheimer): This always uses the default resolver and so ignores any + // module.registerHooks() resolve hooks. Using cascadedLoader.resolveSync would apply them, + // but that needs to handle re-entry when findPackageJSON is called from inside a hook. resolvedTarget = defaultResolve(specifier, { parentURL: `${parentURL}` }).url; } catch (err) { if (err.code === 'ERR_UNSUPPORTED_DIR_IMPORT') { diff --git a/lib/internal/modules/run_main.js b/lib/internal/modules/run_main.js index b0d7d4845eaf..ec97f46f5a0f 100644 --- a/lib/internal/modules/run_main.js +++ b/lib/internal/modules/run_main.js @@ -51,17 +51,12 @@ function resolveMainPath(main) { * @returns {boolean} */ function shouldUseESMLoader(mainPath) { - /** - * @type {string[]} userLoaders A list of custom loaders registered by the user - * (or an empty list when none have been registered). - */ - const userLoaders = getOptionValue('--experimental-loader'); /** * @type {string[]} userImports A list of preloaded modules registered by the user * (or an empty list when none have been registered). */ const userImports = getOptionValue('--import'); - if (userLoaders.length > 0 || userImports.length > 0) { return true; } + if (userImports.length > 0) { return true; } // Determine the module format of the entry point. if (mainPath && StringPrototypeEndsWith(mainPath, '.mjs')) { return true; } @@ -96,8 +91,6 @@ async function asyncRunEntryPointWithESMLoader(callback) { for (let i = 0; i < userImports.length; i++) { await cascadedLoader.import(userImports[i], parentURL, kEmptyObject); } - } else { - cascadedLoader.waitForAsyncLoaderHookInitialization(); } // Any --import above may have registered a VFS provider, so mount now (no-op // if prepareExecution already mounted in the no-import case). @@ -175,11 +168,10 @@ function executeUserEntryPoint(main = process.argv[1]) { const mainPath = resolvedMain || main; const mainURL = getOptionValue('--entry-url') ? new URL(mainPath, getCWDURL()) : pathToFileURL(mainPath); - // When no async loader hooks or --import are registered, load the entry point + // When no --import preloads are registered, load the entry point // directly. The graph is loaded and linked synchronously, and evaluated // synchronously too unless it contains top-level await. - if (getOptionValue('--experimental-loader').length === 0 && - getOptionValue('--import').length === 0) { + if (getOptionValue('--import').length === 0) { const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); const job = cascadedLoader.importForEntryPoint(mainURL.href); if (job === undefined) { diff --git a/lib/internal/process/pre_execution.js b/lib/internal/process/pre_execution.js index 0f5aaf857aeb..b5933f4e9d61 100644 --- a/lib/internal/process/pre_execution.js +++ b/lib/internal/process/pre_execution.js @@ -51,7 +51,6 @@ function prepareMainThreadExecution(expandArgv1 = false, initializeModules = tru expandArgv1, initializeModules, isMainThread: true, - shouldSpawnLoaderHookWorker: initializeModules, shouldPreloadModules: initializeModules, }); } @@ -61,7 +60,6 @@ function prepareTestRunnerMainExecution(loadUserModules = true) { expandArgv1: false, initializeModules: true, isMainThread: true, - shouldSpawnLoaderHookWorker: loadUserModules, shouldPreloadModules: loadUserModules, }); } @@ -73,7 +71,6 @@ function prepareWorkerThreadExecution() { // Module loader initialization in workers are delayed until the worker thread // is ready for execution. initializeModules: false, - shouldSpawnLoaderHookWorker: false, shouldPreloadModules: false, }); } @@ -84,8 +81,8 @@ function prepareShadowRealmExecution() { patchProcessObject(false); setupDebugEnv(); - // Disable custom loaders in ShadowRealm. - initializeModuleLoaders({ shouldSpawnLoaderHookWorker: false, shouldPreloadModules: false }); + // Preload modules are not supported in ShadowRealm. + initializeModuleLoaders({ shouldPreloadModules: false }); const { privateSymbols: { host_defined_option_symbol, @@ -107,7 +104,7 @@ function prepareShadowRealmExecution() { } function prepareExecution(options) { - const { expandArgv1, initializeModules, isMainThread, shouldSpawnLoaderHookWorker, shouldPreloadModules } = options; + const { expandArgv1, initializeModules, isMainThread, shouldPreloadModules } = options; refreshRuntimeOptions(); @@ -172,7 +169,7 @@ function prepareExecution(options) { setupVmModules(); if (initializeModules) { - initializeModuleLoaders({ shouldSpawnLoaderHookWorker, shouldPreloadModules }); + initializeModuleLoaders({ shouldPreloadModules }); } // Mount here only when there is no --import: those preloads run later (inside @@ -319,15 +316,13 @@ function warnAboutRemovedProxyEnvVars() { } function initializeModuleLoaders(options) { - const { shouldSpawnLoaderHookWorker, shouldPreloadModules } = options; + const { shouldPreloadModules } = options; // Initialize certain special module.Module properties and the CJS conditions. const { initializeCJS } = require('internal/modules/cjs/loader'); initializeCJS(); // Initialize the ESM loader and a few module callbacks. - // If shouldSpawnLoaderHookWorker is true, later when the ESM loader is instantiated on-demand, - // it will spawn a loader worker thread to handle async custom loader hooks. const { initializeESM } = require('internal/modules/esm/utils'); - initializeESM(shouldSpawnLoaderHookWorker); + initializeESM(); const { hasStartedUserCJSExecution, @@ -340,9 +335,7 @@ function initializeModuleLoaders(options) { if (getEmbedderOptions().hasEmbedderPreload) { runEmbedderPreload(); } - // Do not enable preload modules if custom loaders are disabled. - // For example, loader workers are responsible for doing this themselves. - // And preload modules are not supported in ShadowRealm as well. + // Preload modules are not supported in ShadowRealm. if (shouldPreloadModules) { loadPreloadModules(); } diff --git a/lib/internal/test_runner/mock/loader.js b/lib/internal/test_runner/mock/loader.js index d64ffdfa0965..266525c8d52a 100644 --- a/lib/internal/test_runner/mock/loader.js +++ b/lib/internal/test_runner/mock/loader.js @@ -60,12 +60,11 @@ function load(url, context, nextLoad) { // Treat builtins as commonjs because customization hooks do not allow a // core module to be replaced. - // Also collapse 'commonjs-sync' and 'require-commonjs' to 'commonjs'. + // Also collapse 'commonjs-sync' to 'commonjs'. let format = original.format; switch (original.format) { case 'builtin': // Deliberate fallthrough - case 'commonjs-sync': // Deliberate fallthrough - case 'require-commonjs': + case 'commonjs-sync': format = 'commonjs'; break; case 'json': diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 728132f779e3..00b0293e85dc 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -44,7 +44,6 @@ const { const workerIo = require('internal/worker/io'); const { drainMessagePort, - receiveMessageOnPort, MessageChannel, messageTypes, kPort, @@ -73,7 +72,6 @@ const { const { ownsProcessState, isMainThread, - isInternalThread, resourceLimits: resourceLimitsRaw, threadId, threadName, @@ -94,7 +92,6 @@ const kOnCouldNotSerializeErr = Symbol('kOnCouldNotSerializeErr'); const kOnErrorMessage = Symbol('kOnErrorMessage'); const kParentSideStdio = Symbol('kParentSideStdio'); const kLoopStartTime = Symbol('kLoopStartTime'); -const kIsInternal = Symbol('kIsInternal'); const kIsOnline = Symbol('kIsOnline'); const kWebWorkerData = Symbol('kWebWorkerData'); @@ -203,13 +200,7 @@ class Worker extends EventEmitter { constructor(filename, options = kEmptyObject) { throwIfBuildingSnapshot('Creating workers'); super(); - const isInternal = arguments[2] === kIsInternal; - debug( - `[${threadId}] create new worker`, - filename, - options, - `isInternal: ${isInternal}`, - ); + debug(`[${threadId}] create new worker`, filename, options); if (options.execArgv) validateArray(options.execArgv, 'options.execArgv'); @@ -220,10 +211,7 @@ class Worker extends EventEmitter { } let url, doEval; - if (isInternal) { - doEval = 'internal'; - url = `node:${filename}`; - } else if (options.eval) { + if (options.eval) { if (typeof filename !== 'string') { throw new ERR_INVALID_ARG_VALUE( 'options.eval', @@ -286,7 +274,6 @@ class Worker extends EventEmitter { options.execArgv, parseResourceLimits(options.resourceLimits), !!(options.trackUnmanagedFds ?? true), - isInternal, name); if (this[kHandle].invalidExecArgv) { throw new ERR_WORKER_INVALID_EXEC_ARGV(this[kHandle].invalidExecArgv); @@ -361,7 +348,6 @@ class Worker extends EventEmitter { type: messageTypes.LOAD_SCRIPT, filename, doEval, - isInternal, cwdCounter: cwdCounter || workerIo.sharedCwdCounter, workerData: options.workerData, webWorkerData: options[kWebWorkerData], @@ -642,20 +628,6 @@ class Worker extends EventEmitter { } } -/** - * A worker which has an internal module for entry point (e.g. internal/module/esm/worker). - * Internal workers bypass the permission model. - */ -class InternalWorker extends Worker { - constructor(filename, options) { - super(filename, options, kIsInternal); - } - - receiveMessageSync() { - return receiveMessageOnPort(this[kPublicPort]); - } -} - function pipeWithoutWarning(source, dest) { const sourceMaxListeners = source._maxListeners; const destMaxListeners = dest._maxListeners; @@ -723,7 +695,6 @@ module.exports = { ownsProcessState, kIsOnline, isMainThread, - isInternalThread, SHARE_ENV, resourceLimits: !isMainThread ? makeResourceLimits(resourceLimitsRaw) : {}, @@ -732,7 +703,6 @@ module.exports = { assignEnvironmentData, threadId, threadName, - InternalWorker, Worker, kPublicPort, kWebWorkerData, diff --git a/lib/module.js b/lib/module.js index 1217172afb3c..60ba0803dc55 100644 --- a/lib/module.js +++ b/lib/module.js @@ -6,7 +6,6 @@ const { setSourceMapsSupport, } = require('internal/source_map/source_map_cache'); const { Module } = require('internal/modules/cjs/loader'); -const { register } = require('internal/modules/esm/loader'); const { SourceMap, } = require('internal/source_map/source_map'); @@ -21,7 +20,6 @@ const { } = require('internal/modules/package_json_reader'); const { stripTypeScriptTypes } = require('internal/modules/typescript'); -Module.register = register; Module.constants = constants; Module.enableCompileCache = enableCompileCache; Module.findPackageJSON = findPackageJSON; diff --git a/lib/worker_threads.js b/lib/worker_threads.js index 622bef3f55c1..b6a0887784d1 100644 --- a/lib/worker_threads.js +++ b/lib/worker_threads.js @@ -3,7 +3,6 @@ const { defineLazyProperties } = require('internal/util'); const { - isInternalThread, isMainThread, SHARE_ENV, resourceLimits, @@ -33,7 +32,7 @@ const { } = require('internal/buffer'); module.exports = { - isInternalThread, + isInternalThread: false, isMainThread, MessagePort, MessageChannel, diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 9892f38d96bd..444d31337531 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -1362,7 +1362,7 @@ static Maybe DefaultImportMetaObjectInitializer(Realm* realm, } // Set a lazy getter of import.meta.resolve - only if the initializer is set, - // which is only the case when run on a non-loader-hook thread. + // which happens once the cascaded loader has been initialized. Local import_meta_resolve_initializer = realm->host_import_meta_resolve_initializer(); if (!import_meta_resolve_initializer.IsEmpty() && diff --git a/src/node_options.cc b/src/node_options.cc index 60a7001fadf5..facbe07d566b 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -859,11 +859,6 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { true); AddOption("--experimental-global-webcrypto", "", NoOp{}, kAllowedInEnvvar); AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvvar); - AddOption("--experimental-loader", - "use the specified module as a custom loader", - &EnvironmentOptions::userland_loaders, - kAllowedInEnvvar); - AddAlias("--loader", "--experimental-loader"); AddOption("--experimental-modules", "", NoOp{}, kAllowedInEnvvar); AddOption("--experimental-wasm-modules", "", NoOp{}, kAllowedInEnvvar); AddOption("--experimental-import-text", diff --git a/src/node_options.h b/src/node_options.h index aa6d1935e7cd..6f7be1dfd0d4 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -99,11 +99,6 @@ class DebugOptions : public Options { break_first_line = true; } - void DisableWaitOrBreakFirstLine() { - inspect_wait = false; - break_first_line = false; - } - bool wait_for_connect() const { return break_first_line || break_node_first_line || inspect_wait; } @@ -185,7 +180,6 @@ class EnvironmentOptions : public Options { std::vector experimental_test_tag_filter; std::vector coverage_include_pattern; std::vector coverage_exclude_pattern; - std::vector userland_loaders; std::vector watch_mode_paths; std::vector preload_cjs_modules; std::vector preload_esm_modules; diff --git a/src/node_watchdog.cc b/src/node_watchdog.cc index ddf986839d0f..50ae9d7075b0 100644 --- a/src/node_watchdog.cc +++ b/src/node_watchdog.cc @@ -305,7 +305,7 @@ std::string FormatProcessTimeoutDiagnostics(Environment* env) { // Running Workers keep the event loop alive through the Environment's own // task queue handle rather than through a HandleWrap. env->ForEachWorker([&](worker::Worker* worker) { - if (worker->is_internal() || !worker->has_ref() || worker->is_stopped()) { + if (!worker->has_ref() || worker->is_stopped()) { return; } std::string details = SPrintF("thread %d", worker->thread_id()); diff --git a/src/node_worker.cc b/src/node_worker.cc index 308d987680d7..9c8f215e094e 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -64,8 +64,7 @@ Worker::Worker(Environment* env, std::shared_ptr per_isolate_opts, std::vector&& exec_argv, std::shared_ptr env_vars, - const SnapshotData* snapshot_data, - const bool is_internal) + const SnapshotData* snapshot_data) : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_WORKER), per_isolate_opts_(per_isolate_opts), exec_argv_(exec_argv), @@ -74,8 +73,7 @@ Worker::Worker(Environment* env, name_(name), env_vars_(env_vars), embedder_preload_(env->embedder_preload()), - snapshot_data_(snapshot_data), - is_internal_(is_internal) { + snapshot_data_(snapshot_data) { Debug(this, "Creating new worker instance with thread id %llu", thread_id_.id); @@ -524,7 +522,6 @@ void Worker::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); THROW_IF_INSUFFICIENT_PERMISSIONS( env, permission::PermissionScope::kWorkerThreads, ""); - bool is_internal = args[5]->IsTrue(); Isolate* isolate = args.GetIsolate(); CHECK(args.IsConstructCall()); @@ -549,9 +546,9 @@ void Worker::New(const FunctionCallbackInfo& args) { url.append(value.out(), value.length()); } - if (!args[6]->IsNullOrUndefined()) { + if (!args[5]->IsNullOrUndefined()) { Utf8Value value( - isolate, args[6]->ToString(env->context()).FromMaybe(Local())); + isolate, args[5]->ToString(env->context()).FromMaybe(Local())); name.append(value.out(), value.length()); } @@ -709,16 +706,6 @@ void Worker::New(const FunctionCallbackInfo& args) { // is inherited but the load behavior must not be. per_isolate_opts->per_env->vfs_load = false; - // Internal workers should not wait for inspector frontend to connect or - // break on the first line of internal scripts. Module loader threads are - // essential to load user codes and must not be blocked by the inspector - // for internal scripts. - // Still, `--inspect-node` can break on the first line of internal scripts. - if (is_internal) { - per_isolate_opts->per_env->get_debug_options() - ->DisableWaitOrBreakFirstLine(); - } - const SnapshotData* snapshot_data = env->isolate_data()->snapshot_data(); Worker* worker = new Worker(env, @@ -728,8 +715,7 @@ void Worker::New(const FunctionCallbackInfo& args) { per_isolate_opts, std::move(exec_argv_out), env_vars, - snapshot_data, - is_internal); + snapshot_data); CHECK(args[3]->IsFloat64Array()); Local limit_info = args[3].As(); @@ -1474,13 +1460,6 @@ void IsMainThreadGetter(Local, info.GetReturnValue().Set(Environment::GetCurrent(info)->is_main_thread()); } -void IsInternalThreadGetter(Local, - const v8::PropertyCallbackInfo& info) { - Worker* worker = - Environment::GetCurrent(info)->isolate_data()->worker_context(); - info.GetReturnValue().Set(worker != nullptr && worker->is_internal()); -} - void OwnsProcessStateGetter(Local, const v8::PropertyCallbackInfo& info) { info.GetReturnValue().Set( @@ -1506,7 +1485,6 @@ void CreateWorkerPerIsolateProperties(IsolateData* isolate_data, lazy("threadId", ThreadIdGetter); lazy("threadName", ThreadNameGetter); lazy("isMainThread", IsMainThreadGetter); - lazy("isInternalThread", IsInternalThreadGetter); lazy("ownsProcessState", OwnsProcessStateGetter); lazy("resourceLimits", ResourceLimitsGetter); } @@ -1615,7 +1593,7 @@ void CreateWorkerPerContextProperties(Local target, Local unused, Local context, void* priv) { - // threadId, threadName, isMainThread, isInternalThread, ownsProcessState + // threadId, threadName, isMainThread, ownsProcessState // and resourceLimits are lazy properties of the per-isolate template (see // CreateWorkerPerIsolateProperties). NODE_DEFINE_CONSTANT(target, kMaxYoungGenerationSizeMb); @@ -1630,7 +1608,6 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(ThreadIdGetter); registry->Register(ThreadNameGetter); registry->Register(IsMainThreadGetter); - registry->Register(IsInternalThreadGetter); registry->Register(OwnsProcessStateGetter); registry->Register(ResourceLimitsGetter); registry->Register(Worker::New); diff --git a/src/node_worker.h b/src/node_worker.h index 03e546534c1b..4261db0c18fc 100644 --- a/src/node_worker.h +++ b/src/node_worker.h @@ -36,8 +36,7 @@ class Worker : public AsyncWrap { std::shared_ptr per_isolate_opts, std::vector&& exec_argv, std::shared_ptr env_vars, - const SnapshotData* snapshot_data, - const bool is_internal); + const SnapshotData* snapshot_data); ~Worker() override; // Run the worker. This is only called from the worker thread. @@ -64,7 +63,6 @@ class Worker : public AsyncWrap { bool is_stopped() const; const SnapshotData* snapshot_data() const { return snapshot_data_; } - bool is_internal() const { return is_internal_; } std::string_view name() const { return name_; } uint64_t thread_id() const { return thread_id_.id; } // Whether the Worker keeps the parent's event loop alive, see @@ -146,7 +144,6 @@ class Worker : public AsyncWrap { Environment* env_ = nullptr; const SnapshotData* snapshot_data_ = nullptr; - const bool is_internal_; friend class WorkerThreadData; }; diff --git a/test/doctool/test-doc-api-json.mjs b/test/doctool/test-doc-api-json.mjs index ba0469da50a1..104ef026c762 100644 --- a/test/doctool/test-doc-api-json.mjs +++ b/test/doctool/test-doc-api-json.mjs @@ -158,5 +158,5 @@ for await (const dirent of await fs.opendir(new URL('../../out/doc/api/', import assert.partialDeepStrictEqual(allExpectedKeys, findAllKeys(json)); } -assert.strictEqual(numberOfDeprecatedSections, 48); // Increase this number every time a new API is deprecated. -assert.strictEqual(numberOfRemovedAPIs, 47); // Increase this number every time a section is marked as removed. +assert.strictEqual(numberOfDeprecatedSections, 47); // Increase this number every time a new API is deprecated. +assert.strictEqual(numberOfRemovedAPIs, 49); // Increase this number every time a section is marked as removed. diff --git a/test/es-module/test-esm-example-loader.mjs b/test/es-module/test-esm-example-loader.mjs deleted file mode 100644 index b85de4e64c4a..000000000000 --- a/test/es-module/test-esm-example-loader.mjs +++ /dev/null @@ -1,6 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/example-loader.mjs -/* eslint-disable node-core/require-common-first, node-core/required-modules */ -import assert from 'assert'; -import ok from '../fixtures/es-modules/test-esm-ok.mjs'; - -assert(ok); diff --git a/test/es-module/test-esm-experimental-warnings.mjs b/test/es-module/test-esm-experimental-warnings.mjs deleted file mode 100644 index 7b3ec4b942ee..000000000000 --- a/test/es-module/test-esm-experimental-warnings.mjs +++ /dev/null @@ -1,50 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: warn for obsolete hooks provided', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should not print warnings when no experimental features are enabled or used', async () => { - const { code, signal, stderr } = await spawnPromisified(execPath, [ - '--input-type=module', - '--eval', - `import ${JSON.stringify(fixtures.fileURL('es-module-loaders', 'module-named-exports.mjs'))}`, - ]); - - assert.doesNotMatch( - stderr, - /ExperimentalWarning/, - new Error('No experimental warning(s) should be emitted when no experimental feature is enabled') - ); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - describe('experimental warnings for enabled experimental feature', () => { - for ( - const [experiment, ...args] of [ - [ - /`--experimental-loader` may be removed in the future/, - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'hooks-custom.mjs'), - ], - ] - ) { - it(`should print for ${experiment.toString().replaceAll('/', '')}`, async () => { - const { code, signal, stderr } = await spawnPromisified(execPath, [ - ...args, - '--input-type=module', - '--eval', - `import ${JSON.stringify(fixtures.fileURL('es-module-loaders', 'module-named-exports.mjs'))}`, - ]); - - assert.match(stderr, /ExperimentalWarning/); - assert.match(stderr, experiment); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - } - }); -}); diff --git a/test/es-module/test-esm-import-assertion-warning.mjs b/test/es-module/test-esm-import-assertion-warning.mjs deleted file mode 100644 index 2f9b7348a2d9..000000000000 --- a/test/es-module/test-esm-import-assertion-warning.mjs +++ /dev/null @@ -1,42 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; - -await Promise.all([ - // Using importAssertions in the resolve hook should warn but still work. - `data:text/javascript,export ${encodeURIComponent(function resolve() { - return { shortCircuit: true, url: 'data:application/json,1', importAssertions: { type: 'json' } }; - })}`, - // Using importAssertions on the context object of the resolve hook should warn but still work. - `data:text/javascript,export ${encodeURIComponent(function resolve(s, c, n) { - const type = c.importAssertions.type; - return { shortCircuit: true, url: 'data:application/json,1', importAttributes: { type: type ?? 'json' } }; - })}`, - // Setting importAssertions on the context object of the load hook should warn but still work. - `data:text/javascript,export ${encodeURIComponent(function load(u, c, n) { - c.importAssertions = { type: 'json' }; - return n('data:application/json,1', c); - })}`, - // Creating a new context object with importAssertions in the load hook should warn but still work. - `data:text/javascript,export ${encodeURIComponent(function load(u, c, n) { - return n('data:application/json,1', { importAssertions: { type: 'json' } }); - })}`, -].map(async (loaderURL) => { - const { stdout, stderr, code } = await spawnPromisified(execPath, [ - '--input-type=module', - '--eval', ` - import assert from 'node:assert'; - import { register } from 'node:module'; - - register(${JSON.stringify(loaderURL)}); - - assert.deepStrictEqual( - { ...await import('data:') }, - { default: 1 } - );`, - ]); - - assert.match(stderr, /Use `importAttributes` instead of `importAssertions`/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); -})); diff --git a/test/es-module/test-esm-import-defers-evaluation.js b/test/es-module/test-esm-import-defers-evaluation.js new file mode 100644 index 000000000000..0679493fe961 --- /dev/null +++ b/test/es-module/test-esm-import-defers-evaluation.js @@ -0,0 +1,16 @@ +'use strict'; +// Tests that import() never evaluates the module before returning to its +// caller, even though loading and linking are synchronous. +const common = require('../common'); +const assert = require('node:assert'); + +const key = '__esmImportDefersEvaluation'; +const url = `data:text/javascript,globalThis.${key} = true; export default 1;`; + +const promise = import(url); +assert.strictEqual(globalThis[key], undefined); +promise.then(common.mustCall((namespace) => { + assert.strictEqual(globalThis[key], true); + assert.strictEqual(namespace.default, 1); + delete globalThis[key]; +})); diff --git a/test/es-module/test-esm-initialization.mjs b/test/es-module/test-esm-initialization.mjs deleted file mode 100644 index c86d3b439496..000000000000 --- a/test/es-module/test-esm-initialization.mjs +++ /dev/null @@ -1,30 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: ensure initialization happens only once', { concurrency: !process.env.TEST_PARALLEL }, () => { - it(async () => { - const { code, stderr, stdout } = await spawnPromisified(execPath, [ - '--experimental-import-meta-resolve', - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--no-warnings', - fixtures.path('es-modules', 'runmain.mjs'), - ]); - - assert.strictEqual(stderr, ''); - /** - * resolveHookRunCount = 2: - * 1. fixtures/…/runmain.mjs - * 2. node:module (imported by fixtures/…/runmain.mjs) - * 3. doesnt-matter.mjs (first import.meta.resolve call) - * 4. fixtures/…/runmain.mjs (entry point) - * 5. doesnt-matter.mjs (second import.meta.resolve call) - */ - assert.strictEqual(stdout.match(/resolve passthru/g)?.length, 5); - assert.strictEqual(code, 0); - }); -}); diff --git a/test/es-module/test-esm-loader-chaining.mjs b/test/es-module/test-esm-loader-chaining.mjs deleted file mode 100644 index 6c266b9da3d8..000000000000 --- a/test/es-module/test-esm-loader-chaining.mjs +++ /dev/null @@ -1,507 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -const setupArgs = [ - '--no-warnings', - '--input-type=module', - '--eval', -]; -const commonInput = 'import os from "node:os"; console.log(os)'; -const commonArgs = [ - ...setupArgs, - commonInput, -]; - -describe('ESM: loader chaining', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should load unadulterated source when there are no loaders', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - ...setupArgs, - 'import fs from "node:fs"; console.log(typeof fs?.constants?.F_OK )', - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /number/); // node:fs is an object - assert.strictEqual(code, 0); - }); - - it('should load properly different source when only load changes something', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /load passthru/); - assert.match(stdout, /resolve passthru/); - assert.match(stdout, /foo/); - assert.strictEqual(code, 0); - }); - - it('should result in proper output from multiple changes in resolve hooks', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-foo.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /resolve 42/); // It did go thru resolve-42 - assert.match(stdout, /foo/); // LIFO, so resolve-foo won - assert.strictEqual(code, 0); - }); - - it('should respect modified context within resolve chain', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-receiving-modified-context.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passing-modified-context.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /bar/); - assert.strictEqual(code, 0); - }); - - it('should accept only the correct arguments', async () => { - const { stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-log-args.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-with-too-many-args.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stdout, /^resolve arg count: 3$/m); - assert.match(stdout, /specifier: 'node:os'/); - assert.match(stdout, /next: \[AsyncFunction: nextResolve\]/); - - assert.match(stdout, /^load arg count: 3$/m); - assert.match(stdout, /url: 'node:os'/); - assert.match(stdout, /next: \[AsyncFunction: nextLoad\]/); - }); - - it('should result in proper output from multiple changes in resolve hooks', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-foo.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /resolve foo/); // It did go thru resolve-foo - assert.match(stdout, /42/); // LIFO, so resolve-42 won - assert.strictEqual(code, 0); - }); - - it('should provide the correct "next" fn when multiple calls to next within same loader', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-foo.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-multiple-next-calls.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - const countFoos = stdout.match(/resolve foo/g)?.length; - - assert.strictEqual(stderr, ''); - assert.strictEqual(countFoos, 2); - assert.strictEqual(code, 0); - }); - - it('should use the correct `name` for next\'s function', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /next: nextResolve/); - assert.strictEqual(code, 0); - }); - - it('should throw for incomplete resolve chain, citing errant loader & hook', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-incomplete.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - assert.match(stdout, /resolve passthru/); - assert.match(stderr, /ERR_LOADER_CHAIN_INCOMPLETE/); - assert.match(stderr, /loader-resolve-incomplete\.mjs/); - assert.match(stderr, /'resolve'/); - assert.strictEqual(code, 1); - }); - - it('should NOT throw when nested resolve hook signaled a short circuit', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-next-modified.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout.trim(), 'foo'); - assert.strictEqual(code, 0); - }); - - it('should NOT throw when nested load hook signaled a short circuit', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-next-modified.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /421/); - assert.strictEqual(code, 0); - }); - - it('should allow loaders to influence subsequent loader resolutions', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-strip-xxx.mjs'), - '--loader', - 'xxx/loader-resolve-strip-yyy.mjs', - ...commonArgs, - ], - { encoding: 'utf8', cwd: fixtures.path('es-module-loaders') }, - ); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - }); - - it('should throw when the resolve chain is broken', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-incomplete.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.doesNotMatch(stdout, /resolve passthru/); - assert.match(stderr, /ERR_LOADER_CHAIN_INCOMPLETE/); - assert.match(stderr, /loader-resolve-incomplete\.mjs/); - assert.match(stderr, /'resolve'/); - assert.strictEqual(code, 1); - }); - - it('should throw for incomplete load chain, citing errant loader & hook', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-incomplete.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stdout, /load passthru/); - assert.match(stderr, /ERR_LOADER_CHAIN_INCOMPLETE/); - assert.match(stderr, /loader-load-incomplete\.mjs/); - assert.match(stderr, /'load'/); - assert.strictEqual(code, 1); - }); - - it('should throw when the load chain is broken', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-incomplete.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.doesNotMatch(stdout, /load passthru/); - assert.match(stderr, /ERR_LOADER_CHAIN_INCOMPLETE/); - assert.match(stderr, /loader-load-incomplete\.mjs/); - assert.match(stderr, /'load'/); - assert.strictEqual(code, 1); - }); - - it('should throw when invalid `specifier` argument passed to `nextResolve`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-bad-next-specifier.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(code, 1); - assert.match(stderr, /ERR_INVALID_ARG_TYPE/); - assert.match(stderr, /loader-resolve-bad-next-specifier\.mjs/); - assert.match(stderr, /'resolve' hook's nextResolve\(\) specifier/); - }); - - it('should throw when resolve hook is invalid', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-null-return.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(code, 1); - assert.match(stderr, /ERR_INVALID_RETURN_VALUE/); - assert.match(stderr, /loader-resolve-null-return\.mjs/); - assert.match(stderr, /'resolve' hook's nextResolve\(\)/); - assert.match(stderr, /an object/); - assert.match(stderr, /got null/); - }); - - it('should throw when invalid `context` argument passed to `nextResolve`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-bad-next-context.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stderr, /ERR_INVALID_ARG_TYPE/); - assert.match(stderr, /loader-resolve-bad-next-context\.mjs/); - assert.match(stderr, /'resolve' hook's nextResolve\(\) context/); - assert.strictEqual(code, 1); - }); - - it('should throw when load hook is invalid', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-null-return.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(code, 1); - assert.match(stderr, /ERR_INVALID_RETURN_VALUE/); - assert.match(stderr, /loader-load-null-return\.mjs/); - assert.match(stderr, /'load' hook's nextLoad\(\)/); - assert.match(stderr, /an object/); - assert.match(stderr, /got null/); - }); - - it('should throw when invalid `url` argument passed to `nextLoad`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-bad-next-url.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stderr, /ERR_INVALID_ARG_TYPE/); - assert.match(stderr, /loader-load-bad-next-url\.mjs/); - assert.match(stderr, /'load' hook's nextLoad\(\) url/); - assert.strictEqual(code, 1); - }); - - it('should throw when invalid `url` argument passed to `nextLoad`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-impersonating-next-url.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stderr, /ERR_INVALID_ARG_VALUE/); - assert.match(stderr, /loader-load-impersonating-next-url\.mjs/); - assert.match(stderr, /'load' hook's nextLoad\(\) url/); - assert.strictEqual(code, 1); - }); - - it('should throw when invalid `context` argument passed to `nextLoad`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-bad-next-context.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - assert.match(stderr, /ERR_INVALID_ARG_TYPE/); - assert.match(stderr, /loader-load-bad-next-context\.mjs/); - assert.match(stderr, /'load' hook's nextLoad\(\) context/); - assert.strictEqual(code, 1); - }); - - it('should allow loaders to influence subsequent loader `import()` calls in `resolve`', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-strip-xxx.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-dynamic-import.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - assert.strictEqual(stderr, ''); - assert.match(stdout, /resolve dynamic import/); // It did go thru resolve-dynamic - assert.strictEqual(code, 0); - }); - - it('should allow loaders to influence subsequent loader `import()` calls in `load`', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-strip-xxx.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-dynamic-import.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - assert.strictEqual(stderr, ''); - assert.match(stdout, /load dynamic import/); // It did go thru load-dynamic - assert.strictEqual(code, 0); - }); -}); diff --git a/test/es-module/test-esm-loader-custom-condition.mjs b/test/es-module/test-esm-loader-custom-condition.mjs deleted file mode 100644 index 075e4fe2b660..000000000000 --- a/test/es-module/test-esm-loader-custom-condition.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-with-custom-condition.mjs -import '../common/index.mjs'; -import assert from 'assert'; -import util from 'util'; - -import * as ns from '../fixtures/es-modules/conditional-exports.mjs'; - -assert.deepStrictEqual({ ...ns }, { default: 'from custom condition' }); - -assert.strictEqual( - util.inspect(ns, { showHidden: false }), - "[Module: null prototype] { default: 'from custom condition' }" -); - -assert.strictEqual( - util.inspect(ns, { showHidden: true }), - '[Module: null prototype] {\n' + - " default: 'from custom condition',\n" + - " [Symbol(Symbol.toStringTag)]: 'Module'\n" + - '}' -); diff --git a/test/es-module/test-esm-loader-default-resolver.mjs b/test/es-module/test-esm-loader-default-resolver.mjs index 2a69010e0504..9f836aa56e0f 100644 --- a/test/es-module/test-esm-loader-default-resolver.mjs +++ b/test/es-module/test-esm-loader-default-resolver.mjs @@ -5,51 +5,6 @@ import { execPath } from 'node:process'; import { describe, it } from 'node:test'; describe('default resolver', () => { - // In these tests `byop` is an acronym for "bring your own protocol", and is the - // protocol our byop-dummy-loader.mjs can load - it('should accept foreign schemas without exception (e.g. byop://something/or-other)', async () => { - const { code, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/byop-dummy-loader.mjs'), - '--input-type=module', - '--eval', - "import 'byop://1/index.mjs'", - ]); - assert.strictEqual(code, 0); - assert.strictEqual(stdout.trim(), 'index.mjs!'); - assert.strictEqual(stderr, ''); - }); - - it('should resolve foreign schemas by doing regular url absolutization', async () => { - const { code, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/byop-dummy-loader.mjs'), - '--input-type=module', - '--eval', - "import 'byop://1/index2.mjs'", - ]); - assert.strictEqual(code, 0); - assert.strictEqual(stdout.trim(), '42'); - assert.strictEqual(stderr, ''); - }); - - // In this test, `byoe` is an acronym for "bring your own extension" - it('should accept foreign extensions without exception (e.g. ..//something.byoe)', async () => { - const { code, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/byop-dummy-loader.mjs'), - '--input-type=module', - '--eval', - "import 'byop://1/index.byoe'", - ]); - assert.strictEqual(code, 0); - assert.strictEqual(stdout.trim(), 'index.byoe!'); - assert.strictEqual(stderr, ''); - }); - it('should identify the parent module of an invalid URL host in import specifier', async () => { if (process.platform === 'win32') return; diff --git a/test/es-module/test-esm-loader-dependency.mjs b/test/es-module/test-esm-loader-dependency.mjs deleted file mode 100644 index 54327b478bf4..000000000000 --- a/test/es-module/test-esm-loader-dependency.mjs +++ /dev/null @@ -1,5 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-with-dep.mjs -/* eslint-disable node-core/require-common-first, node-core/required-modules */ -import '../fixtures/es-modules/test-esm-ok.mjs'; - -// We just test that this module doesn't fail loading diff --git a/test/es-module/test-esm-loader-event-loop.mjs b/test/es-module/test-esm-loader-event-loop.mjs deleted file mode 100644 index d94e55148d85..000000000000 --- a/test/es-module/test-esm-loader-event-loop.mjs +++ /dev/null @@ -1,12 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/hooks-custom.mjs -import { mustCall } from '../common/index.mjs'; - -const done = mustCall(); - - -// Test that the process doesn't exit because of a caught exception thrown as part of dynamic import(). -for (let i = 0; i < 10; i++) { - await import('nonexistent/file.mjs').catch(() => {}); -} - -done(); diff --git a/test/es-module/test-esm-loader-http-imports.mjs b/test/es-module/test-esm-loader-http-imports.mjs deleted file mode 100644 index 96bfffe5b13f..000000000000 --- a/test/es-module/test-esm-loader-http-imports.mjs +++ /dev/null @@ -1,91 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import fixtures from '../common/fixtures.js'; -import assert from 'node:assert'; -import http from 'node:http'; -import path from 'node:path'; -import { execPath } from 'node:process'; -import { promisify } from 'node:util'; -import { describe, it, after } from 'node:test'; - - -const files = { - 'main.mjs': 'export * from "./lib.mjs";', - 'lib.mjs': 'export { sum } from "./sum.mjs";', - 'sum.mjs': 'export function sum(a, b) { return a + b }', - 'console.mjs': ` - import { sum } from './sum.mjs'; - globalThis.sum = sum; - console.log("loaded over http"); - `, -}; - -const requestListener = ({ url }, rsp) => { - const filename = path.basename(url); - const content = files[filename]; - - if (content) { - return rsp - .writeHead(200, { 'Content-Type': 'application/javascript' }) - .end(content); - } - - return rsp - .writeHead(404) - .end(); -}; - -// Leave closing idle connections to the client, so that the loader never -// reuses a keep-alive socket the server has just closed. -const server = http.createServer({ keepAliveTimeout: 0 }, requestListener); - -await promisify(server.listen.bind(server))({ - host: '127.0.0.1', - port: 0, -}); - -const { - address: host, - port, -} = server.address(); - -describe('ESM: http import via loader', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should load using --import flag', async () => { - // ! MUST NOT use spawnSync to avoid blocking the event loop - const { code, signal, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--no-warnings', - '--loader', - fixtures.fileURL('es-module-loaders', 'http-loader.mjs'), - '--import', `http://${host}:${port}/console.mjs`, - '--eval', - 'console.log(sum(1, 2))', - ] - ); - assert.strictEqual(stderr, ''); - assert.match(stdout, /loaded over http\r?\n3/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - it('should load using import inside --eval code', async () => { - // ! MUST NOT use spawnSync to avoid blocking the event loop - const { code, signal, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--no-warnings', - '--loader', - fixtures.fileURL('es-module-loaders', 'http-loader.mjs'), - '--input-type=module', - '--eval', - `import * as main from 'http://${host}:${port}/main.mjs'; console.log(main)`, - ] - ); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, '[Module: null prototype] { sum: [Function: sum] }\n'); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - after(() => server.close()); -}); diff --git a/test/es-module/test-esm-loader-invalid-format.mjs b/test/es-module/test-esm-loader-invalid-format.mjs deleted file mode 100644 index 5a16381e5889..000000000000 --- a/test/es-module/test-esm-loader-invalid-format.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-invalid-format.mjs -import { expectsError, mustCall } from '../common/index.mjs'; -import assert from 'assert'; - -import('../fixtures/es-modules/test-esm-ok.mjs') -.then(assert.fail, expectsError({ - code: 'ERR_UNKNOWN_MODULE_FORMAT', - message: /Unknown module format: esm/, -})) -.then(mustCall()); diff --git a/test/es-module/test-esm-loader-invalid-url.mjs b/test/es-module/test-esm-loader-invalid-url.mjs deleted file mode 100644 index 1ba7c621f7e9..000000000000 --- a/test/es-module/test-esm-loader-invalid-url.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-invalid-url.mjs -import { expectsError, mustCall } from '../common/index.mjs'; -import assert from 'assert'; - -import('../fixtures/es-modules/test-esm-ok.mjs') -.then(assert.fail, (error) => { - expectsError({ code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' })(error); - assert.match(error.message, /loader-invalid-url\.mjs/); -}) -.then(mustCall()); diff --git a/test/es-module/test-esm-loader-mock.mjs b/test/es-module/test-esm-loader-mock.mjs deleted file mode 100644 index cdf56d85415b..000000000000 --- a/test/es-module/test-esm-loader-mock.mjs +++ /dev/null @@ -1,42 +0,0 @@ -import '../common/index.mjs'; -import assert from 'node:assert/strict'; -import { mock } from '../fixtures/es-module-loaders/mock.mjs'; - -mock('node:events', { - EventEmitter: 'This is mocked!', -}); - -// This resolves to node:events -// It is intercepted by mock-loader and doesn't return the normal value -assert.deepStrictEqual(await import('events'), Object.defineProperty({ - __proto__: null, - EventEmitter: 'This is mocked!', -}, Symbol.toStringTag, { - enumerable: false, - value: 'Module', -})); - -const mutator = mock('node:events', { - EventEmitter: 'This is mocked v2!', -}); - -// It is intercepted by mock-loader and doesn't return the normal value. -// This is resolved separately from the import above since the specifiers -// are different. -const mockedV2 = await import('node:events'); -assert.deepStrictEqual(mockedV2, Object.defineProperty({ - __proto__: null, - EventEmitter: 'This is mocked v2!', -}, Symbol.toStringTag, { - enumerable: false, - value: 'Module', -})); - -mutator.EventEmitter = 'This is mocked v3!'; -assert.deepStrictEqual(mockedV2, Object.defineProperty({ - __proto__: null, - EventEmitter: 'This is mocked v3!', -}, Symbol.toStringTag, { - enumerable: false, - value: 'Module', -})); diff --git a/test/es-module/test-esm-loader-modulemap.js b/test/es-module/test-esm-loader-modulemap.js index ba0358368ec1..6dada059c4af 100644 --- a/test/es-module/test-esm-loader-modulemap.js +++ b/test/es-module/test-esm-loader-modulemap.js @@ -4,7 +4,7 @@ require('../common'); const assert = require('assert'); -const { createModuleLoader } = require('internal/modules/esm/loader'); +const { ModuleLoader } = require('internal/modules/esm/loader'); const { LoadCache, ResolveCache } = require('internal/modules/esm/module_map'); const { ModuleJob } = require('internal/modules/esm/module_job'); const createDynamicModule = require( @@ -16,7 +16,7 @@ const jsonModuleDataUrl = 'data:application/json,""'; const stubJsModule = createDynamicModule([], ['default'], jsModuleDataUrl); const stubJsonModule = createDynamicModule([], ['default'], jsonModuleDataUrl); -const loader = createModuleLoader(); +const loader = new ModuleLoader(); const jsModuleJob = new ModuleJob(loader, jsModuleDataUrl, {}, stubJsModule.module); const jsonModuleJob = new ModuleJob(loader, jsonModuleDataUrl, { type: 'json' }, stubJsonModule.module); diff --git a/test/es-module/test-esm-loader-not-found.mjs b/test/es-module/test-esm-loader-not-found.mjs deleted file mode 100644 index 2abaf3078d11..000000000000 --- a/test/es-module/test-esm-loader-not-found.mjs +++ /dev/null @@ -1,24 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: nonexistent loader', () => { - it('should throw', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - 'i-dont-exist', - fixtures.path('print-error-message.js'), - ]); - - assert.notStrictEqual(code, 0); - - // Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'i-dont-exist' imported from - assert.match(stderr, /ERR_MODULE_NOT_FOUND/); - assert.match(stderr, /'i-dont-exist'/); - - assert.ok(!stderr.includes('Bad command or file name')); - }); -}); diff --git a/test/es-module/test-esm-loader-programmatically.mjs b/test/es-module/test-esm-loader-programmatically.mjs deleted file mode 100644 index dd25e3f2430e..000000000000 --- a/test/es-module/test-esm-loader-programmatically.mjs +++ /dev/null @@ -1,251 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -// This test ensures that the register function can register loaders -// programmatically. - -const commonArgs = [ - '--no-warnings', - '--input-type=module', - '--loader=data:text/javascript,', -]; - -const commonEvals = { - import: (module) => `await import(${JSON.stringify(module)});`, - register: (loader, parentURL = 'file:///') => `register(${JSON.stringify(loader)}, ${JSON.stringify(parentURL)});`, - dynamicImport: (module) => `await import(${JSON.stringify(`data:text/javascript,${encodeURIComponent(module)}`)});`, - staticImport: (module) => `import ${JSON.stringify(`data:text/javascript,${encodeURIComponent(module)}`)};`, -}; - -describe('ESM: programmatically register loaders', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('works with only a dummy CLI argument', async () => { - const parentURL = fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'); - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')) + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - `register(${JSON.stringify('./loader-resolve-passthru.mjs')}, ${JSON.stringify({ parentURL })});` + - `register(${JSON.stringify('./loader-load-passthru.mjs')}, ${JSON.stringify({ parentURL })});` + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /resolve passthru/); - assert.match(lines[2], /load passthru/); - assert.match(lines[3], /load passthru/); - assert.match(lines[4], /Hello from dynamic import/); - - assert.strictEqual(lines[5], ''); - }); - - describe('registering via --import', { concurrency: !process.env.TEST_PARALLEL }, () => { - for (const moduleType of ['mjs', 'cjs']) { - it(`should programmatically register a loader from a ${moduleType.toUpperCase()} file`, async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--import', fixtures.fileURL('es-module-loaders', `register-loader.${moduleType}`).href, - '--eval', commonEvals.staticImport('console.log("entry point")'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const [ - passthruStdout, - entryPointStdout, - ] = stdout.split('\n'); - - assert.match(passthruStdout, /resolve passthru/); - assert.match(entryPointStdout, /entry point/); - }); - } - }); - - it('programmatically registered loaders are appended to an existing chaining', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /resolve passthru/); - assert.match(lines[2], /load passthru/); - assert.match(lines[3], /Hello from dynamic import/); - - assert.strictEqual(lines[4], ''); - }); - - it('works registering loaders across files', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - commonEvals.import(fixtures.fileURL('es-module-loaders', 'register-programmatically-loader-load.mjs')) + - commonEvals.import(fixtures.fileURL('es-module-loaders', 'register-programmatically-loader-resolve.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /load passthru/); - assert.match(lines[2], /Hello from dynamic import/); - - assert.strictEqual(lines[3], ''); - }); - - it('works registering loaders across virtual files', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - commonEvals.import(fixtures.fileURL('es-module-loaders', 'register-programmatically-loader-load.mjs')) + - commonEvals.dynamicImport( - commonEvals.import(fixtures.fileURL('es-module-loaders', 'register-programmatically-loader-resolve.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /load passthru/); - assert.match(lines[2], /Hello from dynamic import/); - - assert.strictEqual(lines[3], ''); - }); - - it('works registering the same loaders more them once', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')) + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')) + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /resolve passthru/); - assert.match(lines[2], /load passthru/); - assert.match(lines[3], /load passthru/); - assert.match(lines[4], /Hello from dynamic import/); - - assert.strictEqual(lines[5], ''); - }); - - it('works registering loaders as package name', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register('resolve', fixtures.fileURL('es-module-loaders', 'package.json')) + - commonEvals.register('load', fixtures.fileURL('es-module-loaders', 'package.json')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - // Resolve occurs twice because it is first used to resolve the `load` loader - // _AND THEN_ the `register` module. - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /resolve passthru/); - assert.match(lines[2], /load passthru/); - assert.match(lines[3], /Hello from dynamic import/); - - assert.strictEqual(lines[4], ''); - }); - - it('works without a CLI flag', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--input-type=module', - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /load passthru/); - assert.match(lines[1], /Hello from dynamic import/); - - assert.strictEqual(lines[2], ''); - }); - - it('does not work with a loader specifier that does not exist', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register('./not-found.mjs', import.meta.url) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - assert.match(stderr, /ERR_MODULE_NOT_FOUND/); - }); - - it('does not work with a loader that got syntax errors', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'syntax-error.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - assert.match(stderr, /SyntaxError/); - }); -}); diff --git a/test/es-module/test-esm-loader-resolve-type.mjs b/test/es-module/test-esm-loader-resolve-type.mjs deleted file mode 100644 index 7dcc65a10c09..000000000000 --- a/test/es-module/test-esm-loader-resolve-type.mjs +++ /dev/null @@ -1,48 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as tmpdir from '../common/tmpdir.js'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { mkdir, rm, cp } from 'node:fs/promises'; -import { execPath } from 'node:process'; - -tmpdir.refresh(); - -const base = tmpdir.fileURL(`test-esm-loader-resolve-type-${(Math.random() * Date.now()).toFixed(0)}`); -const moduleName = 'module-counter-by-type'; -const moduleURL = new URL(`${base}/node_modules/${moduleName}`); -try { - await mkdir(moduleURL, { recursive: true }); - await cp( - fixtures.path('es-modules', 'module-counter-by-type'), - moduleURL, - { recursive: true } - ); - - const output = await spawnPromisified( - execPath, - [ - '--no-warnings', - '--input-type=module', - '--eval', - `import { getModuleTypeStats } from ${JSON.stringify(fixtures.fileURL('es-module-loaders', 'hook-resolve-type.mjs'))}; - const before = getModuleTypeStats(); - await import(${JSON.stringify(moduleName)}); - const after = getModuleTypeStats(); - console.log(JSON.stringify({ before, after }));`, - ], - { cwd: base }, - ); - - assert.deepStrictEqual(output, { - code: 0, - signal: null, - stderr: '', - stdout: JSON.stringify({ - before: { importedESM: 0, importedCJS: 0 }, - // Dynamic import in the eval script should increment ESM counter but not CJS counter - after: { importedESM: 1, importedCJS: 0 }, - }) + '\n', - }); -} finally { - await rm(base, { recursive: true, force: true }); -} diff --git a/test/es-module/test-esm-loader-spawn-promisified.mjs b/test/es-module/test-esm-loader-spawn-promisified.mjs deleted file mode 100644 index 2f27f7850f64..000000000000 --- a/test/es-module/test-esm-loader-spawn-promisified.mjs +++ /dev/null @@ -1,304 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -describe('Loader hooks throwing errors', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('throws on nonexistent modules', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "nonexistent/file.mjs"', - ]); - - assert.match(stderr, /ERR_MODULE_NOT_FOUND/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on unknown extensions', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import ${JSON.stringify(fixtures.fileURL('/es-modules/file.unknown'))}`, - ]); - - assert.match(stderr, /ERR_UNKNOWN_FILE_EXTENSION/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on invalid return values', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/badReturnVal.mjs"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on boolean false', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/format.false"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_PROPERTY_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - it('throws on boolean true', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/format.true"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_PROPERTY_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on invalid returned object', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/badReturnFormatVal.mjs"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_PROPERTY_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on unsupported format', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/unsupportedReturnFormatVal.mjs"', - ]); - - assert.match(stderr, /ERR_UNKNOWN_MODULE_FORMAT/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on invalid format property type', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/badReturnSourceVal.mjs"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_PROPERTY_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('rejects dynamic imports for all of the error cases checked above', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await Promise.allSettled([ - import('nonexistent/file.mjs'), - import(${JSON.stringify(fixtures.fileURL('/es-modules/file.unknown'))}), - import('esmHook/badReturnVal.mjs'), - import('esmHook/format.false'), - import('esmHook/format.true'), - import('esmHook/badReturnFormatVal.mjs'), - import('esmHook/unsupportedReturnFormatVal.mjs'), - import('esmHook/badReturnSourceVal.mjs'), - ]).then((results) => { - assert.strictEqual(results.every((result) => result.status === 'rejected'), true); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); -}); - -describe('Loader hooks parsing modules', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('can parse .js files as ESM', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import(${JSON.stringify(fixtures.fileURL('/es-module-loaders/js-as-esm.js'))}) - .then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(parsedModule.namedExport, 'named-export'); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('can define .ext files as ESM', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import(${JSON.stringify(fixtures.fileURL('/es-modules/file.ext'))}) - .then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - const { default: defaultExport } = parsedModule; - assert.strictEqual(typeof defaultExport, 'function'); - assert.strictEqual(defaultExport.name, 'iAmReal'); - assert.strictEqual(defaultExport(), true); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('can predetermine the format in the custom loader resolve hook', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import('esmHook/preknownFormat.pre') - .then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(parsedModule.default, 'hello world'); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('can provide source for a nonexistent file', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import('esmHook/virtual.mjs') - .then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(typeof parsedModule.default, 'undefined'); - assert.strictEqual(parsedModule.message, 'WOOHOO!'); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('ensures that loaders have a separate context from userland', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import(${JSON.stringify(fixtures.fileURL('/es-modules/stateful.mjs'))}) - .then(({ default: count }) => { - assert.strictEqual(count(), 1); - });`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('ensures that user loaders are not bound to the internal loader', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/loader-this-value-inside-hook-functions.mjs'), - '--input-type=module', - '--eval', - ';', // Actual test is inside the loader module. - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('throw maximum call stack error on the loader', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'await import("esmHook/maximumCallStack.mjs")', - ]); - - assert(stderr.includes('Maximum call stack size exceeded')); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); -}); diff --git a/test/es-module/test-esm-loader-stringify-text.mjs b/test/es-module/test-esm-loader-stringify-text.mjs deleted file mode 100644 index 8502375b31aa..000000000000 --- a/test/es-module/test-esm-loader-stringify-text.mjs +++ /dev/null @@ -1,66 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/string-sources.mjs -import { mustCall } from '../common/index.mjs'; -import assert from 'assert'; - -assert.rejects( - import('test:Array'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); -import('test:ArrayBuffer').then( - mustCall(), -); -import('test:BigInt64Array').then( - mustCall(), -); -import('test:BigUint64Array').then( - mustCall(), -); -import('test:Float32Array').then( - mustCall(), -); -import('test:Float64Array').then( - mustCall(), -); -import('test:Int8Array').then( - mustCall(), -); -import('test:Int16Array').then( - mustCall(), -); -import('test:Int32Array').then( - mustCall(), -); -assert.rejects( - import('test:null'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); -assert.rejects( - import('test:Object'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); -import('test:SharedArrayBuffer').then( - mustCall(), -); -import('test:string').then( - mustCall(), -); -assert.rejects( - import('test:String'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); -import('test:Uint8ClampedArray').then( - mustCall(), -); -import('test:Uint16Array').then( - mustCall(), -); -import('test:Uint32Array').then( - mustCall(), -); -import('test:Uint8Array').then( - mustCall(), -); -assert.rejects( - import('test:undefined'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); diff --git a/test/es-module/test-esm-loader-thenable.mjs b/test/es-module/test-esm-loader-thenable.mjs deleted file mode 100644 index d26ba7d476a5..000000000000 --- a/test/es-module/test-esm-loader-thenable.mjs +++ /dev/null @@ -1,43 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: thenable loader hooks', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should behave as a normal promise resolution', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'thenable-load-hook.mjs').href, - fixtures.path('es-modules', 'test-esm-ok.mjs'), - ]); - - assert.strictEqual(code, 0); - assert.ok(!stderr.includes('must not call')); - }); - - it('should crash the node process rejection with an error', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'thenable-load-hook-rejected.mjs').href, - fixtures.path('es-modules', 'test-esm-ok.mjs'), - ]); - - assert.notStrictEqual(code, 0); - assert.match(stderr, /\sError: must crash the process\r?\n/); - assert.ok(!stderr.includes('must not call')); - }); - - it('should just reject without an error (but NOT crash the node process)', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'thenable-load-hook-rejected-no-arguments.mjs').href, - fixtures.path('es-modules', 'test-esm-ok.mjs'), - ]); - - assert.notStrictEqual(code, 0); - assert.match(stderr, /\sundefined\r?\n/); - assert.ok(!stderr.includes('must not call')); - }); -}); diff --git a/test/es-module/test-esm-loader-with-source.mjs b/test/es-module/test-esm-loader-with-source.mjs deleted file mode 100644 index 41dca12dfc6b..000000000000 --- a/test/es-module/test-esm-loader-with-source.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/preset-cjs-source.mjs -import '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'assert'; - -const { default: existingFileSource } = await import(fixtures.fileURL('es-modules', 'cjs-file.cjs')); -const { default: noSuchFileSource } = await import(new URL('./no-such-file.cjs', import.meta.url)); - -assert.strictEqual(existingFileSource, 'no .cjs file was read to get this source'); -assert.strictEqual(noSuchFileSource, 'no .cjs file was read to get this source'); diff --git a/test/es-module/test-esm-loader-with-syntax-error.mjs b/test/es-module/test-esm-loader-with-syntax-error.mjs deleted file mode 100644 index fe41b293a3fc..000000000000 --- a/test/es-module/test-esm-loader-with-syntax-error.mjs +++ /dev/null @@ -1,20 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: loader with syntax error', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should crash the node process', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'syntax-error.mjs').href, - fixtures.path('print-error-message.js'), - ]); - - assert.match(stderr, /SyntaxError/); - assert.ok(!stderr.includes('Bad command or file name')); - assert.notStrictEqual(code, 0); - }); -}); diff --git a/test/es-module/test-esm-loader.mjs b/test/es-module/test-esm-loader.mjs deleted file mode 100644 index de3481432481..000000000000 --- a/test/es-module/test-esm-loader.mjs +++ /dev/null @@ -1,88 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/hooks-custom.mjs -import '../common/index.mjs'; -import assert from 'assert'; - - -await assert.rejects( - import('nonexistent/file.mjs'), - { code: 'ERR_MODULE_NOT_FOUND' }, -); - -await assert.rejects( - import('../fixtures/es-modules/file.unknown'), - { code: 'ERR_UNKNOWN_FILE_EXTENSION' }, -); - -await assert.rejects( - import('esmHook/badReturnVal.mjs'), - { code: 'ERR_INVALID_RETURN_VALUE' }, -); - -// Nullish values are allowed; booleans are not -await assert.rejects( - import('esmHook/format.false'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -); -await assert.rejects( - import('esmHook/format.true'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -); - -await assert.rejects( - import('esmHook/badReturnFormatVal.mjs'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -); - -await assert.rejects( - import('esmHook/unsupportedReturnFormatVal.mjs'), - { code: 'ERR_UNKNOWN_MODULE_FORMAT' }, -); - -await assert.rejects( - import('esmHook/badReturnSourceVal.mjs'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -); - -await assert.rejects(import('esmHook/commonJsNullSource.mjs'), { - code: 'ERR_INVALID_RETURN_PROPERTY_VALUE', - message: /"source".*'load'.*got type bigint/, -}); - -await import('../fixtures/es-module-loaders/js-as-esm.js') -.then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(parsedModule.namedExport, 'named-export'); -}); - -// The custom loader tells node .ext files are MJS -await import('../fixtures/es-modules/file.ext') -.then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - const { default: defaultExport } = parsedModule; - assert.strictEqual(typeof defaultExport, 'function'); - assert.strictEqual(defaultExport.name, 'iAmReal'); - assert.strictEqual(defaultExport(), true); -}); - -// The custom loader's resolve hook predetermines the format -await import('esmHook/preknownFormat.pre') -.then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(parsedModule.default, 'hello world'); -}); - -// The custom loader provides source even though file does not actually exist -await import('esmHook/virtual.mjs') -.then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(typeof parsedModule.default, 'undefined'); - assert.strictEqual(parsedModule.message, 'WOOHOO!'); -}); - -// Ensure custom loaders have separate context from userland -// hooks-custom.mjs also increments count (which starts at 0) -// if both share context, count here would be 2 -await import('../fixtures/es-modules/stateful.mjs') -.then(({ default: count }) => { - assert.strictEqual(count(), 1); -}); diff --git a/test/es-module/test-esm-named-exports.mjs b/test/es-module/test-esm-named-exports.mjs deleted file mode 100644 index bbe9c96b92d9..000000000000 --- a/test/es-module/test-esm-named-exports.mjs +++ /dev/null @@ -1,9 +0,0 @@ -// Flags: --import ./test/fixtures/es-module-loaders/builtin-named-exports.mjs -import '../common/index.mjs'; -import { readFile, __fromLoader } from 'fs'; -import assert from 'assert'; -import ok from '../fixtures/es-modules/test-esm-ok.mjs'; - -assert(ok); -assert(readFile); -assert(__fromLoader); diff --git a/test/es-module/test-esm-preserve-symlinks-not-found-plain.mjs b/test/es-module/test-esm-preserve-symlinks-not-found-plain.mjs deleted file mode 100644 index 7a538e44c072..000000000000 --- a/test/es-module/test-esm-preserve-symlinks-not-found-plain.mjs +++ /dev/null @@ -1,3 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/not-found-assert-loader.mjs -/* eslint-disable node-core/require-common-first, node-core/required-modules */ -import './not-found.js'; diff --git a/test/es-module/test-esm-preserve-symlinks-not-found.mjs b/test/es-module/test-esm-preserve-symlinks-not-found.mjs deleted file mode 100644 index 722dc467d192..000000000000 --- a/test/es-module/test-esm-preserve-symlinks-not-found.mjs +++ /dev/null @@ -1,3 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/not-found-assert-loader.mjs -/* eslint-disable node-core/require-common-first, node-core/required-modules */ -import './not-found.mjs'; diff --git a/test/es-module/test-esm-register-deprecation.mjs b/test/es-module/test-esm-register-deprecation.mjs deleted file mode 100644 index 171e5971a091..000000000000 --- a/test/es-module/test-esm-register-deprecation.mjs +++ /dev/null @@ -1,60 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; - -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -const urlToRegister = fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'); -const urlToRegisterEscaped = JSON.stringify(urlToRegister.href); - - -describe('module.register() deprecation (DEP0205)', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('emits DEP0205 when module.register() is called', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--input-type=module', - '--eval', - `import { register } from 'node:module'; register(${urlToRegisterEscaped});`, - ]); - - assert.match(stderr, /\[DEP0205\]/); - assert.strictEqual(code, 0); - }); - - it('only emits the warning once per process', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--input-type=module', - '--eval', - `import { register } from 'node:module'; - register(${urlToRegisterEscaped}); - register(${urlToRegisterEscaped});`, - ]); - - assert.strictEqual(stderr.split('[DEP0205]').length - 1, 1); - assert.strictEqual(code, 0); - }); - - it('does not emit when --no-deprecation is set', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--no-deprecation', - '--input-type=module', - '--eval', - `import { register } from 'node:module'; register(${urlToRegisterEscaped});`, - ]); - - assert.doesNotMatch(stderr, /DEP0205/); - assert.strictEqual(code, 0); - }); - - it('throws when --throw-deprecation is set', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--throw-deprecation', - '--input-type=module', - '--eval', - `import { register } from 'node:module'; register(${urlToRegisterEscaped});`, - ]); - - assert.match(stderr, /DEP0205/); - assert.notStrictEqual(code, 0); - }); -}); diff --git a/test/es-module/test-esm-require-after-failed-import.js b/test/es-module/test-esm-require-after-failed-import.js new file mode 100644 index 000000000000..6815243212f9 --- /dev/null +++ b/test/es-module/test-esm-require-after-failed-import.js @@ -0,0 +1,15 @@ +'use strict'; +// Tests that require() of an ES module whose earlier import() failed during +// instantiation throws ERR_REQUIRE_ESM_RACE_CONDITION. +const common = require('../common'); +const assert = require('node:assert'); +const fixtures = require('../common/fixtures'); + +const url = fixtures.fileURL('es-modules/require-after-failed-import/mismatched.mjs'); + +assert.rejects(import(url), { name: 'SyntaxError' }).then(common.mustCall(() => { + assert.throws( + () => require(fixtures.path('es-modules/require-after-failed-import/mismatched.mjs')), + { code: 'ERR_REQUIRE_ESM_RACE_CONDITION' }, + ); +})); diff --git a/test/es-module/test-esm-shared-loader-dep.mjs b/test/es-module/test-esm-shared-loader-dep.mjs deleted file mode 100644 index e0015bd0c755..000000000000 --- a/test/es-module/test-esm-shared-loader-dep.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-shared-dep.mjs -import { createRequire } from '../common/index.mjs'; - -import assert from 'assert'; -import '../fixtures/es-modules/test-esm-ok.mjs'; - -const require = createRequire(import.meta.url); -const dep = require('../fixtures/es-module-loaders/loader-dep.js'); - -assert.strictEqual(dep.format, 'module'); diff --git a/test/es-module/test-loaders-unknown-builtin-module.mjs b/test/es-module/test-loaders-unknown-builtin-module.mjs deleted file mode 100644 index c97e52d1e63d..000000000000 --- a/test/es-module/test-loaders-unknown-builtin-module.mjs +++ /dev/null @@ -1,12 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs -import { expectsError, mustCall } from '../common/index.mjs'; -import assert from 'assert'; - -const unknownBuiltinModule = 'node:unknown-builtin-module'; - -import(unknownBuiltinModule) -.then(assert.fail, expectsError({ - code: 'ERR_UNKNOWN_BUILTIN_MODULE', - message: `No such built-in module: ${unknownBuiltinModule}`, -})) -.then(mustCall()); diff --git a/test/es-module/test-loaders-workers-spawned.mjs b/test/es-module/test-loaders-workers-spawned.mjs deleted file mode 100644 index 68c1b863f7ca..000000000000 --- a/test/es-module/test-loaders-workers-spawned.mjs +++ /dev/null @@ -1,83 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -describe('Worker threads do not spawn infinitely', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should not trigger an infinite loop when using a loader exports no recognized hooks', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('empty.js'), - '--eval', - 'setTimeout(() => console.log("hello"),99)', - ]); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /^hello\r?\n$/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('should support a CommonJS entry point and a loader that imports a CommonJS module', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-with-dep.mjs'), - fixtures.path('print-delayed.js'), - ]); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /^delayed\r?\n$/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('should support --require and --import along with using a loader written in CJS and CJS entry point', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--eval', - 'setTimeout(() => console.log("D"),99)', - '--import', - fixtures.fileURL('printC.js'), - '--experimental-loader', - fixtures.fileURL('printB.js'), - '--require', - fixtures.path('printA.js'), - ]); - - assert.strictEqual(stderr, ''); - // We are validating that: - // 1. the `--require` flag is run first from the main thread (and A is printed). - // 2. the `--require` flag is then run on the loader thread (and A is printed). - // 3. the `--loader` module is executed (and B is printed). - // 4. the `--import` module is evaluated once, on the main thread (and C is printed). - // 5. the user code is finally executed (and D is printed). - // The worker code should always run before the --import, but the console.log might arrive late. - assert.match(stdout, /^A\r?\n(A\r?\nB\r?\nC|A\r?\nC\r?\nB|C\r?\nA\r?\nB)\r?\nD\r?\n$/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('should support --require and --import along with using a loader written in ESM and ESM entry point', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--require', - fixtures.path('printA.js'), - '--experimental-loader', - 'data:text/javascript,console.log("B")', - '--import', - fixtures.fileURL('printC.js'), - '--input-type=module', - '--eval', - 'setTimeout(() => console.log("D"),99)', - ]); - - assert.strictEqual(stderr, ''); - // The worker code should always run before the --import, but the console.log might arrive late. - assert.match(stdout, /^A\r?\n(A\r?\nB\r?\nC|A\r?\nC\r?\nB|C\r?\nA\r?\nB)\r?\nD\r?\n$/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); -}); diff --git a/test/es-module/test-require-esm-from-imported-cjs.js b/test/es-module/test-require-esm-from-imported-cjs.js index bbce967a4b7e..b643923313db 100644 --- a/test/es-module/test-require-esm-from-imported-cjs.js +++ b/test/es-module/test-require-esm-from-imported-cjs.js @@ -20,17 +20,3 @@ spawnSyncAndAssert( stdout: / default: { hello: 'world' }/, } ); - -spawnSyncAndAssert( - process.execPath, - [ - '--experimental-require-module', - '--import', - fixtures.fileURL('es-modules', 'require-esm-in-cjs-cache', 'instrument.js'), - fixtures.path('es-modules', 'require-esm-in-cjs-cache', 'app.cjs'), - ], - { - trim: true, - stdout: / default: { hello: 'world' }/, - } -); diff --git a/test/eslint.config_partial.mjs b/test/eslint.config_partial.mjs index 5800eef9407a..0ef7d93df29d 100644 --- a/test/eslint.config_partial.mjs +++ b/test/eslint.config_partial.mjs @@ -217,7 +217,6 @@ export default [ }, { files: [ - 'test/es-module/test-esm-example-loader.js', 'test/es-module/test-esm-type-flag.js', 'test/es-module/test-esm-type-flag-alias.js', 'test/es-module/test-require-module-detect-entry-point.js', diff --git a/test/fixtures/es-module-loaders/builtin-named-exports-loader.mjs b/test/fixtures/es-module-loaders/builtin-named-exports-loader.mjs deleted file mode 100644 index f1b770d04f4f..000000000000 --- a/test/fixtures/es-module-loaders/builtin-named-exports-loader.mjs +++ /dev/null @@ -1,59 +0,0 @@ -import module from 'node:module'; -import { readFileSync } from 'node:fs'; - -/** @type {string} */ -let GET_BUILTIN; -export function initialize(data) { - GET_BUILTIN = data.GET_BUILTIN; -} - -export async function resolve(specifier, context, next) { - const def = await next(specifier, context); - - if (def.url.startsWith('node:')) { - return { - shortCircuit: true, - url: `custom-${def.url}`, - importAttributes: context.importAttributes, - }; - } - return def; -} - -export function load(url, context, next) { - if (url.startsWith('custom-node:')) { - const urlObj = new URL(url); - return { - shortCircuit: true, - source: generateBuiltinModule(urlObj.pathname), - format: 'commonjs', - }; - } else if (context.format === undefined || context.format === null || context.format === 'commonjs') { - return { - shortCircuit: true, - source: readFileSync(new URL(url)), - format: 'commonjs', - }; - } - return next(url); -} - -function generateBuiltinModule(builtinName) { - const builtinInstance = module._load(builtinName); - const builtinExports = [ - ...Object.keys(builtinInstance), - ]; - return `\ -const $builtinInstance = ${GET_BUILTIN}(${JSON.stringify(builtinName)}); - -module.exports = $builtinInstance; -module.exports.__fromLoader = true; - -// We need this for CJS-module-lexer can parse the exported names. -${ - builtinExports - .map(name => `exports.${name} = $builtinInstance.${name};`) - .join('\n') -} -`; -} diff --git a/test/fixtures/es-module-loaders/builtin-named-exports.mjs b/test/fixtures/es-module-loaders/builtin-named-exports.mjs deleted file mode 100644 index 123b12c26bf0..000000000000 --- a/test/fixtures/es-module-loaders/builtin-named-exports.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import * as fixtures from '../../common/fixtures.mjs'; -import { createRequire, register } from 'node:module'; - -const require = createRequire(import.meta.url); - -const GET_BUILTIN = `$__get_builtin_hole_${Date.now()}`; -Object.defineProperty(globalThis, GET_BUILTIN, { - value: builtinName => require(builtinName), - enumerable: false, - configurable: false, -}); - -register(fixtures.fileURL('es-module-loaders/builtin-named-exports-loader.mjs'), { - data: { - GET_BUILTIN, - }, -}); diff --git a/test/fixtures/es-module-loaders/byop-dummy-loader.mjs b/test/fixtures/es-module-loaders/byop-dummy-loader.mjs deleted file mode 100644 index 17a3430b44e3..000000000000 --- a/test/fixtures/es-module-loaders/byop-dummy-loader.mjs +++ /dev/null @@ -1,30 +0,0 @@ -export function load(url, context, nextLoad) { - switch (url) { - case 'byop://1/index.mjs': - return { - source: 'console.log("index.mjs!")', - format: 'module', - shortCircuit: true, - }; - case 'byop://1/index2.mjs': - return { - source: 'import c from "./sub.mjs"; console.log(c);', - format: 'module', - shortCircuit: true, - }; - case 'byop://1/sub.mjs': - return { - source: 'export default 42', - format: 'module', - shortCircuit: true, - }; - case 'byop://1/index.byoe': - return { - source: 'console.log("index.byoe!")', - format: 'module', - shortCircuit: true, - }; - default: - return nextLoad(url, context); - } -} diff --git a/test/fixtures/es-module-loaders/example-loader.mjs b/test/fixtures/es-module-loaders/example-loader.mjs deleted file mode 100644 index 77d44d55f915..000000000000 --- a/test/fixtures/es-module-loaders/example-loader.mjs +++ /dev/null @@ -1,46 +0,0 @@ -import { URL } from 'url'; -import path from 'path'; -import process from 'process'; -import { builtinModules } from 'module'; - -const JS_EXTENSIONS = new Set(['.js', '.mjs']); - -const baseURL = new URL('file://'); -baseURL.pathname = process.cwd() + '/'; - -export function resolve(specifier, { parentURL = baseURL }, next) { - if (builtinModules.includes(specifier)) { - return { - shortCircuit: true, - url: 'node:' + specifier - }; - } - if (/^\.{1,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) { - // For node_modules support: - // return next(specifier); - throw new Error( - `imports must be URLs or begin with './', or '../'; '${specifier}' does not`); - } - const resolved = new URL(specifier, parentURL); - return { - shortCircuit: true, - url: resolved.href - }; -} - -export function getFormat(url, context, defaultGetFormat) { - if (url.startsWith('node:') && builtinModules.includes(url.slice(5))) { - return { - format: 'builtin' - }; - } - const { pathname } = new URL(url); - const ext = path.extname(pathname); - if (!JS_EXTENSIONS.has(ext)) { - throw new Error( - `Cannot load file with non-JavaScript file extension ${ext}.`); - } - return { - format: 'module' - }; -} diff --git a/test/fixtures/es-module-loaders/hook-resolve-type-loader.mjs b/test/fixtures/es-module-loaders/hook-resolve-type-loader.mjs deleted file mode 100644 index c410401876e4..000000000000 --- a/test/fixtures/es-module-loaders/hook-resolve-type-loader.mjs +++ /dev/null @@ -1,25 +0,0 @@ -/** @type {Uint8Array} */ -let data; -/** @type {number} */ -let ESM_MODULE_INDEX; -/** @type {number} */ -let CJS_MODULE_INDEX; - -export function initialize({ sab, ESM_MODULE_INDEX:e, CJS_MODULE_INDEX:c }) { - data = new Uint8Array(sab); - ESM_MODULE_INDEX = e; - CJS_MODULE_INDEX = c; -} - -export async function resolve(specifier, context, next) { - const nextResult = await next(specifier, context); - const { format } = nextResult; - - if (format === 'module' || specifier.endsWith('.mjs')) { - Atomics.add(data, ESM_MODULE_INDEX, 1); - } else if (format == null || format === 'commonjs') { - Atomics.add(data, CJS_MODULE_INDEX, 1); - } - - return nextResult; -} diff --git a/test/fixtures/es-module-loaders/hook-resolve-type.mjs b/test/fixtures/es-module-loaders/hook-resolve-type.mjs deleted file mode 100644 index 7324a08e84b6..000000000000 --- a/test/fixtures/es-module-loaders/hook-resolve-type.mjs +++ /dev/null @@ -1,18 +0,0 @@ -import * as fixtures from '../../common/fixtures.mjs'; -import { register } from 'node:module'; - -const sab = new SharedArrayBuffer(2); -const data = new Uint8Array(sab); - -const ESM_MODULE_INDEX = 0 -const CJS_MODULE_INDEX = 1 - -export function getModuleTypeStats() { - const importedESM = Atomics.load(data, ESM_MODULE_INDEX); - const importedCJS = Atomics.load(data, CJS_MODULE_INDEX); - return { importedESM, importedCJS }; -} - -register(fixtures.fileURL('es-module-loaders/hook-resolve-type-loader.mjs'), { - data: { sab, ESM_MODULE_INDEX, CJS_MODULE_INDEX }, -}); diff --git a/test/fixtures/es-module-loaders/hooks-custom.mjs b/test/fixtures/es-module-loaders/hooks-custom.mjs deleted file mode 100644 index 5109d20f4d37..000000000000 --- a/test/fixtures/es-module-loaders/hooks-custom.mjs +++ /dev/null @@ -1,116 +0,0 @@ -import { pathToFileURL } from 'node:url'; -import count from '../es-modules/stateful.mjs'; - - -// Arbitrary instance of manipulating a module's internal state -// used to assert node-land and user-land have different contexts -count(); - -export function resolve(specifier, { importAttributes }, next) { - let format = ''; - - if (specifier === 'esmHook/format.false') { - format = false; - } - if (specifier === 'esmHook/format.true') { - format = true; - } - if (specifier === 'esmHook/preknownFormat.pre') { - format = 'module'; - } - - if (specifier.startsWith('esmHook')) { - return { - format, - shortCircuit: true, - url: pathToFileURL(specifier).href, - importAttributes, - }; - } - - return next(specifier); -} - -/** - * @param {string} url A fully resolved file url. - * @param {object} context Additional info. - * @param {function} next for now, next is defaultLoad a wrapper for - * defaultGetFormat + defaultGetSource - * @returns {{ format: string, source: (string|SharedArrayBuffer|Uint8Array) }} - */ -export function load(url, context, next) { - // Load all .js files as ESM, regardless of package scope - if (url.endsWith('.js')) { - return next(url, { - ...context, - format: 'module', - }); - } - - if (url.endsWith('.ext')) { - return next(url, { - ...context, - format: 'module', - }); - } - - if (url.endsWith('esmHook/badReturnVal.mjs')) { - return 'export function returnShouldBeObject() {}'; - } - - if (url.endsWith('esmHook/badReturnFormatVal.mjs')) { - return { - format: Array(0), - shortCircuit: true, - source: '', - }; - } - if (url.endsWith('esmHook/unsupportedReturnFormatVal.mjs')) { - return { - format: 'foo', // Not one of the allowable inputs: no translator named 'foo' - shortCircuit: true, - source: '', - }; - } - - if (url.endsWith('esmHook/badReturnSourceVal.mjs')) { - return { - format: 'module', - shortCircuit: true, - source: Array(0), - }; - } - - if (url.endsWith('esmHook/preknownFormat.pre')) { - return { - format: context.format, - shortCircuit: true, - source: `const msg = 'hello world'; export default msg;` - }; - } - - if (url.endsWith('esmHook/virtual.mjs')) { - return { - format: 'module', - shortCircuit: true, - source: `export const message = 'Woohoo!'.toUpperCase();`, - }; - } - - if (url.endsWith('esmHook/commonJsNullSource.mjs')) { - return { - format: 'commonjs', - shortCircuit: true, - source: 1n, - }; - } - - if (url.endsWith('esmHook/maximumCallStack.mjs')) { - function recurse() { - recurse(); - } - recurse(); - } - - return next(url); -} diff --git a/test/fixtures/es-module-loaders/hooks-initialize-port.mjs b/test/fixtures/es-module-loaders/hooks-initialize-port.mjs deleted file mode 100644 index cefe8854297c..000000000000 --- a/test/fixtures/es-module-loaders/hooks-initialize-port.mjs +++ /dev/null @@ -1,16 +0,0 @@ -let thePort = null; - -export async function initialize(port) { - port.postMessage('initialize'); - thePort = port; -} - -export async function resolve(specifier, context, next) { - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - thePort.postMessage(`resolve ${specifier}`); - - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/hooks-initialize.mjs b/test/fixtures/es-module-loaders/hooks-initialize.mjs deleted file mode 100644 index 7622d982a9d7..000000000000 --- a/test/fixtures/es-module-loaders/hooks-initialize.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { writeFileSync } from 'node:fs'; - -let counter = 0; - -export async function initialize() { - writeFileSync(1, `hooks initialize ${++counter}\n`); -} diff --git a/test/fixtures/es-module-loaders/hooks-input.mjs b/test/fixtures/es-module-loaders/hooks-input.mjs deleted file mode 100644 index e4eb159b3987..000000000000 --- a/test/fixtures/es-module-loaders/hooks-input.mjs +++ /dev/null @@ -1,94 +0,0 @@ -// This is expected to be used by test-esm-loader-hooks.mjs via: -// node --loader ./test/fixtures/es-module-loaders/hooks-input.mjs ./test/fixtures/es-modules/json-modules.mjs - -import assert from 'assert'; -import { writeSync } from 'fs'; -import { readFile } from 'fs/promises'; -import { fileURLToPath } from 'url'; - - -let resolveCalls = 0; -let loadCalls = 0; - -export async function resolve(specifier, context, next) { - resolveCalls++; - let url; - - if (resolveCalls === 1) { - url = new URL(specifier).href; - assert.match(specifier, /json-modules\.mjs$/); - - if (!(/\[eval\d*\]$/).test(context.parentURL)) { - assert.strictEqual(context.parentURL, undefined); - } - - assert.deepStrictEqual(context.importAttributes, {}); - } else if (resolveCalls === 2) { - url = new URL(specifier, context.parentURL).href; - assert.match(specifier, /experimental\.json$/); - assert.match(context.parentURL, /json-modules\.mjs$/); - assert.deepStrictEqual(context.importAttributes, { - type: 'json', - }); - } else { - throw new Error(`Unexpected resolve call: ${specifier}`); - } - - // Ensure `context` has all and only the properties it's supposed to - assert.deepStrictEqual(Reflect.ownKeys(context), [ - 'conditions', - 'importAttributes', - 'parentURL', - 'importAssertions', - ]); - assert.ok(Array.isArray(context.conditions)); - assert.strictEqual(typeof next, 'function'); - - const returnValue = { - url, - format: 'test', - shortCircuit: true, - } - - writeSync(1, JSON.stringify(returnValue) + '\n'); // For the test to validate when it parses stdout - - return returnValue; -} - -export async function load(url, context, next) { - loadCalls++; - const source = await readFile(fileURLToPath(url)); - let format; - - if (loadCalls === 1) { - assert.match(url, /json-modules\.mjs$/); - assert.deepStrictEqual(context.importAttributes, {}); - format = 'module'; - } else if (loadCalls === 2) { - assert.match(url, /experimental\.json$/); - assert.deepStrictEqual(context.importAttributes, { - type: 'json', - }); - format = 'json'; - } - - assert.ok(new URL(url)); - // Ensure `context` has all and only the properties it's supposed to - assert.deepStrictEqual(Reflect.ownKeys(context), [ - 'format', - 'importAttributes', - 'importAssertions', - ]); - assert.strictEqual(context.format, 'test'); - assert.strictEqual(typeof next, 'function'); - - const returnValue = { - source, - format, - shortCircuit: true, - }; - - writeSync(1, JSON.stringify(returnValue) + '\n'); // For the test to validate when it parses stdout - - return returnValue; -} diff --git a/test/fixtures/es-module-loaders/http-loader.mjs b/test/fixtures/es-module-loaders/http-loader.mjs deleted file mode 100644 index 4fe8fcb47974..000000000000 --- a/test/fixtures/es-module-loaders/http-loader.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import { get } from 'http'; - -export function load(url, context, nextLoad) { - if (url.startsWith('http://')) { - return new Promise((resolve, reject) => { - get(url, (rsp) => { - let data = ''; - rsp.on('data', (chunk) => data += chunk); - rsp.on('end', () => { - resolve({ - format: 'module', - shortCircuit: true, - source: data, - }); - }); - }) - .on('error', reject); - }); - } - - return nextLoad(url); -} diff --git a/test/fixtures/es-module-loaders/js-as-esm.js b/test/fixtures/es-module-loaders/js-as-esm.js deleted file mode 100644 index b4d2741b2fc5..000000000000 --- a/test/fixtures/es-module-loaders/js-as-esm.js +++ /dev/null @@ -1 +0,0 @@ -export const namedExport = 'named-export'; diff --git a/test/fixtures/es-module-loaders/loader-delayed-async-load.mjs b/test/fixtures/es-module-loaders/loader-delayed-async-load.mjs deleted file mode 100644 index 33bae9bdafd9..000000000000 --- a/test/fixtures/es-module-loaders/loader-delayed-async-load.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function load(a, b, c) { - return new Promise(d => setTimeout(() => d(c(a, b)), 99)); -} diff --git a/test/fixtures/es-module-loaders/loader-dep.js b/test/fixtures/es-module-loaders/loader-dep.js deleted file mode 100644 index c8154ac5dbe6..000000000000 --- a/test/fixtures/es-module-loaders/loader-dep.js +++ /dev/null @@ -1 +0,0 @@ -exports.format = 'module'; diff --git a/test/fixtures/es-module-loaders/loader-edge-cases.mjs b/test/fixtures/es-module-loaders/loader-edge-cases.mjs deleted file mode 100644 index 19af0e2bc078..000000000000 --- a/test/fixtures/es-module-loaders/loader-edge-cases.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { strictEqual } from "node:assert"; -import { isMainThread, workerData, parentPort } from "node:worker_threads"; - -strictEqual(isMainThread, false); - -// We want to make sure that internals are not leaked on the public module: -strictEqual(workerData, null); -strictEqual(parentPort, null); - -// We don't want `import.meta.resolve` being available from loaders -// as the sync implementation is not compatible with calling async -// functions on the same thread. -strictEqual(typeof import.meta.resolve, 'undefined'); diff --git a/test/fixtures/es-module-loaders/loader-exit-on-load.mjs b/test/fixtures/es-module-loaders/loader-exit-on-load.mjs deleted file mode 100644 index 4ee413fa46ce..000000000000 --- a/test/fixtures/es-module-loaders/loader-exit-on-load.mjs +++ /dev/null @@ -1,4 +0,0 @@ -export function load(a, b, next) { - if (a === 'data:exit') process.exit(42); - return next(a, b); -} diff --git a/test/fixtures/es-module-loaders/loader-exit-on-resolve.mjs b/test/fixtures/es-module-loaders/loader-exit-on-resolve.mjs deleted file mode 100644 index cffa4bcc486a..000000000000 --- a/test/fixtures/es-module-loaders/loader-exit-on-resolve.mjs +++ /dev/null @@ -1,4 +0,0 @@ -export function resolve(a, b, next) { - if (a === 'exit:') process.exit(42); - return next(a, b); -} diff --git a/test/fixtures/es-module-loaders/loader-exit-top-level.mjs b/test/fixtures/es-module-loaders/loader-exit-top-level.mjs deleted file mode 100644 index 6427ca06037f..000000000000 --- a/test/fixtures/es-module-loaders/loader-exit-top-level.mjs +++ /dev/null @@ -1 +0,0 @@ -process.exit(42); diff --git a/test/fixtures/es-module-loaders/loader-globalpreload-and-initialize.mjs b/test/fixtures/es-module-loaders/loader-globalpreload-and-initialize.mjs deleted file mode 100644 index 7055b90f4e75..000000000000 --- a/test/fixtures/es-module-loaders/loader-globalpreload-and-initialize.mjs +++ /dev/null @@ -1,2 +0,0 @@ -export function globalPreload() {} -export function initialize() {} diff --git a/test/fixtures/es-module-loaders/loader-globalpreload-only.mjs b/test/fixtures/es-module-loaders/loader-globalpreload-only.mjs deleted file mode 100644 index 6b7f59d63198..000000000000 --- a/test/fixtures/es-module-loaders/loader-globalpreload-only.mjs +++ /dev/null @@ -1 +0,0 @@ -export function globalPreload() {} diff --git a/test/fixtures/es-module-loaders/loader-globalpreload-with-return.mjs b/test/fixtures/es-module-loaders/loader-globalpreload-with-return.mjs deleted file mode 100644 index f54cf72ce5b9..000000000000 --- a/test/fixtures/es-module-loaders/loader-globalpreload-with-return.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function globalPreload() { - return ''; -} diff --git a/test/fixtures/es-module-loaders/loader-initialize-exit.mjs b/test/fixtures/es-module-loaders/loader-initialize-exit.mjs deleted file mode 100644 index 53cb4fa26f01..000000000000 --- a/test/fixtures/es-module-loaders/loader-initialize-exit.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function initialize() { - process.exit(42); -} diff --git a/test/fixtures/es-module-loaders/loader-initialize-never-settling.mjs b/test/fixtures/es-module-loaders/loader-initialize-never-settling.mjs deleted file mode 100644 index 80033b663a5a..000000000000 --- a/test/fixtures/es-module-loaders/loader-initialize-never-settling.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function initialize() { - return new Promise(() => {}); -} diff --git a/test/fixtures/es-module-loaders/loader-initialize-rejecting.mjs b/test/fixtures/es-module-loaders/loader-initialize-rejecting.mjs deleted file mode 100644 index 899accc15114..000000000000 --- a/test/fixtures/es-module-loaders/loader-initialize-rejecting.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function initialize() { - return Promise.reject(); -} diff --git a/test/fixtures/es-module-loaders/loader-initialize-throw-null.mjs b/test/fixtures/es-module-loaders/loader-initialize-throw-null.mjs deleted file mode 100644 index 3d834b5c23cf..000000000000 --- a/test/fixtures/es-module-loaders/loader-initialize-throw-null.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function initialize() { - throw null; -} diff --git a/test/fixtures/es-module-loaders/loader-invalid-format.mjs b/test/fixtures/es-module-loaders/loader-invalid-format.mjs deleted file mode 100644 index dc61a792b2be..000000000000 --- a/test/fixtures/es-module-loaders/loader-invalid-format.mjs +++ /dev/null @@ -1,20 +0,0 @@ -export async function resolve(specifier, { parentURL, importAttributes }, next) { - if (parentURL && specifier === '../fixtures/es-modules/test-esm-ok.mjs') { - return { - shortCircuit: true, - url: 'file:///asdf', - }; - } - return next(specifier); -} - -export async function load(url, context, next) { - if (url === 'file:///asdf') { - return { - format: 'esm', - shortCircuit: true, - source: '', - } - } - return next(url); -} diff --git a/test/fixtures/es-module-loaders/loader-invalid-url.mjs b/test/fixtures/es-module-loaders/loader-invalid-url.mjs deleted file mode 100644 index aac2b16b6f58..000000000000 --- a/test/fixtures/es-module-loaders/loader-invalid-url.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export async function resolve(specifier, { parentURL, importAttributes }, next) { - if (parentURL && specifier === '../fixtures/es-modules/test-esm-ok.mjs') { - return { - shortCircuit: true, - url: specifier, - importAttributes, - }; - } - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-load-bad-next-context.mjs b/test/fixtures/es-module-loaders/loader-load-bad-next-context.mjs deleted file mode 100644 index fe38da04f9ff..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-bad-next-context.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(url, context, next) { - return next(url, []); -} diff --git a/test/fixtures/es-module-loaders/loader-load-bad-next-url.mjs b/test/fixtures/es-module-loaders/loader-load-bad-next-url.mjs deleted file mode 100644 index c6a4c7504d43..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-bad-next-url.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(url, context, next) { - return next([]); -} diff --git a/test/fixtures/es-module-loaders/loader-load-commonjs-with-source.mjs b/test/fixtures/es-module-loaders/loader-load-commonjs-with-source.mjs deleted file mode 100644 index 3f431e630cdd..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-commonjs-with-source.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { readFile } from 'node:fs/promises'; -import { fileURLToPath } from 'node:url'; - -export async function load(url, context, nextLoad) { - const result = await nextLoad(url, context); - if (url.endsWith('/common/index.js')) { - result.source = '"use strict";module.exports=require("node:module").createRequire(' + - JSON.stringify(url) + ')(' + JSON.stringify(fileURLToPath(url)) + ');\n'; - } else if (url.startsWith('file:') && (context.format == null || context.format === 'commonjs')) { - result.source = await readFile(new URL(url)); - } - return result; -} diff --git a/test/fixtures/es-module-loaders/loader-load-dynamic-import.mjs b/test/fixtures/es-module-loaders/loader-load-dynamic-import.mjs deleted file mode 100644 index 96af5507d172..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-dynamic-import.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function load(url, context, next) { - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - // Here for asserting dynamic import - await import('xxx/loader-load-passthru.mjs'); - - writeSync(1, 'load dynamic import' + '\n'); // Signal that this specific hook ran - return next(url, context); -} diff --git a/test/fixtures/es-module-loaders/loader-load-foo-or-42.mjs b/test/fixtures/es-module-loaders/loader-load-foo-or-42.mjs deleted file mode 100644 index 285b81a910ef..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-foo-or-42.mjs +++ /dev/null @@ -1,19 +0,0 @@ -export async function load(url, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - const val = url.includes('42') - ? '42' - : '"foo"'; - - return { - format: 'module', - shortCircuit: true, - source: `export default ${val}`, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-load-impersonating-next-url.mjs b/test/fixtures/es-module-loaders/loader-load-impersonating-next-url.mjs deleted file mode 100644 index 1028e093e468..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-impersonating-next-url.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(url, context, next) { - return next('not/a/url'); -} diff --git a/test/fixtures/es-module-loaders/loader-load-incomplete.mjs b/test/fixtures/es-module-loaders/loader-load-incomplete.mjs deleted file mode 100644 index bf6d5ea254dc..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-incomplete.mjs +++ /dev/null @@ -1,14 +0,0 @@ -export async function load(url, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - return { - format: 'module', - source: 'export default 42', - }; -} diff --git a/test/fixtures/es-module-loaders/loader-load-next-modified.mjs b/test/fixtures/es-module-loaders/loader-load-next-modified.mjs deleted file mode 100644 index 401b52971311..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-next-modified.mjs +++ /dev/null @@ -1,11 +0,0 @@ -export async function load(url, context, next) { - const { - format, - source, - } = await next(url); - - return { - format, - source: source + 1, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-load-null-return.mjs b/test/fixtures/es-module-loaders/loader-load-null-return.mjs deleted file mode 100644 index 252eec4ebc28..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-null-return.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(specifier, context, next) { - return null; -} diff --git a/test/fixtures/es-module-loaders/loader-load-passing-modified-context.mjs b/test/fixtures/es-module-loaders/loader-load-passing-modified-context.mjs deleted file mode 100644 index 7676be766af5..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-passing-modified-context.mjs +++ /dev/null @@ -1,6 +0,0 @@ -export async function load(url, context, next) { - return next(url, { - ...context, - foo: 'bar', - }); -} diff --git a/test/fixtures/es-module-loaders/loader-load-passthru.mjs b/test/fixtures/es-module-loaders/loader-load-passthru.mjs deleted file mode 100644 index 72ff6b56122d..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-passthru.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { writeSync } from 'node:fs'; - -export async function load(url, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - writeSync(1, 'load passthru' + '\n'); // Signal that this specific hook ran - return next(url); -} diff --git a/test/fixtures/es-module-loaders/loader-load-receiving-modified-context.mjs b/test/fixtures/es-module-loaders/loader-load-receiving-modified-context.mjs deleted file mode 100644 index 6e5a1ee71936..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-receiving-modified-context.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function load(url, context, next) { - writeSync(1, context.foo + '\n'); // Expose actual value the hook was called with - return next(url, context); -} diff --git a/test/fixtures/es-module-loaders/loader-load-source-maps.mjs b/test/fixtures/es-module-loaders/loader-load-source-maps.mjs deleted file mode 100644 index bf5ef6b91028..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-source-maps.mjs +++ /dev/null @@ -1,9 +0,0 @@ -import { readFile } from 'node:fs/promises'; - -export async function load(url, context, nextLoad) { - const resolved = await nextLoad(url, context); - if (context.format === 'commonjs') { - resolved.source = await readFile(new URL(url)); - } - return resolved; -} diff --git a/test/fixtures/es-module-loaders/loader-log-args.mjs b/test/fixtures/es-module-loaders/loader-log-args.mjs deleted file mode 100644 index b56fddbce585..000000000000 --- a/test/fixtures/es-module-loaders/loader-log-args.mjs +++ /dev/null @@ -1,31 +0,0 @@ -import { writeSync } from 'node:fs'; -import { inspect } from 'node:util' - -export async function resolve(...args) { - writeSync(1, `resolve arg count: ${args.length}\n`); - writeSync(1, inspect({ - specifier: args[0], - context: args[1], - next: args[2], - }) + '\n'); - - return { - shortCircuit: true, - url: args[0], - }; -} - -export async function load(...args) { - writeSync(1, `load arg count: ${args.length}\n`); - writeSync(1, inspect({ - url: args[0], - context: args[1], - next: args[2], - }) + '\n'); - - return { - format: 'module', - source: '', - shortCircuit: true, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-mixed-opt-in.mjs b/test/fixtures/es-module-loaders/loader-mixed-opt-in.mjs deleted file mode 100644 index 69b17a88249b..000000000000 --- a/test/fixtures/es-module-loaders/loader-mixed-opt-in.mjs +++ /dev/null @@ -1,28 +0,0 @@ -import { createRequire } from 'module'; - -const require = createRequire(import.meta.url); -const fixtures = require('../../common/fixtures.js'); - -const fixturesPath = fixtures.path('empty.js'); - -export function resolve(s, c, n) { - if (s.endsWith('entry-point')) { - return { - shortCircuit: true, - url: 'file:///c:/virtual-entry-point', - format: 'commonjs', - }; - } - return n(s, c); -} - -export async function load(u, c, n) { - if (u === 'file:///c:/virtual-entry-point') { - return { - shortCircuit: true, - source: `"use strict";require(${JSON.stringify(fixturesPath)});console.log("Hello");`, - format: 'commonjs', - }; - } - return n(u, c); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-42.mjs b/test/fixtures/es-module-loaders/loader-resolve-42.mjs deleted file mode 100644 index b571a27a9787..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-42.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - writeSync(1, 'resolve 42' + '\n'); // Signal that this specific hook ran - writeSync(1, `next: ${next.name}\n`); // Expose actual value the hook was called with - - return next('file:///42.mjs'); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-bad-next-context.mjs b/test/fixtures/es-module-loaders/loader-resolve-bad-next-context.mjs deleted file mode 100644 index 881f5875dd02..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-bad-next-context.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function resolve(specifier, context, next) { - return next(specifier, []); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-bad-next-specifier.mjs b/test/fixtures/es-module-loaders/loader-resolve-bad-next-specifier.mjs deleted file mode 100644 index 66c941754f90..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-bad-next-specifier.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function resolve(specifier, context, next) { - return next([]); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-dynamic-import.mjs b/test/fixtures/es-module-loaders/loader-resolve-dynamic-import.mjs deleted file mode 100644 index edc2303ed9aa..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-dynamic-import.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function resolve(specifier, context, next) { - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - // Here for asserting dynamic import - await import('xxx/loader-resolve-passthru.mjs'); - - writeSync(1, 'resolve dynamic import' + '\n'); // Signal that this specific hook ran - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-foo.mjs b/test/fixtures/es-module-loaders/loader-resolve-foo.mjs deleted file mode 100644 index b5e5a419b99d..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-foo.mjs +++ /dev/null @@ -1,15 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - writeSync(1, 'resolve foo' + '\n'); // Signal that this specific hook ran - return next('file:///foo.mjs'); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-incomplete.mjs b/test/fixtures/es-module-loaders/loader-resolve-incomplete.mjs deleted file mode 100644 index cb37a4352718..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-incomplete.mjs +++ /dev/null @@ -1,13 +0,0 @@ -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - return { - url: 'file:///incomplete-resolve-chain.js', - }; -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-multiple-next-calls.mjs b/test/fixtures/es-module-loaders/loader-resolve-multiple-next-calls.mjs deleted file mode 100644 index 91dbec251ede..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-multiple-next-calls.mjs +++ /dev/null @@ -1,9 +0,0 @@ -export async function resolve(specifier, context, next) { - const { url: first } = await next(specifier); - const { url: second } = await next(specifier); - - return { - format: 'module', - url: first, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-next-modified.mjs b/test/fixtures/es-module-loaders/loader-resolve-next-modified.mjs deleted file mode 100644 index a6b8e85455d3..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-next-modified.mjs +++ /dev/null @@ -1,19 +0,0 @@ -export async function resolve(url, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - const { - format, - url: nextUrl, - } = await next(url, context); - - return { - format, - url: `${nextUrl}?foo`, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-null-return.mjs b/test/fixtures/es-module-loaders/loader-resolve-null-return.mjs deleted file mode 100644 index 16c9826a8ba5..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-null-return.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function resolve(specifier, context, next) { - return null; -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-passing-modified-context.mjs b/test/fixtures/es-module-loaders/loader-resolve-passing-modified-context.mjs deleted file mode 100644 index 6a92a6cd8f6a..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-passing-modified-context.mjs +++ /dev/null @@ -1,6 +0,0 @@ -export async function resolve(specifier, context, next) { - return next(specifier, { - ...context, - foo: 'bar', - }); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-passthru.mjs b/test/fixtures/es-module-loaders/loader-resolve-passthru.mjs deleted file mode 100644 index f388f0db273d..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-passthru.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { writeSync } from 'node:fs'; - -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - writeSync(1, 'resolve passthru' + '\n'); // Signal that this specific hook ran - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-receiving-modified-context.mjs b/test/fixtures/es-module-loaders/loader-resolve-receiving-modified-context.mjs deleted file mode 100644 index f6a8fdad53ec..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-receiving-modified-context.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function resolve(specifier, context, next) { - writeSync(1, context.foo + '\n'); // Expose actual value the hook was called with - return next(specifier, context); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-shortcircuit.mjs b/test/fixtures/es-module-loaders/loader-resolve-shortcircuit.mjs deleted file mode 100644 index 00c18e75e2c7..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-shortcircuit.mjs +++ /dev/null @@ -1,14 +0,0 @@ -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - return { - shortCircuit: true, - url: specifier, - } -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-strip-xxx.mjs b/test/fixtures/es-module-loaders/loader-resolve-strip-xxx.mjs deleted file mode 100644 index 996dfd041c0d..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-strip-xxx.mjs +++ /dev/null @@ -1,10 +0,0 @@ -import { writeSync } from 'node:fs'; -import { inspect } from 'node:util'; - -export async function resolve(specifier, context, nextResolve) { - if (specifier.startsWith('node:')) { - return nextResolve(specifier); - } - writeSync(1, `loader-a ${inspect({specifier})}\n`); - return nextResolve(specifier.replace(/^xxx\//, `./`)); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-strip-yyy.mjs b/test/fixtures/es-module-loaders/loader-resolve-strip-yyy.mjs deleted file mode 100644 index 7746469bf817..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-strip-yyy.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { writeSync } from 'node:fs'; -import { inspect } from 'node:util'; - -export async function resolve(specifier, context, nextResolve) { - writeSync(1, `loader-b ${inspect({specifier})}\n`); - return nextResolve(specifier.replace(/^yyy\//, `./`)); -} diff --git a/test/fixtures/es-module-loaders/loader-shared-dep.mjs b/test/fixtures/es-module-loaders/loader-shared-dep.mjs deleted file mode 100644 index d41c1ae40339..000000000000 --- a/test/fixtures/es-module-loaders/loader-shared-dep.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import assert from 'assert'; - -import { createRequire } from '../../common/index.mjs'; - -const require = createRequire(import.meta.url); -const dep = require('./loader-dep.js'); - -export function resolve(specifier, context, next) { - assert.strictEqual(dep.format, 'module'); - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-this-value-inside-hook-functions.mjs b/test/fixtures/es-module-loaders/loader-this-value-inside-hook-functions.mjs deleted file mode 100644 index 2be18c4969ef..000000000000 --- a/test/fixtures/es-module-loaders/loader-this-value-inside-hook-functions.mjs +++ /dev/null @@ -1,21 +0,0 @@ -export function initialize() { - if (this != null) { - throw new Error('hook function must not be bound to loader instance'); - } -} - -export function resolve(url, _, next) { - if (this != null) { - throw new Error('hook function must not be bound to loader instance'); - } - - return next(url); -} - -export function load(url, _, next) { - if (this != null) { - throw new Error('hook function must not be bound to loader instance'); - } - - return next(url); -} diff --git a/test/fixtures/es-module-loaders/loader-throw-bigint.mjs b/test/fixtures/es-module-loaders/loader-throw-bigint.mjs deleted file mode 100644 index 700b0387fa7f..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-bigint.mjs +++ /dev/null @@ -1 +0,0 @@ -throw 1n; diff --git a/test/fixtures/es-module-loaders/loader-throw-boolean.mjs b/test/fixtures/es-module-loaders/loader-throw-boolean.mjs deleted file mode 100644 index 874fbd92e5fa..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-boolean.mjs +++ /dev/null @@ -1 +0,0 @@ -throw true; diff --git a/test/fixtures/es-module-loaders/loader-throw-empty-object.mjs b/test/fixtures/es-module-loaders/loader-throw-empty-object.mjs deleted file mode 100644 index 778886fcb90a..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-empty-object.mjs +++ /dev/null @@ -1 +0,0 @@ -throw {}; diff --git a/test/fixtures/es-module-loaders/loader-throw-error.mjs b/test/fixtures/es-module-loaders/loader-throw-error.mjs deleted file mode 100644 index 816051b6c783..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-error.mjs +++ /dev/null @@ -1 +0,0 @@ -throw new Error('error message'); diff --git a/test/fixtures/es-module-loaders/loader-throw-function.mjs b/test/fixtures/es-module-loaders/loader-throw-function.mjs deleted file mode 100644 index 35503d670976..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-function.mjs +++ /dev/null @@ -1 +0,0 @@ -throw function fnName() {}; diff --git a/test/fixtures/es-module-loaders/loader-throw-null.mjs b/test/fixtures/es-module-loaders/loader-throw-null.mjs deleted file mode 100644 index 37d3d14b8bfe..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-null.mjs +++ /dev/null @@ -1 +0,0 @@ -throw null; diff --git a/test/fixtures/es-module-loaders/loader-throw-number.mjs b/test/fixtures/es-module-loaders/loader-throw-number.mjs deleted file mode 100644 index 6dbc3994c7ac..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-number.mjs +++ /dev/null @@ -1 +0,0 @@ -throw 1; diff --git a/test/fixtures/es-module-loaders/loader-throw-object.mjs b/test/fixtures/es-module-loaders/loader-throw-object.mjs deleted file mode 100644 index fa7c9b7d43af..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-object.mjs +++ /dev/null @@ -1 +0,0 @@ -throw { fn() {}, symbol: Symbol('symbol'), u: undefined }; diff --git a/test/fixtures/es-module-loaders/loader-throw-string.mjs b/test/fixtures/es-module-loaders/loader-throw-string.mjs deleted file mode 100644 index 613a4321f50d..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-string.mjs +++ /dev/null @@ -1 +0,0 @@ -throw 'literal string'; diff --git a/test/fixtures/es-module-loaders/loader-throw-symbol.mjs b/test/fixtures/es-module-loaders/loader-throw-symbol.mjs deleted file mode 100644 index 05876e0b4ada..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-symbol.mjs +++ /dev/null @@ -1 +0,0 @@ -throw Symbol('symbol descriptor'); diff --git a/test/fixtures/es-module-loaders/loader-throw-undefined.mjs b/test/fixtures/es-module-loaders/loader-throw-undefined.mjs deleted file mode 100644 index 38ecbdff9801..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-undefined.mjs +++ /dev/null @@ -1 +0,0 @@ -throw undefined; diff --git a/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs b/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs deleted file mode 100644 index 65e1adf909d0..000000000000 --- a/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs +++ /dev/null @@ -1,7 +0,0 @@ -export function resolve(specifier, context, next) { - if (specifier === 'unknown-builtin-module') return { - url: 'node:unknown-builtin-module' - }; - - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-with-custom-condition.mjs b/test/fixtures/es-module-loaders/loader-with-custom-condition.mjs deleted file mode 100644 index 90c55fa576bb..000000000000 --- a/test/fixtures/es-module-loaders/loader-with-custom-condition.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import { ok, deepStrictEqual } from 'assert'; - -export async function resolve(specifier, context, defaultResolve) { - ok(Array.isArray(context.conditions), 'loader receives conditions array'); - - deepStrictEqual([...context.conditions].sort(), [ - 'import', - 'module-sync', - 'node', - 'node-addons', - ]); - - return defaultResolve(specifier, { - ...context, - conditions: ['custom-condition', ...context.conditions], - }); -} diff --git a/test/fixtures/es-module-loaders/loader-with-dep.mjs b/test/fixtures/es-module-loaders/loader-with-dep.mjs deleted file mode 100644 index 625341eaed7e..000000000000 --- a/test/fixtures/es-module-loaders/loader-with-dep.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import {createRequire} from '../../common/index.mjs'; - -const require = createRequire(import.meta.url); -const dep = require('./loader-dep.js'); - -export async function resolve(specifier, { parentURL, importAttributes }, defaultResolve) { - return { - url: (await defaultResolve(specifier, { parentURL, importAttributes }, defaultResolve)).url, - format: dep.format - }; -} diff --git a/test/fixtures/es-module-loaders/loader-with-too-many-args.mjs b/test/fixtures/es-module-loaders/loader-with-too-many-args.mjs deleted file mode 100644 index 95f40ec15d20..000000000000 --- a/test/fixtures/es-module-loaders/loader-with-too-many-args.mjs +++ /dev/null @@ -1,7 +0,0 @@ -export async function resolve(specifier, context, next) { - return next(specifier, context, 'resolve-extra-arg'); -} - -export async function load(url, context, next) { - return next(url, context, 'load-extra-arg'); -} diff --git a/test/fixtures/es-module-loaders/loader-worker-spawn.mjs b/test/fixtures/es-module-loaders/loader-worker-spawn.mjs deleted file mode 100644 index 2860d116e647..000000000000 --- a/test/fixtures/es-module-loaders/loader-worker-spawn.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { Worker } from 'worker_threads'; -import { createRequire } from 'module'; - -const require = createRequire(import.meta.url); -const fixtures = require('../../common/fixtures.js'); - -new Worker(fixtures.path('empty.js')).unref(); diff --git a/test/fixtures/es-module-loaders/missing-dynamic-instantiate-hook.mjs b/test/fixtures/es-module-loaders/missing-dynamic-instantiate-hook.mjs deleted file mode 100644 index 5d61d81bc31e..000000000000 --- a/test/fixtures/es-module-loaders/missing-dynamic-instantiate-hook.mjs +++ /dev/null @@ -1,17 +0,0 @@ -export function resolve(specifier, context, next) { - if (specifier === 'test') { - return { - url: 'file://' - }; - } - return next(specifier); -} - -export function getFormat(url, context, defaultGetFormat) { - if (url === 'file://') { - return { - format: 'dynamic' - } - } - return defaultGetFormat(url, context, defaultGetFormat); -} diff --git a/test/fixtures/es-module-loaders/mock-loader.mjs b/test/fixtures/es-module-loaders/mock-loader.mjs deleted file mode 100644 index 3bb349b53853..000000000000 --- a/test/fixtures/es-module-loaders/mock-loader.mjs +++ /dev/null @@ -1,133 +0,0 @@ -import { receiveMessageOnPort } from 'node:worker_threads'; -const mockedModuleExports = new Map(); -let currentMockVersion = 0; - -// These hooks enable code running on the application thread to -// swap module resolution results for mocking purposes. It uses this instead -// of import.meta so that CommonJS can still use the functionality. -// -// It does so by allowing non-mocked modules to live in normal URL cache -// locations but creates 'mock-facade:' URL cache location for every time a -// module location is mocked. Since a single URL can be mocked multiple -// times but it cannot be removed from the cache, `mock-facade:` URLs have a -// form of mock-facade:$VERSION:$REPLACING_URL with the parameters being URL -// percent encoded every time a module is resolved. So if a module for -// 'file:///app.js' is mocked it might look like -// 'mock-facade:12:file%3A%2F%2F%2Fapp.js'. This encoding is done to prevent -// problems like mocking URLs with special URL characters like '#' or '?' from -// accidentally being picked up as part of the 'mock-facade:' URL containing -// the mocked URL. -// -// NOTE: due to ESM spec, once a specifier has been resolved in a source text -// it cannot be changed. So things like the following DO NOT WORK: -// -// ```mjs -// import mock from 'test-esm-loader-mock'; // See test-esm-loader-mock.mjs -// mock('file:///app.js', {x:1}); -// const namespace1 = await import('file:///app.js'); -// namespace1.x; // 1 -// mock('file:///app.js', {x:2}); -// const namespace2 = await import('file:///app.js'); -// namespace2.x; // STILL 1, because this source text already set the specifier -// // for 'file:///app.js', a different specifier that resolves -// // to that could still get a new namespace though -// assert(namespace1 === namespace2); -// ``` - -/** - * @param param0 message from the application context - */ -function onPreloadPortMessage({ - mockVersion, resolved, exports -}) { - currentMockVersion = mockVersion; - mockedModuleExports.set(resolved, exports); -} - -/** @type {URL['href']} */ -let mainImportURL; -/** @type {MessagePort} */ -let preloadPort; -export async function initialize(data) { - ({ mainImportURL, port: preloadPort } = data); - - data.port.on('message', onPreloadPortMessage); -} - -/** - * Because Node.js internals use a separate MessagePort for cross-thread - * communication, there could be some messages pending that we should handle - * before continuing. - */ -function doDrainPort() { - let msg; - while (msg = receiveMessageOnPort(preloadPort)) { - onPreloadPortMessage(msg.message); - } -} - -// Rewrites node: loading to mock-facade: so that it can be intercepted -export async function resolve(specifier, context, defaultResolve) { - doDrainPort(); - const def = await defaultResolve(specifier, context); - if (context.parentURL?.startsWith('mock-facade:')) { - // Do nothing, let it get the "real" module - } else if (mockedModuleExports.has(def.url)) { - return { - shortCircuit: true, - url: `mock-facade:${currentMockVersion}:${encodeURIComponent(def.url)}` - }; - }; - return { - shortCircuit: true, - url: def.url, - }; -} - -export async function load(url, context, defaultLoad) { - doDrainPort(); - /** - * Mocked fake module, not going to be handled in default way so it - * generates the source text, then short circuits - */ - if (url.startsWith('mock-facade:')) { - const encodedTargetURL = url.slice(url.lastIndexOf(':') + 1); - return { - shortCircuit: true, - source: generateModule(encodedTargetURL), - format: 'module', - }; - } - return defaultLoad(url, context); -} - -/** - * Generate the source code for a mocked module. - * @param {string} encodedTargetURL the module being mocked - * @returns {string} - */ -function generateModule(encodedTargetURL) { - const exports = mockedModuleExports.get( - decodeURIComponent(encodedTargetURL) - ); - let body = [ - `import { mockedModules } from ${JSON.stringify(mainImportURL)};`, - 'export {};', - 'let mapping = {__proto__: null};', - `const mock = mockedModules.get(${JSON.stringify(encodedTargetURL)});`, - ]; - for (const [i, name] of Object.entries(exports)) { - let key = JSON.stringify(name); - body.push(`var _${i} = mock.namespace[${key}];`); - body.push(`Object.defineProperty(mapping, ${key}, { enumerable: true, set(v) {_${i} = v;}, get() {return _${i};} });`); - body.push(`export {_${i} as ${name}};`); - } - body.push(`mock.listeners.push(${ - () => { - for (var k in mapping) { - mapping[k] = mock.namespace[k]; - } - } - });`); - return body.join('\n'); -} diff --git a/test/fixtures/es-module-loaders/mock.mjs b/test/fixtures/es-module-loaders/mock.mjs deleted file mode 100644 index cb167f1d5204..000000000000 --- a/test/fixtures/es-module-loaders/mock.mjs +++ /dev/null @@ -1,70 +0,0 @@ -import { register } from 'node:module'; -import { MessageChannel } from 'node:worker_threads'; - - -const { port1, port2 } = new MessageChannel(); - -register('./mock-loader.mjs', import.meta.url, { - data: { - port: port2, - mainImportURL: import.meta.url, - }, - transferList: [port2], -}); - -/** - * This is the Map that saves *all* the mocked URL -> replacement Module - * mappings - * @type {Map} - */ -export const mockedModules = new Map(); -let mockVersion = 0; - -/** - * @param {string} resolved an absolute URL HREF string - * @param {object} replacementProperties an object to pick properties from - * to act as a module namespace - * @returns {object} a mutator object that can update the module namespace - * since we can't do something like old Object.observe - */ -export function mock(resolved, replacementProperties) { - const exportNames = Object.keys(replacementProperties); - const namespace = { __proto__: null }; - /** - * @type {Array<(name: string)=>void>} functions to call whenever an - * export name is updated - */ - const listeners = []; - for (const name of exportNames) { - let currentValueForPropertyName = replacementProperties[name]; - Object.defineProperty(namespace, name, { - __proto__: null, - enumerable: true, - get() { - return currentValueForPropertyName; - }, - set(v) { - currentValueForPropertyName = v; - for (const fn of listeners) { - try { - fn(name); - } catch { - /* noop */ - } - } - }, - }); - } - mockedModules.set(encodeURIComponent(resolved), { - namespace, - listeners, - }); - mockVersion++; - // Inform the loader that the `resolved` URL should now use the specific - // `mockVersion` and has export names of `exportNames` - // - // This allows the loader to generate a fake module for that version - // and names the next time it resolves a specifier to equal `resolved` - port1.postMessage({ mockVersion, resolved, exports: exportNames }); - return namespace; -} diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/import.meta.never-resolve.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/import.meta.never-resolve.mjs deleted file mode 100644 index 2bc389cc3e1d..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/import.meta.never-resolve.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import assert from 'node:assert'; -console.log('should be output'); - -assert.throws(() => { - import.meta.resolve('never-settle-resolve'); -}, { - code: 'ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED' -}); diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/loader.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/loader.mjs deleted file mode 100644 index c180583b4c74..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/loader.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export function resolve(specifier, context, next) { - if (specifier === 'never-settle-resolve') return new Promise(() => {}); - if (specifier === 'never-settle-load') return { __proto__: null, shortCircuit: true, url: 'never-settle:///' }; - return next(specifier, context); -} - -export function load(url, context, next) { - if (url === 'never-settle:///') return new Promise(() => {}); - return next(url, context); -} diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.cjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.cjs deleted file mode 100644 index cc81affe7d0d..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.cjs +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -const neverSettlingDynamicImport = import('never-settle-load'); - -console.log('should be output'); - -neverSettlingDynamicImport.then(() => process.exit(1)); diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.mjs deleted file mode 100644 index 3dbf801c7605..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.mjs +++ /dev/null @@ -1,5 +0,0 @@ -const neverSettlingDynamicImport = import('never-settle-load'); - -console.log('should be output'); - -await neverSettlingDynamicImport; diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.cjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.cjs deleted file mode 100644 index bf6387560b47..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.cjs +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -const neverSettlingDynamicImport = import('never-settle-resolve'); - -console.log('should be output'); - -neverSettlingDynamicImport.then(() => process.exit(1)); diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.mjs deleted file mode 100644 index 806a131928c3..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.mjs +++ /dev/null @@ -1,5 +0,0 @@ -const neverSettlingDynamicImport = import('never-settle-resolve'); - -console.log('should be output'); - -await neverSettlingDynamicImport; diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/race.cjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/race.cjs deleted file mode 100644 index 41884ab9d2e7..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/race.cjs +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -Promise.race([ - import('never-settle-resolve'), - import('never-settle-load'), - import('node:process'), -]).then(result => console.log(result.default === process)); diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/race.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/race.mjs deleted file mode 100644 index 8213bbe59d44..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/race.mjs +++ /dev/null @@ -1,7 +0,0 @@ -const result = await Promise.race([ - import('never-settle-resolve'), - import('never-settle-load'), - import('node:process'), -]); - -console.log(result.default === process); diff --git a/test/fixtures/es-module-loaders/node_modules/load/index.mjs b/test/fixtures/es-module-loaders/node_modules/load/index.mjs deleted file mode 100644 index db98e8d9f878..000000000000 --- a/test/fixtures/es-module-loaders/node_modules/load/index.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from '../../loader-load-passthru.mjs' \ No newline at end of file diff --git a/test/fixtures/es-module-loaders/node_modules/load/package.json b/test/fixtures/es-module-loaders/node_modules/load/package.json deleted file mode 100644 index b6629e247888..000000000000 --- a/test/fixtures/es-module-loaders/node_modules/load/package.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "exports": "./index.mjs" -} diff --git a/test/fixtures/es-module-loaders/node_modules/resolve/index.mjs b/test/fixtures/es-module-loaders/node_modules/resolve/index.mjs deleted file mode 100644 index b3769d961359..000000000000 --- a/test/fixtures/es-module-loaders/node_modules/resolve/index.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from '../../loader-resolve-passthru.mjs' \ No newline at end of file diff --git a/test/fixtures/es-module-loaders/node_modules/resolve/package.json b/test/fixtures/es-module-loaders/node_modules/resolve/package.json deleted file mode 100644 index b6629e247888..000000000000 --- a/test/fixtures/es-module-loaders/node_modules/resolve/package.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "exports": "./index.mjs" -} diff --git a/test/fixtures/es-module-loaders/not-found-assert-loader.mjs b/test/fixtures/es-module-loaders/not-found-assert-loader.mjs deleted file mode 100644 index bf66efbd0810..000000000000 --- a/test/fixtures/es-module-loaders/not-found-assert-loader.mjs +++ /dev/null @@ -1,16 +0,0 @@ -import assert from 'node:assert'; - -// A loader that asserts that the defaultResolve will throw "not found" -// (skipping the top-level main of course, and the built-in ones needed for run-worker). -let mainLoad = true; -export async function resolve(specifier, { importAttributes }, next) { - if (mainLoad || specifier === 'path' || specifier === 'worker_threads') { - mainLoad = false; - return next(specifier); - } - await assert.rejects(next(specifier), { code: 'ERR_MODULE_NOT_FOUND' }); - return { - url: 'node:fs', - importAttributes, - }; -} diff --git a/test/fixtures/es-module-loaders/preset-cjs-source.mjs b/test/fixtures/es-module-loaders/preset-cjs-source.mjs deleted file mode 100644 index 2cfa851a23f8..000000000000 --- a/test/fixtures/es-module-loaders/preset-cjs-source.mjs +++ /dev/null @@ -1,21 +0,0 @@ -export function resolve(specifier, context, next) { - if (specifier.endsWith('/no-such-file.cjs')) { - // Shortcut to avoid ERR_MODULE_NOT_FOUND for non-existing file, but keep the url for the load hook. - return { - shortCircuit: true, - url: specifier, - }; - } - return next(specifier); -} - -export function load(href, context, next) { - if (href.endsWith('.cjs')) { - return { - format: 'commonjs', - shortCircuit: true, - source: 'module.exports = "no .cjs file was read to get this source";', - }; - } - return next(href); -} diff --git a/test/fixtures/es-module-loaders/register-hooks-with-current-cwd-parent-url.mjs b/test/fixtures/es-module-loaders/register-hooks-with-current-cwd-parent-url.mjs deleted file mode 100644 index 580d092ab565..000000000000 --- a/test/fixtures/es-module-loaders/register-hooks-with-current-cwd-parent-url.mjs +++ /dev/null @@ -1,3 +0,0 @@ -import { register } from 'node:module'; -import { pathToFileURL } from 'node:url'; -register('./hooks-initialize.mjs', pathToFileURL('./')); diff --git a/test/fixtures/es-module-loaders/register-loader-with-url-parenturl.mjs b/test/fixtures/es-module-loaders/register-loader-with-url-parenturl.mjs deleted file mode 100644 index 1d82d2abc557..000000000000 --- a/test/fixtures/es-module-loaders/register-loader-with-url-parenturl.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import {register} from 'node:module'; -import fixtures from '../../common/fixtures.js'; - -register( - fixtures.fileURL('es-module-loaders/loader-load-foo-or-42.mjs'), - new URL('data:'), -); - -import('node:os').then((result) => { - console.log(JSON.stringify(result)); -}); diff --git a/test/fixtures/es-module-loaders/register-loader.cjs b/test/fixtures/es-module-loaders/register-loader.cjs deleted file mode 100644 index 9e18dfa77e28..000000000000 --- a/test/fixtures/es-module-loaders/register-loader.cjs +++ /dev/null @@ -1,4 +0,0 @@ -const { register } = require('node:module'); -const fixtures = require('../../common/fixtures.js'); - -register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')); diff --git a/test/fixtures/es-module-loaders/register-loader.mjs b/test/fixtures/es-module-loaders/register-loader.mjs deleted file mode 100644 index f3cb2de8da3d..000000000000 --- a/test/fixtures/es-module-loaders/register-loader.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import { register } from 'node:module'; -import fixtures from '../../common/fixtures.js'; - -register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')); diff --git a/test/fixtures/es-module-loaders/register-programmatically-loader-load.mjs b/test/fixtures/es-module-loaders/register-programmatically-loader-load.mjs deleted file mode 100644 index fe22dc7203e9..000000000000 --- a/test/fixtures/es-module-loaders/register-programmatically-loader-load.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import * as fixtures from '../../common/fixtures.mjs'; -import { register } from 'node:module'; - -register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')); diff --git a/test/fixtures/es-module-loaders/register-programmatically-loader-resolve.mjs b/test/fixtures/es-module-loaders/register-programmatically-loader-resolve.mjs deleted file mode 100644 index 3ae8841da834..000000000000 --- a/test/fixtures/es-module-loaders/register-programmatically-loader-resolve.mjs +++ /dev/null @@ -1,3 +0,0 @@ -import { register } from 'node:module'; - -register('./loader-resolve-passthru.mjs', import.meta.url); diff --git a/test/fixtures/es-module-loaders/string-sources.mjs b/test/fixtures/es-module-loaders/string-sources.mjs deleted file mode 100644 index 39ad32c465fa..000000000000 --- a/test/fixtures/es-module-loaders/string-sources.mjs +++ /dev/null @@ -1,43 +0,0 @@ -const SOURCES = { - __proto__: null, - 'test:Array': ['1', '2'], // both `1,2` and `12` are valid ESM - 'test:ArrayBuffer': new ArrayBuffer(0), - 'test:BigInt64Array': new BigInt64Array(0), - 'test:BigUint64Array': new BigUint64Array(0), - 'test:Float32Array': new Float32Array(0), - 'test:Float64Array': new Float64Array(0), - 'test:Int8Array': new Int8Array(0), - 'test:Int16Array': new Int16Array(0), - 'test:Int32Array': new Int32Array(0), - 'test:null': null, - 'test:Object': {}, - 'test:SharedArrayBuffer': new SharedArrayBuffer(0), - 'test:string': '', - 'test:String': new String(''), - 'test:Uint8Array': new Uint8Array(0), - 'test:Uint8ClampedArray': new Uint8ClampedArray(0), - 'test:Uint16Array': new Uint16Array(0), - 'test:Uint32Array': new Uint32Array(0), - 'test:undefined': undefined, -} -export function resolve(specifier, context, next) { - if (specifier.startsWith('test:')) { - return { - importAttributes: context.importAttributes, - shortCircuit: true, - url: specifier, - }; - } - return next(specifier); -} - -export function load(href, context, next) { - if (href.startsWith('test:')) { - return { - format: 'module', - shortCircuit: true, - source: SOURCES[href], - }; - } - return next(href); -} diff --git a/test/fixtures/es-module-loaders/thenable-load-hook-rejected-no-arguments.mjs b/test/fixtures/es-module-loaders/thenable-load-hook-rejected-no-arguments.mjs deleted file mode 100644 index 5e008edecf7c..000000000000 --- a/test/fixtures/es-module-loaders/thenable-load-hook-rejected-no-arguments.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export function load () { - let thenAlreadyAccessed = false; - return { - get then() { - if (thenAlreadyAccessed) throw new Error('must not call'); - thenAlreadyAccessed = true; - return (_, reject) => reject(); - } - }; -} diff --git a/test/fixtures/es-module-loaders/thenable-load-hook-rejected.mjs b/test/fixtures/es-module-loaders/thenable-load-hook-rejected.mjs deleted file mode 100644 index 926f6d0bebd6..000000000000 --- a/test/fixtures/es-module-loaders/thenable-load-hook-rejected.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export function load () { - let thenAlreadyAccessed = false; - return { - get then() { - if (thenAlreadyAccessed) throw new Error('must not call'); - thenAlreadyAccessed = true; - return (_, reject) => reject(new Error('must crash the process')); - } - }; -} diff --git a/test/fixtures/es-module-loaders/thenable-load-hook.mjs b/test/fixtures/es-module-loaders/thenable-load-hook.mjs deleted file mode 100644 index 661f6e21ac69..000000000000 --- a/test/fixtures/es-module-loaders/thenable-load-hook.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export function load(url, context, next) { - let thenAlreadyAccessed = false; - return { - get then() { - if (thenAlreadyAccessed) throw new Error('must not call'); - thenAlreadyAccessed = true; - return (resolve) => resolve(next(url, context)); - } - }; -} diff --git a/test/fixtures/es-modules/require-after-failed-import/dep.mjs b/test/fixtures/es-modules/require-after-failed-import/dep.mjs new file mode 100644 index 000000000000..efeee5db16c0 --- /dev/null +++ b/test/fixtures/es-modules/require-after-failed-import/dep.mjs @@ -0,0 +1 @@ +export const value = 1; diff --git a/test/fixtures/es-modules/require-after-failed-import/mismatched.mjs b/test/fixtures/es-modules/require-after-failed-import/mismatched.mjs new file mode 100644 index 000000000000..9e3f57a169a0 --- /dev/null +++ b/test/fixtures/es-modules/require-after-failed-import/mismatched.mjs @@ -0,0 +1,2 @@ +import { missing } from './dep.mjs'; +export { missing }; diff --git a/test/fixtures/es-modules/require-esm-in-cjs-cache/hooks.js b/test/fixtures/es-modules/require-esm-in-cjs-cache/hooks.js deleted file mode 100644 index f33a40fba773..000000000000 --- a/test/fixtures/es-modules/require-esm-in-cjs-cache/hooks.js +++ /dev/null @@ -1,12 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; - -export async function load(url, context, nextLoad) { - const result = await nextLoad(url, context); - - if (result.format === 'commonjs' && !result.source) { - result.source = readFileSync(fileURLToPath(url), 'utf8'); - } - - return result; -} diff --git a/test/fixtures/es-modules/require-esm-in-cjs-cache/instrument.js b/test/fixtures/es-modules/require-esm-in-cjs-cache/instrument.js deleted file mode 100644 index 1c99b7e9c759..000000000000 --- a/test/fixtures/es-modules/require-esm-in-cjs-cache/instrument.js +++ /dev/null @@ -1,3 +0,0 @@ -import * as mod from 'node:module'; - -mod.register(new URL('hooks.js', import.meta.url).toString()); diff --git a/test/fixtures/es-modules/require-esm-throws-with-loaders.js b/test/fixtures/es-modules/require-esm-throws-with-loaders.js deleted file mode 100644 index 79c5cf96c141..000000000000 --- a/test/fixtures/es-modules/require-esm-throws-with-loaders.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; -const { readFile, __fromLoader } = require('fs'); -const assert = require('assert'); - -assert.throws(() => require('./test-esm-ok.mjs'), { code: 'ERR_REQUIRE_ESM' }); - -assert(readFile); -assert(__fromLoader); diff --git a/test/fixtures/es-modules/worker-condition/hooks-worker.mjs b/test/fixtures/es-modules/worker-condition/hooks-worker.mjs deleted file mode 100644 index ee9cd45bd6c5..000000000000 --- a/test/fixtures/es-modules/worker-condition/hooks-worker.mjs +++ /dev/null @@ -1,6 +0,0 @@ -import { register } from 'node:module'; - -register('./hooks.mjs', import.meta.url); - -const { default: value } = await import('pkg'); -postMessage(value); diff --git a/test/fixtures/es-modules/worker-condition/hooks.mjs b/test/fixtures/es-modules/worker-condition/hooks.mjs deleted file mode 100644 index 8505bafc98db..000000000000 --- a/test/fixtures/es-modules/worker-condition/hooks.mjs +++ /dev/null @@ -1,6 +0,0 @@ -export async function resolve(specifier, context, nextResolve) { - if (specifier === 'pkg' && !context.conditions.includes('worker')) { - throw new Error(`missing worker condition: ${context.conditions}`); - } - return nextResolve(specifier, context); -} diff --git a/test/fixtures/loader-is-internal-thread.js b/test/fixtures/loader-is-internal-thread.js deleted file mode 100644 index d97328bc2075..000000000000 --- a/test/fixtures/loader-is-internal-thread.js +++ /dev/null @@ -1,3 +0,0 @@ -const { isInternalThread } = require('node:worker_threads'); - -console.log(`isInternalThread: ${isInternalThread}`); \ No newline at end of file diff --git a/test/fixtures/module-hooks/get-stats.js b/test/fixtures/module-hooks/get-stats.js deleted file mode 100644 index fa5869a455ce..000000000000 --- a/test/fixtures/module-hooks/get-stats.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -const path = require('path'); - -// Adapted from https://github.com/watson/module-details-from-path/blob/master/index.js -// used by require-in-the-middle to check the logic is still compatible with our new hooks. -exports.getStats = function getStats(filepath) { - const segments = filepath.split(path.sep); - const index = segments.lastIndexOf('node_modules'); - if (index === -1) return {}; - if (!segments[index + 1]) return {}; - const scoped = segments[index + 1][0] === '@'; - const name = scoped ? segments[index + 1] + '/' + segments[index + 2] : segments[index + 1]; - const offset = scoped ? 3 : 2; - return { - name: name, - basedir: segments.slice(0, index + offset).join(path.sep), - path: segments.slice(index + offset).join(path.sep) - } -}; diff --git a/test/fixtures/module-hooks/logger-async-hooks.mjs b/test/fixtures/module-hooks/logger-async-hooks.mjs deleted file mode 100644 index f26d0ce2ae3e..000000000000 --- a/test/fixtures/module-hooks/logger-async-hooks.mjs +++ /dev/null @@ -1,19 +0,0 @@ -import fs from 'node:fs'; - -export async function resolve(specifier, context, nextResolve) { - fs.writeSync(1, `resolve ${specifier} from ${context.parentURL}\n`); - const result = await nextResolve(specifier, context); - result.shortCircuit = true; - return result; -} - -export async function load(url, context, nextLoad) { - fs.writeSync(1, `load ${url}\n`); - const result = await nextLoad(url, context); - result.shortCircuit = true; - // Handle the async loader hook quirk where source can be nullish for CommonJS. - // If this returns that nullish value verbatim, the `require` in imported - // CJS won't get the hook invoked. - result.source ??= fs.readFileSync(new URL(url), 'utf8'); - return result; -} diff --git a/test/fixtures/module-hooks/register-loader-in-sequence.mjs b/test/fixtures/module-hooks/register-loader-in-sequence.mjs deleted file mode 100644 index c129fcfc1809..000000000000 --- a/test/fixtures/module-hooks/register-loader-in-sequence.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import {register} from 'node:module'; -import fixtures from '../../common/fixtures.js'; - -console.log('result 1', register( - fixtures.fileURL('es-module-loaders/hooks-initialize.mjs') -)); -console.log('result 2', register( - fixtures.fileURL('es-module-loaders/hooks-initialize.mjs') -)); - -await import('node:os'); diff --git a/test/fixtures/module-hooks/register-loader-initialize-never-settling.mjs b/test/fixtures/module-hooks/register-loader-initialize-never-settling.mjs deleted file mode 100644 index 13091effa970..000000000000 --- a/test/fixtures/module-hooks/register-loader-initialize-never-settling.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import {register} from 'node:module'; -import fixtures from '../../common/fixtures.js'; - -try { - register(fixtures.fileURL('es-module-loaders/loader-initialize-never-settling.mjs')); -} catch (e) { - console.log('caught', e.code); -} diff --git a/test/fixtures/module-hooks/register-loader-with-cjs.cjs b/test/fixtures/module-hooks/register-loader-with-cjs.cjs deleted file mode 100644 index 2cd6c666bd14..000000000000 --- a/test/fixtures/module-hooks/register-loader-with-cjs.cjs +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; -const {register} = require('node:module'); -const fixtures = require('../../common/fixtures.js'); - -register( - fixtures.fileURL('es-module-loaders/hooks-initialize.mjs'), -); -register( - fixtures.fileURL('es-module-loaders/loader-load-foo-or-42.mjs'), -); - -import('node:os').then((result) => { - console.log(JSON.stringify(result)); -}); diff --git a/test/fixtures/module-hooks/register-loader-with-ports.mjs b/test/fixtures/module-hooks/register-loader-with-ports.mjs deleted file mode 100644 index 45e125f96a20..000000000000 --- a/test/fixtures/module-hooks/register-loader-with-ports.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import {MessageChannel} from 'node:worker_threads'; -import {register} from 'node:module'; -import {once} from 'node:events'; -import fixtures from '../../common/fixtures.js'; - -const {port1, port2} = new MessageChannel(); -port1.on('message', (msg) => { - console.log('message', msg); -}); -const result = register( - fixtures.fileURL('es-module-loaders/hooks-initialize-port.mjs'), - {data: port2, transferList: [port2]}, -); -console.log('register', result); - -const timeout = setTimeout(() => {}, 2**31 - 1); // to keep the process alive. -await Promise.all([ - once(port1, 'message').then(() => once(port1, 'message')), - import('node:os'), -]); -clearTimeout(timeout); -port1.close(); diff --git a/test/fixtures/module-hooks/require-esm-in-hooks-thread/dep.mjs b/test/fixtures/module-hooks/require-esm-in-hooks-thread/dep.mjs deleted file mode 100644 index 3d34ee667697..000000000000 --- a/test/fixtures/module-hooks/require-esm-in-hooks-thread/dep.mjs +++ /dev/null @@ -1 +0,0 @@ -export const value = 'dep:'; diff --git a/test/fixtures/module-hooks/require-esm-in-hooks-thread/esm-with-import.mjs b/test/fixtures/module-hooks/require-esm-in-hooks-thread/esm-with-import.mjs deleted file mode 100644 index 1aad2b7a98c1..000000000000 --- a/test/fixtures/module-hooks/require-esm-in-hooks-thread/esm-with-import.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import { sep } from 'node:path'; -import { value } from './dep.mjs'; - -export const result = `${value}${typeof sep}`; diff --git a/test/fixtures/module-hooks/require-esm-in-hooks-thread/hooks.mjs b/test/fixtures/module-hooks/require-esm-in-hooks-thread/hooks.mjs deleted file mode 100644 index b80b4ef959b7..000000000000 --- a/test/fixtures/module-hooks/require-esm-in-hooks-thread/hooks.mjs +++ /dev/null @@ -1,9 +0,0 @@ -// Loaded on the module.register() hooks thread. It defines no hooks: require()-ing -// an ES module with imports while the hooks module is being loaded is enough. -import { createRequire } from 'node:module'; - -const require = createRequire(import.meta.url); -const { result } = require('./esm-with-import.mjs'); -if (result !== 'dep:string') { - throw new Error(`Unexpected result: ${result}`); -} diff --git a/test/fixtures/module-hooks/require-resolve-paths-caller.js b/test/fixtures/module-hooks/require-resolve-paths-caller.js deleted file mode 100644 index f18b1f377735..000000000000 --- a/test/fixtures/module-hooks/require-resolve-paths-caller.js +++ /dev/null @@ -1,13 +0,0 @@ -// Fixture CJS file that calls require.resolve with the paths option. -'use strict'; -const path = require('path'); -const fixturesDir = path.resolve(__dirname, '..', '..'); -const nodeModules = path.join(fixturesDir, 'node_modules'); - -// Use the paths option to resolve 'bar' from the fixtures node_modules. -const resolved = require.resolve('bar', { paths: [fixturesDir] }); -const expected = path.join(nodeModules, 'bar.js'); -if (resolved !== expected) { - throw new Error(`Expected ${expected}, got ${resolved}`); -} -module.exports = { resolved }; diff --git a/test/fixtures/module-hooks/sync-and-async/app.js b/test/fixtures/module-hooks/sync-and-async/app.js deleted file mode 100644 index c14477b70f71..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/app.js +++ /dev/null @@ -1,2 +0,0 @@ -console.log('Hello world'); - diff --git a/test/fixtures/module-hooks/sync-and-async/async-customize-loader.js b/test/fixtures/module-hooks/sync-and-async/async-customize-loader.js deleted file mode 100644 index ac961f0b97a3..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/async-customize-loader.js +++ /dev/null @@ -1,10 +0,0 @@ -export async function load(url, context, nextLoad) { - if (url.endsWith('app.js')) { - return { - shortCircuit: true, - format: 'module', - source: 'console.log("customized by async hook");', - }; - } - return nextLoad(url, context); -} diff --git a/test/fixtures/module-hooks/sync-and-async/async-customize.js b/test/fixtures/module-hooks/sync-and-async/async-customize.js deleted file mode 100644 index 78bf7fc5564b..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/async-customize.js +++ /dev/null @@ -1,3 +0,0 @@ -import { register } from 'node:module'; - -register(new URL('async-customize-loader.js', import.meta.url)); diff --git a/test/fixtures/module-hooks/sync-and-async/async-forward-loader.js b/test/fixtures/module-hooks/sync-and-async/async-forward-loader.js deleted file mode 100644 index 4a1ced7e8dbf..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/async-forward-loader.js +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(url, context, nextLoad) { - return nextLoad(url, context); -} diff --git a/test/fixtures/module-hooks/sync-and-async/async-forward.js b/test/fixtures/module-hooks/sync-and-async/async-forward.js deleted file mode 100644 index fd10aa6df898..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/async-forward.js +++ /dev/null @@ -1,3 +0,0 @@ -import { register } from 'node:module'; - -register(new URL('async-forward-loader.js', import.meta.url)); diff --git a/test/fixtures/module-hooks/sync-and-async/sync-customize.js b/test/fixtures/module-hooks/sync-and-async/sync-customize.js deleted file mode 100644 index 90d63db1c7cc..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/sync-customize.js +++ /dev/null @@ -1,14 +0,0 @@ -import { registerHooks } from 'node:module'; - -registerHooks({ - load(url, context, nextLoad) { - if (url.endsWith('app.js')) { - return { - shortCircuit: true, - format: 'module', - source: 'console.log("customized by sync hook")', - }; - } - return nextLoad(url, context); - }, -}); diff --git a/test/fixtures/module-hooks/sync-and-async/sync-forward.js b/test/fixtures/module-hooks/sync-and-async/sync-forward.js deleted file mode 100644 index 2688a240dc88..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/sync-forward.js +++ /dev/null @@ -1,7 +0,0 @@ -import { registerHooks } from 'node:module'; - -registerHooks({ - load(url, context, nextLoad) { - return nextLoad(url, context); - }, -}); diff --git a/test/fixtures/print-delayed.js b/test/fixtures/print-delayed.js deleted file mode 100644 index 42eb45615b2a..000000000000 --- a/test/fixtures/print-delayed.js +++ /dev/null @@ -1,3 +0,0 @@ -setTimeout(() => { - console.log('delayed'); -}, 100); diff --git a/test/module-hooks/test-async-loader-hooks-called-with-expected-args.mjs b/test/module-hooks/test-async-loader-hooks-called-with-expected-args.mjs deleted file mode 100644 index 195bf02bb6fd..000000000000 --- a/test/module-hooks/test-async-loader-hooks-called-with-expected-args.mjs +++ /dev/null @@ -1,28 +0,0 @@ -// Test that loader hooks are called with all expected arguments -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/hooks-input.mjs'), - fixtures.path('es-modules/json-modules.mjs'), - ], - { - stdout(output) { - const lines = output.split('\n'); - assert.match(lines[0], /{"url":"file:\/\/\/.*\/json-modules\.mjs","format":"test","shortCircuit":true}/); - assert.match(lines[1], /{"source":{"type":"Buffer","data":\[.*\]},"format":"module","shortCircuit":true}/); - assert.match(lines[2], /{"url":"file:\/\/\/.*\/experimental\.json","format":"test","shortCircuit":true}/); - assert.match(lines[3], /{"source":{"type":"Buffer","data":\[.*\]},"format":"json","shortCircuit":true}/); - assert.strictEqual(lines.length, 4); - }, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-called-with-register.mjs b/test/module-hooks/test-async-loader-hooks-called-with-register.mjs deleted file mode 100644 index d1f9181240d7..000000000000 --- a/test/module-hooks/test-async-loader-hooks-called-with-register.mjs +++ /dev/null @@ -1,31 +0,0 @@ -// Test that loader hooks are called with all expected arguments using register function -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader=data:text/javascript,', - '--input-type=module', - '--eval', - "import { register } from 'node:module';" + - `register(${JSON.stringify(fixtures.fileURL('es-module-loaders/hooks-input.mjs'))});` + - `await import(${JSON.stringify(fixtures.fileURL('es-modules/json-modules.mjs'))});`, - ], - { - stdout(output) { - const lines = output.split('\n'); - assert.match(lines[0], /{"url":"file:\/\/\/.*\/json-modules\.mjs","format":"test","shortCircuit":true}/); - assert.match(lines[1], /{"source":{"type":"Buffer","data":\[.*\]},"format":"module","shortCircuit":true}/); - assert.match(lines[2], /{"url":"file:\/\/\/.*\/experimental\.json","format":"test","shortCircuit":true}/); - assert.match(lines[3], /{"source":{"type":"Buffer","data":\[.*\]},"format":"json","shortCircuit":true}/); - assert.strictEqual(lines.length, 4); - }, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-globalpreload-no-warning-with-initialize.mjs b/test/module-hooks/test-async-loader-hooks-globalpreload-no-warning-with-initialize.mjs deleted file mode 100644 index 54501748bcea..000000000000 --- a/test/module-hooks/test-async-loader-hooks-globalpreload-no-warning-with-initialize.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test that `globalPreload` should not emit warning when `initialize` is supplied - -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-globalpreload-and-initialize.mjs'), - fixtures.path('empty.js'), - ], - { - stderr(output) { - assert.doesNotMatch(output, /`globalPreload` has been removed; use `initialize` instead/); - }, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-globalpreload-warning.mjs b/test/module-hooks/test-async-loader-hooks-globalpreload-warning.mjs deleted file mode 100644 index 36a2c0089a91..000000000000 --- a/test/module-hooks/test-async-loader-hooks-globalpreload-warning.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Test that `globalPreload` should emit warning -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-globalpreload-only.mjs'), - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-globalpreload-with-return.mjs'), - fixtures.path('empty.js'), - ], - { - stderr(output) { - const matches = output.match(/`globalPreload` has been removed; use `initialize` instead/g); - assert.strictEqual(matches.length, 1); - }, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-in-sequence.mjs b/test/module-hooks/test-async-loader-hooks-initialize-in-sequence.mjs deleted file mode 100644 index bc973f587845..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-in-sequence.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test that `initialize` should execute in sequence -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - fixtures.path('module-hooks/register-loader-in-sequence.mjs'), - ], - { - stdout: 'hooks initialize 1\n' + - 'result 1 undefined\n' + - 'hooks initialize 2\n' + - 'result 2 undefined', - trim: true, - stderr: '', - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-invoke.mjs b/test/module-hooks/test-async-loader-hooks-initialize-invoke.mjs deleted file mode 100644 index 72dc87c12e35..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-invoke.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that `initialize` should be invoked correctly -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/hooks-initialize.mjs'), - '--input-type=module', - '--eval', - 'import os from "node:os";', - ], - { - stdout: 'hooks initialize 1', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-never-settling.mjs b/test/module-hooks/test-async-loader-hooks-initialize-never-settling.mjs deleted file mode 100644 index d1c12238ef0c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-never-settling.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// Test that `initialize` returning never-settling promise should be handled -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - fixtures.path('module-hooks/register-loader-initialize-never-settling.mjs'), - ], - { - stdout: 'caught ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-process-exit.mjs b/test/module-hooks/test-async-loader-hooks-initialize-process-exit.mjs deleted file mode 100644 index d9476af27e8f..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-process-exit.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Test that it should be fine to call `process.exit` from a `initialize` hook -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-initialize-exit.mjs'), - '--input-type=module', - '--eval', - 'import "node:os"', - ], - { - status: 42, - signal: null, - stdout: '', - stderr: '', - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-rejecting.mjs b/test/module-hooks/test-async-loader-hooks-initialize-rejecting.mjs deleted file mode 100644 index e5d2a62fbc86..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-rejecting.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that `initialize` returning rejecting promise should be handled -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-initialize-rejecting.mjs'), - '--input-type=module', - '--eval', - 'import "node:os"', - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /undefined$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-throw-null.mjs b/test/module-hooks/test-async-loader-hooks-initialize-throw-null.mjs deleted file mode 100644 index 69844e31ae91..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-throw-null.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that `initialize` throwing null should be handled -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-initialize-throw-null.mjs'), - '--input-type=module', - '--eval', - 'import "node:os"', - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /null$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-mixed-opt-in.mjs b/test/module-hooks/test-async-loader-hooks-mixed-opt-in.mjs deleted file mode 100644 index 398df25d7bbe..000000000000 --- a/test/module-hooks/test-async-loader-hooks-mixed-opt-in.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that loader should handle mixed of opt-in modules and non-opt-in ones -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-mixed-opt-in.mjs'), - 'entry-point', - ], - { - stdout: 'Hello', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-import-meta-resolve.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-import-meta-resolve.mjs deleted file mode 100644 index 35a4f7a566e5..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-import-meta-resolve.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test import.meta.resolve of a never-settling resolve should throw in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/import.meta.never-resolve.mjs'), - ], - { - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-load-cjs.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-load-cjs.mjs deleted file mode 100644 index 05401b9080b3..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-load-cjs.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test never-settling load in CJS files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-load.cjs'), - ], - { - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-no-warning.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-no-warning.mjs deleted file mode 100644 index dbadecc32876..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-no-warning.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test top-level await of a never-settling load without warning in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-load.mjs'), - ], - { - status: 13, - signal: null, - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-with-warning.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-with-warning.mjs deleted file mode 100644 index d4b30ae23f86..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-with-warning.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test top-level await of a never-settling load with warning in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-load.mjs'), - ], - { - status: 13, - signal: null, - stdout: /^should be output$/, - stderr: /Warning: Detected unsettled top-level await at.+never-load\.mjs:5/, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-race-cjs.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-race-cjs.mjs deleted file mode 100644 index 1de677f88838..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-race-cjs.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test race of never-settling hooks in CJS files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/race.cjs'), - ], - { - stdout: /^true$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-race-esm.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-race-esm.mjs deleted file mode 100644 index e662dc43210d..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-race-esm.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test top-level await of a race of never-settling hooks in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/race.mjs'), - ], - { - stdout: /^true$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-cjs.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-resolve-cjs.mjs deleted file mode 100644 index 1469a7b313cc..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-cjs.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test never-settling resolve in CJS files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-resolve.cjs'), - ], - { - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-no-warning.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-no-warning.mjs deleted file mode 100644 index 43a7a98127c8..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-no-warning.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test top-level await of a never-settling resolve without warning in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-resolve.mjs'), - ], - { - status: 13, - signal: null, - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-with-warning.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-with-warning.mjs deleted file mode 100644 index 1a4c40c8bb96..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-with-warning.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test top-level await of a never-settling resolve with warning in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-resolve.mjs'), - ], - { - status: 13, - signal: null, - stdout: /^should be output$/, - stderr: /Warning: Detected unsettled top-level await at.+never-resolve\.mjs:5/, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-no-leak-internals.mjs b/test/module-hooks/test-async-loader-hooks-no-leak-internals.mjs deleted file mode 100644 index 781aed8601f5..000000000000 --- a/test/module-hooks/test-async-loader-hooks-no-leak-internals.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that loader hooks should not leak internals or expose import.meta.resolve -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-edge-cases.mjs'), - fixtures.path('empty.js'), - ], - { - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-process-exit-async.mjs b/test/module-hooks/test-async-loader-hooks-process-exit-async.mjs deleted file mode 100644 index af3b939bcf8c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-process-exit-async.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that it should be fine to call `process.exit` from a custom async hook -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-exit-on-load.mjs'), - '--input-type=module', - '--eval', - 'import "data:exit"', - ], - { - status: 42, - signal: null, - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-process-exit-sync.mjs b/test/module-hooks/test-async-loader-hooks-process-exit-sync.mjs deleted file mode 100644 index 64c079b90b75..000000000000 --- a/test/module-hooks/test-async-loader-hooks-process-exit-sync.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that it should be fine to call `process.exit` from a custom sync hook -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-exit-on-resolve.mjs'), - '--input-type=module', - '--eval', - 'import "data:text/javascript,import.meta.resolve(%22exit:%22)"', - ], - { - status: 42, - signal: null, - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-process-exit-top-level.mjs b/test/module-hooks/test-async-loader-hooks-process-exit-top-level.mjs deleted file mode 100644 index a25c0013c507..000000000000 --- a/test/module-hooks/test-async-loader-hooks-process-exit-top-level.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that it should be fine to call process.exit from the loader thread top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-exit-top-level.mjs'), - fixtures.path('empty.js'), - ], - { - status: 42, - signal: null, - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-cjs.mjs b/test/module-hooks/test-async-loader-hooks-register-with-cjs.mjs deleted file mode 100644 index 8d83ee6be878..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-cjs.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that `register` should work with cjs -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - fixtures.path('module-hooks/register-loader-with-cjs.cjs'), - ], - { - stdout(output) { - assert.deepStrictEqual(output.split('\n').sort(), ['hooks initialize 1', '{"default":"foo"}', ''].sort()); - }, - stderr: '', - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-import.mjs b/test/module-hooks/test-async-loader-hooks-register-with-import.mjs deleted file mode 100644 index 454eccb5c624..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-import.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that `register` should work with `import` -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--import', - fixtures.fileURL('es-module-loaders/register-loader.mjs'), - '--input-type=module', - '--eval', - 'import "node:os"', - ], - { - stdout: 'resolve passthru', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-ports.mjs b/test/module-hooks/test-async-loader-hooks-register-with-ports.mjs deleted file mode 100644 index 022760596fd9..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-ports.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// Test that loader should allow communicating with loader via `register` ports -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - fixtures.path('module-hooks/register-loader-with-ports.mjs'), - ], - { - stdout: 'register undefined\nmessage initialize\nmessage resolve node:os', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-require.mjs b/test/module-hooks/test-async-loader-hooks-register-with-require.mjs deleted file mode 100644 index 87ea43f8a66c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-require.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that `register` should work with `require` -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--require', - fixtures.path('es-module-loaders/register-loader.cjs'), - '--input-type=module', - '--eval', - 'import "node:os";', - ], - { - stdout: 'resolve passthru\nresolve passthru', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-url-parenturl.mjs b/test/module-hooks/test-async-loader-hooks-register-with-url-parenturl.mjs deleted file mode 100644 index a033ab3c4d2f..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-url-parenturl.mjs +++ /dev/null @@ -1,26 +0,0 @@ -// Test that `register` should accept URL objects as `parentURL` -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--import', - fixtures.fileURL('es-module-loaders/register-hooks-with-current-cwd-parent-url.mjs'), - fixtures.path('es-module-loaders/register-loader-with-url-parenturl.mjs'), - ], - { - cwd: fixtures.path('es-module-loaders/'), - }, - { - stdout(output) { - assert.deepStrictEqual(output.split('\n').sort(), ['hooks initialize 1', '{"default":"foo"}'].sort()); - }, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-remove-beforeexit-listener.mjs b/test/module-hooks/test-async-loader-hooks-remove-beforeexit-listener.mjs deleted file mode 100644 index 9a28bb59dd31..000000000000 --- a/test/module-hooks/test-async-loader-hooks-remove-beforeexit-listener.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that it should be fine to call `process.removeAllListeners("beforeExit")`("beforeExit") from the main thread -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-delayed-async-load.mjs'), - '--input-type=module', - '--eval', - 'setInterval(() => process.removeAllListeners("beforeExit"),1).unref();await import("data:text/javascript,")', - ], - { - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-require-esm-in-hooks-thread.mjs b/test/module-hooks/test-async-loader-hooks-require-esm-in-hooks-thread.mjs deleted file mode 100644 index 8a647568ffee..000000000000 --- a/test/module-hooks/test-async-loader-hooks-require-esm-in-hooks-thread.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Test that require(esm) of a module with imports works while loading a module.register() hooks module. -// Refs: https://github.com/nodejs/node/issues/66767 -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--input-type=module', - '--eval', - `import { register } from 'node:module'; - register(${JSON.stringify(fixtures.fileURL('module-hooks/require-esm-in-hooks-thread/hooks.mjs'))}); - console.log('ok');`, - ], - { - stdout: 'ok', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-require-resolve-default.mjs b/test/module-hooks/test-async-loader-hooks-require-resolve-default.mjs deleted file mode 100644 index 71e539fe118b..000000000000 --- a/test/module-hooks/test-async-loader-hooks-require-resolve-default.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that loader should use CJS loader to respond to `require.resolve` calls by default -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-resolve-passthru.mjs'), - fixtures.path('require-resolve.js'), - ], - { - stdout: 'resolve passthru', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-require-resolve-opt-in.mjs b/test/module-hooks/test-async-loader-hooks-require-resolve-opt-in.mjs deleted file mode 100644 index 0cbf2fd2d942..000000000000 --- a/test/module-hooks/test-async-loader-hooks-require-resolve-opt-in.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader should use ESM loader to respond to `require.resolve` calls when opting in -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-load-commonjs-with-source.mjs'), - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-resolve-passthru.mjs'), - fixtures.path('require-resolve.js'), - ], - { - stdout: 'resolve passthru\n'.repeat(10).trim(), - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-source-maps-cjs.mjs b/test/module-hooks/test-async-loader-hooks-source-maps-cjs.mjs deleted file mode 100644 index 83bd53405d1b..000000000000 --- a/test/module-hooks/test-async-loader-hooks-source-maps-cjs.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Test that loader should support source maps in commonjs translator -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--enable-source-maps', - '--import', - fixtures.fileURL('es-module-loaders/loader-load-source-maps.mjs'), - fixtures.path('source-map/throw-on-require.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /throw-on-require\.ts:9:9/, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-bigint.mjs b/test/module-hooks/test-async-loader-hooks-throw-bigint.mjs deleted file mode 100644 index 34136f81bf21..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-bigint.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle bigint thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-bigint.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^1$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-boolean.mjs b/test/module-hooks/test-async-loader-hooks-throw-boolean.mjs deleted file mode 100644 index 476fad3c1415..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-boolean.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle boolean thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-boolean.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^true$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-empty-object.mjs b/test/module-hooks/test-async-loader-hooks-throw-empty-object.mjs deleted file mode 100644 index ac09704c28ca..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-empty-object.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle empty plain object thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-empty-object.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^\{\}$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-error.mjs b/test/module-hooks/test-async-loader-hooks-throw-error.mjs deleted file mode 100644 index b37ce50db1e3..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-error.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle regular Error object thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-error.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^Error: error message$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-function.mjs b/test/module-hooks/test-async-loader-hooks-throw-function.mjs deleted file mode 100644 index bb371f727c84..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-function.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle function thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-function.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^\[Function: fnName\]$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-null.mjs b/test/module-hooks/test-async-loader-hooks-throw-null.mjs deleted file mode 100644 index 33528ff2b975..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-null.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle null thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-null.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^null$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-number.mjs b/test/module-hooks/test-async-loader-hooks-throw-number.mjs deleted file mode 100644 index da1f301089ca..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-number.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle number thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-number.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^1$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-object.mjs b/test/module-hooks/test-async-loader-hooks-throw-object.mjs deleted file mode 100644 index 8280bd0d105b..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-object.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle plain object thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-object.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^\{ fn: \[Function: fn\], symbol: Symbol\(symbol\), u: undefined \}$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-string.mjs b/test/module-hooks/test-async-loader-hooks-throw-string.mjs deleted file mode 100644 index 4ea6372e865c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-string.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle string thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-string.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^literal string$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-symbol.mjs b/test/module-hooks/test-async-loader-hooks-throw-symbol.mjs deleted file mode 100644 index 44339537ba9c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-symbol.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that loader hooks should handle symbol thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-symbol.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', // Throwing a symbol doesn't produce any output - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-undefined.mjs b/test/module-hooks/test-async-loader-hooks-throw-undefined.mjs deleted file mode 100644 index aff5292a857f..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-undefined.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle undefined thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-undefined.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^undefined$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-use-hooks-require-esm.mjs b/test/module-hooks/test-async-loader-hooks-use-hooks-require-esm.mjs deleted file mode 100644 index 1eee6a6014aa..000000000000 --- a/test/module-hooks/test-async-loader-hooks-use-hooks-require-esm.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test that loader should use hooks for require of ESM -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-deprecation', - '--no-experimental-require-module', - '--import', - fixtures.fileURL('es-module-loaders/builtin-named-exports.mjs'), - fixtures.path('es-modules/require-esm-throws-with-loaders.js'), - ], - { - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-with-worker-permission-allowed.mjs b/test/module-hooks/test-async-loader-hooks-with-worker-permission-allowed.mjs deleted file mode 100644 index 9be7e8c39600..000000000000 --- a/test/module-hooks/test-async-loader-hooks-with-worker-permission-allowed.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that loader hooks should allow spawning workers when allowed by CLI flags -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--permission', - '--allow-worker', - '--allow-fs-read', - '*', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-worker-spawn.mjs'), - fixtures.path('es-modules/esm-top-level-await.mjs'), - ], - { - stdout: /^1\n2$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-with-worker-permission-restricted.mjs b/test/module-hooks/test-async-loader-hooks-with-worker-permission-restricted.mjs deleted file mode 100644 index fe76f2f5842c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-with-worker-permission-restricted.mjs +++ /dev/null @@ -1,25 +0,0 @@ -// Test that loader hooks should not allow spawning workers if restricted by CLI flags -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--permission', - '--allow-fs-read', - '*', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-worker-spawn.mjs'), - fixtures.path('es-modules/esm-top-level-await.mjs'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /code: 'ERR_ACCESS_DENIED'/, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-without-worker-permission.mjs b/test/module-hooks/test-async-loader-hooks-without-worker-permission.mjs deleted file mode 100644 index 21589234144d..000000000000 --- a/test/module-hooks/test-async-loader-hooks-without-worker-permission.mjs +++ /dev/null @@ -1,25 +0,0 @@ -// Test that loader hooks should not work without worker permission -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--permission', - '--allow-fs-read', - '*', - '--experimental-loader', - fixtures.fileURL('empty.js'), - fixtures.path('es-modules/esm-top-level-await.mjs'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /Error: Access to this API has been restricted/, - trim: true, - }, -); diff --git a/test/module-hooks/test-module-hooks-load-async-and-sync.js b/test/module-hooks/test-module-hooks-load-async-and-sync.js deleted file mode 100644 index 75f4987942f9..000000000000 --- a/test/module-hooks/test-module-hooks-load-async-and-sync.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; -// This tests that sync and async hooks can be mixed. - -require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); -const fixtures = require('../common/fixtures'); - -const app = fixtures.path('module-hooks', 'sync-and-async', 'app.js'); - -const testCases = [ - // When mixing sync and async hooks, the sync ones always run first. - { preload: ['sync-customize', 'async-customize'], stdout: 'customized by sync hook' }, - { preload: ['async-customize', 'sync-customize'], stdout: 'customized by sync hook' }, - // It should still work when neither hook does any customization. - { preload: ['sync-forward', 'async-forward'], stdout: 'Hello world' }, - { preload: ['async-forward', 'sync-forward'], stdout: 'Hello world' }, - // It should work when only one hook is customizing. - { preload: ['sync-customize', 'async-forward'], stdout: 'customized by sync hook' }, - { preload: ['async-customize', 'sync-forward'], stdout: 'customized by async hook' }, -]; - - -for (const { preload, stdout } of testCases) { - const importArgs = []; - for (const p of preload) { - importArgs.push('--import', fixtures.fileURL(`module-hooks/sync-and-async/${p}.js`)); - } - spawnSyncAndAssert(process.execPath, [...importArgs, app], { - stdout, - trim: true, - }); -} diff --git a/test/module-hooks/test-module-hooks-load-builtin-import.mjs b/test/module-hooks/test-module-hooks-load-builtin-import.mjs index f78c69692fe0..159189f53c5d 100644 --- a/test/module-hooks/test-module-hooks-load-builtin-import.mjs +++ b/test/module-hooks/test-module-hooks-load-builtin-import.mjs @@ -5,8 +5,7 @@ import process from 'node:process'; // This tests that imported builtins get null as source from default // step, and the source returned are ignored. -// TODO(joyeecheung): this is to align with the module.register() behavior -// but perhaps the load hooks should not be invoked for builtins at all. +// TODO(joyeecheung): perhaps the load hooks should not be invoked for builtins at all. // Pick a builtin that's unlikely to be loaded already - like zlib. assert(!process.moduleLoadList.includes('NativeModule zlib')); diff --git a/test/module-hooks/test-module-hooks-load-builtin-require.js b/test/module-hooks/test-module-hooks-load-builtin-require.js index d86eb4b9df76..ac4de0f14da3 100644 --- a/test/module-hooks/test-module-hooks-load-builtin-require.js +++ b/test/module-hooks/test-module-hooks-load-builtin-require.js @@ -7,8 +7,7 @@ const { registerHooks } = require('module'); // This tests that required builtins get null as source from default // step, and the source returned are ignored. -// TODO(joyeecheung): this is to align with the module.register() behavior -// but perhaps the load hooks should not be invoked for builtins at all. +// TODO(joyeecheung): perhaps the load hooks should not be invoked for builtins at all. // Pick a builtin that's unlikely to be loaded already - like zlib. assert(!process.moduleLoadList.includes('NativeModule zlib')); diff --git a/test/module-hooks/test-module-hooks-resolve-require-resolve-loaded-with-source.js b/test/module-hooks/test-module-hooks-resolve-require-resolve-loaded-with-source.js deleted file mode 100644 index de66beda5b2e..000000000000 --- a/test/module-hooks/test-module-hooks-resolve-require-resolve-loaded-with-source.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -// This tests that require.resolve() in a CJS file loaded via the re-invented -// require (triggered when module.register() installs an async loader that -// provides source for a CJS file) still goes through resolve hooks registered -// via module.registerHooks(). - -const common = require('../common'); -const assert = require('assert'); -const { register, registerHooks } = require('module'); -const fixtures = require('../common/fixtures'); -const { pathToFileURL } = require('url'); - -const redirectedPath = fixtures.path('module-hooks', 'redirected-assert.js'); - -// Register an async loader that provides source for CJS files, which triggers -// the re-invented require path. -register(fixtures.fileURL('module-hooks', 'logger-async-hooks.mjs')); - -const hook = registerHooks({ - resolve: common.mustCall((specifier, context, nextResolve) => { - if (specifier === 'test-require-resolve-hook-target') { - return { - url: pathToFileURL(redirectedPath).href, - shortCircuit: true, - }; - } - return nextResolve(specifier, context); - }, 2), -}); - -import('../fixtures/module-hooks/require-resolve-caller.js').then(common.mustCall((ns) => { - assert.strictEqual(ns.default.resolved, redirectedPath); - hook.deregister(); -})); diff --git a/test/parallel/test-esm-loader-hooks-inspect-brk.js b/test/parallel/test-esm-loader-hooks-inspect-brk.js deleted file mode 100644 index 251ebb230dcd..000000000000 --- a/test/parallel/test-esm-loader-hooks-inspect-brk.js +++ /dev/null @@ -1,31 +0,0 @@ -// This tests esm loader's internal worker will not be blocked by --inspect-brk. -// Regression: https://github.com/nodejs/node/issues/53681 - -'use strict'; -const common = require('../common'); - -common.skipIfInspectorDisabled(); - -const assert = require('assert'); -const fixtures = require('../common/fixtures'); -const { NodeInstance } = require('../common/inspector-helper.js'); - -async function runTest() { - const main = fixtures.path('es-module-loaders', 'register-loader.mjs'); - const child = new NodeInstance(['--inspect-brk=0'], '', main); - - const session = await child.connectInspectorSession(); - await session.send({ method: 'NodeRuntime.enable' }); - await session.waitForNotification('NodeRuntime.waitingForDebugger'); - await session.send([ - { 'method': 'Runtime.enable' }, - { 'method': 'Debugger.enable' }, - { 'method': 'Runtime.runIfWaitingForDebugger' }, - ]); - await session.send({ method: 'NodeRuntime.disable' }); - await session.waitForNotification('Debugger.paused'); - await session.runToCompletion(); - assert.strictEqual((await child.expectShutdown()).exitCode, 0); -} - -runTest(); diff --git a/test/parallel/test-esm-loader-hooks-inspect-wait.js b/test/parallel/test-esm-loader-hooks-inspect-wait.js deleted file mode 100644 index 427b05641cce..000000000000 --- a/test/parallel/test-esm-loader-hooks-inspect-wait.js +++ /dev/null @@ -1,35 +0,0 @@ -// This tests esm loader's internal worker will not be blocked by --inspect-wait. -// Regression: https://github.com/nodejs/node/issues/53681 - -'use strict'; -const common = require('../common'); - -common.skipIfInspectorDisabled(); - -const assert = require('assert'); -const fixtures = require('../common/fixtures'); -const { NodeInstance } = require('../common/inspector-helper.js'); - -async function runTest() { - const main = fixtures.path('es-module-loaders', 'register-loader.mjs'); - process.env.NODE_DEBUG = 'esm,async_loader_worker'; - const child = new NodeInstance(['--inspect-wait=0'], '', main); - - const session = await child.connectInspectorSession(); - await session.send({ method: 'NodeRuntime.enable' }); - await session.waitForNotification('NodeRuntime.waitingForDebugger'); - await session.send([ - { 'method': 'Runtime.enable' }, - { 'method': 'Debugger.enable' }, - { 'method': 'Runtime.runIfWaitingForDebugger' }, - ]); - await session.send({ method: 'NodeRuntime.disable' }); - await session.waitForDisconnect(); - const result = await child.expectShutdown(); - assert.deepStrictEqual(result, { - exitCode: 0, - signal: null, - }); -} - -runTest(); diff --git a/test/parallel/test-is-internal-thread.mjs b/test/parallel/test-is-internal-thread.mjs index 27f20f2d2176..6592e236116d 100644 --- a/test/parallel/test-is-internal-thread.mjs +++ b/test/parallel/test-is-internal-thread.mjs @@ -1,33 +1,16 @@ -import { mustCall, spawnPromisified } from '../common/index.mjs'; +import { mustCall } from '../common/index.mjs'; import * as fixtures from '../common/fixtures.mjs'; import assert from 'node:assert'; -import { execPath } from 'node:process'; import { describe, it } from 'node:test'; import { isInternalThread, Worker } from 'node:worker_threads'; describe('worker_threads.isInternalThread', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should be true inside the loader thread', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('loader-is-internal-thread.js'), - '--eval', - 'setTimeout(() => {},99)', - ]); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /isInternalThread: true/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - it('should be false inside the main thread', async () => { assert.strictEqual(isInternalThread, false); }); it('should be false inside a regular worker thread', async () => { const worker = new Worker(fixtures.path('worker-is-internal-thread.js')); - worker.on('message', mustCall((message) => { assert.strictEqual(message, 'isInternalThread: false'); })); diff --git a/test/parallel/test-permission-allow-inspector.js b/test/parallel/test-permission-allow-inspector.js deleted file mode 100644 index 05022ff24044..000000000000 --- a/test/parallel/test-permission-allow-inspector.js +++ /dev/null @@ -1,54 +0,0 @@ -// Flags: --permission --allow-fs-read=* --allow-inspector -'use strict'; - -const common = require('../common'); - -common.skipIfInspectorDisabled(); - -const { Session } = require('node:inspector/promises'); -const assert = require('node:assert'); - -const session = new Session(); -session.connect(); - -// Guarantee WorkerImpl doesn't gets bypassed -(async () => { - await session.post('Debugger.enable'); - await session.post('Runtime.enable'); - - globalThis.Worker = require('node:worker_threads').Worker; - - const { result: { objectId } } = await session.post('Runtime.evaluate', { expression: 'Worker' }); - const { internalProperties } = await session.post('Runtime.getProperties', { objectId: objectId }); - const { - value: { - value: { scriptId } - } - } = internalProperties.filter((prop) => prop.name === '[[FunctionLocation]]')[0]; - const { scriptSource } = await session.post('Debugger.getScriptSource', { scriptId }); - - const lineNumber = scriptSource.substring(0, scriptSource.indexOf('new WorkerImpl')).split('\n').length; - - // Attempt to bypass it based on https://hackerone.com/reports/1962701 - await session.post('Debugger.setBreakpointByUrl', { - lineNumber: lineNumber, - url: 'node:internal/worker', - columnNumber: 0, - condition: '((isInternal = true),false)' - }); - - assert.throws(() => { - new Worker(` - const child_process = require("node:child_process"); - console.log(child_process.execSync("ls -l").toString()); - - console.log(require("fs").readFileSync("/etc/passwd").toString()) - `, { - eval: true, - }); - }, { - message: 'Access to this API has been restricted. Use --allow-worker to manage permissions.', - code: 'ERR_ACCESS_DENIED', - permission: 'WorkerThreads' - }); -})().then(common.mustCall()); diff --git a/test/parallel/test-process-env-allowed-flags-are-documented.js b/test/parallel/test-process-env-allowed-flags-are-documented.js index 910fec097b69..ba33ae989863 100644 --- a/test/parallel/test-process-env-allowed-flags-are-documented.js +++ b/test/parallel/test-process-env-allowed-flags-are-documented.js @@ -137,7 +137,6 @@ assert(undocumented.delete('--experimental-worker')); assert(undocumented.delete('--napi-modules')); assert(undocumented.delete('--node-snapshot')); assert(undocumented.delete('--no-node-snapshot')); -assert(undocumented.delete('--loader')); assert(undocumented.delete('--verify-base-objects')); assert(undocumented.delete('--no-verify-base-objects')); assert(undocumented.delete('--trace-promises')); diff --git a/test/parallel/test-webworker-conditions.js b/test/parallel/test-webworker-conditions.js index 313e3f3d643d..6cf564597eb0 100644 --- a/test/parallel/test-webworker-conditions.js +++ b/test/parallel/test-webworker-conditions.js @@ -70,8 +70,4 @@ function runWebWorker(url, options) { const [threadResult] = await once(thread, 'message'); assert.deepStrictEqual(threadResult, { thread: 'default', webWorker: 'worker' }); - // Async module customization hooks registered from a Web Worker. - assert.strictEqual( - await runWebWorker(new URL('hooks-worker.mjs', base), { type: 'module' }), - 'worker'); })().then(common.mustCall()); diff --git a/typings/internalBinding/worker.d.ts b/typings/internalBinding/worker.d.ts index e168ff8abb17..7801b2c569dd 100644 --- a/typings/internalBinding/worker.d.ts +++ b/typings/internalBinding/worker.d.ts @@ -41,7 +41,6 @@ export interface WorkerBinding { threadId: number; threadName: string; isMainThread: boolean; - isInternalThread: boolean; ownsProcessState: boolean; resourceLimits?: Float64Array; kMaxYoungGenerationSizeMb: number; From 085941ad493398b00acaa9bea60655ce2ce29cee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Guilherme=20Ara=C3=BAjo?= Date: Sat, 14 Nov 2026 21:39:09 -0300 Subject: [PATCH 020/253] src: write strings to streams without flattening MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit StreamBase::WriteString() created a String::ValueView twice, the first time in StringBytes::StorageSize() only to read the length. A ValueView flattens the string, so writing a string built by concatenation, such as the header of an HTTP response, allocated a flat copy on the V8 heap before copying it again into the write buffer. Read the length from the string in StorageSize(), and copy one-byte strings that fit the stack buffer with String::WriteOneByte(), which does not flatten. For UTF-8 the characters go to the last third of the buffer and are converted into the rest of it: a Latin-1 character takes at most two bytes. Assisted-by: Claude Signed-off-by: Guilherme Araújo PR-URL: https://github.com/nodejs/node/pull/67435 Reviewed-By: James M Snell Reviewed-By: Philipp Dunkel --- src/stream_base.cc | 56 ++++++++++++----- src/string_bytes.cc | 16 ++--- .../test-net-write-concatenated-string.js | 60 ++++++++++++++++++ .../test-net-writev-concatenated-string.js | 62 +++++++++++++++++++ 4 files changed, 170 insertions(+), 24 deletions(-) create mode 100644 test/parallel/test-net-write-concatenated-string.js create mode 100644 test/parallel/test-net-writev-concatenated-string.js diff --git a/src/stream_base.cc b/src/stream_base.cc index f36a4b7056ba..8592ca269a0c 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -8,6 +8,7 @@ #include "node_buffer.h" #include "node_errors.h" #include "node_external_reference.h" +#include "simdutf.h" #include "string_bytes.h" #include "util-inl.h" #include "v8.h" @@ -196,6 +197,38 @@ int StreamBase::FinishWrite(const v8::FunctionCallbackInfo& args, return res.err; } +namespace { + +// Same as StringBytes::Write(), but copies one-byte strings out with +// String::WriteOneByte(), which does not flatten them: strings written to a +// stream are often built by concatenation (e.g. HTTP headers) and not used +// again. +size_t WriteStringWithoutFlattening(Isolate* isolate, + char* buf, + size_t buflen, + Local string, + enum encoding enc) { + const size_t length = string->Length(); + if (length == 0) return 0; + if (string->IsOneByte()) { + if ((enc == ASCII || enc == LATIN1) && buflen >= length) { + string->WriteOneByte(isolate, 0, length, reinterpret_cast(buf)); + return length; + } + if (enc == UTF8 && buflen >= 3 * length) { + // Latin-1 takes at most 2 UTF-8 bytes per char: convert from the last + // third into the first two. + char* latin1 = buf + 2 * length; + string->WriteOneByte( + isolate, 0, length, reinterpret_cast(latin1)); + return simdutf::convert_latin1_to_utf8(latin1, length, buf); + } + } + return StringBytes::Write(isolate, buf, buflen, string, enc); +} + +} // namespace + int StreamBase::Writev(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); @@ -297,11 +330,8 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { if (!chunks->Get(context, i * 2 + 1).ToLocal(&next_chunk)) return -1; enum encoding encoding = ParseEncoding(isolate, next_chunk); - str_size = StringBytes::Write(isolate, - str_storage, - str_size, - string, - encoding); + str_size = WriteStringWithoutFlattening( + isolate, str_storage, str_size, string, encoding); bufs[i].base = str_storage; bufs[i].len = str_size; offset += str_size; @@ -372,7 +402,7 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { if (args[2]->IsObject()) send_handle_obj = args[2].As(); - // Compute the size of the storage that the string will be flattened into. + // Compute the size of the storage that the string will be written into. // For UTF8 strings that are very long, go ahead and take the hit for // computing their actual size, rather than tripling the storage. size_t storage_size; @@ -395,11 +425,8 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { bool try_write = HasDoTryWrite() && storage_size <= sizeof(stack_storage) && (!IsIPCPipe() || send_handle_obj.IsEmpty()); if (try_write) { - data_size = StringBytes::Write(isolate, - stack_storage, - storage_size, - string, - enc); + data_size = WriteStringWithoutFlattening( + isolate, stack_storage, storage_size, string, enc); buf = uv_buf_init(stack_storage, data_size); uv_buf_t* bufs = &buf; @@ -433,11 +460,8 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { // Write it bs = ArrayBuffer::NewBackingStore( isolate, storage_size, BackingStoreInitializationMode::kUninitialized); - data_size = StringBytes::Write(isolate, - static_cast(bs->Data()), - storage_size, - string, - enc); + data_size = WriteStringWithoutFlattening( + isolate, static_cast(bs->Data()), storage_size, string, enc); } CHECK_LE(data_size, storage_size); diff --git a/src/string_bytes.cc b/src/string_bytes.cc index 94b579b6984d..9aec2abc41a5 100644 --- a/src/string_bytes.cc +++ b/src/string_bytes.cc @@ -468,13 +468,13 @@ Maybe StringBytes::StorageSize(Isolate* isolate, Local str; if (!val->ToString(isolate->GetCurrentContext()).ToLocal(&str)) return Nothing(); - String::ValueView view(isolate, str); + const size_t length = str->Length(); size_t data_size = 0; switch (encoding) { case ASCII: case LATIN1: - data_size = view.length(); + data_size = length; break; case BUFFER: @@ -482,24 +482,24 @@ Maybe StringBytes::StorageSize(Isolate* isolate, // A single UCS2 codepoint never takes up more than 3 utf8 bytes. // It is an exercise for the caller to decide when a string is // long enough to justify calling Size() instead of StorageSize() - data_size = 3 * view.length(); + data_size = 3 * length; break; case UCS2: - data_size = view.length() * sizeof(uint16_t); + data_size = length * sizeof(uint16_t); break; case BASE64URL: - data_size = simdutf::base64_length_from_binary(view.length(), - simdutf::base64_url); + data_size = + simdutf::base64_length_from_binary(length, simdutf::base64_url); break; case BASE64: - data_size = simdutf::base64_length_from_binary(view.length()); + data_size = simdutf::base64_length_from_binary(length); break; case HEX: - data_size = view.length() / 2; + data_size = length / 2; break; default: diff --git a/test/parallel/test-net-write-concatenated-string.js b/test/parallel/test-net-write-concatenated-string.js new file mode 100644 index 000000000000..8bfc7a4dd485 --- /dev/null +++ b/test/parallel/test-net-write-concatenated-string.js @@ -0,0 +1,60 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + +// Writes concatenated strings around the size limits of the stack buffer used +// by StreamBase::WriteString() and checks the bytes on the wire. + +function concat(length, base) { + let str = ''; + for (let i = 0; i < length; i++) + str += String.fromCharCode(base + i % 16); + return str; +} + +const cases = []; +for (const length of [0, 13, 5461, 5462, 16384, 16385]) { + // ASCII, non-ASCII Latin-1, two-byte. + for (const base of [0x61, 0xe0, 0x2000]) { + for (const encoding of ['utf8', 'latin1', 'ascii']) { + cases.push({ length, base, encoding }); + } + } +} + +const expected = []; + +const server = net.createServer(common.mustCall((socket) => { + const chunks = []; + socket.on('data', (chunk) => chunks.push(chunk)); + socket.on('end', common.mustCall(() => { + const actual = Buffer.concat(chunks); + let offset = 0; + for (const [i, buf] of expected.entries()) { + const { length, base, encoding } = cases[i]; + assert.deepStrictEqual( + actual.subarray(offset, offset + buf.length), + buf, + `length ${length}, base 0x${base.toString(16)}, ${encoding}`); + offset += buf.length; + } + assert.strictEqual(offset, actual.length); + server.close(); + })); +})); + +server.listen(0, common.mustCall(() => { + const socket = net.connect(server.address().port); + let i = 0; + function next() { + if (i === cases.length) return socket.end(); + const { length, base, encoding } = cases[i++]; + const str = concat(length, base); + // Each write waits for the previous one so that it goes through + // WriteString() and not Writev(). + socket.write(str, encoding, common.mustSucceed(next)); + expected.push(Buffer.from(str, encoding)); + } + socket.on('connect', common.mustCall(next)); +})); diff --git a/test/parallel/test-net-writev-concatenated-string.js b/test/parallel/test-net-writev-concatenated-string.js new file mode 100644 index 000000000000..975630fe1ac2 --- /dev/null +++ b/test/parallel/test-net-writev-concatenated-string.js @@ -0,0 +1,62 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + +// Writes concatenated strings with a Buffer after each of them in a single +// StreamBase::Writev() call, like an HTTP response header followed by a Buffer +// body, and checks the bytes on the wire. + +function concat(length, base) { + let str = ''; + for (let i = 0; i < length; i++) + str += String.fromCharCode(base + i % 16); + return str; +} + +const separator = Buffer.from('|'); +const writes = []; +// Writev() reserves 3 bytes per character for UTF-8 strings of up to 65535 +// characters and the exact size for longer ones. +for (const length of [0, 13, 5461, 16385, 65535, 65536]) { + // ASCII, non-ASCII Latin-1, two-byte. + for (const base of [0x61, 0xe0, 0x2000]) { + for (const encoding of ['utf8', 'latin1', 'ascii']) { + writes.push({ + label: `length ${length}, base 0x${base.toString(16)}, ${encoding}`, + str: concat(length, base), + encoding, + }); + } + } +} + +const server = net.createServer(common.mustCall((socket) => { + const chunks = []; + socket.on('data', (chunk) => chunks.push(chunk)); + socket.on('end', common.mustCall(() => { + const actual = Buffer.concat(chunks); + let offset = 0; + for (const { label, str, encoding } of writes) { + const expected = Buffer.concat([Buffer.from(str, encoding), separator]); + assert.deepStrictEqual( + actual.subarray(offset, offset + expected.length), expected, label); + offset += expected.length; + } + assert.strictEqual(offset, actual.length); + server.close(); + })); +})); + +server.listen(0, common.mustCall(() => { + const socket = net.connect(server.address().port, common.mustCall(() => { + // Corked writes are flushed together with Writev(). + socket.cork(); + for (const { str, encoding } of writes) { + socket.write(str, encoding); + socket.write(separator); + } + socket.uncork(); + socket.end(); + })); +})); From 56bc6f0fded8205825f82912faf7daeb78d3fcfd Mon Sep 17 00:00:00 2001 From: Christian Aurich Zanettini Martins Date: Sun, 15 Nov 2026 01:17:27 -0300 Subject: [PATCH 021/253] fs: use correct position when retrying writev writevAll() tracks the position for the next attempt in its `pos` argument, but calls fs.writev() with `this.pos`. WriteStream._writev() advances `this.pos` by the whole batch right after starting the write, so a retry from the asynchronous callback resumes at the end of the batch instead of after the bytes that reached the file. A partial write leaves a hole and puts the remainder past its place; an EAGAIN retry moves forward even though nothing was written. Use the local `pos`, as writeAll() already does. Signed-off-by: Christian Aurich Zanettini Martins PR-URL: https://github.com/nodejs/node/pull/66203 Refs: https://github.com/nodejs/node/pull/49211 Reviewed-By: Robert Nagy Reviewed-By: Matteo Collina --- lib/internal/fs/streams.js | 2 +- ...t-fs-write-stream-writev-retry-position.js | 74 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-fs-write-stream-writev-retry-position.js diff --git a/lib/internal/fs/streams.js b/lib/internal/fs/streams.js index c8c86b59640a..5fd47bb5e49f 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -473,7 +473,7 @@ function writeAll(data, size, pos, cb, retries = 0) { } function writevAll(chunks, size, pos, cb, retries = 0) { - this[kFs].writev(this.fd, chunks, this.pos, (er, bytesWritten, buffers) => { + this[kFs].writev(this.fd, chunks, pos, (er, bytesWritten, buffers) => { // No data currently available and operation should be retried later. if (er?.code === 'EAGAIN') { er = null; diff --git a/test/parallel/test-fs-write-stream-writev-retry-position.js b/test/parallel/test-fs-write-stream-writev-retry-position.js new file mode 100644 index 000000000000..17dfb474ceff --- /dev/null +++ b/test/parallel/test-fs-write-stream-writev-retry-position.js @@ -0,0 +1,74 @@ +'use strict'; +const common = require('../common'); +const tmpdir = require('../common/tmpdir'); +const assert = require('assert'); +const fs = require('fs'); + +tmpdir.refresh(); + +const data = 'AAAABBBBCCCC'; + +// Report back fewer bytes than were handed over, asynchronously: the retry has +// to observe the position as it is after _writev() advanced this.pos by the +// whole batch. +function shortWrite(bytes) { + return (fd, chunks, position, cb) => { + const head = Buffer.concat(chunks).subarray(0, bytes); + fs.write(fd, head, 0, bytes, position, + (er, bytesWritten) => cb(er, bytesWritten, chunks)); + }; +} + +function eagain(fd, chunks, position, cb) { + process.nextTick(cb, Object.assign(new Error(), { code: 'EAGAIN' }), 0, chunks); +} + +// The positions handed to writev() are the contract under test: watching the +// resulting file alone would still pass if some later rewrite happened to land +// the bytes correctly by another route. +function run(name, { prefix = '', start, firstCall }, expectedPositions) { + const file = tmpdir.resolve(`partial-writev-${name}.txt`); + fs.writeFileSync(file, prefix); + + const positions = []; + const stream = fs.createWriteStream(file, { + flags: 'r+', + start, + fs: { + ...fs, + writev: common.mustCall((fd, chunks, position, cb) => { + positions.push(position); + if (positions.length === 1) { + firstCall(fd, chunks, position, cb); + } else { + fs.writev(fd, chunks, position, cb); + } + }, 2), + }, + }); + + stream.cork(); + stream.write('AAAA'); + stream.write('BBBB'); + stream.write('CCCC'); + stream.uncork(); + stream.end(); + + stream.on('error', common.mustNotCall()); + stream.on('close', common.mustCall(() => { + if (expectedPositions !== undefined) { + assert.deepStrictEqual(positions, expectedPositions, `${name} positions`); + } + assert.strictEqual(fs.readFileSync(file, 'utf8'), prefix + data, name); + })); +} + +// Partial write: resume right after the bytes that reached the disk. +run('start-5', { prefix: '#####', start: 5, firstCall: shortWrite(3) }, [5, 8]); +run('start-0', { start: 0, firstCall: shortWrite(3) }, [0, 3]); + +// EAGAIN: nothing was written, so the retry goes back to the same position. +run('eagain', { prefix: '#####', start: 5, firstCall: eagain }, [5, 5]); + +// Without a start the stream follows the fd offset; only the bytes matter. +run('no-start', { firstCall: shortWrite(3) }); From 9af13a6f03b5f9b2d7382194850f28e17128b968 Mon Sep 17 00:00:00 2001 From: Jason Zhang Date: Sun, 15 Nov 2026 15:18:02 +1030 Subject: [PATCH 022/253] src: avoid aborting on filesystem errors in node --run `node --run` called the throwing overloads of `std::filesystem::is_directory()` and `std::filesystem::current_path()`. An unreadable `node_modules` directory or a removed working directory made them throw, and the uncaught exception aborted the process. Use the `std::error_code` overloads instead. A `node_modules/.bin` that cannot be inspected is skipped, and a missing working directory is reported as a regular error. Signed-off-by: jazelly PR-URL: https://github.com/nodejs/node/pull/67270 Fixes: https://github.com/nodejs/node/issues/67269 Reviewed-By: James M Snell Reviewed-By: Yagiz Nizipli Reviewed-By: Jake Yuesong Li --- src/node_task_runner.cc | 14 +++++++++-- test/parallel/test-node-run.js | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/node_task_runner.cc b/src/node_task_runner.cc index 136dec24fa02..b9716846abfc 100644 --- a/src/node_task_runner.cc +++ b/src/node_task_runner.cc @@ -233,7 +233,9 @@ FindPackageJson(const std::filesystem::path& cwd) { directory_path = directory_path.parent_path()) { // Append "path/node_modules/.bin" to the env var, if it is a directory. auto node_modules_bin = directory_path / "node_modules" / ".bin"; - if (std::filesystem::is_directory(node_modules_bin)) { + // Skip directories that can't be inspected (e.g. permission denied). + std::error_code error_code; + if (std::filesystem::is_directory(node_modules_bin, error_code)) { path_env_var += ConvertPathToUTF8(node_modules_bin) + env_var_separator; } @@ -279,7 +281,15 @@ static void PrintScripts(FILE* out, void RunTask(const std::shared_ptr& result, std::string_view command_id, const std::vector& positional_args) { - auto cwd = std::filesystem::current_path(); + std::error_code error_code; + auto cwd = std::filesystem::current_path(error_code); + if (error_code) { + fprintf(stderr, + "Can't determine the current working directory: %s\n", + error_code.message().c_str()); + result->exit_code_ = ExitCode::kGenericUserError; + return; + } auto package_json = FindPackageJson(cwd); if (!package_json.has_value()) { diff --git a/test/parallel/test-node-run.js b/test/parallel/test-node-run.js index 57faa80b9f82..b276c54ca23e 100644 --- a/test/parallel/test-node-run.js +++ b/test/parallel/test-node-run.js @@ -12,6 +12,8 @@ const fixtures = require('../common/fixtures'); const tmpdir = require('../common/tmpdir'); const envSuffix = common.isWindows ? '-windows' : ''; +tmpdir.refresh(); + describe('node --run [command]', { concurrency: !process.env.TEST_PARALLEL }, () => { it('returns error on non-existent file', async () => { const child = await common.spawnPromisified( @@ -336,4 +338,45 @@ describe('node --run [command]', { concurrency: !process.env.TEST_PARALLEL }, () assert.strictEqual(child.stdout, ''); assert.strictEqual(child.code, 1); }); + + it('skips node_modules directories that cannot be inspected', { + skip: common.isWindows || process.getuid() === 0, + }, async () => { + const projectDir = tmpdir.resolve('unreadable-node-modules'); + const nodeModules = path.join(projectDir, 'node_modules'); + fs.mkdirSync(nodeModules, { recursive: true }); + fs.writeFileSync(path.join(projectDir, 'package.json'), JSON.stringify({ + scripts: { test: 'echo ok' }, + })); + fs.chmodSync(nodeModules, 0o000); + try { + const child = await common.spawnPromisified( + process.execPath, + [ '--run', 'test'], + { cwd: projectDir }, + ); + assert.strictEqual(child.stdout.trim(), 'ok'); + assert.strictEqual(child.stderr, ''); + assert.strictEqual(child.code, 0); + } finally { + fs.chmodSync(nodeModules, 0o755); + } + }); + + it('returns error when the current working directory is removed', { + // Windows, SunOS, AIX and IBM i refuse to remove a directory that is in + // use as a cwd. + skip: common.isWindows || common.isSunOS || common.isAIX || common.isIBMi, + }, async () => { + const removedDir = tmpdir.resolve('removed-cwd'); + fs.mkdirSync(removedDir); + const child = await common.spawnPromisified( + '/bin/sh', + [ '-c', 'rmdir "$PWD" && exec "$0" --run test', process.execPath], + { cwd: removedDir }, + ); + assert.match(child.stderr, /Can't determine the current working directory/); + assert.strictEqual(child.stdout, ''); + assert.strictEqual(child.code, 1); + }); }); From c8b430f17fae5ea9a0789fdfa2bbba6a8dffc743 Mon Sep 17 00:00:00 2001 From: Hamza Kargin Date: Sun, 15 Nov 2026 13:43:51 +0400 Subject: [PATCH 023/253] fs: respect setDefaultHighWaterMark in ReadStream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ReadStream ignored stream.setDefaultHighWaterMark() and always used 64 KiB. Use the user-set value when there is one, and keep 64 KiB otherwise so Windows does not drop to the 16 KiB stream default. Fixes: https://github.com/nodejs/node/issues/66937 Signed-off-by: Hamza Kargın PR-URL: https://github.com/nodejs/node/pull/66956 Reviewed-By: Robert Nagy Reviewed-By: Gürgün Dayıoğlu --- doc/api/fs.md | 10 ++++-- lib/internal/fs/streams.js | 3 +- lib/internal/streams/state.js | 7 ++++ .../test-fs-read-stream-set-default-hwm.js | 34 +++++++++++++++++++ 4 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 test/parallel/test-fs-read-stream-set-default-hwm.js diff --git a/doc/api/fs.md b/doc/api/fs.md index 93e6e7c68a18..929ea3029576 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -265,7 +265,8 @@ added: v16.11.0 * `emitClose` {boolean} **Default:** `true` * `start` {integer} * `end` {integer} **Default:** `Infinity` - * `highWaterMark` {integer} **Default:** `64 * 1024` + * `highWaterMark` {integer} **Default:** `64 * 1024`, or the value set with + [`stream.setDefaultHighWaterMark()`][] * `signal` {AbortSignal|undefined} **Default:** `undefined` * Returns: {fs.ReadStream} @@ -781,7 +782,8 @@ added: v18.11.0 * `emitClose` {boolean} **Default:** `true` * `start` {integer} * `end` {integer} **Default:** `Infinity` - * `highWaterMark` {integer} **Default:** `64 * 1024` + * `highWaterMark` {integer} **Default:** `64 * 1024`, or the value set with + [`stream.setDefaultHighWaterMark()`][] * Returns: {readline.InterfaceConstructor} Convenience method to create a `readline` interface and stream over the file. @@ -3104,7 +3106,8 @@ changes: * `emitClose` {boolean} **Default:** `true` * `start` {integer} * `end` {integer} **Default:** `Infinity` - * `highWaterMark` {integer} **Default:** `64 * 1024` + * `highWaterMark` {integer} **Default:** `64 * 1024`, or the value set with + [`stream.setDefaultHighWaterMark()`][] * `fs` {Object|null} **Default:** `null` * `signal` {AbortSignal|null} **Default:** `null` * `windowsHandle` {bigint} A raw Win32 `HANDLE` value to read from, in place @@ -9787,6 +9790,7 @@ the file contents. [`path.matchesGlob()`]: path.md#pathmatchesglobpath-pattern [`statfs.bsize`]: #statfsbsize [`stream.getDefaultHighWaterMark()`]: stream.md#streamgetdefaulthighwatermarkobjectmode +[`stream.setDefaultHighWaterMark()`]: stream.md#streamsetdefaulthighwatermarkobjectmode-value [`stream/iter pipeTo()`]: stream_iter.md#pipetosource-transforms-writer-options [`stream/iter pull()`]: stream_iter.md#pullsource-transforms-options [`stream/iter pullSync()`]: stream_iter.md#pullsyncsource-transforms diff --git a/lib/internal/fs/streams.js b/lib/internal/fs/streams.js index 5fd47bb5e49f..9bfbaa011255 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -33,6 +33,7 @@ const { validateThisInternalField, } = require('internal/validators'); const { errorOrDestroy } = require('internal/streams/destroy'); +const { getUserDefaultHighWaterMark } = require('internal/streams/state'); const fs = require('fs'); const { kRef, kUnref, FileHandle } = require('internal/fs/promises'); const { Buffer } = require('buffer'); @@ -193,7 +194,7 @@ function ReadStream(path, options) { // A little bit bigger buffer and water marks by default options = copyObject(getOptions(options, kEmptyObject)); if (options.highWaterMark === undefined) - options.highWaterMark = 64 * 1024; + options.highWaterMark = getUserDefaultHighWaterMark() ?? 64 * 1024; if (options.autoDestroy === undefined) { options.autoDestroy = false; diff --git a/lib/internal/streams/state.js b/lib/internal/streams/state.js index 46e0ff9c9553..c68dba2a4d88 100644 --- a/lib/internal/streams/state.js +++ b/lib/internal/streams/state.js @@ -11,6 +11,7 @@ const { ERR_INVALID_ARG_VALUE } = require('internal/errors').codes; // TODO (fix): For some reason Windows CI fails with bigger hwm. let defaultHighWaterMarkBytes = process.platform === 'win32' ? 16 * 1024 : 64 * 1024; let defaultHighWaterMarkObjectMode = 16; +let defaultHighWaterMarkBytesSet = false; function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : @@ -27,9 +28,14 @@ function setDefaultHighWaterMark(objectMode, value) { defaultHighWaterMarkObjectMode = value; } else { defaultHighWaterMarkBytes = value; + defaultHighWaterMarkBytesSet = true; } } +function getUserDefaultHighWaterMark() { + return defaultHighWaterMarkBytesSet ? defaultHighWaterMarkBytes : undefined; +} + function getHighWaterMark(state, options, duplexKey, isDuplex) { const hwm = highWaterMarkFrom(options, isDuplex, duplexKey); if (hwm != null) { @@ -47,5 +53,6 @@ function getHighWaterMark(state, options, duplexKey, isDuplex) { module.exports = { getHighWaterMark, getDefaultHighWaterMark, + getUserDefaultHighWaterMark, setDefaultHighWaterMark, }; diff --git a/test/parallel/test-fs-read-stream-set-default-hwm.js b/test/parallel/test-fs-read-stream-set-default-hwm.js new file mode 100644 index 000000000000..3ec78dacc43a --- /dev/null +++ b/test/parallel/test-fs-read-stream-set-default-hwm.js @@ -0,0 +1,34 @@ +'use strict'; + +const common = require('../common'); + +const assert = require('node:assert'); +const fs = require('node:fs'); +const { setDefaultHighWaterMark } = require('node:stream'); + +{ + const stream = fs.createReadStream(__filename); + assert.strictEqual(stream.readableHighWaterMark, 64 * 1024); + stream.destroy(); +} + +setDefaultHighWaterMark(false, 1024 * 1024); + +{ + const stream = fs.createReadStream(__filename); + assert.strictEqual(stream.readableHighWaterMark, 1024 * 1024); + stream.destroy(); +} + +{ + const stream = fs.createReadStream(__filename, { highWaterMark: 1024 }); + assert.strictEqual(stream.readableHighWaterMark, 1024); + stream.destroy(); +} + +fs.promises.open(__filename).then(async (fh) => { + const stream = fh.createReadStream({ autoClose: false }); + assert.strictEqual(stream.readableHighWaterMark, 1024 * 1024); + stream.destroy(); + await fh.close(); +}).then(common.mustCall()); From 50aa2316153a80e02408b87d00a005529691d666 Mon Sep 17 00:00:00 2001 From: Livia Medeiros Date: Sun, 15 Nov 2026 19:52:26 +0800 Subject: [PATCH 024/253] util: use `Map.prototype.getOrInsert()` in circular reference formatting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: LiviaMedeiros PR-URL: https://github.com/nodejs/node/pull/67451 Reviewed-By: Jordan Harband Reviewed-By: René --- lib/internal/util/inspect.js | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 26cf23bf0fa3..30bfa41b0ce5 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1173,17 +1173,8 @@ function formatValue(ctx, value, recurseTimes, typedArray) { // Using an array here is actually better for the average case than using // a Set. `seen` will only check for the depth and will never grow too large. if (ctx.seen.includes(value)) { - let index = 1; - if (ctx.circular === undefined) { - ctx.circular = new SafeMap(); - ctx.circular.set(value, index); - } else { - index = ctx.circular.get(value); - if (index === undefined) { - index = ctx.circular.size + 1; - ctx.circular.set(value, index); - } - } + ctx.circular ??= new SafeMap(); + const index = ctx.circular.getOrInsert(value, ctx.circular.size + 1); return ctx.stylize(`[Circular *${index}]`, 'special'); } From 399228bd0ffd99699772f46c9a4ff135a967ea51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCrg=C3=BCn=20Day=C4=B1o=C4=9Flu?= Date: Sun, 15 Nov 2026 22:15:27 +0300 Subject: [PATCH 025/253] fs,path: fix glob globstar section bounds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The last start index of each globstar-delimited body section was computed from the non-globstar prefix counts in reverse order. When sections have different lengths, the bound is too tight, so paths such as `a/b/c/d/e` failed to match `**/a/b/c/**/d/**`. This affected `path.matchesGlob()` and `exclude` patterns in `fs.glob()`. Compute the bound from the number of non-globstar parts in the section and every section after it. Signed-off-by: Gürgün Dayıoğlu PR-URL: https://github.com/nodejs/node/pull/66738 Reviewed-By: Aviv Keller Reviewed-By: Efe Karasakal --- src/glob/glob_matcher.cc | 9 +++------ test/parallel/test-path-glob.js | 6 ++++++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/glob/glob_matcher.cc b/src/glob/glob_matcher.cc index e0cca5cf43e6..53d59fb8a358 100644 --- a/src/glob/glob_matcher.cc +++ b/src/glob/glob_matcher.cc @@ -673,12 +673,9 @@ class PathMatcher { } const ptrdiff_t file_length = static_cast(file.size()) - static_cast(file_tail_match); - { - size_t i = sections.size() - 1; - for (Section& s : sections) { - s.after = file_length - (static_cast(sections[i--].non_gs) + - static_cast(s.end - s.begin)); - } + // leave room for this section and every section after it + for (Section& s : sections) { + s.after = file_length - static_cast(non_gs - s.non_gs); } return MatchBodySections( file, pattern, sections, fi, 0, 0, file_tail_match != 0); diff --git a/test/parallel/test-path-glob.js b/test/parallel/test-path-glob.js index 11633f52245e..6b53e26bdd6f 100644 --- a/test/parallel/test-path-glob.js +++ b/test/parallel/test-path-glob.js @@ -16,6 +16,9 @@ const globs = { ['foo\\bar\\baz\\boo', 'foo\\[bc-r]ar\\baz\\*', true], // Matches 'bar' or 'car' in 'foo\\bar' ['foo\\bar\\baz', 'foo/**', true], // Matches anything in 'foo' ['foo\\bar\\baz', '*', false], // No match + ['a\\b\\c\\d\\e', '**/a/b/c/**/d/**', true], // Globstar sections of different lengths + ['x\\a\\b\\c\\d\\e', '**/a/b/c/**/d/**/e', true], // Globstar sections of different lengths + ['a\\b\\c\\d', '**/a/b/c/**/d/**', false], // Trailing globstar needs a segment ], posix: [ ['foo/bar/baz', 'foo/[bcr]ar/baz', true], // Matches 'bar' or 'car' in 'foo/bar' @@ -28,6 +31,9 @@ const globs = { ['foo/bar/baz/boo', 'foo/[bc-r]ar/baz/*', true], // Matches 'bar' or 'car' in 'foo/bar' ['foo/bar/baz', 'foo/**', true], // Matches anything in 'foo' ['foo/bar/baz', '*', false], // No match + ['a/b/c/d/e', '**/a/b/c/**/d/**', true], // Globstar sections of different lengths + ['x/a/b/c/d/e', '**/a/b/c/**/d/**/e', true], // Globstar sections of different lengths + ['a/b/c/d', '**/a/b/c/**/d/**', false], // Trailing globstar needs a segment ], }; From f4bdf9bdcf8312be2089b663a6c610792d1335d8 Mon Sep 17 00:00:00 2001 From: Hilary Asogwa <76795262+Dansatch@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:01:09 +0000 Subject: [PATCH 026/253] url: validate href setter receiver first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Validate the URL receiver before converting the assigned href value. Fixes: https://github.com/nodejs/node/issues/67344 Signed-off-by: dansatch PR-URL: https://github.com/nodejs/node/pull/67350 Reviewed-By: Antoine du Hamel Reviewed-By: Gürgün Dayıoğlu --- lib/internal/url.js | 3 ++- .../test-whatwg-url-custom-href-side-effect.js | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/internal/url.js b/lib/internal/url.js index 0fe819fe129c..2d1339702b96 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -1022,8 +1022,9 @@ class URL { } set href(value) { + const context = this.#context; value = `${value}`; - const href = bindingUrl.update(this.#context.href, updateActions.kHref, value); + const href = bindingUrl.update(context.href, updateActions.kHref, value); if (!href) { throw new ERR_INVALID_URL(value); } this.#updateContext(href, true); } diff --git a/test/parallel/test-whatwg-url-custom-href-side-effect.js b/test/parallel/test-whatwg-url-custom-href-side-effect.js index 30967d9feaef..daecb2a2226f 100644 --- a/test/parallel/test-whatwg-url-custom-href-side-effect.js +++ b/test/parallel/test-whatwg-url-custom-href-side-effect.js @@ -13,3 +13,19 @@ assert.throws(() => { }); assert.deepStrictEqual(url, ref); + +const setHref = Object.getOwnPropertyDescriptor(URL.prototype, 'href').set; +let calls = 0; + +assert.throws(() => { + setHref.call({}, { + toString() { + calls++; + return 'https://example.com/'; + }, + }); +}, { + name: 'TypeError', +}); + +assert.strictEqual(calls, 0); From f82c9d3200e189287811d050b31ad9bfdc383c6a Mon Sep 17 00:00:00 2001 From: Roberto Bianchi Date: Sun, 15 Nov 2026 23:01:21 +0100 Subject: [PATCH 027/253] lib: use indexed appends for dependent signals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Avoid a primordial push call for each dependent signal. Signed-off-by: Roberto Bianchi PR-URL: https://github.com/nodejs/node/pull/67299 Reviewed-By: Gürgün Dayıoğlu Reviewed-By: Jordan Harband Reviewed-By: James M Snell --- lib/internal/abort_controller.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/internal/abort_controller.js b/lib/internal/abort_controller.js index 7daa63e1f91d..9f524d5cb5e2 100644 --- a/lib/internal/abort_controller.js +++ b/lib/internal/abort_controller.js @@ -4,7 +4,6 @@ // in https://github.com/mysticatea/abort-controller (MIT license) const { - ArrayPrototypePush, FunctionPrototypeCall, ObjectAssign, ObjectDefineProperties, @@ -577,7 +576,7 @@ function abortSignal(signal, reason) { dependentSignal[kReason] = reason; dependentSignal[kAborted] = true; // 2. Append dependentSignal to dependentSignalsToAbort. - ArrayPrototypePush(dependentSignalsToAbort, dependentSignal); + dependentSignalsToAbort[dependentSignalsToAbort.length] = dependentSignal; } }); } From add0fde1d154b4a927b7306b09a6d23df1f4f3a6 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Mon, 16 Nov 2026 01:31:32 +0100 Subject: [PATCH 028/253] tls: normalize session buffer views MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Client sessions can be supplied as ArrayBuffer views, but session state checks only recognize Buffers. Normalize views to Buffers before applying those checks, preserving their byte offset and length. This hardens session reuse handling and keeps tagged sessions reusable when stored as typed arrays. Assisted-by: Codex Signed-off-by: Matteo Collina PR-URL: https://github.com/nodejs/node/pull/67251 Reviewed-By: Robert Nagy Reviewed-By: James M Snell Reviewed-By: Filip Skokan Reviewed-By: Gürgün Dayıoğlu --- lib/internal/tls/wrap.js | 3 + .../test-tls-session-arraybuffer-view.js | 127 ++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 test/parallel/test-tls-session-arraybuffer-view.js diff --git a/lib/internal/tls/wrap.js b/lib/internal/tls/wrap.js index 4e295d9f8ca5..2d5886ea8010 100644 --- a/lib/internal/tls/wrap.js +++ b/lib/internal/tls/wrap.js @@ -175,6 +175,9 @@ function getSessionForReuse(session, options) { if (options?.isServer) return session; + if (!Buffer.isBuffer(session) && isArrayBufferView(session)) + session = Buffer.from(session.buffer, session.byteOffset, session.byteLength); + const wrappedSession = unwrapSessionState(session); if (wrappedSession !== undefined) { const servername = getSessionServerIdentity(options); diff --git a/test/parallel/test-tls-session-arraybuffer-view.js b/test/parallel/test-tls-session-arraybuffer-view.js new file mode 100644 index 000000000000..2853c7a2239e --- /dev/null +++ b/test/parallel/test-tls-session-arraybuffer-view.js @@ -0,0 +1,127 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const { once } = require('events'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); + +async function connect(options, useSetter = false, captureSession = false) { + const { session, ...connectOptions } = options; + const socket = tls.connect(useSetter ? connectOptions : options); + const closed = new Promise((resolve) => { + socket.once('close', common.mustCall(resolve)); + }); + if (useSetter) + socket.setSession(session); + const sessionPromise = captureSession ? once(socket, 'session') : undefined; + socket.resume(); + + try { + await once(socket, 'secureConnect'); + const result = { + reused: socket.isSessionReused(), + authorized: socket.authorized, + session: captureSession ? (await sessionPromise)[0] : undefined, + }; + await closed; + return result; + } finally { + socket.destroy(); + } +} + +function offsetView(session, View) { + // Keep unrelated bytes on both sides to check that only the view is used. + const buffer = new ArrayBuffer(session.length + 16); + new Uint8Array(buffer).fill(0xff); + new Uint8Array(buffer, 8, session.length).set(session); + return new View(buffer, 8, session.length); +} + +async function testVersion(version) { + const server = tls.createServer({ + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem'), + minVersion: version, + maxVersion: version, + }, (socket) => socket.end('ok')); + server.listen(0); + await once(server, 'listening'); + + try { + const options = { + port: server.address().port, + host: '127.0.0.1', + servername: 'agent1', + ca: fixtures.readKey('ca1-cert.pem'), + minVersion: version, + maxVersion: version, + }; + const first = await connect(options, false, true); + assert.strictEqual(first.authorized, true); + assert.strictEqual(first.reused, false); + + const tagged = first.session; + const prefix = Buffer.from('\0nodejs:tls:session:1\0'); + assert.deepStrictEqual(tagged.subarray(0, prefix.length), prefix); + const raw = tagged.subarray( + prefix.length + 2 + tagged.readUInt16BE(prefix.length)); + + const conversions = [ + (session) => session, + (session) => session.toString('latin1'), + (session) => new Uint8Array(session), + (session) => new Uint8ClampedArray(session), + (session) => new Int8Array(session), + (session) => offsetView(session, Uint8Array), + (session) => offsetView(session, DataView), + ]; + + for (const convert of conversions) { + for (const useSetter of [false, true]) { + // Untagged sessions must cause a full handshake on verified clients. + const fresh = await connect({ + ...options, + session: convert(raw), + }, useSetter); + assert.strictEqual(fresh.authorized, true); + assert.strictEqual(fresh.reused, false); + + // A tagged session still resumes for its authenticated host. + const resumed = await connect({ + ...options, + session: convert(tagged), + }, useSetter); + assert.strictEqual(resumed.authorized, true); + assert.strictEqual(resumed.reused, true); + + for (const session of [raw, tagged]) { + await assert.rejects(connect({ + ...options, + servername: 'bank.example', + session: convert(session), + }, useSetter), { code: 'ERR_TLS_CERT_ALTNAME_INVALID' }); + } + + // Raw sessions remain usable when verification is explicitly disabled. + const unverified = await connect({ + ...options, + session: convert(raw), + rejectUnauthorized: false, + }, useSetter); + assert.strictEqual(unverified.reused, true); + } + } + } finally { + server.close(); + await once(server, 'close'); + } +} + +(async () => { + await testVersion('TLSv1.2'); + await testVersion('TLSv1.3'); +})().then(common.mustCall()); From 5e297a0843e693e85299c9af9bfaa535fbb1a31f Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 14 Nov 2026 07:02:31 +0800 Subject: [PATCH 029/253] doc: deprecate `util.TextDecoder` and `util.TextEncoder` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: LiviaMedeiros PR-URL: https://github.com/nodejs/node/pull/67461 Reviewed-By: Aviv Keller Reviewed-By: James M Snell Reviewed-By: Antoine du Hamel Reviewed-By: Filip Skokan Reviewed-By: Gürgün Dayıoğlu --- doc/api/deprecations.md | 14 ++++++++++++++ doc/api/util.md | 2 ++ test/doctool/test-doc-api-json.mjs | 2 +- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index fc333e937d6b..b31bfffc11bc 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -4847,6 +4847,20 @@ Type: Documentation-only `node:sqlite`'s `StatementSync` class was renamed to `Statement`. `StatementSync` is kept as a deprecated alias. Use `Statement` instead. +### DEP0212: `util.TextDecoder` and `util.TextEncoder` + + + +Type: Documentation-only + +`node:util`'s `util.TextDecoder` and `util.TextEncoder` are deprecated. +Use global `TextDecoder` and `TextEncoder` instead. + [DEP0142]: #dep0142-repl_builtinlibs [DEP0156]: #dep0156-aborted-property-and-abort-aborted-event-in-http [NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf diff --git a/doc/api/util.md b/doc/api/util.md index c30831019d0e..176722568e48 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -2928,6 +2928,7 @@ The full list of formats can be found in [modifiers][]. -The WHATWG `TextDecoder` class. See the [`TextDecoder`][] section. +An implementation of the [WHATWG Encoding Standard][] `TextDecoder` API. + +```js +const decoder = new TextDecoder(); +const u8arr = new Uint8Array([72, 101, 108, 108, 111]); +console.log(decoder.decode(u8arr)); // Hello +``` + +### WHATWG supported encodings + +Per the [WHATWG Encoding Standard][], the encodings supported by the +`TextDecoder` API are outlined in the tables below. For each encoding, +one or more aliases may be used. + +Different Node.js build configurations support different sets of encodings. +(see [Internationalization][]) + +#### Encodings supported by default (with full ICU data) + +| Encoding | Aliases | +| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` | +| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` | +| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` | +| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` | +| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` | +| `'iso-8859-6'` | `'arabic'`, `'asmo-708'`, `'csiso88596e'`, `'csiso88596i'`, `'csisolatinarabic'`, `'ecma-114'`, `'iso-8859-6-e'`, `'iso-8859-6-i'`, `'iso-ir-127'`, `'iso8859-6'`, `'iso88596'`, `'iso_8859-6'`, `'iso_8859-6:1987'` | +| `'iso-8859-7'` | `'csisolatingreek'`, `'ecma-118'`, `'elot_928'`, `'greek'`, `'greek8'`, `'iso-ir-126'`, `'iso8859-7'`, `'iso88597'`, `'iso_8859-7'`, `'iso_8859-7:1987'`, `'sun_eu_greek'` | +| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` | +| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` | +| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` | +| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` | +| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` | +| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` | +| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` | +| `'koi8-u'` | `'koi8-ru'` | +| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` | +| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` | +| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` | +| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` | +| `'windows-1252'` | `'ansi_x3.4-1968'`, `'ascii'`, `'cp1252'`, `'cp819'`, `'csisolatin1'`, `'ibm819'`, `'iso-8859-1'`, `'iso-ir-100'`, `'iso8859-1'`, `'iso88591'`, `'iso_8859-1'`, `'iso_8859-1:1987'`, `'l1'`, `'latin1'`, `'us-ascii'`, `'x-cp1252'` | +| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` | +| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` | +| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` | +| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` | +| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` | +| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` | +| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` | +| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` | +| `'gb18030'` | | +| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` | +| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` | +| `'iso-2022-jp'` | `'csiso2022jp'` | +| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | +| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | + +#### Encodings supported when Node.js is built with the `small-icu` option + +| Encoding | Aliases | +| ------------ | ------------------------------- | +| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | +| `'utf-16le'` | `'utf-16'` | +| `'utf-16be'` | | + +#### Encodings supported when ICU is disabled + +| Encoding | Aliases | +| ------------ | ------------------------------- | +| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | +| `'utf-16le'` | `'utf-16'` | + +The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] +is not supported. + +### `new TextDecoder([encoding[, options]])` + +* `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance + supports. **Default:** `'utf-8'`. +* `options` {Object} + * `fatal` {boolean} `true` if decoding failures are fatal. + This option is not supported when ICU is disabled + (see [Internationalization][]). **Default:** `false`. + * `ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte + order mark in the decoded result. When `false`, the byte order mark will + be removed from the output. This option is only used when `encoding` is + `'utf-8'`, `'utf-16be'`, or `'utf-16le'`. **Default:** `false`. + +Creates a new `TextDecoder` instance. The `encoding` may specify one of the +supported encodings or an alias. + +The `TextDecoder` class is also available on the global object. + +### `textDecoder.decode([input[, options]])` + +* `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView`, or + `TypedArray` instance containing the encoded data. +* `options` {Object} + * `stream` {boolean} `true` if additional chunks of data are expected. + **Default:** `false`. +* Returns: {string} + +Decodes the `input` and returns a string. If `options.stream` is `true`, any +incomplete byte sequences occurring at the end of the `input` are buffered +internally and emitted after the next call to `textDecoder.decode()`. + +If `textDecoder.fatal` is `true`, decoding errors that occur will result in a +`TypeError` being thrown. + +### `textDecoder.encoding` + +* Type: {string} + +The encoding supported by the `TextDecoder` instance. + +### `textDecoder.fatal` + +* Type: {boolean} + +The value will be `true` if decoding errors result in a `TypeError` being +thrown. + +### `textDecoder.ignoreBOM` + +* Type: {boolean} + +The value will be `true` if the decoding result will include the byte order +mark. ## Class: `TextDecoderStream` @@ -1214,7 +1340,51 @@ A browser-compatible implementation of [`TextDecoderStream`][]. added: v11.0.0 --> -The WHATWG `TextEncoder` class. See the [`TextEncoder`][] section. +An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All +instances of `TextEncoder` only support UTF-8 encoding. + +```js +const encoder = new TextEncoder(); +const uint8array = encoder.encode('this is some data'); +``` + +The `TextEncoder` class is also available on the global object. + +### `textEncoder.encode([input])` + +* `input` {string} The text to encode. **Default:** an empty string. +* Returns: {Uint8Array} + +UTF-8 encodes the `input` string and returns a `Uint8Array` containing the +encoded bytes. + +### `textEncoder.encodeInto(src, dest)` + + + +* `src` {string} The text to encode. +* `dest` {Uint8Array} The array to hold the encode result. +* Returns: {Object} + * `read` {number} The read Unicode code units of src. + * `written` {number} The written UTF-8 bytes of dest. + +UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object +containing the read Unicode code units and written UTF-8 bytes. + +```js +const encoder = new TextEncoder(); +const src = 'this is some data'; +const dest = new Uint8Array(10); +const { read, written } = encoder.encodeInto(src, dest); +``` + +### `textEncoder.encoding` + +* Type: {string} + +The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. ## Class: `TextEncoderStream` @@ -1476,9 +1646,11 @@ A browser-compatible implementation of [`WritableStreamDefaultWriter`][]. [CommonJS modules]: modules.md [ECMAScript module]: esm.md [HTML Standard]: https://html.spec.whatwg.org/multipage/workers.html +[Internationalization]: intl.md [Navigator API]: https://html.spec.whatwg.org/multipage/system-state.html#the-navigator-object [RFC 5646]: https://www.rfc-editor.org/rfc/rfc5646.txt [Refable protocol]: process.md#processrefmayberefable +[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ [Web Crypto API]: webcrypto.md [`--experimental-eventsource`]: cli.md#--experimental-eventsource [`--experimental-web-worker`]: cli.md#--experimental-web-worker @@ -1510,9 +1682,7 @@ A browser-compatible implementation of [`WritableStreamDefaultWriter`][]. [`Request`]: #class-request [`Response`]: #class-response [`TextDecoderStream`]: webstreams.md#class-textdecoderstream -[`TextDecoder`]: util.md#class-utiltextdecoder [`TextEncoderStream`]: webstreams.md#class-textencoderstream -[`TextEncoder`]: util.md#class-utiltextencoder [`TransformStreamDefaultController`]: webstreams.md#class-transformstreamdefaultcontroller [`TransformStream`]: webstreams.md#class-transformstream [`URLPattern`]: url.md#class-urlpattern diff --git a/doc/api/util.md b/doc/api/util.md index 176722568e48..c284f3c8b2d8 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -2935,133 +2935,7 @@ changes: description: The class is now available on the global object. --> -An implementation of the [WHATWG Encoding Standard][] `TextDecoder` API. - -```js -const decoder = new TextDecoder(); -const u8arr = new Uint8Array([72, 101, 108, 108, 111]); -console.log(decoder.decode(u8arr)); // Hello -``` - -### WHATWG supported encodings - -Per the [WHATWG Encoding Standard][], the encodings supported by the -`TextDecoder` API are outlined in the tables below. For each encoding, -one or more aliases may be used. - -Different Node.js build configurations support different sets of encodings. -(see [Internationalization][]) - -#### Encodings supported by default (with full ICU data) - -| Encoding | Aliases | -| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` | -| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` | -| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` | -| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` | -| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` | -| `'iso-8859-6'` | `'arabic'`, `'asmo-708'`, `'csiso88596e'`, `'csiso88596i'`, `'csisolatinarabic'`, `'ecma-114'`, `'iso-8859-6-e'`, `'iso-8859-6-i'`, `'iso-ir-127'`, `'iso8859-6'`, `'iso88596'`, `'iso_8859-6'`, `'iso_8859-6:1987'` | -| `'iso-8859-7'` | `'csisolatingreek'`, `'ecma-118'`, `'elot_928'`, `'greek'`, `'greek8'`, `'iso-ir-126'`, `'iso8859-7'`, `'iso88597'`, `'iso_8859-7'`, `'iso_8859-7:1987'`, `'sun_eu_greek'` | -| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` | -| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` | -| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` | -| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` | -| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` | -| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` | -| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` | -| `'koi8-u'` | `'koi8-ru'` | -| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` | -| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` | -| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` | -| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` | -| `'windows-1252'` | `'ansi_x3.4-1968'`, `'ascii'`, `'cp1252'`, `'cp819'`, `'csisolatin1'`, `'ibm819'`, `'iso-8859-1'`, `'iso-ir-100'`, `'iso8859-1'`, `'iso88591'`, `'iso_8859-1'`, `'iso_8859-1:1987'`, `'l1'`, `'latin1'`, `'us-ascii'`, `'x-cp1252'` | -| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` | -| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` | -| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` | -| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` | -| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` | -| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` | -| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` | -| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` | -| `'gb18030'` | | -| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` | -| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` | -| `'iso-2022-jp'` | `'csiso2022jp'` | -| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | -| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | - -#### Encodings supported when Node.js is built with the `small-icu` option - -| Encoding | Aliases | -| ------------ | ------------------------------- | -| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | -| `'utf-16le'` | `'utf-16'` | -| `'utf-16be'` | | - -#### Encodings supported when ICU is disabled - -| Encoding | Aliases | -| ------------ | ------------------------------- | -| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | -| `'utf-16le'` | `'utf-16'` | - -The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] -is not supported. - -### `new TextDecoder([encoding[, options]])` - -* `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance - supports. **Default:** `'utf-8'`. -* `options` {Object} - * `fatal` {boolean} `true` if decoding failures are fatal. - This option is not supported when ICU is disabled - (see [Internationalization][]). **Default:** `false`. - * `ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte - order mark in the decoded result. When `false`, the byte order mark will - be removed from the output. This option is only used when `encoding` is - `'utf-8'`, `'utf-16be'`, or `'utf-16le'`. **Default:** `false`. - -Creates a new `TextDecoder` instance. The `encoding` may specify one of the -supported encodings or an alias. - -The `TextDecoder` class is also available on the global object. - -### `textDecoder.decode([input[, options]])` - -* `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView`, or - `TypedArray` instance containing the encoded data. -* `options` {Object} - * `stream` {boolean} `true` if additional chunks of data are expected. - **Default:** `false`. -* Returns: {string} - -Decodes the `input` and returns a string. If `options.stream` is `true`, any -incomplete byte sequences occurring at the end of the `input` are buffered -internally and emitted after the next call to `textDecoder.decode()`. - -If `textDecoder.fatal` is `true`, decoding errors that occur will result in a -`TypeError` being thrown. - -### `textDecoder.encoding` - -* Type: {string} - -The encoding supported by the `TextDecoder` instance. - -### `textDecoder.fatal` - -* Type: {boolean} - -The value will be `true` if decoding errors result in a `TypeError` being -thrown. - -### `textDecoder.ignoreBOM` - -* Type: {boolean} - -The value will be `true` if the decoding result will include the byte order -mark. +Deprecated alias for global [`TextDecoder`][]. ## Class: `util.TextEncoder` @@ -3074,51 +2948,7 @@ changes: description: The class is now available on the global object. --> -An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All -instances of `TextEncoder` only support UTF-8 encoding. - -```js -const encoder = new TextEncoder(); -const uint8array = encoder.encode('this is some data'); -``` - -The `TextEncoder` class is also available on the global object. - -### `textEncoder.encode([input])` - -* `input` {string} The text to encode. **Default:** an empty string. -* Returns: {Uint8Array} - -UTF-8 encodes the `input` string and returns a `Uint8Array` containing the -encoded bytes. - -### `textEncoder.encodeInto(src, dest)` - - - -* `src` {string} The text to encode. -* `dest` {Uint8Array} The array to hold the encode result. -* Returns: {Object} - * `read` {number} The read Unicode code units of src. - * `written` {number} The written UTF-8 bytes of dest. - -UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object -containing the read Unicode code units and written UTF-8 bytes. - -```js -const encoder = new TextEncoder(); -const src = 'this is some data'; -const dest = new Uint8Array(10); -const { read, written } = encoder.encodeInto(src, dest); -``` - -### `textEncoder.encoding` - -* Type: {string} - -The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. +Deprecated alias for global [`TextEncoder`][]. ## `util.toUSVString(string)` @@ -4163,9 +3993,7 @@ npx codemod@latest @nodejs/util-is [Custom inspection functions on objects]: #custom-inspection-functions-on-objects [Custom promisified functions]: #custom-promisified-functions [Customizing `util.inspect` colors]: #customizing-utilinspect-colors -[Internationalization]: intl.md [Module Namespace Object]: https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects -[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ [`'uncaughtException'`]: process.md#event-uncaughtexception [`'warning'`]: process.md#event-warning [`Array.isArray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray @@ -4176,6 +4004,8 @@ npx codemod@latest @nodejs/util-is [`Object.assign()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign [`Object.freeze()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze [`Runtime.ScriptId`]: https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId +[`TextDecoder`]: globals.md#class-textdecoder +[`TextEncoder`]: globals.md#class-textencoder [`assert.deepStrictEqual()`]: assert.md#assertdeepstrictequalactual-expected-message [`assert.partialDeepStrictEqual()`]: assert.md#assertpartialdeepstrictequalactual-expected-message [`console.error()`]: console.md#consoleerrordata-args From 189e0f1d213f2cc0a2af427d09d2cfaaf3b26b9f Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 14 Nov 2026 07:40:41 +0800 Subject: [PATCH 032/253] test: remove unnecessary imports for `TextDecoder` and `TextEncoder` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: LiviaMedeiros PR-URL: https://github.com/nodejs/node/pull/67461 Reviewed-By: Aviv Keller Reviewed-By: James M Snell Reviewed-By: Antoine du Hamel Reviewed-By: Filip Skokan Reviewed-By: Gürgün Dayıoğlu --- test/parallel/test-blob-file-backed.js | 1 - test/parallel/test-buffer-isascii.js | 1 - test/parallel/test-buffer-isutf8.js | 1 - 3 files changed, 3 deletions(-) diff --git a/test/parallel/test-blob-file-backed.js b/test/parallel/test-blob-file-backed.js index c5a5ce14807d..769aa5642980 100644 --- a/test/parallel/test-blob-file-backed.js +++ b/test/parallel/test-blob-file-backed.js @@ -2,7 +2,6 @@ const common = require('../common'); const assert = require('assert'); -const { TextDecoder } = require('util'); const { writeFileSync, openAsBlob, diff --git a/test/parallel/test-buffer-isascii.js b/test/parallel/test-buffer-isascii.js index 48cc96a17d61..7fe32038757c 100644 --- a/test/parallel/test-buffer-isascii.js +++ b/test/parallel/test-buffer-isascii.js @@ -3,7 +3,6 @@ require('../common'); const assert = require('assert'); const { isAscii, Buffer } = require('buffer'); -const { TextEncoder } = require('util'); const encoder = new TextEncoder(); diff --git a/test/parallel/test-buffer-isutf8.js b/test/parallel/test-buffer-isutf8.js index 151fc0baf4ae..f6efe95c8b27 100644 --- a/test/parallel/test-buffer-isutf8.js +++ b/test/parallel/test-buffer-isutf8.js @@ -3,7 +3,6 @@ require('../common'); const assert = require('assert'); const { isUtf8, Buffer } = require('buffer'); -const { TextEncoder } = require('util'); const encoder = new TextEncoder(); From 4df70155603f33ac10f609df2c44e84f7ad1404b Mon Sep 17 00:00:00 2001 From: Roberto Bianchi Date: Mon, 16 Nov 2026 10:15:51 +0100 Subject: [PATCH 033/253] util: use indexed writes in Set and Map inspection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Avoid the cost of primordial push calls for each formatted entry. Signed-off-by: Roberto Bianchi PR-URL: https://github.com/nodejs/node/pull/67295 Reviewed-By: Gürgün Dayıoğlu Reviewed-By: Jordan Harband Reviewed-By: James M Snell --- benchmark/util/inspect.js | 22 +++++++++++++++++++++- lib/internal/util/inspect.js | 12 +++++------- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/benchmark/util/inspect.js b/benchmark/util/inspect.js index 23beac0039b2..43062daff871 100644 --- a/benchmark/util/inspect.js +++ b/benchmark/util/inspect.js @@ -2,6 +2,7 @@ const util = require('util'); const common = require('../common.js'); +const assert = require('node:assert'); const opts = { showHidden: { showHidden: true }, @@ -20,6 +21,8 @@ const bench = common.createBenchmark(main, { 'String_boxed', 'Date', 'Set', + 'Set_large', + 'Map', 'Error', 'Array', 'TypedArray', @@ -30,11 +33,14 @@ const bench = common.createBenchmark(main, { }); function benchmark(n, obj, options) { + let output; bench.start(); for (let i = 0; i < n; i += 1) { - util.inspect(obj, options); + output = util.inspect(obj, options); } bench.end(n); + assert.strictEqual(typeof output, 'string'); + assert.notStrictEqual(output.length, 0); } function main({ method, n, option }) { @@ -85,6 +91,20 @@ function main({ method, n, option }) { obj = new Set([5, 3]); benchmark(n, obj, options); break; + case 'Set_large': + obj = new Set(); + for (let i = 0; i < 50; i++) { + obj.add(i); + } + benchmark(n, obj, options); + break; + case 'Map': + obj = new Map(); + for (let i = 0; i < 50; i++) { + obj.set(i, i); + } + benchmark(n, obj, options); + break; case 'Error': benchmark(n, new Error('error'), options); break; diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 30bfa41b0ce5..3128d5e50301 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -2398,11 +2398,11 @@ function formatSet(value, ctx, ignored, recurseTimes) { let i = 0; for (const v of value) { if (i >= maxLength) break; - ArrayPrototypePush(output, formatValue(ctx, v, recurseTimes)); + output[output.length] = formatValue(ctx, v, recurseTimes); i++; } if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + output[output.length] = remainingText(remaining); } ctx.indentationLvl -= 2; return output; @@ -2417,14 +2417,12 @@ function formatMap(value, ctx, ignored, recurseTimes) { let i = 0; for (const { 0: k, 1: v } of value) { if (i >= maxLength) break; - ArrayPrototypePush( - output, - `${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`, - ); + output[output.length] = + `${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`; i++; } if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + output[output.length] = remainingText(remaining); } ctx.indentationLvl -= 2; return output; From 7be00a936da683fada38a095881d5619a04453dd Mon Sep 17 00:00:00 2001 From: sangwook Date: Mon, 16 Nov 2026 18:47:39 +0900 Subject: [PATCH 034/253] test_runner: add tags and workerId to SuiteContext TestContext exposes tags and workerId, but SuiteContext does not, so a describe() callback cannot read the suite's tags, including the ones inherited from ancestor suites. Expose both on SuiteContext as well. Signed-off-by: sangwook PR-URL: https://github.com/nodejs/node/pull/67312 Reviewed-By: Colin Ihrig Reviewed-By: Chemi Atlow Reviewed-By: Moshe Atlow --- doc/api/test.md | 26 +++++++++++++++++++ lib/internal/test_runner/test.js | 9 +++++++ .../fixtures/test-runner/worker-id/test-1.mjs | 8 +++++- .../parallel/test-runner-tags-inheritance.mjs | 17 ++++++++++++ 4 files changed, 59 insertions(+), 1 deletion(-) diff --git a/doc/api/test.md b/doc/api/test.md index 01703227f8cf..d3badba70bdd 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -5139,6 +5139,32 @@ The attempt number of the suite. This value is zero-based, so the first attempt the second attempt is `1`, and so on. This property is useful in conjunction with the `--test-rerun-failures` option to determine the attempt number of the current run. +### `context.tags` + + + +> Stability: 1.0 - Early development + +* Type: {string\[]} + +A frozen array of the suite's flattened lowercased tags, in declaration +order, including any tags inherited from ancestor suites. Empty when the +suite has no tags. See [Test tags][]. + +### `context.workerId` + + + +* Type: {number|undefined} + +The unique identifier of the worker running the current test file. This value +is derived from the `NODE_TEST_WORKER_ID` environment variable, and is +`undefined` when not running in a test context. + ### `context.diagnostic(message)` - + [Error [ERR_TEST_FAILURE]: thrown from sync throw fail] { code: 'ERR_TEST_FAILURE', @@ -63,7 +63,7 @@ - + [Error [ERR_TEST_FAILURE]: thrown from async throw fail] { code: 'ERR_TEST_FAILURE', @@ -74,7 +74,7 @@ } - + [Error [ERR_TEST_FAILURE]: thrown from async throw fail] { @@ -86,7 +86,7 @@ } - + [Error [ERR_TEST_FAILURE]: Expected values to be strictly equal: @@ -112,7 +112,7 @@ true !== false - + [Error [ERR_TEST_FAILURE]: rejected from reject fail] { code: 'ERR_TEST_FAILURE', @@ -129,7 +129,7 @@ true !== false - + Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail at TestContext.<anonymous> (/test/fixtures/test-runner/output/output.js:125:11) { @@ -145,7 +145,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail - + [Error [ERR_TEST_FAILURE]: Symbol(thrown symbol from sync throw non-error fail)] { code: 'ERR_TEST_FAILURE', failureType: 'testCodeFailure', cause: Symbol(thrown symbol from sync throw non-error fail) } @@ -169,7 +169,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail - + [Error [ERR_TEST_FAILURE]: this should be executed] { code: 'ERR_TEST_FAILURE', @@ -195,7 +195,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail - + [Error [ERR_TEST_FAILURE]: callback failure] { code: 'ERR_TEST_FAILURE', @@ -209,12 +209,12 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail - + [Error [ERR_TEST_FAILURE]: passed a callback but also returned a Promise] { code: 'ERR_TEST_FAILURE', failureType: 'callbackAndPromisePresent', cause: 'passed a callback but also returned a Promise' } - + [Error [ERR_TEST_FAILURE]: thrown from callback throw] { code: 'ERR_TEST_FAILURE', @@ -225,7 +225,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail } - + Error [ERR_TEST_FAILURE]: callback invoked multiple times at TestContext.<anonymous> (/test/fixtures/test-runner/output/output.js:272:3) { @@ -236,7 +236,7 @@ Error [ERR_TEST_FAILURE]: callback invoked multiple times - + Error [ERR_TEST_FAILURE]: callback invoked multiple times at { @@ -251,7 +251,7 @@ Error [ERR_TEST_FAILURE]: callback invoked multiple times } - + Error [ERR_TEST_FAILURE]: thrown from callback async throw at { @@ -269,12 +269,12 @@ Error [ERR_TEST_FAILURE]: thrown from callback async throw - + [Error [ERR_TEST_FAILURE]: customized] { code: 'ERR_TEST_FAILURE', failureType: 'testCodeFailure', cause: customized } - + [Error [ERR_TEST_FAILURE]: { foo: 1, @@ -287,7 +287,7 @@ Error [ERR_TEST_FAILURE]: thrown from callback async throw - + Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at first at TestContext.<anonymous> (/test/fixtures/test-runner/output/output.js:334:11) { @@ -301,7 +301,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at first } - + Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at second at TestContext.<anonymous> (/test/fixtures/test-runner/output/output.js:337:11) { @@ -316,12 +316,12 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at second - + [Error [ERR_TEST_FAILURE]: test timed out after 5ms] { code: 'ERR_TEST_FAILURE', failureType: 'testTimeoutFailure', cause: 'test timed out after 5ms' } - + [Error [ERR_TEST_FAILURE]: test timed out after 5ms] { code: 'ERR_TEST_FAILURE', failureType: 'testTimeoutFailure', cause: 'test timed out after 5ms' } @@ -329,12 +329,12 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at second - + [Error [ERR_TEST_FAILURE]: custom error] { code: 'ERR_TEST_FAILURE', failureType: 'testCodeFailure', cause: 'custom error' } - + Error [ERR_TEST_FAILURE]: foo at { @@ -346,7 +346,7 @@ Error [ERR_TEST_FAILURE]: foo } - + Error [ERR_TEST_FAILURE]: bar at { @@ -358,7 +358,7 @@ Error [ERR_TEST_FAILURE]: bar } - + [Error [ERR_TEST_FAILURE]: Expected values to be loosely deep-equal: @@ -443,7 +443,7 @@ should loosely deep-equal } - + Error [ERR_TEST_FAILURE]: test could not be started because its parent finished at Immediate.<anonymous> (/test/fixtures/test-runner/output/output.js:197:7) { From ee149feeee61bdc1559422bc4407a56f774ee469 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Mon, 16 Nov 2026 07:54:47 -0800 Subject: [PATCH 037/253] src: warn when heap would exceed pointer compression limit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In builds without pointer compression, emit a process warning with the code HEAP_EXCEEDS_POINTER_COMPRESSION_LIMIT when the heap that survives a full garbage collection suggests that it would not fit in the 4 GiB cage that limits the heap of each isolate when pointer compression is enabled. Pointer compression shrinks a heap by at most half, and by about 40% in practice, so the warning says the heap is likely to exceed the limit from 6.5 GiB, and that it will exceed the limit from 8 GiB. The check runs in a GC epilogue callback for mark-compact GCs only, is done at most once per Environment, and unregisters itself after the warning has been scheduled. The warning can be silenced with --disable-warning=HEAP_EXCEEDS_POINTER_COMPRESSION_LIMIT. Assisted-by: Claude Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/67468 Reviewed-By: Matteo Collina Reviewed-By: Yagiz Nizipli Reviewed-By: Gürgün Dayıoğlu --- doc/api/process.md | 26 ++++ src/env-inl.h | 6 + src/env.cc | 79 +++++++++++ src/env.h | 35 +++++ src/node.cc | 3 + src/node_v8.cc | 21 +++ .../test-heap-pointer-compression-warning.js | 134 ++++++++++++++++++ 7 files changed, 304 insertions(+) create mode 100644 test/parallel/test-heap-pointer-compression-warning.js diff --git a/doc/api/process.md b/doc/api/process.md index d47983a97b4e..2bcac6597665 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -598,6 +598,32 @@ A few of the warning types that are most common include: that will be ignored rather than treated as an error. One example is use of the HTTP response status message when using the HTTP/2 compatibility API. +#### Heap size and pointer compression + + + +When Node.js is built with V8 pointer compression enabled, the V8 heap of each +thread (the main thread and every [`Worker`][]) is limited to 4 GiB, regardless +of `--max-old-space-size`. Pointer compression reduces heap usage, typically by +about 40% and never by more than half, so a heap that is larger than 4 GiB +without pointer compression may or may not fit under that limit. + +In builds without pointer compression, Node.js emits a warning with the code +`'HEAP_EXCEEDS_POINTER_COMPRESSION_LIMIT'` when the heap of a thread that +survives a full garbage collection reaches: + +* 6.5 GiB: the heap is likely to exceed the limit with pointer compression. +* 8 GiB: the heap will exceed the limit with pointer compression. + +The warning is emitted at most once per thread, with the wording that matches +the heap size at the time. Memory outside the V8 heap, such as the contents of +{ArrayBuffer}s and {Buffer}s, does not count toward the limit. + +The warning can be silenced with +`--disable-warning=HEAP_EXCEEDS_POINTER_COMPRESSION_LIMIT`. + ### Event: `'worker'` UL;P$Yj@WAr!2C83rtmeAk4%!O)nNiRmI>tEDnZlF&^RhS*W< z5Fxcf#fu1&%iRxlZKLsSir8w4AtL0)mLTgGo)LYRcU5;52TC;^4hiLAd*g>kPKBOo zYxtw5C~~x`rcAy%0;912iEX(pA6AK5%WAIDcf&|feHI+6aTZMMA%lh&UjvGN-CPjy zV)t$COd3WqrkdvSU`4#@FVx_O77f2-7M(j)baS4W5I(ukR}TwQlC)9{GN6Oqd1`L3 zgw9wuq%+*sy&OR&RUGIO>T2Yeal(myDRn%<>Yl&RB(NYzpc%x}CW$!PAT8DCm;Jnw zkM}vSCA%w2*Ly)*kdv15!LR-3R@D2|r1g@O{3D ze+WR;`2zL6SyZcRNW3UgNR;zX7N$2o!Ye3v8$H#Y$R#WbVpb$SB;HZivu)~`gXy-X zKnjjJiq%wADu>=O3GGa<*pvBcdnZv6fcYZP?C#Z3^24QHffeo&J%W9Ch@!gu2i{lq z_2Ta@i}`3!1s`!jaGOehDNxKb^()@8_=VB8DyALmEMh*y@g49m&vGf|bOUFU3ioDD z5q=$F)O_#HXY{WnoWg#6f>4ig-B|aLyvU{Fu~`*V!BWOzz6S;&$sA`i3`x1dmk&AI zTakDvBoFE&Zs4GQ;;`3lXD#2_C?G5E!xS3vXnvehY#!@DW`IzCnS>COO0re^oGN<7 z><3rA`GE2A$u=|tE-+}tJsjC3?)%PFYqy8X6Dl%aL>W}#L#FuwZ|+TysLrso+4SZS z#-K@(1_^?JsLg6B2aD0hAuu?|VP7nhbGK1)DaXFu(*{}pz?fCuH&jC6ej4Uvx&H8k z+UCg+9#5d8(KTIvD|bX)Y^}6v0SQ-E_AYE_glcgYzJPv+=Aj;*;yss}?tu0?)#HG2 zmi`C;3Db=>(NkIs3miHe`#Of)=C|AD$zUPA%H#JM)s)$`L3+Vpjl0e@dQqn__}woO zFi8UygZ}PdU%Ppt%hdKfwN`#{uzWt-cha<&84hGGdL8tChD?5So=!mggc7MXTD`YA zsr@DlF@7_^(BI1YjaOCQb)4ToHek&KeZp?>%`srh-P~C+HHCZ5b=8xaj7S+qObHknp0Yl2e^*UcRFz6Y+DrrUX?c~an zALanZ?fcz-le8+rm;6htAcx^5(PiwBOeEJYmcVVOw{FH|im-22Ux)#g{I|V9hOJn1 z-z!*|&+8244*W;Q`c&n=#24_co|wEKx+6bJr+%3(4)ae-#-+5McAgj9s4J--&~QsA z7NYlSb#FezVW2?}YBJz_<;%Nvj^5+3-GvD^k*I zR4tMYJ45k_pBIkf`=>8Dh1mq-=T~sLkEYH+JHBr>{xVt6BHY?CANhh*Vd9US#Vm>U zouf&pWMKC`vRJy5wUP-W&qw}*(o|%4aq?=}P!INHWyyS0XaCW%CB3uvq}RJa$mLF{ z_7ZP@Zrpzf_As{KsPZ*C_0>|Xf@IgOPjG2lm`)-fduMKG)d!n@^}M|lal+id zo*aywR2^HEaFF=j>;8p7mucIsWYG|vt#Ye>tBgI9ZMXZwx<+34(5LH(LEehEp>HFN zYMrMYx`bYqMv)mTuq&ZRaE#X0Wtos$sq!knh(F%ug_yX6LI-g8-qz&27oYb!rV}vX zn{v5_78yiEmH6RMMiKLTaMD7L?&FJm-T5(xmj-_zzv@W(Y*2MBvo8{ZG|`3sJ40i1f2;_Xmj?>^UJ=hOB=klLK%S#__u1e)dn zDx8HsfvrAS1@%Ar-4T2tFOqZ!{${ZEWw&j`#}8(nzP!5oo1wb0RQfPmJDLRd<1N9A$JC>Vx}jeI6d)sg9Xl3J2*1j zO=wwQ&qtNqJxsYnd5&kc^<6Mj0y^qP%SZP59JZjJE3dudo@riJ>|iMp6H9Ccan=n} zk-ET0MqEPzY2PG1=`NL5srj(UQ!?FG*8l-3vb3=hs=X7mUWT!6%u6l4jVMHa4!#QH zo{?WJ!i6`Q{qdsn&nWdS=Yo8H2#`Lks|FyA&Ev_Q zf|2K!$;7bz7Z`iZx|_^BTmS={rMJgBVkCHNxj~SjV|1Xpg-pUeWI37 zX;k{&W#>*#24k|OWM`b&G(APjcV+Ek(-~d#+qt;6>*#W6jBK$8U=>||_~3lPp~jt- zpi$K&BOxJ$Dv{ox;bd5OQJdyjjkqdlt|zDt1!|kTQhlziiDC)@M@5hWtBK1Mg8M2Ycx9%m(xgJDEij-&$kuZsQb07Ki8)d_x2A_ zWEdo$NQ&ck`0MB8pT&KD!{!^Bu9pr3tMgy!x1-2TIpmN%_fHyx<@|a%aaM_%VwV@f z`OO0zwz43T^GJg;a8R@$`8oH#_$ilZVl;85V|zx~oOFPdkSyf^wlRyOe{b*%QzS(oU4paS#j3T?rS*IJsd-kU1q zw9Z*nx_4U`Q!97z>LO!w~Yv+HP7%C`UbT>B5=C;*3xHl6DC=2U^8ssx#b_R8ChVnokzZRSZTFn zXMEc;X3^tFXxcchLr?A`yp*MI9IA;E4?lq|1#(W-^xs3)7*B%`pYBQ; zDZiL0R<&!TI$=h&E=H5{7aMGWK}{yjXe_wk8rYW#3Q1ph+fetXy`J;>y9BlLU6bh? z&W_4|lFDAkRfO{QF20pAtKSHZS}sV_pZukflDX5VKe%me%Pd(03O@xmTlM;rv~l#aAL!%fDV;l8Qm#iLmk1pqRplo5{%Bji9?op{kp?>3ux9hw$8Lg7gw^~ z;jpX7&Z6o;s`Nu|0uLLV&F+&fY^5Qw7z4w9ab}Oo`oy8QtGH{7Ux{vgpf@1pVle|G zqFhn3WSfIcV)I$gHRwQP%yI=0>2*&%KG*(wGx@UhMY5{zxh_M`c-(rn^~40WM-u0v zKHmfTOmBujW{|VxNvP@tqZF?qXlJ8r4AXjNC#C%@70n?O02}2Jp6;J48bZ=!90d=5 z$?2hBIOU?U6u>H1yO{ti5s@UtR{hWm%9YkPZFoZkbc%ixK%vmw@U#LGjQIf~T$uP_k;W%z;!Q7Rzxlt9iqd_Jmczd}0+pa5e9;_IW&9$lcUnrVJ|n)s}3VJ==fAqFHwAwoMvgkZtwS>z6T1cRQ;`wayQzkqJ4g zjdoRhvxVWx@kP)GHh1|}U^i5M5WZ~^_LQ7pH_)J`xPkK0mqAaN<#)S&G4CUDUfdC| z0SF{zq77OAEx$?e)W&Dq85Nlz-A9%a3(&(YR@icK;l2=7+0 z*E)#D_|fFw^5B^iTfS{DHq~pZ(76cDDFs)&uA73eFG!ZFS?@}u>I;5;xcS6BX1)i! z9V-{SJdujTVsd0CZww(vu|051$?=ce8m{R=4{hkWGz~b1frcVO-Z#p%_H5hM%ltBmaagtA<}+kDB_Wk>h|v66cZRDf53&G06PVfR|_ zg=Y}kPW($q>wg{mDLH05dS`GSw{0TI^!6zU7E}@PWyt2d5uAi6P>zT>3yhtxN^8nE zCMZN@)*8EL*WlnmUV+`feQ|aU?bHq}R&XqFC~I=M6&^4=B;vb&NRYgyGm3e@3T*q+ zRxcc*VNUOQ^RpE8532KIDoAghY-dG-Z!Zrfyw@!(%4qn%&FBn!uF2R{B(j0)jJe=| zKXDKyr|)yM{6h<{u)w(?0OenG!RWsVU1DP{7B}stxN&cj+sdCS$ zgb>rb`Bl%0JnJlgJ_ABIhtN3ueHyRFQgge=ye!I%HNMcj7~cXs{Sh|0v?M3IaLPF) z>Cz$pBGLbKQ!7STp+E-}6Rlyw}p7&*qVP&BOlWZA_jE)TxazZdG z%bzJQkVt=jcMlO@!5C+RU9FuhtWw=k&GH&&CtGpGf(c5;x=Sdp|6LcB^XF=2DaN&! z=*B>`?w$_H-gCxm!{|;{3ka|0U->)IvI90(r!=nqOXvO9^{msCa6#o~BDN&))147# z3#dt0K9cL!e4axM9D;puU*s-x2=X*jy>dJMVZR@LwW4VO$2=6AZbT6HA1G_0iIhhi zF{X!+uj@h@HWgtJ{kU6fd8cMJ0*t0@mRyokiIcdUdG??sYHB&BX@Xb>dj~&s-^;27 z(Cn1`Pe%I&^+GL?ZKSSq$z+P_vWqSDw{S~_MfhyVWdO&fVdovl5%&1RvP7SxN!|;# z!qJU?bJPu=+!jlo(oYH;(ejuBCJE|mP%fQOs|H06GliYC`H;A|x~;m#0`qW-mwu;u z6*d8$;A@il|FBs~ec?aCJ3kvEHLppujI4mM_p$X5p}$NYi-2o*yoY^)e22KA56L*> z-(TWqp>4=KwS57upNY)6St603zdjKNqCwk#_n?;N`#0XtOYBIaG1O3i{Dr{KluntG@yOMK$Y$Lhd<#s(C%D@)=eOh!=CW0Y1 zJY|yT@APJVTeaVE0UmGkI0aBc2mrZ9JiW>r(#{m0H`!4AuO)X$(Q-Cg}uz|$81ok(0Gcg*(gdl zw;(*olURkr*c+%Sux3#q)l;?kKjEcbxGhDEp^D=0*yUKmP;W5%_uH&x9Gf41tPm6M z-Cqrt+9WsT5XW(E`5mlWZLS`Gbb1GUus5Xtulb@sWMRuXmx3>tRC$=f6*Ih%!! zWq4dd(#J-rfe3=$a*eOIDekoqRtGz5`xb7=613sYt|DzMP7CAI4*EGRkS0NF;t;Kx zN*o62BZbxhO`C23B>!h~M9;Q=+MykLw{M)C-bHtSoxf*Kn#rK=uRKbvU0oayV3i{- zmiIB`&V+|2hpq(waDY2YqNP5qjxQX7*wG zAOwU1L+|`42<5LRCvw_HD?zxC%;oEv%zR(1M(n?~*bsXMm}vk(BZe=3ZVEyc049+z z$|;TbduqfPAZ1$vwCAnkAbk2q<%;@ae49beNUJkHycINtcu9EMI-&(eLWwo_Bl0?Q zrMW-`aoKCGy^A)h*YwO;@$cD1hIBRKPTn{{hGIfW0W((~I{N$}mZ^Qta;SkU(5;Q#c3 zS3x=8fl)*fd9*zEieSQ-E^ zlZoS4Gz;FgyU1chWhomnz%v9?++FJSIKZ+%7c3uF8c!s! z1?4H{vCpo5xiy|PpEqq76M+TzUFKgup#9-MYzP5sN_`d@hF>tI&1yp!U=jd;uXI^k zF+7l>eKtRS|5$>R6di>Kq;`D=t^XhrPb9O$idGMfX>j`*KOf4)bi=*Z{?}k|)jbu{ zd3mFGNS_*Wz8m0b#DcFOzOVo_k*PdF7(Q$ZX;k}v8EJ-K$x|WezXZ7ZGq1lC^>v_3 zqJB!;n)VsG`~&sO9a$K;5;v3H&lSS&k^C-_hI+%U33mbv!T1nVBI@&wfdoCDz*^_J~=#NR{!^PZVWe``3FonV#ihK+i#fEMIWohnN8Dwnr(ZxWRIBB@eDyxK#Q`TZ7Ir&5KTk`vhA{E)I4j4N&!7O%hEt=_ zmUiVvhD_``K4z~UE>}6<<;<3Ua@_=(BR-f9XS_c8US?YVUI1|G9G5RnHVQI2y90_a zt-o=KwP~|GVD4+7o$DdjH|C!al0BE#H5cakWtc3T&lV`Oe7``#km3)>PLy@_V}AZc zoG?~YDx@dgPQPv>qrcjWqt`X2PPdAm*hnqB zEr9{$E{6mARMriPD5<^>=rFYQV5Rr{e;C}(`+qY7+F_ryR+FKc69O_elR?81w=LxY zhBE^(I5?9QktPs1FgXe@Ol59obZ8(mIXE?w!3QXR?OR)O6Gs+)*RSYDTw9sx`=u(C zDvV?B8i-?=0L$_qF$w6qYD^IyDzDNQBP0zxqj!;BUvcJI1|b; zAq+kplZx&=Q(EIQFl{^&nls}hJ_WPh;Zrit>0YrQ=pJjiQXQc|L}=Opiqa|!9Fe6N z`X6Y2CNN<+b{KGSf(C*KFR|5tW*}jVVv^HVqnQ-OcZ4xaN{g+=LPn3R2Eyt<1J9)8 zpkV@&PDmopq?a@hOa=v}Rx-s&Ovt2&n6R2DX-!91!<2GhYAv)T^{ivc1RB5&jze%T zR$hR+<4gr5NN}dPq8Z6Fi7A|7T7rgfnrY>KTt_&=wDvS(nT`@V$Fw7hd2IJGklq+T z1mUqg#5EoRO(qGqAgK)qMhyOfb zlKdj#2(Dz1UPV1gA!W$Hk`TsKhv+B|)JRLvjaVbh0#LLV&cR}u)ST>%McNP;Il+}I zN&^Q@@e#=(BG`ko5Zn`BK}wR>i~#(9W2hJjd`LosQDg`u3AB-uBCt9d5yk@)mWqHU z1nnijkvXIypegP;KmOP$FTUJXtb9Bgjc1**d-q`$@1GAwpE~8?cyd`y*gKApcQVLA!@yGb!Xj{Ga0QP>w}s{b>mIWoe`IBsl~2bPV^$uqNAiIE^iv0a|Gtx@ zcZC;(8ehbqt62(D1htl<&<|v3z#cjL&KW9`RnR@FN)D_BbkqHI?rup+qi;4wS0Yt1qnb{osE zBg57#vt_rj6b}V#P6Vhng_C-J!PDyk1!XUmtyx-INR*>FOQ#Di>|R+KQ#dMNHA|}s zqugFuYEwwR$gs%x1vl$6>;t332t)~$BqVjDK4wtl3=%q*Zm;aPD;%{Q#16^a?8SvO zHx$-FMa77-L4H?zW#?_-(fJWO#6w}_ezijwDxf8@LkNluNZA!Ti`ol+kVbY+6=-Po zi4<+9MCim0p@(*Euk1APrcZI8jVzq;du69|VG=O4mW2#ruiPZEB~Cn%of3tYdap|_+QxCb(|w_?=`2W*h-|FqI@WDP}-|@XqKEv zIYqfpXusDmQ0TH{R?Y^06ra6@fifJ$CxroyqJ=Sfuk180aJEeBv@f{dYZ&10T6mqp zKq-gnvsZ2+p!lRPP|~6JsJ+?}aUFQZCFZy?`#6#rfz0oz%?xNwQZ-NOg*iOSHba6E=}1; zylIBj@sg3~n+j0zdE^SJ(Yo<8o0sMwfX?@RF4kgYdagP3);Ry6+YXRu@gymb#_^(X7;(<%g`Uq>I@OCzRL50$ zY%O_%)0p;uq}jA5&&mZAA9<%Wi`8j`j#m{0R)N>+pqh(&<9fvj9Z^Y7SP&ZAeZq|L z5eJGe;mMsIhdf|R1>#{e8C#=YW7c!b1h`oMQ;O(V2@aOf6L_>sTnC55FMtS1o>rJ> zo0wYCHrG#2!#z>`-j`PDc{RN_iU-y9H-XeQbioMB-T z5uh!P{}*@E^|{7ex?jx7=sz!_e_%tI*EQ(jdbY03OoUi=%+%K{cebp*uOy+gg2%I8K@R(m+BdN*x zlAM_4qvon+Ku7Y;XAJ?@iMHv#T#+JC)s93@*EAE89TZfxS}|Nw3bTe3b1Ag3E(d%= zPb=x`Wt*Spxwtn|SBtcs>Brpd6}nx+)=KXRfH)TN-b= zQio%bFiul{6L)%7KL@m^Z4pANJYUnM4#s$qIi}TVyjZ26^%P?(RlOZY9FW=` z)<;9q*rRzA5t`0Zx9!og*vweaubt8`U9DgEiug3G(bUMGQwxzO`6+%10#ehzG`r;W zK-V;ryb|}#*QV#%kQ^F2eD>1fS+Y=n8s{tFZ1IAEj`2s;v_Bc#&c>5;tbf_N!IR&f zot(aY{EsIu4h6^ju=jDwbXstDIR4Du{Qyh+AY&*BK|x4wDW?5uG@}zpr+m`8eO3)V zUgOr=PDxzo*$;vqp3Hi~LI3gSlgx8S|D4 z4gRRgtMT2W{8(O>*I#b0t5G?BD2L@uIfBW?qY7rbttNxJEHJuGWip)5z{=mxV z;4=(5yPi~4Is0>5-j#oppUW@hU&|)e_c8I&;p?;Wf5OBsPBsBZ%>ktSS4^z7nfM2x zYa=_^u(1+N8^44dtMcQd>dmT2G!7JRt7z||;@Ph!&o7=u6~lTBWvDfOMC#g+hI*rh z$-&DC`THnzdieJA^eGfN-{dmQYlV1th(hzIuwkP*DJYI|SUf{uoR-fK952gX5Fo!U zg~*%oE!^9i!nK3xC&bH#Nw5E@nhmR~Sv{V_fY}sC)y-vZdRPx&cF+GsGU7U9-^n^dF7KaLXjItCGi<5_k2VHg+GH)&10Tg<1)6s$LcB>W<5 zr$Z9A9lU?0@GbwUCgUYM2!0R_JMYl_M*nn>}$G5UOfx{Mb6C92Kf-^X}pWRoH ziyFBvMfH*!qT$x$w=c_fxmWpk^6SydSR1>~zgirHR1b>$FgMMA_DD&FX+%K30r4h~ z$x5H*rD0x8*QR`Nuatj&-aR_(MzdU8Y%+|b45H{on}aEA!!ANB*@bTBc9BwUvdfkX zk_u-sKn;$j%6Fs7YBKGQC)FZmmi50^Jvcsod-~>x^zUwjg-Ean^fU4F#m;(E(CxRx z%jS-0UH(~C?q0Qj;pAzzdw5F9z1`?qWP@M{^MVd=W}zJd;QOkb<{O>+;SR|Y`Ft?x z53Bz8_RC~e-rNmmgWKV9Y|DG)yt9|xlNYa`=f&o}#mr+{@2ILgTjKx?HM%^eFDB3R0b~<`q8|&Tno6 zF2}=RZ?fnIVh2!t?hku6ttwOZkc}RI66&y;P8V&!=%?eK0o z?+3Ot02@mGx{S8k1;~4)_0#7^XRm*bklD}%*o+u0;cfq5#B6B-(jn;tDETGg<5j!n zEuD<&R;^io@V0dYOV(Sh2696+Xnes>lMwi@H?86~LRD;L0cVM7)f7lX7uE2RIkWE9H@Evj7YTDY&SI`^WM)c~oG30lkx7B5}6cvp=>s&TcSX{9M;l*Z)wwkh&>Yg00+oC#=Mt#EDuo_ z9_s`8-Yt`;CWH_GQO{%!!GtMo;ij0w9_~^-)CO$(FwKPGi${#-)9$JY9H(Rqo}P|Bsg5=`pc>G5Jth=B~u2 z$J5mVPF(LVtm%2PYwzl;Z>=#?dUrgkel5m-z;W$@O`2hGTa|vTj{5lU!Qrb{8Jf~w z{}21BH}Su8-bd|#$eX)2WuDV}ssy~#X!4qm=f7WGerCQ_{j1W-6kFfaeZlMgGcAz2 z@EzE>7hyD-zD#BNL-2O)h=k{1lhOl2io^7b_zJBQu2L zbTvulU;$GFjgZs`1)t2aR0W{C@$^nfW*HY_JyT6CJ3Fq_yp;T;EG{EsOQc(RLn;eW z74-d+vVu!;x%B-MjJfpPGK-2!fcoL135MpDlMk?K)|>k6+xEB$i7*II{{EHYO%q`r!)Eh6=_ChCsof{CuE? zO$>qI62ztNnU|IiZs) z=HJf9sXJBUyQVzTHT0J4y1glP+b+J(dGpJYs@pT!gtl){J2&mdG$%=!7NPB@*6p}o zU+1wik1=nfEyL5C{6k8&YYTY!oJB)+nA-L34sp^A*}e7ak(-Ju8W#sVpH?f}TxG#@ zeBr^h`HF1E7fkGrNh}qbb*Jcj(k&kK2RvJL`0njGsA<8QzEC#m?z6gMUu@$%2Esb9gRAU|=+s>UK0OC`;#j2An;fEcC>7c~|wR5N8<*%9L6oW-amIJKkZ z3fC8o$y^AFXn&t^{BUnu*tW5*QMQ-Y=|#XH;t zc}-W!D+&BtGo|?VFS~a^JWq~$tzo-+I{rx3iM_@7R&VS+N9%?uzq|eMo9U~6%Pqr_ z=Uve|o^@w(ty7b0bpPnTDalW`keRuc9MWz!QJRDRMgakM{SX`Kt x7=hdc3G-g+6*M!+iU^%gDeq3-d-a>VF2jt%=~~*%a@>}d#%5fqs;>TSTmTU%+|K|2 diff --git a/deps/libffi/doc/libffi.texi b/deps/libffi/doc/libffi.texi index 4d2802c5bd97..619c4ed34e99 100644 --- a/deps/libffi/doc/libffi.texi +++ b/deps/libffi/doc/libffi.texi @@ -566,6 +566,12 @@ Note that arrays cannot be passed or returned by value in C -- structure types created like this should only be used to refer to members of real @code{FFI_TYPE_STRUCT} objects. +Some ABIs classify array fields differently from structurally identical +structure fields. Because @code{ffi_type} has no separate array tag, this +emulation cannot express that distinction. On those targets, passing or +returning an enclosing structure containing an emulated array by value is +not supported. + However, a phony array type like this will not cause any errors from @code{libffi} if you use it as an argument or return type. This may be confusing. diff --git a/deps/libffi/doc/mdate-sh b/deps/libffi/doc/mdate-sh index e6d572d4cee9..22396e406796 100755 --- a/deps/libffi/doc/mdate-sh +++ b/deps/libffi/doc/mdate-sh @@ -1,9 +1,10 @@ #!/bin/sh -# Get modification time of a file or directory and pretty-print it. +# Get modification time of a file or directory, or value of +# $SOURCE_DATE_EPOCH, and pretty-print it, formatted like 1 January 2000. -scriptversion=2018-03-07.03; # UTC +scriptversion=2025-06-25.21; # UTC -# Copyright (C) 1995-2021 Free Software Foundation, Inc. +# Copyright (C) 1995-2025 Free Software Foundation, Inc. # written by Ulrich Drepper , June 1995 # # This program is free software; you can redistribute it and/or modify @@ -50,21 +51,46 @@ Pretty-print the modification day of FILE, in the format: 1 January 1970 Report bugs to . +GNU Automake home page: . +General help using GNU software: . EOF exit $? ;; -v | --v*) - echo "mdate-sh $scriptversion" + echo "mdate-sh (GNU Automake) $scriptversion" exit $? ;; esac +# Warn if more than one file given. +if test $# -ne 1; then + echo "$0: warning: multiple files given, using first: $*" >&2 +fi + error () { echo "$0: $1" >&2 exit 1 } +# set $month ("January") and $nummonth (1) given arg MON ("Jan"). +mon_to_month () +{ + case $1 in + Jan) month=January; nummonth=1;; + Feb) month=February; nummonth=2;; + Mar) month=March; nummonth=3;; + Apr) month=April; nummonth=4;; + May) month=May; nummonth=5;; + Jun) month=June; nummonth=6;; + Jul) month=July; nummonth=7;; + Aug) month=August; nummonth=8;; + Sep) month=September; nummonth=9;; + Oct) month=October; nummonth=10;; + Nov) month=November; nummonth=11;; + Dec) month=December; nummonth=12;; + esac +} # Prevent date giving response in another language. LANG=C @@ -78,6 +104,7 @@ export LC_TIME TZ=UTC0 export TZ +# # GNU ls changes its time format in response to the TIME_STYLE # variable. Since we cannot assume 'unset' works, revert this # variable to its documented default. @@ -123,20 +150,7 @@ do shift # Add another shift to the command. command="$command shift;" - case $1 in - Jan) month=January; nummonth=1;; - Feb) month=February; nummonth=2;; - Mar) month=March; nummonth=3;; - Apr) month=April; nummonth=4;; - May) month=May; nummonth=5;; - Jun) month=June; nummonth=6;; - Jul) month=July; nummonth=7;; - Aug) month=August; nummonth=8;; - Sep) month=September; nummonth=9;; - Oct) month=October; nummonth=10;; - Nov) month=November; nummonth=11;; - Dec) month=December; nummonth=12;; - esac + mon_to_month $1 done test -n "$month" || error "failed parsing '$ls_command /' output" @@ -150,7 +164,6 @@ eval $command # Because of the dummy argument above, month is in $2. # # On a POSIX system, we should have -# # $# = 5 # $1 = file size # $2 = month @@ -159,7 +172,6 @@ eval $command # $5 = filename # # On Darwin 7.7.0 and 7.6.0, we have -# # $# = 4 # $1 = day # $2 = month @@ -167,20 +179,7 @@ eval $command # $4 = filename # Get the month. -case $2 in - Jan) month=January; nummonth=1;; - Feb) month=February; nummonth=2;; - Mar) month=March; nummonth=3;; - Apr) month=April; nummonth=4;; - May) month=May; nummonth=5;; - Jun) month=June; nummonth=6;; - Jul) month=July; nummonth=7;; - Aug) month=August; nummonth=8;; - Sep) month=September; nummonth=9;; - Oct) month=October; nummonth=10;; - Nov) month=November; nummonth=11;; - Dec) month=December; nummonth=12;; -esac +mon_to_month $2 case $3 in ???*) day=$1;; @@ -205,9 +204,9 @@ case $3 in Nov) nummonthtod=11;; Dec) nummonthtod=12;; esac - # For the first six month of the year the time notation can also + # For the first six months of the year the time notation can also # be used for files modified in the last year. - if (expr $nummonth \> $nummonthtod) > /dev/null; + if (expr $nummonth \> $nummonthtod) >/dev/null; then year=`expr $year - 1` fi;; @@ -220,9 +219,9 @@ echo $day $month $year # Local Variables: # mode: shell-script # sh-indentation: 2 -# eval: (add-hook 'before-save-hook 'time-stamp) +# eval: (add-hook 'before-save-hook 'time-stamp nil t) # time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-format: "%Y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: diff --git a/deps/libffi/doc/stamp-vti b/deps/libffi/doc/stamp-vti index dc281e38e0f6..c9adde9c03f9 100644 --- a/deps/libffi/doc/stamp-vti +++ b/deps/libffi/doc/stamp-vti @@ -1,4 +1,4 @@ -@set UPDATED 8 August 2026 -@set UPDATED-MONTH August 2026 -@set EDITION 3.8.0 -@set VERSION 3.8.0 +@set UPDATED 14 November 2026 +@set UPDATED-MONTH November 2026 +@set EDITION 3.8.1 +@set VERSION 3.8.1 diff --git a/deps/libffi/doc/texinfo.tex b/deps/libffi/doc/texinfo.tex index e48383defc4a..5d2f174ee9b2 100755 --- a/deps/libffi/doc/texinfo.tex +++ b/deps/libffi/doc/texinfo.tex @@ -1,11 +1,11 @@ % texinfo.tex -- TeX macros to handle Texinfo files. -% +% % Load plain if necessary, i.e., if running under initex. \expandafter\ifx\csname fmtname\endcsname\relax\input plain\fi % -\def\texinfoversion{2021-04-25.21} +\def\texinfoversion{2025-10-25.20} % -% Copyright 1985, 1986, 1988, 1990-2021 Free Software Foundation, Inc. +% Copyright 1985, 1986, 1988, 1990-2025 Free Software Foundation, Inc. % % This texinfo.tex file is free software: you can redistribute it and/or % modify it under the terms of the GNU General Public License as @@ -58,12 +58,6 @@ \message{Loading texinfo [version \texinfoversion]:} -% If in a .fmt file, print the version number -% and turn on active characters that we couldn't do earlier because -% they might have appeared in the input file name. -\everyjob{\message{[Texinfo version \texinfoversion]}% - \catcode`+=\active \catcode`\_=\active} - % LaTeX's \typeout. This ensures that the messages it is used for % are identical in format to the corresponding ones from latex/pdflatex. \def\typeout{\immediate\write17}% @@ -162,8 +156,9 @@ % Give the space character the catcode for a space. \def\spaceisspace{\catcode`\ =10\relax} -% Likewise for ^^M, the end of line character. -\def\endlineisspace{\catcode13=10\relax} +% Used to ignore an active newline that may appear immediately after +% a macro name. +{\catcode13=\active \gdef\ignoreactivenewline{\let^^M\empty}} \chardef\dashChar = `\- \chardef\slashChar = `\/ @@ -218,7 +213,7 @@ % @errormsg{MSG}. Do the index-like expansions on MSG, but if things % aren't perfect, it's not the end of the world, being an error message, % after all. -% +% \def\errormsg{\begingroup \indexnofonts \doerrormsg} \def\doerrormsg#1{\errmessage{#1}} @@ -241,9 +236,6 @@ % \def\finalout{\overfullrule=0pt } -\newdimen\outerhsize \newdimen\outervsize % set by the paper size routines -\newdimen\topandbottommargin \topandbottommargin=.75in - % Output a mark which sets \thischapter, \thissection and \thiscolor. % We dump everything together because we only have one kind of mark. % This works because we only use \botmark / \topmark, not \firstmark. @@ -284,8 +276,7 @@ % \topmark doesn't work for the very first chapter (after the title % page or the contents), so we use \firstmark there -- this gets us % the mark with the chapter defs, unless the user sneaks in, e.g., -% @setcolor (or @url, or @link, etc.) between @contents and the very -% first @chapter. +% @setcolor (or @url etc.) between @contents and the very first @chapter. \def\gettopheadingmarks{% \ifcase0\the\savedtopmark\fi \ifx\thischapter\empty \ifcase0\firstmark\fi \fi @@ -296,7 +287,6 @@ % Avoid "undefined control sequence" errors. \def\currentchapterdefs{} \def\currentsectiondefs{} -\def\currentsection{} \def\prevchapterdefs{} \def\prevsectiondefs{} \def\currentcolordefs{} @@ -317,16 +307,8 @@ \newbox\footlinebox % When outputting the double column layout for indices, an output routine -% is run several times, which hides the original value of \topmark. This -% can lead to a page heading being output and duplicating the chapter heading -% of the index. Hence, save the contents of \topmark at the beginning of -% the output routine. The saved contents are valid until we actually -% \shipout a page. -% -% (We used to run a short output routine to actually set \topmark and -% \firstmark to the right values, but if this was called with an empty page -% containing whatsits for writing index entries, the whatsits would be thrown -% away and the index auxiliary file would remain empty.) +% is run several times, hiding the original value of \topmark. Hence, save +% \topmark at the beginning. % \newtoks\savedtopmark \newif\iftopmarksaved @@ -351,15 +333,9 @@ % \checkchapterpage % - % Retrieve the information for the headings from the marks in the page, - % and call Plain TeX's \makeheadline and \makefootline, which use the - % values in \headline and \footline. - % - % Common context changes for both heading and footing. - % Do this outside of the \shipout so @code etc. will be expanded in - % the headline as they should be, not taken literally (outputting ''code). + % Make the heading and footing. \makeheadline and \makefootline + % use the contents of \headline and \footline. \def\commonheadfootline{\let\hsize=\txipagewidth \texinfochars} - % \ifodd\pageno \getoddheadingmarks \else \getevenheadingmarks \fi \global\setbox\headlinebox = \vbox{\commonheadfootline \makeheadline}% \ifodd\pageno \getoddfootingmarks \else \getevenfootingmarks \fi @@ -449,43 +425,22 @@ }% } -% First remove any @comment, then any @c comment. Pass the result on to -% \argcheckspaces. +% First remove any @comment, then any @c comment. Pass the result on to +% \argremovespace. \def\argremovecomment#1\comment#2\ArgTerm{\argremovec #1\c\ArgTerm} -\def\argremovec#1\c#2\ArgTerm{\argcheckspaces#1\^^M\ArgTerm} - -% Each occurrence of `\^^M' or `\^^M' is replaced by a single space. -% -% \argremovec might leave us with trailing space, e.g., +\def\argremovec#1\c#2\ArgTerm{\argremovespace#1$ $\ArgTerm} +% \argremovec might leave us with trailing space, though; e.g., % @end itemize @c foo -% This space token undergoes the same procedure and is eventually removed -% by \finishparsearg. -% -\def\argcheckspaces#1\^^M{\argcheckspacesX#1\^^M \^^M} -\def\argcheckspacesX#1 \^^M{\argcheckspacesY#1\^^M} -\def\argcheckspacesY#1\^^M#2\^^M#3\ArgTerm{% - \def\temp{#3}% - \ifx\temp\empty - % Do not use \next, perhaps the caller of \parsearg uses it; reuse \temp: - \let\temp\finishparsearg - \else - \let\temp\argcheckspaces - \fi - % Put the space token in: - \temp#1 #3\ArgTerm -} +% Note that the argument cannot contain the TeX $, as its catcode is +% changed to \other when Texinfo source is read. +\def\argremovespace#1 $#2\ArgTerm{\finishparsearg#1$\ArgTerm} % If a _delimited_ argument is enclosed in braces, they get stripped; so % to get _exactly_ the rest of the line, we had to prevent such situation. -% We prepended an \empty token at the very beginning and we expand it now, -% just before passing the control to \argtorun. -% (Similarly, we have to think about #3 of \argcheckspacesY above: it is -% either the null string, or it ends with \^^M---thus there is no danger -% that a pair of braces would be stripped. -% -% But first, we have to remove the trailing space token. -% -\def\finishparsearg#1 \ArgTerm{\expandafter\argtorun\expandafter{#1}} +% We prepended an \empty token at the very beginning and we expand it +% just before passing the control to \next. +% (But first, we have to remove the remaining $ or two.) +\def\finishparsearg#1$#2\ArgTerm{\expandafter\argtorun\expandafter{#1}} % \parseargdef - define a command taking an argument on the line @@ -528,8 +483,8 @@ % \envdef\foo{...} % \def\Efoo{...} % -% It's the responsibility of \envdef to insert \begingroup before the -% actual body; @end closes the group after calling \Efoo. \envdef also +% \envdef inserts \begingroup before the actual body; @end calls +% \Efoo then closes the group with \endgroup. \envdef also % defines \thisenv, so the current environment is known; @end checks % whether the environment name matches. The \checkenv macro can also be % used to check whether the current environment is the one expected. @@ -547,7 +502,7 @@ % ... but they get defined via ``\envdef\foo{...}'': \long\def\envdef#1#2{\def#1{\startenvironment#1#2}} -\def\envparseargdef#1#2{\parseargdef#1{\startenvironment#1#2}} +\long\def\envparseargdef#1#2{\parseargdef#1{\startenvironment#1#2}} % Check whether we're in the right environment: \def\checkenv#1{% @@ -608,6 +563,9 @@ % @/ allows a line break. \let\/=\allowbreak +% @- allows explicit insertion of hyphenation points +\def\-{\discretionary{\normaldash}{}{}}% + % @. is an end-of-sentence period. \def\.{.\spacefactor=\endofsentencespacefactor\space} @@ -617,21 +575,6 @@ % @? is an end-of-sentence query. \def\?{?\spacefactor=\endofsentencespacefactor\space} -% @frenchspacing on|off says whether to put extra space after punctuation. -% -\def\onword{on} -\def\offword{off} -% -\parseargdef\frenchspacing{% - \def\temp{#1}% - \ifx\temp\onword \plainfrenchspacing - \else\ifx\temp\offword \plainnonfrenchspacing - \else - \errhelp = \EMsimple - \errmessage{Unknown @frenchspacing option `\temp', must be on|off}% - \fi\fi -} - % @w prevents a word break. Without the \leavevmode, @w at the % beginning of a paragraph, when TeX is still in vertical mode, would % produce a whole line of output instead of starting the paragraph. @@ -725,32 +668,22 @@ \dimen2 = \ht\strutbox \advance\dimen2 by \dp\strutbox \ifdim\dimen0 > \dimen2 + % This is similar to the 'needspace' module in LaTeX. + % The first penalty allows a break if the end of the page is + % not too far away. Following penalties and skips are discarded. + % Otherwise, require at least \dimen0 of vertical space. % - % Do a \strut just to make the height of this box be normal, so the - % normal leading is inserted relative to the preceding line. - % And a page break here is fine. - \vtop to #1\mil{\strut\vfil}% - % - % TeX does not even consider page breaks if a penalty added to the - % main vertical list is 10000 or more. But in order to see if the - % empty box we just added fits on the page, we must make it consider - % page breaks. On the other hand, we don't want to actually break the - % page after the empty box. So we use a penalty of 9999. - % - % There is an extremely small chance that TeX will actually break the - % page at this \penalty, if there are no other feasible breakpoints in - % sight. (If the user is using lots of big @group commands, which - % almost-but-not-quite fill up a page, TeX will have a hard time doing - % good page breaking, for example.) However, I could not construct an - % example where a page broke at this \penalty; if it happens in a real - % document, then we can reconsider our strategy. + % (We used to use a \vtop to reserve space, but this had spacing issues + % when followed by a section heading, as it was not a "discardable item". + % This also has the benefit of providing glue before the page break if + % there isn't enough space.) + \vskip0pt plus \dimen0 + \penalty-100 + \vskip0pt plus -\dimen0 + \vskip \dimen0 \penalty9999 - % - % Back up by the size of the box, whether we did a page break or not. - \kern -#1\mil - % - % Do not allow a page break right after this kern. - \nobreak + \vskip -\dimen0 + \penalty0\relax % this hides the above glue from \safewhatsit and \dobreak \fi } @@ -1018,8 +951,16 @@ \let\setfilename=\comment % @bye. -\outer\def\bye{\chappager\pagelabels\tracingstats=1\ptexend} +\outer\def\bye{% + \chappager\pagelabels + % possibly set in \printindex + \ifx\byeerror\relax\else\errmessage{\byeerror}\fi + \tracingstats=1\ptexend} +% set in \donoderef below, but we need to define this here so that +% conditionals balance inside the large \ifpdf ... \fi blocks below. +\newif\ifnodeseen +\nodeseenfalse \message{pdf,} % adobe `portable' document format @@ -1038,15 +979,52 @@ \newif\ifpdf \newif\ifpdfmakepagedest +% when pdftex is run in dvi mode, \pdfoutput is defined (so \pdfoutput=1 +% can be set). So we test for \relax and 0 as well as being undefined. +\ifx\pdfoutput\thisisundefined +\else + \ifx\pdfoutput\relax + \else + \ifcase\pdfoutput + \else + \pdftrue + \fi + \fi +\fi + +\newif\ifxetex +\ifx\XeTeXrevision\thisisundefined\else + \xetextrue +\fi + +\newif\ifluatex +\ifx\luatexversion\thisisundefined\else + \luatextrue + \ifnum\luatexversion>84 + \pdftrue + \fi +\fi + +\newif\ifpdforxetex +\ifpdf + \pdforxetextrue +\fi +\ifxetex + \pdforxetextrue +\fi + + + +% Whether to use non-ASCII bytes in internal link targets. Presently this +% is almost always on. +\newif\iftxiuseunicodedestname +\txiuseunicodedestnametrue + % % For LuaTeX % -\newif\iftxiuseunicodedestname -\txiuseunicodedestnamefalse % For pdfTeX etc. - -\ifx\luatexversion\thisisundefined -\else +\ifluatex % Use Unicode destination names \txiuseunicodedestnametrue % Escape PDF strings with converting UTF-16 from UTF-8 @@ -1093,13 +1071,13 @@ end end } - % The -2 in the arguments here gives all the input to TeX catcode 12 - % (other) or 10 (space), preventing undefined control sequence errors. See + % The -2 in the arguments here gives all the input to TeX catcode 12 + % (other) or 10 (space), preventing undefined control sequence errors. See % https://lists.gnu.org/archive/html/bug-texinfo/2019-08/msg00031.html % \endgroup \def\pdfescapestring#1{\directlua{PDFescstr('\luaescapestring{#1}')}} - \ifnum\luatexversion>84 + \ifpdf % For LuaTeX >= 0.85 \def\pdfdest{\pdfextension dest} \let\pdfoutput\outputmode @@ -1122,52 +1100,36 @@ \fi \fi -% when pdftex is run in dvi mode, \pdfoutput is defined (so \pdfoutput=1 -% can be set). So we test for \relax and 0 as well as being undefined. -\ifx\pdfoutput\thisisundefined -\else - \ifx\pdfoutput\relax - \else - \ifcase\pdfoutput - \else - \pdftrue - \fi - \fi -\fi - -\newif\ifpdforxetex -\pdforxetexfalse -\ifpdf - \pdforxetextrue -\fi -\ifx\XeTeXrevision\thisisundefined\else - \pdforxetextrue -\fi - % Output page labels information. % See PDF reference v.1.7 p.594, section 8.3.1. +% Page label ranges must be increasing. \ifpdf \def\pagelabels{% \def\title{0 << /P (T-) /S /D >>}% - \edef\roman{\the\romancount << /S /r >>}% - \edef\arabic{\the\arabiccount << /S /D >>}% - % - % Page label ranges must be increasing. Remove any duplicates. - % (There is a slight chance of this being wrong if e.g. there is - % a @contents but no @titlepage, etc.) % - \ifnum\romancount=0 \def\roman{}\fi - \ifnum\arabiccount=0 \def\title{}% - \else - \ifnum\romancount=\arabiccount \def\roman{}\fi - \fi - % - \ifnum\romancount<\arabiccount - \pdfcatalog{/PageLabels << /Nums [\title \roman \arabic ] >> }\relax + % support @contents at very end of document + \ifnum\contentsendcount=\pagecount + \ifnum\arabiccount<\romancount + \pdfcatalog{/PageLabels << /Nums + [\title + \the\arabiccount << /S /D >> + \the\romancount << /S /r >> + ] >> }\relax + \fi + % no contents in document + \else\ifnum\contentsendcount=0 + \pdfcatalog{/PageLabels << /Nums + [\title + \the\arabiccount << /S /D >> + ] >> }\relax \else - \pdfcatalog{/PageLabels << /Nums [\title \arabic \roman ] >> }\relax - \fi + \pdfcatalog{/PageLabels << /Nums + [\title + \the\romancount << /S /r >> + \the\contentsendcount << /S /D >> + ] >> }\relax + \fi\fi } \else \let\pagelabels\relax @@ -1176,6 +1138,8 @@ \newcount\pagecount \pagecount=0 \newcount\romancount \romancount=0 \newcount\arabiccount \arabiccount=0 +\newcount\contentsendcount \contentsendcount=0 + \ifpdf \let\ptxadvancepageno\advancepageno \def\advancepageno{% @@ -1188,7 +1152,7 @@ % for display in the outlines, and in other places. Thus, we have to % double any backslashes. Otherwise, a name like "\node" will be % interpreted as a newline (\n), followed by o, d, e. Not good. -% +% % See http://www.ntg.nl/pipermail/ntg-pdftex/2004-July/000654.html and % related messages. The final outcome is that it is up to the TeX user % to double the backslashes and otherwise make the string valid, so @@ -1222,54 +1186,90 @@ be supported due to the design of the PDF format; use regular TeX (DVI output) for that.)} +% definitions for pdftex or luatex with pdf output \ifpdf + % Strings in PDF outlines can either be ASCII, or encoded in UTF-16BE + % with BOM. Unfortunately there is no simple way with pdftex to output + % UTF-16, so we have to do some quite convoluted expansion games if we + % find the string contains a non-ASCII codepoint if we want these to + % display correctly. We generated the UTF-16 sequences in + % \DeclareUnicodeCharacter and we access them here. + % + \def\defpdfoutlinetextunicode#1{% + \def\pdfoutlinetext{#1}% + % + % Make UTF-8 sequences expand to UTF-16 definitions. + \passthroughcharsfalse \utfbytespdftrue + \utfviiidefinedwarningfalse + % + % Completely expand, eliminating any control sequences such as \code, + % leaving only possibly \utfbytes. + \let\utfbytes\relax + \pdfaccentliterals + \xdef\pdfoutlinetextchecked{#1}% + \checkutfbytes + }% + % Check if \utfbytes occurs in expansion. + \def\checkutfbytes{% + \expandafter\checkutfbytesz\pdfoutlinetextchecked\utfbytes\finish + }% + \def\checkutfbytesz#1\utfbytes#2\finish{% + \def\after{#2}% + \ifx\after\empty + % No further action needed. Output ASCII string as-is, as converting + % to UTF-16 is somewhat slow (and uses more space). + \global\let\pdfoutlinetext\pdfoutlinetextchecked + \else + \passthroughcharstrue % pass UTF-8 sequences unaltered + \xdef\pdfoutlinetext{\pdfoutlinetext}% + \expandafter\expandutfsixteen\expandafter{\pdfoutlinetext}\pdfoutlinetext + \fi + }% % - % Color manipulation macros using ideas from pdfcolor.tex, - % except using rgb instead of cmyk; the latter is said to render as a - % very dark gray on-screen and a very dark halftone in print, instead - % of actual black. The dark red here is dark enough to print on paper as - % nearly black, but still distinguishable for online viewing. We use - % black by default, though. - \def\rgbDarkRed{0.50 0.09 0.12} - \def\rgbBlack{0 0 0} - % - % rg sets the color for filling (usual text, etc.); - % RG sets the color for stroking (thin rules, e.g., normal _'s). - \def\pdfsetcolor#1{\pdfliteral{#1 rg #1 RG}} + \catcode2=1 % begin-group character + \catcode3=2 % end-group character % - % Set color, and create a mark which defines \thiscolor accordingly, - % so that \makeheadline knows which color to restore. - \def\setcolor#1{% - \xdef\currentcolordefs{\gdef\noexpand\thiscolor{#1}}% - \domark - \pdfsetcolor{#1}% - } + % argument should be pure UTF-8 with no control sequences. convert to + % UTF-16BE by inserting null bytes before bytes < 128 and expanding + % UTF-8 multibyte sequences to saved UTF-16BE sequences. + \def\expandutfsixteen#1#2{% + \bgroup \asciitounicode + \passthroughcharsfalse + \let\utfbytes\asis + % + % for Byte Order Mark (BOM) + \catcode"FE=12 + \catcode"FF=12 + % + % we want to treat { and } in #1 as any other ASCII bytes. however, + % we need grouping characters for \scantokens and definitions/assignments, + % so define alternative grouping characters using control characters + % that are unlikely to occur. + % this does not affect 0x02 or 0x03 bytes arising from expansion as + % these are tokens with different catcodes. + \catcode"02=1 % begin-group character + \catcode"03=2 % end-group character + % + \expandafter\xdef\expandafter#2\scantokens{% + ^^02^^fe^^ff#1^^03}% + % NB we need \scantokens to provide both the open and close group tokens + % for \xdef otherwise there is an e-TeX error "File ended while + % scanning definition of..." + % NB \scantokens is a e-TeX command which is assumed to be provided by + % pdfTeX. + % + \egroup + }% % - \def\maincolor{\rgbBlack} - \pdfsetcolor{\maincolor} - \edef\thiscolor{\maincolor} - \def\currentcolordefs{} + \catcode2=12 \catcode3=12 % defaults % - \def\makefootline{% - \baselineskip24pt - \line{\pdfsetcolor{\maincolor}\the\footline}% - } + % Color support % - \def\makeheadline{% - \vbox to 0pt{% - \vskip-22.5pt - \line{% - \vbox to8.5pt{}% - % Extract \thiscolor definition from the marks. - \getcolormarks - % Typeset the headline with \maincolor, then restore the color. - \pdfsetcolor{\maincolor}\the\headline\pdfsetcolor{\thiscolor}% - }% - \vss - }% - \nointerlineskip - } + % rg sets the color for filling (usual text, etc.); + % RG sets the color for stroking (thin rules, e.g., normal _'s). + \def\pdfsetcolor#1{\pdfliteral{#1 rg #1 RG}} % + % PDF outline support % \pdfcatalog{/PageMode /UseOutlines} % @@ -1366,18 +1366,15 @@ \def\pdfoutlinetext{#1}% \else \ifx \declaredencoding \utfeight - \ifx\luatexversion\thisisundefined - % For pdfTeX with UTF-8. - % TODO: the PDF format can use UTF-16 in bookmark strings, - % but the code for this isn't done yet. - % Use ASCII approximations. - \passthroughcharsfalse - \def\pdfoutlinetext{#1}% - \else + \ifluatex % For LuaTeX with UTF-8. % Pass through Unicode characters for title texts. \passthroughcharstrue - \def\pdfoutlinetext{#1}% + \pdfaccentliterals + \xdef\pdfoutlinetext{#1}% + \else + % For pdfTeX with UTF-8. + \defpdfoutlinetextunicode{#1}% \fi \else % For non-Latin-1 or non-UTF-8 encodings. @@ -1396,14 +1393,6 @@ \safewhatsit{\pdfdest name{\pdfdestname} xyz}% } % - % used to mark target names; must be expandable. - \def\pdfmkpgn#1{#1} - % - % by default, use black for everything. - \def\urlcolor{\rgbBlack} - \def\linkcolor{\rgbBlack} - \def\endlink{\setcolor{\maincolor}\pdfendlink} - % % Adding outlines to PDF; macros for calculating structure of outlines % come from Petr Olsak \def\expnumber#1{\expandafter\ifx\csname#1\endcsname\relax 0% @@ -1429,7 +1418,7 @@ \def\pdfdestname{#4}% \fi % - \pdfoutline goto name{\pdfmkpgn{\pdfdestname}}#2{\pdfoutlinetext}% + \pdfoutline goto name{\pdfdestname}#2{\pdfoutlinetext}% } % \def\pdfmakeoutlines{% @@ -1440,15 +1429,18 @@ \def\thischapnum{##2}% \def\thissecnum{0}% \def\thissubsecnum{0}% + \def\indexlastsec{chap\thischapnum}% }% \def\numsecentry##1##2##3##4{% \advancenumber{chap\thischapnum}% \def\thissecnum{##2}% \def\thissubsecnum{0}% + \def\indexlastsec{sec\thissecnum}% }% \def\numsubsecentry##1##2##3##4{% \advancenumber{sec\thissecnum}% \def\thissubsecnum{##2}% + \def\indexlastsec{subsec\thissecnum}% }% \def\numsubsubsecentry##1##2##3##4{% \advancenumber{subsec\thissubsecnum}% @@ -1456,7 +1448,13 @@ \def\thischapnum{0}% \def\thissecnum{0}% \def\thissubsecnum{0}% + \let\indexlastsec\empty % + % Index initials are subsidiary to whatever sectioning command just + % occurred, usually @appendix or @chapter but occasionally a lower level. + \def\idxinitialentry##1##2##3##4{% + \expandafter\advancenumber\expandafter{\indexlastsec}% + }% % use \def rather than \let here because we redefine \chapentry et % al. a second time, below. \def\appentry{\numchapentry}% @@ -1467,6 +1465,7 @@ \def\unnsecentry{\numsecentry}% \def\unnsubsecentry{\numsubsecentry}% \def\unnsubsubsecentry{\numsubsubsecentry}% + % \readdatafile{toc}% % % Read toc second time, this time actually producing the outlines. @@ -1476,7 +1475,7 @@ % We use the node names as the destinations. % % Currently we prefix the section name with the section number - % for chapter and appendix headings only in order to avoid too much + % for chapter and appendix headings only in order to avoid too much % horizontal space being required in the PDF viewer. \def\numchapentry##1##2##3##4{% \dopdfoutline{##2 ##1}{count-\expnumber{chap##2}}{##3}{##4}}% @@ -1488,28 +1487,23 @@ \dopdfoutline{##1}{count-\expnumber{subsec##2}}{##3}{##4}}% \def\numsubsubsecentry##1##2##3##4{% count is always zero \dopdfoutline{##1}{}{##3}{##4}}% - % - % PDF outlines are displayed using system fonts, instead of - % document fonts. Therefore we cannot use special characters, - % since the encoding is unknown. For example, the eogonek from - % Latin 2 (0xea) gets translated to a | character. Info from - % Staszek Wawrykiewicz, 19 Jan 2004 04:09:24 +0100. - % - % TODO this right, we have to translate 8-bit characters to - % their "best" equivalent, based on the @documentencoding. Too - % much work for too little return. Just use the ASCII equivalents - % we use for the index sort strings. - % - \indexnofonts + \def\idxinitialentry##1##2##3##4{% + \dopdfoutline{##1}{}{idx.##1.##2}{##4}}% + % + \ifnodeseen\else \dopdfoutlinecontents \fi % for @contents at beginning \setupdatafile % We can have normal brace characters in the PDF outlines, unlike % Texinfo index files. So set that up. \def\{{\lbracecharliteral}% \def\}{\rbracecharliteral}% \catcode`\\=\active \otherbackslash - \input \tocreadfilename + \input \tocreadfilename\relax + \ifnodeseen \dopdfoutlinecontents \fi % for @contents at end \endgroup } + \def\dopdfoutlinecontents{% + \expandafter\dopdfoutline\expandafter{\putwordTOC}{}{txi.CONTENTS}{}% + } {\catcode`[=1 \catcode`]=2 \catcode`{=\other \catcode`}=\other \gdef\lbracecharliteral[{]% @@ -1535,54 +1529,16 @@ \else \let \startlink \pdfstartlink \fi - % make a live url in pdf output. - \def\pdfurl#1{% - \begingroup - % it seems we really need yet another set of dummies; have not - % tried to figure out what each command should do in the context - % of @url. for now, just make @/ a no-op, that's the only one - % people have actually reported a problem with. - % - \normalturnoffactive - \def\@{@}% - \let\/=\empty - \makevalueexpandable - % do we want to go so far as to use \indexnofonts instead of just - % special-casing \var here? - \def\var##1{##1}% - % - \leavevmode\setcolor{\urlcolor}% - \startlink attr{/Border [0 0 0]}% - user{/Subtype /Link /A << /S /URI /URI (#1) >>}% - \endgroup} - % \pdfgettoks - Surround page numbers in #1 with @pdflink. #1 may - % be a simple number, or a list of numbers in the case of an index - % entry. - \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}} - \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks} - \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks} - \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}} - \def\maketoks{% - \expandafter\poptoks\the\toksA|ENDTOKS|\relax - \ifx\first0\adn0 - \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3 - \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6 - \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9 - \else - \ifnum0=\countA\else\makelink\fi - \ifx\first.\let\next=\done\else - \let\next=\maketoks - \addtokens{\toksB}{\the\toksD} - \ifx\first,\addtokens{\toksB}{\space}\fi - \fi - \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi - \next} - \def\makelink{\addtokens{\toksB}% - {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0} - \def\pdflink#1{% - \startlink attr{/Border [0 0 0]} goto name{\pdfmkpgn{#1}} - \setcolor{\linkcolor}#1\endlink} - \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st} + \def\pdfmakeurl#1{% + \startlink attr{/Border [0 0 0]}% + user{/Subtype /Link /A << /S /URI /URI (#1) >>}% + }% + \def\endlink{\setcolor{\maincolor}\pdfendlink} + % + \def\pdflink#1{\pdflinkpage{#1}{#1}}% + \def\pdflinkpage#1#2{% + \startlink attr{/Border [0 0 0]} goto name{#1} + \setcolor{\linkcolor}#2\endlink} \else % non-pdf mode \let\pdfmkdest = \gobble @@ -1591,13 +1547,12 @@ \let\setcolor = \gobble \let\pdfsetcolor = \gobble \let\pdfmakeoutlines = \relax -\fi % \ifx\pdfoutput +\fi % % For XeTeX % -\ifx\XeTeXrevision\thisisundefined -\else +\ifxetex % % XeTeX version check % @@ -1623,45 +1578,8 @@ \fi % % Color support - % - \def\rgbDarkRed{0.50 0.09 0.12} - \def\rgbBlack{0 0 0} - % \def\pdfsetcolor#1{\special{pdf:scolor [#1]}} % - % Set color, and create a mark which defines \thiscolor accordingly, - % so that \makeheadline knows which color to restore. - \def\setcolor#1{% - \xdef\currentcolordefs{\gdef\noexpand\thiscolor{#1}}% - \domark - \pdfsetcolor{#1}% - } - % - \def\maincolor{\rgbBlack} - \pdfsetcolor{\maincolor} - \edef\thiscolor{\maincolor} - \def\currentcolordefs{} - % - \def\makefootline{% - \baselineskip24pt - \line{\pdfsetcolor{\maincolor}\the\footline}% - } - % - \def\makeheadline{% - \vbox to 0pt{% - \vskip-22.5pt - \line{% - \vbox to8.5pt{}% - % Extract \thiscolor definition from the marks. - \getcolormarks - % Typeset the headline with \maincolor, then restore the color. - \pdfsetcolor{\maincolor}\the\headline\pdfsetcolor{\thiscolor}% - }% - \vss - }% - \nointerlineskip - } - % % PDF outline support % % Emulate pdfTeX primitive @@ -1699,11 +1617,6 @@ \safewhatsit{\pdfdest name{\pdfdestname} xyz}% } % - % by default, use black for everything. - \def\urlcolor{\rgbBlack} - \def\linkcolor{\rgbBlack} - \def\endlink{\setcolor{\maincolor}\pdfendlink} - % \def\dopdfoutline#1#2#3#4{% \setpdfoutlinetext{#1} \setpdfdestname{#3} @@ -1717,24 +1630,30 @@ % \def\pdfmakeoutlines{% \begingroup - % % For XeTeX, counts of subentries are not necessary. % Therefore, we read toc only once. % % We use node names as destinations. % % Currently we prefix the section name with the section number - % for chapter and appendix headings only in order to avoid too much + % for chapter and appendix headings only in order to avoid too much % horizontal space being required in the PDF viewer. \def\partentry##1##2##3##4{}% ignore parts in the outlines \def\numchapentry##1##2##3##4{% - \dopdfoutline{##2 ##1}{1}{##3}{##4}}% + \dopdfoutline{##2 ##1}{1}{##3}{##4}% + \def\indexseclevel{2}}% \def\numsecentry##1##2##3##4{% - \dopdfoutline{##1}{2}{##3}{##4}}% + \dopdfoutline{##1}{2}{##3}{##4}% + \def\indexseclevel{3}}% \def\numsubsecentry##1##2##3##4{% - \dopdfoutline{##1}{3}{##3}{##4}}% + \dopdfoutline{##1}{3}{##3}{##4}% + \def\indexseclevel{4}}% \def\numsubsubsecentry##1##2##3##4{% - \dopdfoutline{##1}{4}{##3}{##4}}% + \dopdfoutline{##1}{4}{##3}{##4}% + \def\indexseclevel{5}}% + % + \def\idxinitialentry##1##2##3##4{% + \dopdfoutline{##1}{\indexseclevel}{idx.##1.##2}{##4}}% % \let\appentry\numchapentry% \let\appsecentry\numsecentry% @@ -1750,15 +1669,25 @@ % Therefore, the encoding and the language may not be considered. % \indexnofonts + \pdfaccentliterals + \ifnodeseen\else \dopdfoutlinecontents \fi % for @contents at beginning + % \setupdatafile % We can have normal brace characters in the PDF outlines, unlike % Texinfo index files. So set that up. \def\{{\lbracecharliteral}% \def\}{\rbracecharliteral}% \catcode`\\=\active \otherbackslash - \input \tocreadfilename + \xetexpreauxfile + \input \tocreadfilename\relax + \xetexpostauxfile + \ifnodeseen \dopdfoutlinecontents \fi % for @contents at end \endgroup } + \def\dopdfoutlinecontents{% + \expandafter\dopdfoutline\expandafter + {\putwordTOC}{1}{txi.CONTENTS}{txi.CONTENTS}% + } {\catcode`[=1 \catcode`]=2 \catcode`{=\other \catcode`}=\other \gdef\lbracecharliteral[{]% @@ -1771,7 +1700,7 @@ % However, due to a UTF-16 conversion issue of xdvipdfmx 20150315, % ``\special{pdf:dest ...}'' cannot handle non-ASCII strings. % It is fixed by xdvipdfmx 20160106 (TeX Live SVN r39753). -% + % \def\skipspaces#1{\def\PP{#1}\def\D{|}% \ifx\PP\D\let\nextsp\relax \else\let\nextsp\skipspaces @@ -1786,54 +1715,17 @@ \edef\temp{#1}% \expandafter\skipspaces\temp|\relax } - % make a live url in pdf output. - \def\pdfurl#1{% - \begingroup - % it seems we really need yet another set of dummies; have not - % tried to figure out what each command should do in the context - % of @url. for now, just make @/ a no-op, that's the only one - % people have actually reported a problem with. - % - \normalturnoffactive - \def\@{@}% - \let\/=\empty - \makevalueexpandable - % do we want to go so far as to use \indexnofonts instead of just - % special-casing \var here? - \def\var##1{##1}% - % - \leavevmode\setcolor{\urlcolor}% - \special{pdf:bann << /Border [0 0 0] - /Subtype /Link /A << /S /URI /URI (#1) >> >>}% - \endgroup} + \def\pdfmakeurl#1{% + \special{pdf:bann << /Border [0 0 0] + /Subtype /Link /A << /S /URI /URI (#1) >> >>}% + } \def\endlink{\setcolor{\maincolor}\special{pdf:eann}} - \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}} - \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks} - \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks} - \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}} - \def\maketoks{% - \expandafter\poptoks\the\toksA|ENDTOKS|\relax - \ifx\first0\adn0 - \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3 - \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6 - \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9 - \else - \ifnum0=\countA\else\makelink\fi - \ifx\first.\let\next=\done\else - \let\next=\maketoks - \addtokens{\toksB}{\the\toksD} - \ifx\first,\addtokens{\toksB}{\space}\fi - \fi - \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi - \next} - \def\makelink{\addtokens{\toksB}% - {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0} - \def\pdflink#1{% + \def\pdflink#1{\pdflinkpage{#1}{#1}}% + \def\pdflinkpage#1#2{% \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A << /S /GoTo /D (#1) >> >>}% - \setcolor{\linkcolor}#1\endlink} - \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st} -% + \setcolor{\linkcolor}#2\endlink} + % % % @image support % @@ -1890,6 +1782,164 @@ } \fi +% common definitions and code for pdftex, luatex and xetex +\ifpdforxetex + % The dark red here is dark enough to print on paper as + % nearly black, but still distinguishable for online viewing. We use + % black by default, though. + \def\rgbDarkRed{0.50 0.09 0.12} + \def\rgbBlack{0 0 0} + % + % Set color, and create a mark which defines \thiscolor accordingly, + % so that \makeheadline knows which color to restore. + \def\curcolor{0 0 0}% + \def\setcolor#1{% + \ifx#1\curcolor\else + \xdef\currentcolordefs{\gdef\noexpand\thiscolor{#1}}% + \domark + \pdfsetcolor{#1}% + \xdef\curcolor{#1}% + \fi + } + % + \let\maincolor\rgbBlack + \pdfsetcolor{\maincolor} + \edef\thiscolor{\maincolor} + \def\currentcolordefs{} + % + \def\makefootline{% + \baselineskip24pt + \line{\pdfsetcolor{\maincolor}\the\footline}% + } + % + \def\makeheadline{% + \vbox to 0pt{% + \vskip-22.5pt + \line{% + \vbox to8.5pt{}% + % Extract \thiscolor definition from the marks. + \getcolormarks + % Typeset the headline with \maincolor, then restore the color. + \pdfsetcolor{\maincolor}\the\headline\pdfsetcolor{\thiscolor}% + }% + \vss + }% + \nointerlineskip + } + % + % by default, use black for everything. + \def\urlcolor{\rgbBlack} + \let\linkcolor\rgbBlack + % + % make a live url in pdf output. + \def\pdfurl#1{% + \begingroup + % it seems we really need yet another set of dummies; have not + % tried to figure out what each command should do in the context + % of @url. for now, just make @/ a no-op, that's the only one + % people have actually reported a problem with. + % + \normalturnoffactive + \def\@{@}% + \let\/=\empty + \makevalueexpandable + % do we want to go so far as to use \indexnofonts instead of just + % special-casing \var here? + \def\var##1{##1}% + % + \leavevmode\setcolor{\urlcolor}% + \pdfmakeurl{#1}% + \endgroup} + % + % \pdfgettoks - Surround page numbers in #1 with @pdflink. #1 may + % be a simple number, or a list of numbers in the case of an index + % entry. + \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}} + \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks} + \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks} + \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}} + \def\maketoks{% + \expandafter\poptoks\the\toksA|ENDTOKS|\relax + \ifx\first0\adn0 + \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3 + \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6 + \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9 + \else + \ifnum0=\countA\else\makelink\fi + \ifx\first.\let\next=\done\else + \let\next=\maketoks + \addtokens{\toksB}{\the\toksD} + \ifx\first,\addtokens{\toksB}{\space}\fi + \fi + \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi + \next} + \def\makelink{\addtokens{\toksB}% + {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0} + \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st} +\fi + +\ifpdforxetex + % for pdftex. + {\catcode`^^cc=13 + \gdef\pdfaccentliteralsutfviii{% + % For PDF outline only. Unicode combining accents follow the + % character they modify. Note we need at least the first byte + % of the UTF-8 sequences to have an active catcode to allow the + % definitions to do their magic. + \def\"##1{##1^^cc^^88}% U+0308 + \def\'##1{##1^^cc^^81}% U+0301 + \def\,##1{##1^^cc^^a7}% U+0327 + \def\=##1{##1^^cc^^85}% U+0305 + \def\^##1{##1^^cc^^82}% U+0302 + \def\`##1{##1^^cc^^80}% U+0300 + \def\~##1{##1^^cc^^83}% U+0303 + \def\dotaccent##1{##1^^cc^^87}% U+0307 + \def\H##1{##1^^cc^^8b}% U+030B + \def\ogonek##1{##1^^cc^^a8}% U+0328 + \def\ringaccent##1{##1^^cc^^8a}% U+030A + \def\u##1{##1^^cc^^8c}% U+0306 + \def\ubaraccent##1{##1^^cc^^b1}% U+0331 + \def\udotaccent##1{##1^^cc^^a3}% U+0323 + \def\v##1{##1^^cc^^8c}% U+030C + % this definition of @tieaccent will only work with exactly two characters + % in argument as we need to insert the combining character between them. + \def\tieaccent##1{\tieaccentz##1}% + \def\tieaccentz##1##2{##1^^cd^^a1##2} % U+0361 + }}% + % + % for xetex and luatex, which both support extended ^^^^ escapes and + % process the Unicode codepoint as a single token. + \gdef\pdfaccentliteralsnative{% + \def\"##1{##1^^^^0308}% + \def\'##1{##1^^^^0301}% + \def\,##1{##1^^^^0327}% + \def\=##1{##1^^^^0305}% + \def\^##1{##1^^^^0302}% + \def\`##1{##1^^^^0300}% + \def\~##1{##1^^^^0303}% + \def\dotaccent##1{##1^^^^0307}% + \def\H##1{##1^^^^030b}% + \def\ogonek##1{##1^^^^0328}% + \def\ringaccent##1{##1^^^^030a}% + \def\u##1{##1^^^^0306}% + \def\ubaraccent##1{##1^^^^0331}% + \def\udotaccent##1{##1^^^^0323}% + \def\v##1{##1^^^^030c}% + \def\tieaccent##1{\tieaccentz##1}% + \def\tieaccentz##1##2{##1^^^^0361##2} % U+0361 + }% + % + % use the appropriate definition + \ifluatex + \let\pdfaccentliterals\pdfaccentliteralsnative + \else + \ifxetex + \let\pdfaccentliterals\pdfaccentliteralsnative + \else + \let\pdfaccentliterals\pdfaccentliteralsutfviii + \fi + \fi +\fi % \message{fonts,} @@ -2176,6 +2226,11 @@ \pdffontattr#1{/ToUnicode \the\pdflastobj\space 0 R}% }% \fi\fi +% +% This is what gets called when #5 of \setfont is empty. +\let\cmap\gobble +% +% (end of cmaps) % Set the font macro #1 to the font named \fontprefix#2. @@ -2191,11 +2246,10 @@ \def\setfont#1#2#3#4#5{% \font#1=\fontprefix#2#3 scaled #4 \csname cmap#5\endcsname#1% + \ifx#2\ttshape\hyphenchar#1=-1 \fi + \ifx#2\ttbshape\hyphenchar#1=-1 \fi + \ifx#2\ttslshape\hyphenchar#1=-1 \fi } -% This is what gets called when #5 of \setfont is empty. -\let\cmap\gobble -% -% (end of cmaps) % Use cm as the default font prefix. % To specify the font prefix, you must define \fontprefix @@ -2558,7 +2612,7 @@ \def\it{\fam=\itfam \setfontstyle{it}} \def\sl{\fam=\slfam \setfontstyle{sl}} \def\bf{\fam=\bffam \setfontstyle{bf}}\def\bfstylename{bf} -\def\tt{\fam=\ttfam \setfontstyle{tt}}\def\ttstylename{tt} +\def\tt{\fam=\ttfam \setfontstyle{tt}} % Texinfo sort of supports the sans serif font style, which plain TeX does not. % So we set up a \sf. @@ -2586,34 +2640,30 @@ \scriptfont\sffam=\sevensf } -% -% The font-changing commands (all called \...fonts) redefine the meanings -% of \STYLEfont, instead of just \STYLE. We do this because \STYLE needs -% to also set the current \fam for math mode. Our \STYLE (e.g., \rm) -% commands hardwire \STYLEfont to set the current font. -% -% The fonts used for \ifont are for "math italics" (\itfont is for italics -% in regular text). \syfont is also used in math mode only. -% -% Each font-changing command also sets the names \lsize (one size lower) -% and \lllsize (three sizes lower). These relative commands are used -% in, e.g., the LaTeX logo and acronyms. -% -% This all needs generalizing, badly. + +% \defineassignfonts{SIZE} - +% Define sequence \assignfontsSIZE, which switches between font sizes +% by redefining the meanings of \STYLEfont. (Just \STYLE additionally sets +% the current \fam for math mode.) % +\def\defineassignfonts#1{% + \expandafter\edef\csname assignfonts#1\endcsname{% + \let\noexpand\rmfont\csname #1rm\endcsname + \let\noexpand\itfont\csname #1it\endcsname + \let\noexpand\slfont\csname #1sl\endcsname + \let\noexpand\bffont\csname #1bf\endcsname + \let\noexpand\ttfont\csname #1tt\endcsname + \let\noexpand\smallcaps\csname #1sc\endcsname + \let\noexpand\sffont \csname #1sf\endcsname + \let\noexpand\ifont \csname #1i\endcsname + \let\noexpand\syfont \csname #1sy\endcsname + \let\noexpand\ttslfont\csname #1ttsl\endcsname + } +} \def\assignfonts#1{% - \expandafter\let\expandafter\rmfont\csname #1rm\endcsname - \expandafter\let\expandafter\itfont\csname #1it\endcsname - \expandafter\let\expandafter\slfont\csname #1sl\endcsname - \expandafter\let\expandafter\bffont\csname #1bf\endcsname - \expandafter\let\expandafter\ttfont\csname #1tt\endcsname - \expandafter\let\expandafter\smallcaps\csname #1sc\endcsname - \expandafter\let\expandafter\sffont \csname #1sf\endcsname - \expandafter\let\expandafter\ifont \csname #1i\endcsname - \expandafter\let\expandafter\syfont \csname #1sy\endcsname - \expandafter\let\expandafter\ttslfont\csname #1ttsl\endcsname + \csname assignfonts#1\endcsname } \newif\ifrmisbold @@ -2637,12 +2687,21 @@ \csname\curfontstyle\endcsname }% +% Define the font-changing commands (all called \...fonts). +% Each font-changing command also sets the names \lsize (one size lower) +% and \lllsize (three sizes lower). These relative commands are used +% in, e.g., the LaTeX logo and acronyms. +% +% Note: The fonts used for \ifont are for "math italics" (\itfont is for +% italics in regular text). \syfont is also used in math mode only. +% \def\definefontsetatsize#1#2#3#4#5{% + \defineassignfonts{#1}% \expandafter\def\csname #1fonts\endcsname{% \def\curfontsize{#1}% \def\lsize{#2}\def\lllsize{#3}% \csname rmisbold#5\endcsname - \assignfonts{#1}% + \csname assignfonts#1\endcsname \resetmathfonts \setleading{#4}% }} @@ -2687,9 +2746,22 @@ % Check if we are currently using a typewriter font. Since all the % Computer Modern typewriter fonts have zero interword stretch (and % shrink), and it is reasonable to expect all typewriter fonts to have -% this property, we can check that font parameter. -% -\def\ifmonospace{\ifdim\fontdimen3\font=0pt } +% this property, we can check that font parameter. #1 is what to +% print if we are indeed using \tt; #2 is what to print otherwise. +\def\ifusingtt#1#2{\ifdim \fontdimen3\font=0pt #1\else #2\fi} + +% Same as above, but check for italic font. Actually this also catches +% non-italic slanted fonts since it is impossible to distinguish them from +% italic fonts. But since this is only used by $ and it uses \sl anyway +% this is not a problem. +\def\ifusingit#1#2{\ifdim \fontdimen1\font>0pt #1\else #2\fi} + + +% Check if internal flag is clear, i.e. has not been @set. +\def\ifflagclear#1#2#3{% + \expandafter\ifx\csname SET#1\endcsname\relax + #2\else#3\fi +} { \catcode`\'=\active @@ -2698,45 +2770,37 @@ \gdef\setcodequotes{\let`\codequoteleft \let'\codequoteright} \gdef\setregularquotes{\let`\lq \let'\rq} } +\setregularquotes -% Allow an option to not use regular directed right quote/apostrophe -% (char 0x27), but instead the undirected quote from cmtt (char 0x0d). -% The undirected quote is ugly, so don't make it the default, but it -% works for pasting with more pdf viewers (at least evince), the -% lilypond developers report. xpdf does work with the regular 0x27. +% output for ' in @code +% in tt font hex 0D (undirected) or 27 (curly right quote) % \def\codequoteright{% - \ifmonospace - \expandafter\ifx\csname SETtxicodequoteundirected\endcsname\relax - \expandafter\ifx\csname SETcodequoteundirected\endcsname\relax - '% - \else \char'15 \fi - \else \char'15 \fi - \else - '% - \fi + \ifusingtt + {\ifflagclear{txicodequoteundirected}% + {\ifflagclear{codequoteundirected}% + {'}% + {\char"0D }}% + {\char"0D }}% + {'}% } -% -% and a similar option for the left quote char vs. a grave accent. -% Modern fonts display ASCII 0x60 as a grave accent, so some people like -% the code environments to do likewise. + +% output for ` in @code +% in tt font hex 12 (grave accent) or 60 (curly left quote) +% \relax disables Spanish ligatures ?` and !` of \tt font. % \def\codequoteleft{% - \ifmonospace - \expandafter\ifx\csname SETtxicodequotebacktick\endcsname\relax - \expandafter\ifx\csname SETcodequotebacktick\endcsname\relax - % [Knuth] pp. 380,381,391 - % \relax disables Spanish ligatures ?` and !` of \tt font. - \relax`% - \else \char'22 \fi - \else \char'22 \fi - \else - \relax`% - \fi + \ifusingtt + {\ifflagclear{txicodequotebacktick}% + {\ifflagclear{codequotebacktick}% + {\relax`}% + {\char"12 }}% + {\char"12 }}% + {\relax`}% } % Commands to set the quote options. -% +% \parseargdef\codequoteundirected{% \def\temp{#1}% \ifx\temp\onword @@ -2750,7 +2814,7 @@ \errmessage{Unknown @codequoteundirected value `\temp', must be on|off}% \fi\fi } -% + \parseargdef\codequotebacktick{% \def\temp{#1}% \ifx\temp\onword @@ -2765,6 +2829,11 @@ \fi\fi } +% Turn them on by default +\let\SETtxicodequoteundirected = t +\let\SETtxicodequotebacktick = t + + % [Knuth] pp. 380,381,391, disable Spanish ligatures ?` and !` of \tt font. \def\noligaturesquoteleft{\relax\lq} @@ -2777,17 +2846,18 @@ % If we are in a monospaced environment, however, 1) always use \ttsl, % and 2) do not add an italic correction. \def\dosmartslant#1#2{% - \ifusingtt + \ifusingtt {{\ttsl #2}\let\next=\relax}% - {\def\next{{#1#2}\futurelet\next\smartitaliccorrection}}% + {\def\next{{#1#2}\smartitaliccorrection}}% \next } \def\smartslanted{\dosmartslant\sl} \def\smartitalic{\dosmartslant\it} -% Output an italic correction unless \next (presumed to be the following -% character) is such as not to need one. -\def\smartitaliccorrection{% +% Output an italic correction unless the following character is such as +% not to need one. +\def\smartitaliccorrection{\futurelet\next\smartitaliccorrectionx} +\def\smartitaliccorrectionx{% \ifx\next,% \else\ifx\next-% \else\ifx\next.% @@ -2798,43 +2868,52 @@ \aftersmartic } -% Unconditional use \ttsl, and no ic. @var is set to this for defuns. -\def\ttslanted#1{{\ttsl #1}} - -% @cite is like \smartslanted except unconditionally use \sl. We never want -% ttsl for book titles, do we? -\def\cite#1{{\sl #1}\futurelet\next\smartitaliccorrection} +% @cite unconditionally uses \sl with \smartitaliccorrection. +\def\cite#1{{\sl #1}\smartitaliccorrection} +% By default, use ttsl font for @var when used in code context. +% To unconditionally use \sl for @var, @clear txicodevaristt. This +% gives consistency for parameter names whether they are in @def, +% @table @code or a regular paragraph. \def\aftersmartic{} \def\var#1{% \let\saveaftersmartic = \aftersmartic \def\aftersmartic{\null\let\aftersmartic=\saveaftersmartic}% - \smartslanted{#1}% + % The \null is to reset \spacefactor. + % + \ifflagclear{txicodevaristt}% + {\def\varnext{{{\sl #1}}\smartitaliccorrection}}% + {\def\varnext{\smartslanted{#1}}}% + \varnext } +\def\SETtxicodevaristt{}% @set txicodevaristt + \let\i=\smartitalic \let\slanted=\smartslanted \let\dfn=\smartslanted \let\emph=\smartitalic -% Explicit font changes: @r, @sc, undocumented @ii. -\def\r#1{{\rm #1}} % roman font +% @r for roman font, used for code comment +\def\r#1{{% + \usenormaldash % get --, --- ligatures even if in @code + \defcharsdefault % in case on def line + \rm #1}} +{\catcode`-=\active \gdef\usenormaldash{\let-\normaldash}} + +% @sc, undocumented @ii. \def\sc#1{{\smallcaps#1}} % smallcaps font \def\ii#1{{\it #1}} % italic font % @b, explicit bold. Also @strong. -\def\b#1{{\bf #1}} +\def\b#1{{\bf \defcharsdefault #1}} \let\strong=\b % @sansserif, explicit sans. \def\sansserif#1{{\sf #1}} -% We can't just use \exhyphenpenalty, because that only has effect at -% the end of a paragraph. Restore normal hyphenation at the end of the -% group within which \nohyphenation is presumably called. -% -\def\nohyphenation{\hyphenchar\font = -1 \aftergroup\restorehyphenation} -\def\restorehyphenation{\hyphenchar\font = `- } +\newif\iffrenchspacing +\frenchspacingfalse % Set sfcode to normal for the chars that usually have another value. % Can't use plain's \frenchspacing because it uses the `\x notation, and @@ -2842,21 +2921,45 @@ % \catcode`@=11 \def\plainfrenchspacing{% - \sfcode`\.=\@m \sfcode`\?=\@m \sfcode`\!=\@m - \sfcode`\:=\@m \sfcode`\;=\@m \sfcode`\,=\@m - \def\endofsentencespacefactor{1000}% for @. and friends + \iffrenchspacing\else + \frenchspacingtrue + \sfcode`\.=\@m \sfcode`\?=\@m \sfcode`\!=\@m + \sfcode`\:=\@m \sfcode`\;=\@m \sfcode`\,=\@m + \def\endofsentencespacefactor{1000}% for @. and friends + \fi } \def\plainnonfrenchspacing{% - \sfcode`\.3000\sfcode`\?3000\sfcode`\!3000 - \sfcode`\:2000\sfcode`\;1500\sfcode`\,1250 - \def\endofsentencespacefactor{3000}% for @. and friends + \iffrenchspacing + \frenchspacingfalse + \sfcode`\.3000\sfcode`\?3000\sfcode`\!3000 + \sfcode`\:2000\sfcode`\;1500\sfcode`\,1250 + \def\endofsentencespacefactor{3000}% for @. and friends + \fi } \catcode`@=\other \def\endofsentencespacefactor{3000}% default +% @frenchspacing on|off says whether to put extra space after punctuation. +% +\def\onword{on} +\def\offword{off} +% +\let\frenchspacingsetting\plainnonfrenchspacing % used in output routine +\parseargdef\frenchspacing{% + \def\temp{#1}% + \ifx\temp\onword \let\frenchspacingsetting\plainfrenchspacing + \else\ifx\temp\offword \let\frenchspacingsetting\plainnonfrenchspacing + \else + \errhelp = \EMsimple + \errmessage{Unknown @frenchspacing option `\temp', must be on|off}% + \fi\fi + \frenchspacingsetting +} + + % @t, explicit typewriter. \def\t#1{% - {\tt \plainfrenchspacing #1}% + {\tt \defcharsdefault \plainfrenchspacing #1}% \null } @@ -2877,27 +2980,29 @@ % Switch to typewriter. \tt % - % But `\ ' produces the large typewriter interword space. + % `\ ' produces the large typewriter interword space. \def\ {{\spaceskip = 0pt{} }}% % - % Turn off hyphenation. - \nohyphenation - % \plainfrenchspacing #1% }% \null % reset spacefactor to 1000 } -% We *must* turn on hyphenation at `-' and `_' in @code. -% (But see \codedashfinish below.) +% This is for LuaTeX: It is not sufficient to disable hyphenation at +% explicit dashes by setting `\hyphenchar` to -1. +\def\dashnobreak{% + \normaldash + \penalty 10000 } + +% We must turn on hyphenation at `-' and `_' in @code. % Otherwise, it is too hard to avoid overfull hboxes % in the Emacs manual, the Library manual, etc. +% We explicitly allow hyphenation at these characters +% using \discretionary. % -% Unfortunately, TeX uses one parameter (\hyphenchar) to control -% both hyphenation at - and hyphenation within words. -% We must therefore turn them both off (\tclose does that) -% and arrange explicitly to hyphenate at a dash. -- rms. +% Hyphenation at - and hyphenation within words was turned off +% by default for the tt fonts using the \hyphenchar parameter of TeX. { \catcode`\-=\active \catcode`\_=\active \catcode`\'=\active \catcode`\`=\active @@ -2910,37 +3015,42 @@ \let-\codedash \let_\codeunder \else - \let-\normaldash + \let-\dashnobreak \let_\realunder \fi - % Given -foo (with a single dash), we do not want to allow a break - % after the hyphen. - \global\let\codedashprev=\codedash - % \codex } % \gdef\codedash{\futurelet\next\codedashfinish} \gdef\codedashfinish{% \normaldash % always output the dash character itself. - % + % % Now, output a discretionary to allow a line break, unless % (a) the next character is a -, or - % (b) the preceding character is a -. + % (b) the preceding character is a -, or + % (c) we are at the start of the string. + % In both cases (b) and (c), \codedashnobreak should be set to \codedash. + % % E.g., given --posix, we do not want to allow a break after either -. % Given --foo-bar, we do want to allow a break between the - and the b. \ifx\next\codedash \else - \ifx\codedashprev\codedash + \ifx\codedashnobreak\codedash \else \discretionary{}{}{}\fi \fi % we need the space after the = for the case when \next itself is a % space token; it would get swallowed otherwise. As in @code{- a}. - \global\let\codedashprev= \next + \global\let\codedashnobreak= \next } } \def\normaldash{-} % -\def\codex #1{\tclose{#1}\endgroup} +\def\codex #1{\tclose{% + % Given -foo (with a single dash), we do not want to allow a break + % after the -. \codedashnobreak is set to the first character in + % @code. + \futurelet\codedashnobreak\relax + #1% +}\endgroup} \def\codeunder{% % this is all so @math{@code{var_name}+1} can work. In math mode, _ @@ -3020,25 +3130,25 @@ % For pdfTeX and LuaTeX \ifurefurlonlylink % PDF plus option to not display url, show just arg - \unhbox0 + \unhbox0 \else % PDF, normally display both arg and url for consistency, % visibility, if the pdf is eventually used to print, etc. \unhbox0\ (\urefcode{#1})% \fi \else - \ifx\XeTeXrevision\thisisundefined - \unhbox0\ (\urefcode{#1})% DVI, always show arg and url - \else + \ifxetex % For XeTeX \ifurefurlonlylink % PDF plus option to not display url, show just arg - \unhbox0 + \unhbox0 \else % PDF, normally display both arg and url for consistency, % visibility, if the pdf is eventually used to print, etc. \unhbox0\ (\urefcode{#1})% \fi + \else + \unhbox0\ (\urefcode{#1})% DVI, always show arg and url \fi \fi \else @@ -3091,10 +3201,10 @@ } } -% By default we'll break after the special characters, but some people like to -% break before the special chars, so allow that. Also allow no breaking at +% By default we'll break after the special characters, but some people like to +% break before the special chars, so allow that. Also allow no breaking at % all, for manual control. -% +% \parseargdef\urefbreakstyle{% \def\txiarg{#1}% \ifx\txiarg\wordnone @@ -3113,16 +3223,17 @@ \def\wordnone{none} % Allow a ragged right output to aid breaking long URL's. There can -% be a break at the \allowbreak with no extra glue (if the existing stretch in +% be a break at the \allowbreak with no extra glue (if the existing stretch in % the line is sufficient), a break at the \penalty with extra glue added % at the end of the line, or no break at all here. -% Changing the value of the penalty and/or the amount of stretch affects how +% Changing the value of the penalty and/or the amount of stretch affects how % preferable one choice is over the other. +% Check test cases in doc/texinfo-tex-test.texi before making any changes. \def\urefallowbreak{% \penalty0\relax - \hskip 0pt plus 2 em\relax + \hskip 0pt plus 3 em\relax \penalty1000\relax - \hskip 0pt plus -2 em\relax + \hskip 0pt plus -3 em\relax } \urefbreakstyle after @@ -3171,16 +3282,8 @@ % Default is `distinct'. \kbdinputstyle distinct -% @kbd is like @code, except that if the argument is just one @key command, -% then @kbd has no effect. -\def\kbd#1{{\def\look{#1}\expandafter\kbdsub\look??\par}} - -\def\xkey{\key} -\def\kbdsub#1#2#3\par{% - \def\one{#1}\def\three{#3}\def\threex{??}% - \ifx\one\xkey\ifx\threex\three \key{#2}% - \else{\tclose{\kbdfont\setcodequotes\look}}\fi - \else{\tclose{\kbdfont\setcodequotes\look}}\fi +\def\kbd#1{% + \tclose{\kbdfont\setcodequotes#1}% } % definition of @key that produces a lozenge. Doesn't adjust to text size. @@ -3193,14 +3296,9 @@ % \kern-0.4pt\hrule}% % \kern-.06em\raise0.4pt\hbox{\angleright}}}} -% definition of @key with no lozenge. If the current font is already -% monospace, don't change it; that way, we respect @kbdinputstyle. But -% if it isn't monospace, then use \tt. +% definition of @key with no lozenge. % -\def\key#1{{\setregularquotes - \nohyphenation - \ifmonospace\else\tt\fi - #1}\null} +\def\key#1{{\setregularquotes \tt #1}\null} % @clicksequence{File @click{} Open ...} \def\clicksequence#1{\begingroup #1\endgroup} @@ -3344,7 +3442,7 @@ % @inlinefmt{FMTNAME,PROCESSED-TEXT} and @inlineraw{FMTNAME,RAW-TEXT}. % Ignore unless FMTNAME == tex; then it is like @iftex and @tex, % except specified as a normal braced arg, so no newlines to worry about. -% +% \def\outfmtnametex{tex} % \long\def\inlinefmt#1{\doinlinefmt #1,\finish} @@ -3352,7 +3450,7 @@ \def\inlinefmtname{#1}% \ifx\inlinefmtname\outfmtnametex \ignorespaces #2\fi } -% +% % @inlinefmtifelse{FMTNAME,THEN-TEXT,ELSE-TEXT} expands THEN-TEXT if % FMTNAME is tex, else ELSE-TEXT. \long\def\inlinefmtifelse#1{\doinlinefmtifelse #1,,,\finish} @@ -3368,7 +3466,7 @@ % *right* brace they would have to use a command anyway, so they may as % well use a command to get a left brace too. We could re-use the % delimiter character idea from \verb, but it seems like overkill. -% +% \long\def\inlineraw{\tex \doinlineraw} \long\def\doinlineraw#1{\doinlinerawtwo #1,\finish} \def\doinlinerawtwo#1,#2,\finish{% @@ -3403,8 +3501,8 @@ \let\atchar=\@ % @{ @} @lbracechar{} @rbracechar{} all generate brace characters. -\def\lbracechar{{\ifmonospace\char123\else\ensuremath\lbrace\fi}} -\def\rbracechar{{\ifmonospace\char125\else\ensuremath\rbrace\fi}} +\def\lbracechar{{\ifusingtt{\char123}{\ensuremath\lbrace}}} +\def\rbracechar{{\ifusingtt{\char125}{\ensuremath\rbrace}}} \let\{=\lbracechar \let\}=\rbracechar @@ -3458,8 +3556,13 @@ % Revert to plain's \scriptsize, which is 7pt. \count255=\the\fam $\fam\count255 \scriptstyle A$% \else - % For 11pt, we can use our lllsize. - \switchtolllsize A% + \ifx\curfontsize\smallword + % For footnotes and indices + \count255=\the\fam $\fam\count255 \scriptstyle A$% + \else + % For 11pt, we can use our lllsize. + \switchtolllsize A% + \fi \fi }% \vss @@ -3467,6 +3570,7 @@ \kern-.15em \TeX } +\def\smallword{small} % Some math mode symbols. Define \ensuremath to switch into math mode % unless we are already there. Expansion tricks may not be needed here, @@ -3545,7 +3649,7 @@ % @pounds{} is a sterling sign, which Knuth put in the CM italic font. % -\def\pounds{\ifmonospace{\ecfont\char"BF}\else{\it\$}\fi} +\def\pounds{{\ifusingtt{\ecfont\char"BF}{\it\$}}} % @euro{} comes from a separate font, depending on the current style. % We use the free feym* fonts from the eurosym package by Henrik @@ -3614,6 +3718,9 @@ \def\quotedblbase{{\ecfont \char"12}} \def\quotesinglbase{{\ecfont \char"0D}} % +\def\L{{\ecfont \char"8A}} % L with stroke +\def\l{{\ecfont \char"AA}} % l with stroke +% % This positioning is not perfect (see the ogonek LaTeX package), but % we have the precomposed glyphs for the most common cases. We put the % tests to use those glyphs in the single \ogonek macro so we have fewer @@ -3645,7 +3752,7 @@ % for non-CM glyphs. That is ec* for regular text and tc* for the text % companion symbols (LaTeX TS1 encoding). Both are part of the ec % package and follow the same conventions. -% +% \def\ecfont{\etcfont{e}} \def\tcfont{\etcfont{t}} % @@ -3656,21 +3763,29 @@ % hopefully nobody will notice/care. \edef\ecsize{\csname\curfontsize ecsize\endcsname}% \edef\nominalsize{\csname\curfontsize nominalsize\endcsname}% - \ifmonospace - % typewriter: - \font\thisecfont = #1ctt\ecsize \space at \nominalsize - \else - \ifx\curfontstyle\bfstylename - % bold: - \font\thisecfont = #1cb\ifusingit{i}{x}\ecsize \space at \nominalsize - \else - % regular: - \font\thisecfont = #1c\ifusingit{ti}{rm}\ecsize \space at \nominalsize - \fi - \fi + \ifusingtt + % typewriter: + {\font\thisecfont = #1ctt\ecsize \space at \nominalsize}% + % else + {\ifx\curfontstyle\bfstylename + \etcfontbold{#1}% + \else + \ifrmisbold + \etcfontbold{#1}% + \else + % regular: + \font\thisecfont = #1c\ifusingit{ti}{rm}\ecsize \space + at \nominalsize + \fi + \fi}% \thisecfont } +\def\etcfontbold#1{% + % bold: + \font\thisecfont = #1cb\ifusingit{i}{x}\ecsize \space at \nominalsize +} + % @registeredsymbol - R in a circle. The font for the R should really % be smaller yet, but lllsize is the best we can do for now. % Adapted from the plain.tex definition of \copyright. @@ -3683,7 +3798,10 @@ % @textdegree - the normal degrees sign. % -\def\textdegree{$^\circ$} +\def\textdegree{% + \ifmmode ^\circ + \else {\tcfont \char 176}% + \fi} % Laurent Siebenmann reports \Orb undefined with: % Textures 1.7.7 (preloaded format=plain 93.10.14) (68K) 16 APR 2004 02:38 @@ -3700,11 +3818,11 @@ % only change font for tt for correct kerning and to avoid using % \ecfont unless necessary. \def\quotedblleft{% - \ifmonospace{\ecfont\char"10}\else{\char"5C}\fi + \ifusingtt{{\ecfont\char"10}}{{\char"5C}}% } \def\quotedblright{% - \ifmonospace{\ecfont\char"11}\else{\char`\"}\fi + \ifusingtt{{\ecfont\char"11}}{{\char`\"}}% } @@ -3725,17 +3843,18 @@ after the title page.}}% \def\setshortcontentsaftertitlepage{% \errmessage{@setshortcontentsaftertitlepage has been removed as a Texinfo - command; move your @shortcontents and @contents commands if you + command; move your @shortcontents and @contents commands if you want the contents after the title page.}}% \parseargdef\shorttitlepage{% - \begingroup \hbox{}\vskip 1.5in \chaprm \centerline{#1}% - \endgroup\page\hbox{}\page} + {\headingsoff \begingroup \hbox{}\vskip 1.5in \chaprm \centerline{#1}% + \endgroup\page\hbox{}\page}\pageone} \envdef\titlepage{% % Open one extra group, as we want to close it in the middle of \Etitlepage. \begingroup \parindent=0pt \textfonts + \headingsoff % Leave some space at the very top of the page. \vglue\titlepagetopglue % No rule at page bottom unless we print one at the top with @title. @@ -3763,15 +3882,14 @@ % If we use the new definition of \page, we always get a blank page % after the title page, which we certainly don't want. \oldpage + \pageone \endgroup % - % Need this before the \...aftertitlepage checks so that if they are - % in effect the toc pages will come out with page numbers. - \HEADINGSon } \def\finishtitlepage{% - \vskip4pt \hrule height 2pt width \hsize + \ifseenauthor \vskip4pt \else \vskip 0pt plus 1filll \fi + \hrule height 2pt width \hsize \vskip\titlepagebottomglue \finishedtitlepagetrue } @@ -3780,7 +3898,7 @@ % don't worry much about spacing, ragged right. This should be used % inside a \vbox, and fonts need to be set appropriately first. \par should % be specified before the end of the \vbox, since a vbox is a group. -% +% \def\raggedtitlesettings{% \rm \hyphenpenalty=10000 @@ -3794,33 +3912,105 @@ \let\subtitlerm=\rmfont \def\subtitlefont{\subtitlerm \normalbaselineskip = 13pt \normalbaselines} +\let\savedtitle\empty +\let\savedsubtitlegroup\empty +\let\savedauthorgroup\empty + \parseargdef\title{% - \checkenv\titlepage - \vbox{\titlefonts \raggedtitlesettings #1\par}% - % print a rule at the page bottom also. - \finishedtitlepagefalse - \vskip4pt \hrule height 4pt width \hsize \vskip4pt + \expandafter\ifx\thisenv\documentinfo + \gdef\savedtitle{#1}% + \else + \checkenv\titlepage + \vbox{\titlefonts \raggedtitlesettings #1\par}% + % print a rule at the page bottom also. + \finishedtitlepagefalse + \vskip4pt \hrule height 4pt width \hsize \vskip4pt + \fi } \parseargdef\subtitle{% - \checkenv\titlepage - {\subtitlefont \rightline{#1}}% + \expandafter\ifx\thisenv\documentinfo + \ifx\savedsubtitlegroup\empty + \gdef\savedsubtitlegroup{\savedsubtitle{#1}}% + \else + \expandafter\gdef\expandafter\savedsubtitlegroup\expandafter{% + \savedsubtitlegroup\savedsubtitle{#1}}% + \fi + \else + \checkenv\titlepage + {\subtitlefont \rightline{#1}}% + \fi } % @author should come last, but may come many times. % It can also be used inside @quotation. % \parseargdef\author{% - \def\temp{\quotation}% - \ifx\thisenv\temp - \def\quotationauthor{#1}% printed in \Equotation. - \else - \checkenv\titlepage - \ifseenauthor\else \vskip 0pt plus 1filll \seenauthortrue \fi - {\secfonts\rm \leftline{#1}}% + \expandafter\ifx\thisenv\documentinfo + \ifx\savedauthorgroup\empty + \gdef\savedauthorgroup{\savedauthor{#1}}% + \else + \expandafter\gdef\expandafter\savedauthorgroup\expandafter{% + \savedauthorgroup\savedauthor{#1}}% + \fi + \else + \def\temp{\quotation}% + \ifx\thisenv\temp + \def\quotationauthor{#1}% printed in \Equotation. + \else + \checkenv\titlepage + \ifseenauthor\else \vskip 0pt plus 1filll \seenauthortrue \fi + {\secfonts\rm \leftline{#1}}% + \fi + \fi +} + +% @maketitle +{\obeylines +\gdef\maketitle{% +\titlepage +\ifx\savedtitle\empty\else + \title \savedtitle + \ifx\savedsubtitlegroup\empty\else + \savedsubtitlegroup +\fi\fi +\ifx\savedauthorgroup\empty\else + \savedauthorgroup +\fi +% start verso page if either copying or publication text is given +\ifx\copyingtext\relax + \ifx\publicationtext\relax\else + \page \vskip 0pt plus 1filll \fi +\else + \page \vskip 0pt plus 1filll +\fi +\ifx\publicationtext\relax\else + \insertpublication + \sp 1 +\fi +\ifx\copyingtext\relax\else + \insertcopying +\fi +\end titlepage } +% \savedauthor{#1}, called with braces. output an @author line. +\gdef\savedauthor#1{% +\author#1 +} + +% \savedsubtitle{#1}, called with braces. output a @subtitle line. +\gdef\savedsubtitle#1{% +\subtitle#1 +} +} % \obeylines + +% @documentinfo block +\envdef\documentinfo{% +} +\def\Edocumentinfo{}% + % Set up page headings and footings. @@ -3834,15 +4024,16 @@ \newtoks\oddfootline % footline on odd pages % Now make \makeheadline and \makefootline in Plain TeX use those variables -\headline={{\textfonts\rm +\headline={{\textfonts\rm\frenchspacingsetting \ifchapterpage \ifodd\pageno\the\oddchapheadline\else\the\evenchapheadline\fi \else \ifodd\pageno\the\oddheadline\else\the\evenheadline\fi \fi}} -\footline={{\textfonts\rm \ifodd\pageno \the\oddfootline - \else \the\evenfootline \fi}\HEADINGShook} +\footline={{\textfonts\rm\frenchspacingsetting + \ifodd\pageno \the\oddfootline \else \the\evenfootline \fi}% + \HEADINGShook} \let\HEADINGShook=\relax % Commands to set those variables. @@ -3935,46 +4126,37 @@ } \def\HEADINGSoff{{\globaldefs=1 \headingsoff}} % global setting -\HEADINGSoff % it's the default -% When we turn headings on, set the page number to 1. +% Set the page number to 1. \def\pageone{ \global\pageno=1 \global\arabiccount = \pagecount } +\let\contentsalignmacro = \chappager + +% \def\HEADINGSon{\HEADINGSdouble} % defined by \CHAPPAGon + % For double-sided printing, put current file name in lower left corner, % chapter name on inside top of right hand pages, document % title on inside top of left hand pages, and page numbers on outside top % edge of all pages. -\def\HEADINGSdouble{% -\pageone -\HEADINGSdoublex -} -\let\contentsalignmacro = \chappager - -% For single-sided printing, chapter title goes across top left of page, -% page number on top right. -\def\HEADINGSsingle{% -\pageone -\HEADINGSsinglex -} -\def\HEADINGSon{\HEADINGSdouble} - -\def\HEADINGSafter{\let\HEADINGShook=\HEADINGSdoublex} +\def\HEADINGSafter{\let\HEADINGShook=\HEADINGSdouble} \let\HEADINGSdoubleafter=\HEADINGSafter -\def\HEADINGSdoublex{% +\def\HEADINGSdouble{% \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\folio\hfil\thistitle}} \global\oddheadline={\line{\thischapter\hfil\folio}} -\global\evenchapheadline={\line{\folio\hfil}} +\global\evenchapheadline={\line{\folio\hfil\thistitle}} \global\oddchapheadline={\line{\hfil\folio}} \global\let\contentsalignmacro = \chapoddpage } -\def\HEADINGSsingleafter{\let\HEADINGShook=\HEADINGSsinglex} -\def\HEADINGSsinglex{% +% For single-sided printing, chapter title goes across top left of page, +% page number on top right. +\def\HEADINGSsingleafter{\let\HEADINGShook=\HEADINGSsingle} +\def\HEADINGSsingle{% \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\thischapter\hfil\folio}} @@ -3986,7 +4168,6 @@ % for @setchapternewpage off \def\HEADINGSsinglechapoff{% -\pageone \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\thischapter\hfil\folio}} @@ -4356,8 +4537,7 @@ % undo it ourselves. \def\headitemfont{\b}% for people to use in the template row; not changeable \def\headitem{% - \checkenv\multitable - \crcr + \crcr % must appear first \gdef\headitemcrhook{\nobreak}% attempt to avoid page break after headings \global\everytab={\bf}% can't use \headitemfont since the parsing differs \the\everytab % for the first item @@ -4419,7 +4599,7 @@ % Find the correct column width \hsize=\expandafter\csname col\the\colcount\endcsname % - \rightskip=0pt + \advance\rightskip by -1\rightskip % Zero leaving only any stretch \ifnum\colcount=1 \advance\hsize by\leftskip % Add indent of surrounding text \else @@ -4442,7 +4622,7 @@ \message{conditionals,} -% @iftex, @ifnotdocbook, @ifnothtml, @ifnotinfo, @ifnotplaintext, +% @iftex, @ifnotdocbook, @ifnothtml, @ifnotinfo, @ifnotlatex, @ifnotplaintext, % @ifnotxml always succeed. They currently do nothing; we don't % attempt to check whether the conditionals are properly nested. But we % have to remember that they are conditionals, so that @end doesn't @@ -4456,6 +4636,7 @@ \makecond{ifnotdocbook} \makecond{ifnothtml} \makecond{ifnotinfo} +\makecond{ifnotlatex} \makecond{ifnotplaintext} \makecond{ifnotxml} @@ -4468,10 +4649,12 @@ \def\ifdocbook{\doignore{ifdocbook}} \def\ifhtml{\doignore{ifhtml}} \def\ifinfo{\doignore{ifinfo}} +\def\iflatex{\doignore{iflatex}} \def\ifnottex{\doignore{ifnottex}} \def\ifplaintext{\doignore{ifplaintext}} \def\ifxml{\doignore{ifxml}} \def\ignore{\doignore{ignore}} +\def\latex{\doignore{latex}} \def\menu{\doignore{menu}} \def\xml{\doignore{xml}} @@ -4613,7 +4796,7 @@ % Like \expandablevalue, but completely expandable (the \message in the % definition above operates at the execution level of TeX). Used when % writing to auxiliary files, due to the expansion that \write does. -% If flag is undefined, pass through an unexpanded @value command: maybe it +% If flag is undefined, pass through an unexpanded @value command: maybe it % will be set by the time it is read back in. % % NB flag names containing - or _ may not work here. @@ -4637,7 +4820,7 @@ % @ifset VAR ... @end ifset reads the `...' iff VAR has been defined % with @set. -% +% % To get the special treatment we need for `@end ifset,' we call % \makecond and then redefine. % @@ -4670,7 +4853,7 @@ % without the @) is in fact defined. We can only feasibly check at the % TeX level, so something like `mathcode' is going to considered % defined even though it is not a Texinfo command. -% +% \makecond{ifcommanddefined} \def\ifcommanddefined{\parsearg{\doifcmddefined{\let\next=\ifcmddefinedfail}}} % @@ -4710,13 +4893,11 @@ % except not \outer, so it can be used within macros and \if's. \edef\newwrite{\makecsname{ptexnewwrite}} -% \newindex {foo} defines an index named IX. +% \newindex {IX} defines an index named IX. % It automatically defines \IXindex such that % \IXindex ...rest of line... puts an entry in the index IX. % It also defines \IXindfile to be the number of the output channel for % the file that accumulates this index. The file's extension is IX. -% The name of an index should be no more than 2 characters long -% for the sake of vms. % \def\newindex#1{% \expandafter\chardef\csname#1indfile\endcsname=0 @@ -4778,22 +4959,7 @@ \def\docodeindex#1{\edef\indexname{#1}\parsearg\docodeindexxxx} \def\docodeindexxxx #1{\docind{\indexname}{#1}} - -% Used for the aux, toc and index files to prevent expansion of Texinfo -% commands. -% -\def\atdummies{% - \definedummyletter\@% - \definedummyletter\ % - \definedummyletter\{% - \definedummyletter\}% - \definedummyletter\&% - % - % Do the redefinitions. - \definedummies - \otherbackslash -} - + % \definedummyword defines \#1 as \string\#1\space, thus effectively % preventing its expansion. This is used only for control words, % not control letters, because the \space would be incorrect for @@ -4809,110 +4975,91 @@ % \def\definedummyword #1{\def#1{\string#1\space}}% \def\definedummyletter#1{\def#1{\string#1}}% -\let\definedummyaccent\definedummyletter -% Called from \atdummies to prevent the expansion of commands. +% Used for the aux, toc and index files to prevent expansion of Texinfo +% commands. Most of the commands are controlled through the +% \ifdummies conditional. % -\def\definedummies{% +\def\atdummies{% + \dummiestrue % - \let\commondummyword\definedummyword - \let\commondummyletter\definedummyletter - \let\commondummyaccent\definedummyaccent - \commondummiesnofonts + \definedummyletter\@% + \definedummyletter\ % + \definedummyletter\{% + \definedummyletter\}% + \definedummyletter\&% % \definedummyletter\_% \definedummyletter\-% % - % Non-English letters. - \definedummyword\AA - \definedummyword\AE - \definedummyword\DH - \definedummyword\L - \definedummyword\O - \definedummyword\OE - \definedummyword\TH - \definedummyword\aa - \definedummyword\ae - \definedummyword\dh - \definedummyword\exclamdown - \definedummyword\l - \definedummyword\o - \definedummyword\oe - \definedummyword\ordf - \definedummyword\ordm - \definedummyword\questiondown - \definedummyword\ss - \definedummyword\th - % - % Although these internal commands shouldn't show up, sometimes they do. - \definedummyword\bf - \definedummyword\gtr - \definedummyword\hat - \definedummyword\less - \definedummyword\sf - \definedummyword\sl - \definedummyword\tclose - \definedummyword\tt - % - \definedummyword\LaTeX - \definedummyword\TeX - % - % Assorted special characters. - \definedummyword\ampchar - \definedummyword\atchar - \definedummyword\arrow - \definedummyword\backslashchar - \definedummyword\bullet - \definedummyword\comma - \definedummyword\copyright - \definedummyword\registeredsymbol - \definedummyword\dots - \definedummyword\enddots - \definedummyword\entrybreak - \definedummyword\equiv - \definedummyword\error - \definedummyword\euro - \definedummyword\expansion - \definedummyword\geq - \definedummyword\guillemetleft - \definedummyword\guillemetright - \definedummyword\guilsinglleft - \definedummyword\guilsinglright - \definedummyword\lbracechar - \definedummyword\leq - \definedummyword\mathopsup - \definedummyword\minus - \definedummyword\ogonek - \definedummyword\pounds - \definedummyword\point - \definedummyword\print - \definedummyword\quotedblbase - \definedummyword\quotedblleft - \definedummyword\quotedblright - \definedummyword\quoteleft - \definedummyword\quoteright - \definedummyword\quotesinglbase - \definedummyword\rbracechar - \definedummyword\result - \definedummyword\sub - \definedummyword\sup - \definedummyword\textdegree - % \definedummyword\subentry % % We want to disable all macros so that they are not expanded by \write. + \let\commondummyword\definedummyword \macrolist \let\value\dummyvalue % - \normalturnoffactive -} - -% \commondummiesnofonts: common to \definedummies and \indexnofonts. -% Define \commondummyletter, \commondummyaccent and \commondummyword before -% using. Used for accents, font commands, and various control letters. -% -\def\commondummiesnofonts{% - % Control letters and accents. + \turnoffactive +} + +\newif\ifdummies +\newif\ifindexnofonts + +\def\commondummyletter#1{% + \expandafter\let\csname\string#1:impl\endcsname#1% + \edef#1{% + \noexpand\ifindexnofonts + % empty expansion + \noexpand\else + \noexpand\ifdummies\string#1% + \noexpand\else + \noexpand\jumptwofi % dispose of the \fi + \expandafter\noexpand\csname\string#1:impl\endcsname + \noexpand\fi + \noexpand\fi}% +} + +\def\commondummyaccent#1{% + \expandafter\let\csname\string#1:impl\endcsname#1% + \edef#1{% + \noexpand\ifindexnofonts + \noexpand\expandafter % dispose of \else ... \fi + \noexpand\asis + \noexpand\else + \noexpand\ifdummies\string#1% + \noexpand\else + \noexpand\jumptwofi % dispose of the \fi + \expandafter\noexpand\csname\string#1:impl\endcsname + \noexpand\fi + \noexpand\fi}% +} + +% Like \commondummyaccent but add a \space at the end of the dummy expansion +% #2 is the expansion used for \indexnofonts. #2 is always followed by +% \asis to remove a pair of following braces. +\def\commondummyword#1#2{% + \expandafter\let\csname\string#1:impl\endcsname#1% + \expandafter\def\csname\string#1:ixnf\endcsname{#2\asis}% + \edef#1{% + \noexpand\ifindexnofonts + \noexpand\expandafter % dispose of \else ... \fi + \expandafter\noexpand\csname\string#1:ixnf\endcsname + \noexpand\else + \noexpand\ifdummies\string#1\space + \noexpand\else + \noexpand\jumptwofi % dispose of the \fi \fi + \expandafter\noexpand\csname\string#1:impl\endcsname + \noexpand\fi + \noexpand\fi}% +} +\def\jumptwofi#1\fi\fi{\fi\fi#1} + +% For \atdummies and \indexnofonts. \atdummies sets +% \dummiestrue and \indexnofonts sets \indexnofontstrue. +\def\definedummies{ + % @-sign is always an escape character when reading auxiliary files + \escapechar = `\@ + % \commondummyletter\!% \commondummyaccent\"% \commondummyaccent\'% @@ -4926,58 +5073,124 @@ \commondummyaccent\^% \commondummyaccent\`% \commondummyaccent\~% - \commondummyword\u - \commondummyword\v - \commondummyword\H - \commondummyword\dotaccent - \commondummyword\ogonek - \commondummyword\ringaccent - \commondummyword\tieaccent - \commondummyword\ubaraccent - \commondummyword\udotaccent - \commondummyword\dotless + % + % Control letters and accents. + \commondummyword\u {}% + \commondummyword\v {}% + \commondummyword\H {}% + \commondummyword\dotaccent {}% + \commondummyword\ogonek {}% + \commondummyword\ringaccent {}% + \commondummyword\tieaccent {}% + \commondummyword\ubaraccent {}% + \commondummyword\udotaccent {}% + \commondummyword\dotless {}% % % Texinfo font commands. - \commondummyword\b - \commondummyword\i - \commondummyword\r - \commondummyword\sansserif - \commondummyword\sc - \commondummyword\slanted - \commondummyword\t + \commondummyword\b {}% + \commondummyword\i {}% + \commondummyword\r {}% + \commondummyword\sansserif {}% + \commondummyword\sc {}% + \commondummyword\slanted {}% + \commondummyword\t {}% % % Commands that take arguments. - \commondummyword\abbr - \commondummyword\acronym - \commondummyword\anchor - \commondummyword\cite - \commondummyword\code - \commondummyword\command - \commondummyword\dfn - \commondummyword\dmn - \commondummyword\email - \commondummyword\emph - \commondummyword\env - \commondummyword\file - \commondummyword\image - \commondummyword\indicateurl - \commondummyword\inforef - \commondummyword\kbd - \commondummyword\key - \commondummyword\math - \commondummyword\option - \commondummyword\pxref - \commondummyword\ref - \commondummyword\samp - \commondummyword\strong - \commondummyword\tie - \commondummyword\U - \commondummyword\uref - \commondummyword\url - \commondummyword\var - \commondummyword\verb - \commondummyword\w - \commondummyword\xref + \commondummyword\abbr {}% + \commondummyword\acronym {}% + \commondummyword\anchor {}% + \commondummyword\cite {}% + \commondummyword\code {}% + \commondummyword\command {}% + \commondummyword\dfn {}% + \commondummyword\dmn {}% + \commondummyword\email {}% + \commondummyword\emph {}% + \commondummyword\env {}% + \commondummyword\file {}% + \commondummyword\image {}% + \commondummyword\indicateurl{}% + \commondummyword\inforef {}% + \commondummyword\kbd {}% + \commondummyword\key {}% + \commondummyword\link {}% + \commondummyword\math {}% + \commondummyword\option {}% + \commondummyword\pxref {}% + \commondummyword\ref {}% + \commondummyword\samp {}% + \commondummyword\strong {}% + \commondummyword\tie {}% + \commondummyword\U {}% + \commondummyword\uref {}% + \commondummyword\url {}% + \commondummyword\var {}% + \commondummyword\verb {}% + \commondummyword\w {}% + \commondummyword\xref {}% + % + \commondummyword\AA {AA}% + \commondummyword\AE {AE}% + \commondummyword\DH {DZZ}% + \commondummyword\L {L}% + \commondummyword\O {O}% + \commondummyword\OE {OE}% + \commondummyword\TH {TH}% + \commondummyword\aa {aa}% + \commondummyword\ae {ae}% + \commondummyword\dh {dzz}% + \commondummyword\exclamdown {!}% + \commondummyword\l {l}% + \commondummyword\o {o}% + \commondummyword\oe {oe}% + \commondummyword\ordf {a}% + \commondummyword\ordm {o}% + \commondummyword\questiondown {?}% + \commondummyword\ss {ss}% + \commondummyword\th {th}% + % + \commondummyword\LaTeX {LaTeX}% + \commondummyword\TeX {TeX}% + % + % Assorted special characters. + \commondummyword\ampchar {\normalamp}% + \commondummyword\atchar {\@}% + \commondummyword\arrow {->}% + \commondummyword\backslashchar {\realbackslash}% + \commondummyword\bullet {bullet}% + \commondummyword\comma {,}% + \commondummyword\copyright {copyright}% + \commondummyword\dots {...}% + \commondummyword\enddots {...}% + \commondummyword\entrybreak {}% + \commondummyword\equiv {===}% + \commondummyword\error {error}% + \commondummyword\euro {euro}% + \commondummyword\expansion {==>}% + \commondummyword\geq {>=}% + \commondummyword\guillemetleft {<<}% + \commondummyword\guillemetright {>>}% + \commondummyword\guilsinglleft {<}% + \commondummyword\guilsinglright {>}% + \commondummyword\lbracechar {\{}% + \commondummyword\leq {<=}% + \commondummyword\mathopsup {sup}% + \commondummyword\minus {-}% + \commondummyword\pounds {pounds}% + \commondummyword\point {.}% + \commondummyword\print {-|}% + \commondummyword\quotedblbase {"}% + \commondummyword\quotedblleft {"}% + \commondummyword\quotedblright {"}% + \commondummyword\quoteleft {`}% + \commondummyword\quoteright {'}% + \commondummyword\quotesinglbase {,}% + \commondummyword\rbracechar {\}}% + \commondummyword\registeredsymbol {R}% + \commondummyword\result {=>}% + \commondummyword\sub {}% + \commondummyword\sup {}% + \commondummyword\textdegree {o}% } \let\indexlbrace\relax @@ -4995,25 +5208,24 @@ \catcode`\-=13 \catcode`\`=13 \gdef\indexnonalnumdisappear{% - \expandafter\ifx\csname SETtxiindexlquoteignore\endcsname\relax\else + \ifflagclear{txiindexlquoteignore}{}{% % @set txiindexlquoteignore makes us ignore left quotes in the sort term. % (Introduced for FSFS 2nd ed.) \let`=\empty - \fi + }% % - \expandafter\ifx\csname SETtxiindexbackslashignore\endcsname\relax\else + \ifflagclear{txiindexbackslashignore}{}{% \backslashdisappear - \fi - % - \expandafter\ifx\csname SETtxiindexhyphenignore\endcsname\relax\else + }% + \ifflagclear{txiindexhyphenignore}{}{% \def-{}% - \fi - \expandafter\ifx\csname SETtxiindexlessthanignore\endcsname\relax\else + }% + \ifflagclear{txiindexlessthanignore}{}{% \def<{}% - \fi - \expandafter\ifx\csname SETtxiindexatsignignore\endcsname\relax\else + }% + \ifflagclear{txiindexatsignignore}{}{% \def\@{}% - \fi + }% } \gdef\indexnonalnumreappear{% @@ -5029,18 +5241,7 @@ % would be for a given command (usually its argument). % \def\indexnofonts{% - % Accent commands should become @asis. - \def\commondummyaccent##1{\let##1\asis}% - % We can just ignore other control letters. - \def\commondummyletter##1{\let##1\empty}% - % All control words become @asis by default; overrides below. - \let\commondummyword\commondummyaccent - \commondummiesnofonts - % - % Don't no-op \tt, since it isn't a user-level command - % and is used in the definitions of the active chars like <, >, |, etc. - % Likewise with the other plain tex font commands. - %\let\tt=\asis + \indexnofontstrue % \def\ { }% \def\@{@}% @@ -5049,88 +5250,23 @@ % \uccode`\1=`\{ \uppercase{\def\{{1}}% \uccode`\1=`\} \uppercase{\def\}{1}}% - \let\lbracechar\{% - \let\rbracechar\}% - % - % Non-English letters. - \def\AA{AA}% - \def\AE{AE}% - \def\DH{DZZ}% - \def\L{L}% - \def\OE{OE}% - \def\O{O}% - \def\TH{TH}% - \def\aa{aa}% - \def\ae{ae}% - \def\dh{dzz}% - \def\exclamdown{!}% - \def\l{l}% - \def\oe{oe}% - \def\ordf{a}% - \def\ordm{o}% - \def\o{o}% - \def\questiondown{?}% - \def\ss{ss}% - \def\th{th}% - % - \let\do\indexnofontsdef - % - \do\LaTeX{LaTeX}% - \do\TeX{TeX}% + \def\lbracechar##1{\{}% + \def\rbracechar##1{\}}% % - % Assorted special characters. - \do\atchar{@}% - \do\arrow{->}% - \do\bullet{bullet}% - \do\comma{,}% - \do\copyright{copyright}% - \do\dots{...}% - \do\enddots{...}% - \do\equiv{==}% - \do\error{error}% - \do\euro{euro}% - \do\expansion{==>}% - \do\geq{>=}% - \do\guillemetleft{<<}% - \do\guillemetright{>>}% - \do\guilsinglleft{<}% - \do\guilsinglright{>}% - \do\leq{<=}% - \do\lbracechar{\{}% - \do\minus{-}% - \do\point{.}% - \do\pounds{pounds}% - \do\print{-|}% - \do\quotedblbase{"}% - \do\quotedblleft{"}% - \do\quotedblright{"}% - \do\quoteleft{`}% - \do\quoteright{'}% - \do\quotesinglbase{,}% - \do\rbracechar{\}}% - \do\registeredsymbol{R}% - \do\result{=>}% - \do\textdegree{o}% % % We need to get rid of all macros, leaving only the arguments (if present). % Of course this is not nearly correct, but it is the best we can do for now. - % makeinfo does not expand macros in the argument to @deffn, which ends up - % writing an index entry, and texindex isn't prepared for an index sort entry - % that starts with \. % % Since macro invocations are followed by braces, we can just redefine them % to take a single TeX argument. The case of a macro invocation that % goes to end-of-line is not handled. % + \def\commondummyword##1{\let##1\asis}% \macrolist \let\value\indexnofontsvalue } -% Give the control sequence a definition that removes the {} that follows -% its use, e.g. @AA{} -> AA -\def\indexnofontsdef#1#2{\def#1##1{#2}}% - - + % #1 is the index name, #2 is the entry text. @@ -5171,7 +5307,7 @@ \ifx\suffix\indexisfl\def\suffix{f1}\fi % Open the file \immediate\openout\csname#1indfile\endcsname \jobname.\suffix - % Using \immediate above here prevents an object entering into the current + % Using \immediate above here prevents an object entering into the current % box, which could confound checks such as those in \safewhatsit for % preceding skips. \typeout{Writing index file \jobname.\suffix}% @@ -5223,7 +5359,7 @@ \ifx\segment\isfinish \else % - % Fully expand the segment, throwing away any @sortas directives, and + % Fully expand the segment, throwing away any @sortas directives, and % trim spaces. \edef\trimmed{\segment}% \edef\trimmed{\expandafter\eatspaces\expandafter{\trimmed}}% @@ -5260,7 +5396,10 @@ \xdef\trimmed{\segment}% \xdef\trimmed{\expandafter\eatspaces\expandafter{\trimmed}}% \xdef\indexsortkey{\trimmed}% - \ifx\indexsortkey\empty\xdef\indexsortkey{ }\fi + \ifx\indexsortkey\empty + \message{Empty index sort key near line \the\inputlineno}% + \xdef\indexsortkey{ }% + \fi }\fi % % Append to \fullindexsortkey. @@ -5284,14 +5423,14 @@ % the current value of \escapechar. \def\escapeisbackslash{\escapechar=`\\} -% Use \ in index files by default. texi2dvi didn't support @ as the escape -% character (as it checked for "\entry" in the files, and not "@entry"). When -% the new version of texi2dvi has had a chance to become more prevalent, then -% the escape character can change back to @ again. This should be an easy -% change to make now because both @ and \ are only used as escape characters in -% index files, never standing for themselves. +% Uncomment to use \ in index files by default. Old texi2dvi (before 2019) +% didn't support @ as the escape character (as it checked for "\entry" in +% the files, and not "@entry"). +% In the future we can remove this flag and simplify the code for +% index files and backslashes, once the support is no longer likely to be +% useful. % -\set txiindexescapeisbackslash +% \set txiindexescapeisbackslash % Write the entry in \indextext to the index file. % @@ -5305,16 +5444,14 @@ % \atdummies % - \expandafter\ifx\csname SETtxiindexescapeisbackslash\endcsname\relax\else - \escapeisbackslash - \fi + \ifflagclear{txiindexescapeisbackslash}{}{\escapeisbackslash}% % % For texindex which always views { and } as separators. \def\{{\lbracechar{}}% \def\}{\rbracechar{}}% \uccode`\~=`\\ \uppercase{\def~{\backslashchar{}}}% % - % Split the entry into primary entry and any subentries, and get the index + % Split the entry into primary entry and any subentries, and get the index % sort key. \splitindexentry\indextext % @@ -5459,6 +5596,8 @@ \tolerance = 9500 \plainfrenchspacing \everypar = {}% don't want the \kern\-parindent from indentation suppression. + \let\entry\indexentry + \ifxetex\xetexpreauxfile\fi % % See comment in \requireopenindexfile. \def\indexname{#1}\ifx\indexname\indexisfl\def\indexname{f1}\fi @@ -5484,40 +5623,48 @@ \fi \fi \closein 1 + \ifxetex\xetexpostauxfile\fi \endgroup} +% Checked in @bye +\let\byeerror\relax + % If the index file starts with a backslash, forgo reading the index % file altogether. If somebody upgrades texinfo.tex they may still have % old index files using \ as the escape character. Reading this would % at best lead to typesetting garbage, at worst a TeX syntax error. \def\printindexzz#1#2\finish{% - \expandafter\ifx\csname SETtxiindexescapeisbackslash\endcsname\relax + \ifflagclear{txiindexescapeisbackslash}{% \uccode`\~=`\\ \uppercase{\if\noexpand~}\noexpand#1 - \expandafter\ifx\csname SETtxiskipindexfileswithbackslash\endcsname\relax -\errmessage{% -ERROR: A sorted index file in an obsolete format was skipped. + \ifflagclear{txiskipindexfileswithbackslash}{% + % Delay the error message until the very end to give a chance + % for the whole index to be output as input for texindex. + \global\def\byeerror{% +ERROR: A sorted index file in an obsolete format was skipped. To fix this problem, please upgrade your version of 'texi2dvi' or 'texi2pdf' to that at . -If you are using an old version of 'texindex' (part of the Texinfo +If you are using an old version of 'texindex' (part of the Texinfo distribution), you may also need to upgrade to a newer version (at least 6.0). You may be able to typeset the index if you run 'texindex \jobname.\indexname' yourself. -You could also try setting the 'txiindexescapeisbackslash' flag by +You could also try setting the 'txiindexescapeisbackslash' flag by running a command like -'texi2dvi -t "@set txiindexescapeisbackslash" \jobname.texi'. If you do +'texi2dvi -t "@set txiindexescapeisbackslash" \jobname.texi'. If you do this, Texinfo will try to use index files in the old format. -If you continue to have problems, deleting the index files and starting again +If you continue to have problems, deleting the index files and starting again might help (with 'rm \jobname.?? \jobname.??s')% }% - \else + }{% (Skipped sorted index file in obsolete format) - \fi + }% \else \begindoublecolumns + \ifxetex\xetexpreauxfile\fi \input \jobname.\indexname s + \ifxetex\xetexpostauxfile\fi \enddoublecolumns \fi - \else + }{% \begindoublecolumns \catcode`\\=0\relax % @@ -5525,11 +5672,39 @@ % should work because we (hopefully) don't otherwise use @ in index files. %\catcode`\@=12\relax \catcode`\@=0\relax + \ifxetex\xetexpreauxfile\fi \input \jobname.\indexname s + \ifxetex\xetexpostauxfile\fi \enddoublecolumns + }% +} + +\def\indexentry#1#2{% + \let\entrypagetarget\empty + \ifpdforxetex + % only link the index text to the page if no comma appears in the + % list of pages, i.e. there is only one page + \checkpagelistcomma{#2}\pagelistcomma + \expandafter\ifcase\pagelistcomma + \def\entrypagetarget{#2}% + \fi + \fi% + \entryinternal{#1}{#2}% +} + +\def\checkpagelistcomma#1#2{% + \checkpagelistcommaxx#2#1,\finish +} +\def\checkpagelistcommaxx#1#2,#3\finish{% + \def\tmp{#3}% + \ifx\tmp\empty + \def#1{0\relax} + \else + \def#1{1\relax} \fi } + % These macros are used by the sorted index file itself. % Change them to control the appearance of the index. @@ -5566,7 +5741,6 @@ \def\initial{% \bgroup - \initialglyphs \initialx } @@ -5579,7 +5753,7 @@ % bottom of a column to reduce an increase in inter-line spacing. \nobreak \vskip 0pt plus 5\baselineskip - \penalty -300 + \penalty -300 \vskip 0pt plus -5\baselineskip % % Typeset the initial. Making this add up to a whole number of @@ -5589,7 +5763,10 @@ % % No shrink because it confuses \balancecolumns. \vskip 1.67\baselineskip plus 1\baselineskip - \leftline{\secfonts \kern-0.05em \secbf #1}% + \doindexinitialentry{#1}% + \initialglyphs + \leftline{% + \secfonts \kern-0.05em \secbf #1}% % \secfonts is inside the argument of \leftline so that the change of % \baselineskip will not affect any glue inserted before the vbox that % \leftline creates. @@ -5599,14 +5776,48 @@ \egroup % \initialglyphs } +\def\doindexinitialentry#1{% + \ifpdforxetex + \global\advance\idxinitialno by 1 + \def\indexlbrace{\{}% + \def\indexrbrace{\}}% + \def\indexbackslash{\realbackslash}% + \def\indexatchar{\@}% + \writetocentry{idxinitial}{\asis #1}{IDX\the\idxinitialno}% + % The @asis removes a pair of braces around e.g. {@indexatchar} that + % are output by texindex. + % + \pdfmkdest{idx.\asis #1.IDX\the\idxinitialno}% + \fi +} + +% No listing in TOC +\def\idxinitialentry#1#2#3#4{} + +% For index initials. +\newcount\idxinitialno \idxinitialno=1 + + \newdimen\entryrightmargin \entryrightmargin=0pt -% \entry typesets a paragraph consisting of the text (#1), dot leaders, and -% then page number (#2) flushed to the right margin. It is used for index -% and table of contents entries. The paragraph is indented by \leftskip. -% -\def\entry{% +% amount to indent subsequent lines in an entry when it spans more than +% one line. +\newdimen\entrycontskip +\entrycontskip=1em + +% for PDF output, whether to make the text of the entry a link to the section. +% set for @contents and @shortcontents. +\newif\iflinkentrytext + +% \entryinternal typesets a paragraph consisting of the text (#1), dot +% leaders, and then page number (#2) flushed to the right margin. It is +% used for index and table of contents entries. The paragraph is indented +% by \leftskip. +% For PDF output, if \linkentrytexttrue and \tocnodetarget is set, link text +% to the referenced node. Else if \entrypagetarget is set, link text to the +% page. +\def\entryinternal{% \begingroup % % Start a new paragraph if necessary, so our assignments below can't @@ -5628,7 +5839,7 @@ } \def\entrybreak{\unskip\space\ignorespaces}% \def\doentry{% - % Save the text of the entry + % Save the text of the entry in \boxA \global\setbox\boxA=\hbox\bgroup \bgroup % Instead of the swallowed brace. \noindent @@ -5638,12 +5849,31 @@ % with catcodes occurring. } {\catcode`\@=11 +% #1 is the page number \gdef\finishentry#1{% - \egroup % end box A + \egroup % end \boxA \dimen@ = \wd\boxA % Length of text of entry + % add any leaders and page number to \boxA. \global\setbox\boxA=\hbox\bgroup - \unhbox\boxA - % #1 is the page number. + \ifpdforxetex + \iflinkentrytext + \ifx\tocnodetarget\empty + \unhbox\boxA + \else + \startxreflink{\tocnodetarget}{}% + \unhbox\boxA + \endlink + \fi + \else + \ifx\entrypagetarget\empty + \unhbox\boxA + \else + \pdflinkpage{\entrypagetarget}{\unhbox\boxA}% + \fi + \fi + \else + \unhbox\boxA + \fi % % Get the width of the page numbers, and only use % leaders if they are present. @@ -5654,14 +5884,23 @@ % \null\nobreak\indexdotfill % Have leaders before the page number. % + \hskip\skip\thinshrinkable \ifpdforxetex - \pdfgettoks#1.% - \hskip\skip\thinshrinkable\the\toksA + \ifx\tocnodetarget\empty + \pdfgettoks#1.% + \the\toksA + \else + % Should just be a single page number in toc + \startxreflink{\tocnodetarget}{}% + #1\endlink + \fi \else - \hskip\skip\thinshrinkable #1% + #1% \fi \fi \egroup % end \boxA + % + % now output \ifdim\wd\boxB = 0pt \noindent\unhbox\boxA\par \nobreak @@ -5679,41 +5918,17 @@ \parfillskip=0pt plus -1fill % \advance\rightskip by \entryrightmargin - % Determine how far we can stretch into the margin. - % This allows, e.g., "Appendix H GNU Free Documentation License" to - % fit on one line in @letterpaper format. - \ifdim\entryrightmargin>2.1em - \dimen@i=2.1em - \else - \dimen@i=0em - \fi - \advance \parfillskip by 0pt minus 1\dimen@i % \dimen@ii = \hsize \advance\dimen@ii by -1\leftskip \advance\dimen@ii by -1\entryrightmargin - \advance\dimen@ii by 1\dimen@i \ifdim\wd\boxA > \dimen@ii % If the entry doesn't fit in one line \ifdim\dimen@ > 0.8\dimen@ii % due to long index text - % Try to split the text roughly evenly. \dimen@ will be the length of - % the first line. - \dimen@ = 0.7\dimen@ - \dimen@ii = \hsize - \ifnum\dimen@>\dimen@ii - % If the entry is too long (for example, if it needs more than - % two lines), use all the space in the first line. - \dimen@ = \dimen@ii - \fi \advance\leftskip by 0pt plus 1fill % ragged right - \advance \dimen@ by 1\rightskip - \parshape = 2 0pt \dimen@ 0em \dimen@ii - % Ideally we'd add a finite glue at the end of the first line only, - % instead of using \parshape with explicit line lengths, but TeX - % doesn't seem to provide a way to do such a thing. % % Indent all lines but the first one. - \advance\leftskip by 1em - \advance\parindent by -1em + \advance\leftskip by \entrycontskip + \advance\parindent by -\entrycontskip \fi\fi \indent % start paragraph \unhbox\boxA @@ -5736,12 +5951,11 @@ \newskip\thinshrinkable \skip\thinshrinkable=.15em minus .15em -% Like plain.tex's \dotfill, except uses up at least 1 em. +% Like plain.tex's \dotfill, except uses up at least 0.5 em. % The filll stretch here overpowers both the fil and fill stretch to push % the page number to the right. \def\indexdotfill{\cleaders - \hbox{$\mathsurround=0pt \mkern1.5mu.\mkern1.5mu$}\hskip 1em plus 1filll} - + \hbox{$\mathsurround=0pt \mkern1.5mu.\mkern1.5mu$}\hskip 0.5em plus 1filll} \def\primary #1{\line{#1\hfil}} @@ -5794,7 +6008,7 @@ % below is chosen so that the gutter has the same value (well, +-<1pt) % as it did when we hard-coded it. % - % We put the result in a separate register, \doublecolumhsize, so we + % We put the result in a separate register, \doublecolumnhsize, so we % can restore it in \pagesofar, after \hsize itself has (potentially) % been clobbered. % @@ -5903,7 +6117,7 @@ \newbox\balancedcolumns \setbox\balancedcolumns=\vbox{shouldnt see this}% % -% Only called for the last of the double column material. \doublecolumnout +% Only called for the last of the double column material. \doublecolumnout % does the others. \def\balancecolumns{% \setbox0 = \vbox{\unvbox\PAGE}% like \box255 but more efficient, see p.120. @@ -5931,7 +6145,7 @@ }% % Now the left column is in box 1, and the right column in box 3. % - % Check whether the left column has come out higher than the page itself. + % Check whether the left column has come out higher than the page itself. % (Note that we have doubled \vsize for the double columns, so % the actual height of the page is 0.5\vsize). \ifdim2\ht1>\vsize @@ -5963,7 +6177,7 @@ % Chapters, sections, etc. % Let's start with @part. -\outer\parseargdef\part{\partzzz{#1}} +\parseargdef\part{\partzzz{#1}} \def\partzzz#1{% \chapoddpage \null @@ -6189,8 +6403,7 @@ % normally unnmhead0 calls unnumberedzzz: \outer\parseargdef\unnumbered{\unnmhead0{#1}} \def\unnumberedzzz#1{% - \global\secno=0 \global\subsecno=0 \global\subsubsecno=0 - \global\advance\unnumberedno by 1 + \global\advance\unnumberedno by 1 % % Since an unnumbered has no number, no prefix for figures. \global\let\chaplevelprefix = \empty @@ -6228,7 +6441,7 @@ \let\top\unnumbered % Sections. -% +% \outer\parseargdef\numberedsec{\numhead1{#1}} % normally calls seczzz \def\seczzz#1{% \global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1 @@ -6246,12 +6459,12 @@ % normally calls unnumberedseczzz: \outer\parseargdef\unnumberedsec{\unnmhead1{#1}} \def\unnumberedseczzz#1{% - \global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1 - \sectionheading{#1}{sec}{Ynothing}{\the\unnumberedno.\the\secno}% + \global\advance\unnumberedno by 1 + \sectionheading{#1}{sec}{Ynothing}{\the\unnumberedno}% } % Subsections. -% +% % normally calls numberedsubseczzz: \outer\parseargdef\numberedsubsec{\numhead2{#1}} \def\numberedsubseczzz#1{% @@ -6270,13 +6483,12 @@ % normally calls unnumberedsubseczzz: \outer\parseargdef\unnumberedsubsec{\unnmhead2{#1}} \def\unnumberedsubseczzz#1{% - \global\subsubsecno=0 \global\advance\subsecno by 1 - \sectionheading{#1}{subsec}{Ynothing}% - {\the\unnumberedno.\the\secno.\the\subsecno}% + \global\advance\unnumberedno by 1 + \sectionheading{#1}{subsec}{Ynothing}{\the\unnumberedno}% } % Subsubsections. -% +% % normally numberedsubsubseczzz: \outer\parseargdef\numberedsubsubsec{\numhead3{#1}} \def\numberedsubsubseczzz#1{% @@ -6296,9 +6508,8 @@ % normally unnumberedsubsubseczzz: \outer\parseargdef\unnumberedsubsubsec{\unnmhead3{#1}} \def\unnumberedsubsubseczzz#1{% - \global\advance\subsubsecno by 1 - \sectionheading{#1}{subsubsec}{Ynothing}% - {\the\unnumberedno.\the\secno.\the\subsecno.\the\subsubsecno}% + \global\advance\unnumberedno by 1 + \sectionheading{#1}{subsubsec}{Ynothing}{\the\unnumberedno}% } % These macros control what the section commands do, according @@ -6330,6 +6541,10 @@ \parseargdef\subsubheading{\sectionheading{#1}{subsubsec}{Yomitfromtoc}{} \suppressfirstparagraphindent} +% @xrefname - give text with printed name for linking to node and allow +% referencing node, but do not print any heading. +\parseargdef\xrefname{\donoderef{Yomitfromtoc}{#1}}% + % These macros generate a chapter, section, etc. heading only % (including whitespace, linebreaking, etc. around it), % given all the information in convenient, parsed form. @@ -6361,7 +6576,7 @@ \fi } -\parseargdef\setchapternewpage{\csname CHAPPAG#1\endcsname} +\parseargdef\setchapternewpage{\csname CHAPPAG#1\endcsname\HEADINGSon} \def\CHAPPAGoff{% \global\let\contentsalignmacro = \chappager @@ -6378,7 +6593,7 @@ \global\let\pchapsepmacro=\chapoddpage \global\def\HEADINGSon{\HEADINGSdouble}} -\CHAPPAGon +\setchapternewpage on % \chapmacro - Chapter opening. % @@ -6391,6 +6606,16 @@ \def\Yappendixkeyword{Yappendix} \def\Yomitfromtockeyword{Yomitfromtoc} % +% +% Definitions for @thischapter. These can be overridden in translation +% files. +\def\thischapterAppendix{% + \putwordAppendix{} \thischapternum: \thischaptername} + +\def\thischapterChapter{% + \putwordChapter{} \thischapternum: \thischaptername} +% +% \def\chapmacro#1#2#3{% \expandafter\ifx\thisenv\titlepage\else \checkenv{}% chapters, etc., should not start inside an environment. @@ -6413,22 +6638,14 @@ \xdef\currentchapterdefs{% \gdef\noexpand\thischaptername{\the\toks0}% \gdef\noexpand\thischapternum{\appendixletter}% - % \noexpand\putwordAppendix avoids expanding indigestible - % commands in some of the translations. - \gdef\noexpand\thischapter{\noexpand\putwordAppendix{} - \noexpand\thischapternum: - \noexpand\thischaptername}% + \let\noexpand\thischapter\noexpand\thischapterAppendix }% \else \toks0={#1}% \xdef\currentchapterdefs{% \gdef\noexpand\thischaptername{\the\toks0}% \gdef\noexpand\thischapternum{\the\chapno}% - % \noexpand\putwordChapter avoids expanding indigestible - % commands in some of the translations. - \gdef\noexpand\thischapter{\noexpand\putwordChapter{} - \noexpand\thischapternum: - \noexpand\thischaptername}% + \let\noexpand\thischapter\noexpand\thischapterChapter }% \fi\fi\fi % @@ -6449,11 +6666,6 @@ \chapfonts \rm \let\footnote=\errfootnoteheading % give better error message % - % Have to define \currentsection before calling \donoderef, because the - % xref code eventually uses it. On the other hand, it has to be called - % after \pchapsepmacro, or the headline will change too soon. - \gdef\currentsection{#1}% - % % Only insert the separating space if we have a chapter/appendix % number, and don't print the unnumbered ``number''. \ifx\temptype\Ynothingkeyword @@ -6480,7 +6692,7 @@ % been typeset. If the destination for the pdf outline is after the % text, then jumping from the outline may wind up with the text not % being visible, for instance under high magnification. - \donoderef{#2}% + \donoderef{#2}{#1}% % % Typeset the actual heading. \nobreak % Avoid page breaks at the interline glue. @@ -6514,6 +6726,12 @@ \def\subsubsecheadingskip{\subsecheadingskip} \def\subsubsecheadingbreak{\subsecheadingbreak} +% Definition for @thissection. This can be overridden in translation +% files. +\def\thissectionDef{% + \putwordSection{} \thissectionnum: \thissectionname} +% + % Print any size, any type, section title. % @@ -6555,11 +6773,7 @@ \xdef\currentsectiondefs{% \gdef\noexpand\thissectionname{\the\toks0}% \gdef\noexpand\thissectionnum{#4}% - % \noexpand\putwordSection avoids expanding indigestible - % commands in some of the translations. - \gdef\noexpand\thissection{\noexpand\putwordSection{} - \noexpand\thissectionnum: - \noexpand\thissectionname}% + \let\noexpand\thissection\noexpand\thissectionDef }% \fi \else @@ -6568,11 +6782,7 @@ \xdef\currentsectiondefs{% \gdef\noexpand\thissectionname{\the\toks0}% \gdef\noexpand\thissectionnum{#4}% - % \noexpand\putwordSection avoids expanding indigestible - % commands in some of the translations. - \gdef\noexpand\thissection{\noexpand\putwordSection{} - \noexpand\thissectionnum: - \noexpand\thissectionname}% + \let\noexpand\thissection\noexpand\thissectionDef }% \fi \fi\fi\fi @@ -6598,21 +6808,17 @@ \ifx\temptype\Ynothingkeyword \setbox0 = \hbox{}% \def\toctype{unn}% - \gdef\currentsection{#1}% \else\ifx\temptype\Yomitfromtockeyword - % for @headings -- no section number, don't include in toc, - % and don't redefine \currentsection. + % for @headings -- no section number, don't include in toc. \setbox0 = \hbox{}% \def\toctype{omit}% \let\sectionlevel=\empty \else\ifx\temptype\Yappendixkeyword \setbox0 = \hbox{#4\enspace}% \def\toctype{app}% - \gdef\currentsection{#1}% \else \setbox0 = \hbox{#4\enspace}% \def\toctype{num}% - \gdef\currentsection{#1}% \fi\fi\fi % % Write the toc entry (before \donoderef). See comments in \chapmacro. @@ -6620,7 +6826,7 @@ % % Write the node reference (= pdf destination for pdftex). % Again, see comments in \chapmacro. - \donoderef{#3}% + \donoderef{#3}{#1}% % % Interline glue will be inserted when the vbox is completed. % That glue will be a valid breakpoint for the page, since it'll be @@ -6732,18 +6938,95 @@ \input \tocreadfilename } +% process toc file to find the maximum width of the section numbers for +% each chapter +\def\findsecnowidths{% + \begingroup + \setupdatafile + \activecatcodes + \secentryfonts + % Redefinitions + \def\numchapentry##1##2##3##4{% + \def\curchapname{secnowidth-##2}% + \curchapmax=0pt + }% + \let\appentry\numchapentry + % + \def\numsecentry##1##2##3##4{% + \def\cursecname{secnowidth-##2}% + \cursecmax=0pt + % + \setbox0=\hbox{##2}% + \ifdim\wd0>\curchapmax + \curchapmax=\wd0 + \expandafter\xdef\csname\curchapname\endcsname{\the\wd0}% + \fi + }% + \let\appsecentry\numsecentry + % + \def\numsubsecentry##1##2##3##4{% + \def\curssecname{secnowidth-##2}% + \curssecmax=0pt + % + \setbox0=\hbox{##2}% + \ifdim\wd0>\cursecmax + \cursecmax=\wd0 + \expandafter\xdef\csname\cursecname\endcsname{\the\wd0}% + \fi + }% + \let\appsubsecentry\numsubsecentry + % + \def\numsubsubsecentry##1##2##3##4{% + \setbox0=\hbox{##2}% + \ifdim\wd0>\curssecmax + \curssecmax=\wd0 + \expandafter\xdef\csname\curssecname\endcsname{\the\wd0}% + \fi + }% + \let\appsubsubsecentry\numsubsubsecentry + % + % Discard any output by outputting to dummy vbox, in case the toc file + % contains macros that we have not redefined above. + \setbox\dummybox\vbox\bgroup + \input \tocreadfilename\relax + \egroup + \endgroup +} +\newdimen\curchapmax +\newdimen\cursecmax +\newdimen\curssecmax + + +% set #1 to the maximum section width for #2 +\def\retrievesecnowidth#1#2{% + \expandafter\let\expandafter\savedsecnowidth \csname secnowidth-#2\endcsname + \ifx\savedsecnowidth\relax + #1=0pt + \else + #1=\savedsecnowidth + \fi +} +\newdimen\secnowidthchap +\secnowidthchap=0pt +\newdimen\secnowidthsec +\secnowidthsec=0pt +\newdimen\secnowidthssec +\secnowidthssec=0pt + + \newskip\contentsrightmargin \contentsrightmargin=1in \newcount\savepageno \newcount\lastnegativepageno \lastnegativepageno = -1 % Prepare to read what we've written to \tocfile. % -\def\startcontents#1{% +\def\startcontents#1#2{% % If @setchapternewpage on, and @headings double, the contents should % start on an odd page, unlike chapters. \contentsalignmacro \immediate\closeout\tocfile % + #2% % Don't need to put `Contents' or `Short Contents' in the headline. % It is abundantly clear what they are. \chapmacro{#1}{Yomitfromtoc}{}% @@ -6758,8 +7041,14 @@ \def\thistitle{}% no title in double-sided headings % Record where the Roman numerals started. \ifnum\romancount=0 \global\romancount=\pagecount \fi + \linkentrytexttrue } +% \raggedbottom in plain.tex hardcodes \topskip so override it +\catcode`\@=11 +\def\raggedbottom{\advance\topskip by 0pt plus30pt \r@ggedbottomtrue} +\catcode`\@=\other + % redefined for the two-volume lispref. We always output on % \jobname.toc even if this is redefined. % @@ -6768,9 +7057,12 @@ % Normal (long) toc. % \def\contents{% - \startcontents{\putwordTOC}% + \startcontents{\putwordTOC}{\contentsmkdest}% + \ifxetex\xetexpreauxfile\fi + \penalty2 % mark beginning of contents \openin 1 \tocreadfilename\space \ifeof 1 \else + \findsecnowidths \readtocfile \fi \vfill \eject @@ -6779,13 +7071,18 @@ \pdfmakeoutlines \fi \closein 1 + \ifxetex\xetexpostauxfile\fi \endgroup \contentsendroman } +\def\contentsmkdest{% + \pdfmkdest{txi.CONTENTS}% +} + % And just the chapters. \def\summarycontents{% - \startcontents{\putwordShortTOC}% + \startcontents{\putwordShortTOC}{}% % \let\partentry = \shortpartentry \let\numchapentry = \shortchapentry @@ -6798,6 +7095,7 @@ \rm \hyphenpenalty = 10000 \advance\baselineskip by 1pt % Open it up a little. + \extrasecnoskip=0.4pt \def\numsecentry##1##2##3##4{} \let\appsecentry = \numsecentry \let\unnsecentry = \numsecentry @@ -6807,11 +7105,13 @@ \let\numsubsubsecentry = \numsecentry \let\appsubsubsecentry = \numsecentry \let\unnsubsubsecentry = \numsecentry + \ifxetex\xetexpreauxfile\fi \openin 1 \tocreadfilename\space \ifeof 1 \else \readtocfile \fi \closein 1 + \ifxetex\xetexpostauxfile\fi \vfill \eject \contentsalignmacro % in case @setchapternewpage odd is in effect \endgroup @@ -6822,12 +7122,8 @@ % Get ready to use Arabic numerals again \def\contentsendroman{% \lastnegativepageno = \pageno - \global\pageno = \savepageno - % - % If \romancount > \arabiccount, the contents are at the end of the - % document. Otherwise, advance where the Arabic numerals start for - % the page numbers. - \ifnum\romancount>\arabiccount\else\global\arabiccount=\pagecount\fi + \global\pageno=1 + \contentsendcount = \pagecount } % Typeset the label for a chapter or appendix for the short contents. @@ -6837,8 +7133,6 @@ % This space should be enough, since a single number is .5em, and the % widest letter (M) is 1em, at least in the Computer Modern fonts. % But use \hss just in case. - % (This space doesn't include the extra space that gets added after - % the label; that gets put in by \shortchapentry above.) % % We'd like to right-justify chapter numbers, but that looks strange % with appendix letters. And right-justifying numbers and @@ -6848,39 +7142,55 @@ \hbox to 1em{#1\hss}% } -% These macros generate individual entries in the table of contents. -% The first argument is the chapter or section name. -% The last argument is the page number. -% The arguments in between are the chapter number, section number, ... +% These macros generate individual entries in the table of contents, +% and are read in from the *.toc file. +% +% The arguments are like: +% \def\numchapentry#1#2#3#4 +% #1 - the chapter or section name. +% #2 - section number +% #3 - level of section (e.g "chap", "sec") +% #4 - page number -% Parts, in the main contents. Replace the part number, which doesn't -% exist, with an empty box. Let's hope all the numbers have the same width. -% Also ignore the page number, which is conventionally not printed. -\def\numeralbox{\setbox0=\hbox{8}\hbox to \wd0{\hfil}} +% Parts, in the main contents. Ignore the page number, which is +% conventionally not printed. \def\partentry#1#2#3#4{% + \ifnum\lastpenalty = 2 + % use less space if at very first entry of contents + \vskip 1\baselineskip plus .33\baselineskip minus .25\baselineskip + \else + \vskip 2\baselineskip plus .66\baselineskip minus .5\baselineskip + \fi % Add stretch and a bonus for breaking the page before the part heading. % This reduces the chance of the page being broken immediately after the % part heading, before a following chapter heading. - \vskip 0pt plus 5\baselineskip + \vskip 0pt plus 3\baselineskip \penalty-300 - \vskip 0pt plus -5\baselineskip - \dochapentry{\numeralbox\labelspace#1}{}% + \vskip 0pt plus -3\baselineskip + \begingroup + \secfonts \rm + \entryinternal{#1}{}% + \endgroup + \afterpartentrytrue } +\newif\ifafterpartentry % % Parts, in the short toc. \def\shortpartentry#1#2#3#4{% \penalty-300 \vskip.5\baselineskip plus.15\baselineskip minus.1\baselineskip - \shortchapentry{{\bf #1}}{\numeralbox}{}{}% + \tocentry{{\bf #1}}{}{}{}% } % Chapters, in the main contents. -\def\numchapentry#1#2#3#4{\dochapentry{#2\labelspace#1}{#4}} +\def\numchapentry#1#2#3#4{% + \retrievesecnowidth\secnowidthchap{#2}% + \dochapentry{#1}{#2}{#3}{#4}% +} % Chapters, in the short toc. -% See comments in \dochapentry re vbox and related settings. \def\shortchapentry#1#2#3#4{% - \tocentry{\shortchaplabel{#2}\labelspace #1}{\doshortpageno\bgroup#4\egroup}% + \tocentry{#1}{\shortchaplabel{#2}}{#3}{#4}% } % Appendices, in the main contents. @@ -6891,70 +7201,119 @@ \setbox0 = \hbox{\putwordAppendix{} M}% \hbox to \wd0{\putwordAppendix{} #1\hss}} % -\def\appentry#1#2#3#4{\dochapentry{\appendixbox{#2}\hskip.7em#1}{#4}} +\def\appentry#1#2#3#4{% + \retrievesecnowidth\secnowidthchap{#2}% + \dochapentry{\appendixbox{#2}\hskip.7em#1}{}{#3}{#4}% +} % Unnumbered chapters. -\def\unnchapentry#1#2#3#4{\dochapentry{#1}{#4}} -\def\shortunnchapentry#1#2#3#4{\tocentry{#1}{\doshortpageno\bgroup#4\egroup}} +\def\unnchapentry#1#2#3#4{\dochapentry{#1}{}{#3}{#4}} +\def\shortunnchapentry#1#2#3#4{\tocentry{#1}{}{#3}{#4}} % Sections. -\def\numsecentry#1#2#3#4{\dosecentry{#2\labelspace#1}{#4}} +\def\numsecentry#1#2#3#4{% + \retrievesecnowidth\secnowidthsec{#2}% + \dosecentry{#1}{#2}{#3}{#4}% +} \let\appsecentry=\numsecentry -\def\unnsecentry#1#2#3#4{\dosecentry{#1}{#4}} +\def\unnsecentry#1#2#3#4{% + \retrievesecnowidth\secnowidthsec{#2}% + \dosecentry{#1}{}{#3}{#4}% +} % Subsections. -\def\numsubsecentry#1#2#3#4{\dosubsecentry{#2\labelspace#1}{#4}} +\def\numsubsecentry#1#2#3#4{% + \retrievesecnowidth\secnowidthssec{#2}% + \dosubsecentry{#1}{#2}{#3}{#4}% +} \let\appsubsecentry=\numsubsecentry -\def\unnsubsecentry#1#2#3#4{\dosubsecentry{#1}{#4}} +\def\unnsubsecentry#1#2#3#4{% + \retrievesecnowidth\secnowidthssec{#2}% + \dosubsecentry{#1}{}{#3}{#4}% +} % And subsubsections. -\def\numsubsubsecentry#1#2#3#4{\dosubsubsecentry{#2\labelspace#1}{#4}} +\def\numsubsubsecentry#1#2#3#4{\dosubsubsecentry{#1}{#2}{#3}{#4}} \let\appsubsubsecentry=\numsubsubsecentry -\def\unnsubsubsecentry#1#2#3#4{\dosubsubsecentry{#1}{#4}} +\def\unnsubsubsecentry#1#2#3#4{\dosubsubsecentry{#1}{}{#3}{#4}} % This parameter controls the indentation of the various levels. % Same as \defaultparindent. \newdimen\tocindent \tocindent = 15pt -% Now for the actual typesetting. In all these, #1 is the text and #2 is the -% page number. +% Now for the actual typesetting. In all these, #1 is the text, #2 is +% a section number if present, #3 is the node, and #4 is the page number. % % If the toc has to be broken over pages, we want it to be at chapters % if at all possible; hence the \penalty. -\def\dochapentry#1#2{% - \penalty-300 \vskip1\baselineskip plus.33\baselineskip minus.25\baselineskip +\def\dochapentry#1#2#3#4{% + \ifafterpartentry + \afterpartentryfalse + \penalty5000 + \else + \penalty-300 + \fi + \vskip1\baselineskip plus.33\baselineskip minus.25\baselineskip \begingroup % Move the page numbers slightly to the right \advance\entryrightmargin by -0.05em \chapentryfonts - \tocentry{#1}{\dopageno\bgroup#2\egroup}% + \extrasecnoskip=0.4em % separate chapter number more + \tocentry{#1}{#2}{#3}{#4}% \endgroup \nobreak\vskip .25\baselineskip plus.1\baselineskip } -\def\dosecentry#1#2{\begingroup +\def\dosecentry#1#2#3#4{\begingroup + \secnowidth=\secnowidthchap \secentryfonts \leftskip=\tocindent - \tocentry{#1}{\dopageno\bgroup#2\egroup}% + \tocentry{#1}{#2}{#3}{#4}% \endgroup} -\def\dosubsecentry#1#2{\begingroup +\def\dosubsecentry#1#2#3#4{\begingroup + \secnowidth=\secnowidthsec \subsecentryfonts \leftskip=2\tocindent - \tocentry{#1}{\dopageno\bgroup#2\egroup}% + \tocentry{#1}{#2}{#3}{#4}% \endgroup} -\def\dosubsubsecentry#1#2{\begingroup +\def\dosubsubsecentry#1#2#3#4{\begingroup + \secnowidth=\secnowidthssec \subsubsecentryfonts \leftskip=3\tocindent - \tocentry{#1}{\dopageno\bgroup#2\egroup}% + \tocentry{#1}{#2}{#3}{#4}% \endgroup} -% We use the same \entry macro as for the index entries. -\let\tocentry = \entry +% Used for the maximum width of a section number so we can align +% section titles. +\newdimen\secnowidth +\secnowidth=0pt +\newdimen\extrasecnoskip +\extrasecnoskip=0pt -% Space between chapter (or whatever) number and the title. -\def\labelspace{\hskip1em \relax} +\let\tocnodetarget\empty +\let\entrypagetarget\empty -\def\dopageno#1{{\rm #1}} -\def\doshortpageno#1{{\rm #1}} +% \tocentry{TITLE}{SEC NO}{NODE}{PAGE} +% +\def\tocentry#1#2#3#4{% + \def\tocnodetarget{#3}% + \def\secno{#2}% + \ifx\empty\secno + \entryinternal{#1}{#4}% + \else + \ifdim 0pt=\secnowidth + \setbox0=\hbox{#2\hskip\labelspace\hskip\extrasecnoskip}% + \else + \advance\secnowidth by \labelspace + \advance\secnowidth by \extrasecnoskip + \setbox0=\hbox to \secnowidth{% + #2\hskip\labelspace\hskip\extrasecnoskip\hfill}% + \fi + \entrycontskip=\wd0 + \entryinternal{\box0 #1}{#4}% + \fi +} +\newdimen\labelspace +\labelspace=0.6em \def\chapentryfonts{\secfonts \rm} \def\secentryfonts{\textfonts} @@ -7100,19 +7459,25 @@ \newdimen\cartouter\newdimen\cartinner \newskip\normbskip\newskip\normpskip\newskip\normlskip - -\envdef\cartouche{% +\envparseargdef\cartouche{% \cartouchefontdefs \ifhmode\par\fi % can't be in the midst of a paragraph. \startsavinginserts \lskip=\leftskip \rskip=\rightskip \leftskip=0pt\rightskip=0pt % we want these *outside*. + % + % Set paragraph width for text inside cartouche. There are + % left and right margins of 3pt each plus two vrules 0.4pt each. \cartinner=\hsize \advance\cartinner by-\lskip \advance\cartinner by-\rskip + \advance\cartinner by -6.8pt + % + % For drawing top and bottom of cartouche. Each corner char + % adds 6pt and we take off the width of a rule to line up with the + % right boundary perfectly. \cartouter=\hsize - \advance\cartouter by 18.4pt % allow for 3pt kerns on either - % side, and for 6pt waste from - % each corner char, and rule thickness + \advance\cartouter by 11.6pt + % \normbskip=\baselineskip \normpskip=\parskip \normlskip=\lineskip % % If this cartouche directly follows a sectioning command, we need the @@ -7120,20 +7485,23 @@ % collide with the section heading. \ifnum\lastpenalty>10000 \vskip\parskip \penalty\lastpenalty \fi % - \setbox\groupbox=\vbox\bgroup + \setbox\groupbox=\vtop\bgroup \baselineskip=0pt\parskip=0pt\lineskip=0pt \carttop \hbox\bgroup - \hskip\lskip - \vrule\kern3pt - \vbox\bgroup - \kern3pt - \hsize=\cartinner - \baselineskip=\normbskip - \lineskip=\normlskip - \parskip=\normpskip - \vskip -\parskip - \comment % For explanation, see the end of def\group. + \hskip\lskip + \vrule\kern3pt + \vbox\bgroup + \hsize=\cartinner + \baselineskip=\normbskip + \lineskip=\normlskip + \parskip=\normpskip + \def\arg{#1}% + \ifx\arg\empty\else + \centerV{\hfil \bf #1 \hfil}% + \fi + \kern3pt + \vskip -\parskip } \def\Ecartouche{% \ifhmode\par\fi @@ -7287,22 +7655,6 @@ } \let\Eraggedright\par -\envdef\raggedleft{% - \parindent=0pt \leftskip0pt plus2em - \spaceskip.3333em \xspaceskip.5em \parfillskip=0pt - \hbadness=10000 % Last line will usually be underfull, so turn off - % badness reporting. -} -\let\Eraggedleft\par - -\envdef\raggedcenter{% - \parindent=0pt \rightskip0pt plus1em \leftskip0pt plus1em - \spaceskip.3333em \xspaceskip.5em \parfillskip=0pt - \hbadness=10000 % Last line will usually be underfull, so turn off - % badness reporting. -} -\let\Eraggedcenter\par - % @quotation does normal linebreaking (hence we can't use \nonfillstart) % and narrows the margins. We keep \parskip nonzero in general, since @@ -7342,7 +7694,7 @@ % @indentedblock is like @quotation, but indents only on the left and % has no optional argument. -% +% \makedispenvdef{indentedblock}{\indentedblockstart} % \def\indentedblockstart{% @@ -7400,8 +7752,9 @@ \endgroup % \def\setupverb{% - \tt % easiest (and conventionally used) font for verbatim + \tt \def\par{\leavevmode\endgraf}% + \parindent = 0pt \setcodequotes \tabeightspaces % Respect line breaks, @@ -7525,9 +7878,12 @@ % file; b) letting users define the frontmatter in as flexible order as % possible is desirable. % -\def\copying{\checkenv{}\begingroup\scanargctxt\docopying} -\def\docopying#1@end copying{\endgroup\def\copyingtext{#1}} -% +\def\copying{\checkenv{}\begingroup\macrobodyctxt\docopying} +{\catcode`\ =\other +\gdef\docopying#1@end copying{\endgroup\def\copyingtext{#1}} +} +\let\copyingtext\relax + \def\insertcopying{% \begingroup \parindent = 0pt % paragraph indentation looks wrong on title page @@ -7535,6 +7891,18 @@ \endgroup } +\def\publication{\checkenv{}\begingroup\macrobodyctxt\dopublication} +{\catcode`\ =\other +\gdef\dopublication#1@end publication{\endgroup\def\publicationtext{#1}} +} +\let\publicationtext\relax + +\def\insertpublication{% + \begingroup + \parindent = 0pt % paragraph indentation looks wrong on title page + \scanexp\publicationtext + \endgroup +} \message{defuns,} % @defun etc. @@ -7575,31 +7943,19 @@ \exdentamount=\defbodyindent } -\def\dodefunx#1{% - % First, check whether we are in the right environment: - \checkenv#1% - % - % As above, allow line break if we have multiple x headers in a row. - % It's not a great place, though. - \ifnum\lastpenalty=10002 \penalty3000 \else \defunpenalty=10002 \fi - % - % And now, it's time to reuse the body of the original defun: - \expandafter\gobbledefun#1% -} -\def\gobbledefun#1\startdefun{} - -% \printdefunline \deffnheader{text} +% Called as \printdefunline \deffooheader{text} % \def\printdefunline#1#2{% \begingroup - % call \deffnheader: + \plainfrenchspacing + % call \deffooheader: #1#2 \endheader % common ending: \interlinepenalty = 10000 \advance\rightskip by 0pt plus 1fil\relax \endgraf \nobreak\vskip -\parskip - \penalty\defunpenalty % signal to \startdefun and \dodefunx + \penalty\defunpenalty % signal to \startdefun and \deffoox % Some of the @defun-type tags do not enable magic parentheses, % rendering the following check redundant. But we don't optimize. \checkparencounts @@ -7608,29 +7964,55 @@ \def\Edefun{\endgraf\medbreak} -% \makedefun{deffn} creates \deffn, \deffnx and \Edeffn; -% the only thing remaining is to define \deffnheader. +% @defblock, @defline do not automatically create index entries +\envdef\defblock{% + \startdefun +} +\let\Edefblock\Edefun + +\def\defline{% + \doingtypefnfalse + \parseargusing\activeparens{\printdefunline\deflineheader}% +} +\def\deflineheader#1 #2 #3\endheader{% + \printdefname{#1}{}{#2}\magicamp\defunargs{#3\unskip}% +} + +\def\deftypeline{% + \doingtypefntrue + \parseargusing\activeparens{\printdefunline\deftypelineheader}% +} +\def\deftypelineheader#1 #2 #3 #4\endheader{% + \printdefname{#1}{#2}{#3}\magicamp\defunargs{#4\unskip}% +} + +% \makedefun{deffoo} (\deffooheader parameters) { (\deffooheader expansion) } % +% Define \deffoo, \deffoox \Edeffoo and \deffooheader. \def\makedefun#1{% \expandafter\let\csname E#1\endcsname = \Edefun \edef\temp{\noexpand\domakedefun \makecsname{#1}\makecsname{#1x}\makecsname{#1header}}% \temp } - -% \domakedefun \deffn \deffnx \deffnheader { (defn. of \deffnheader) } -% -% Define \deffn and \deffnx, without parameters. -% \deffnheader has to be defined explicitly. -% \def\domakedefun#1#2#3{% \envdef#1{% \startdefun \doingtypefnfalse % distinguish typed functions from all else \parseargusing\activeparens{\printdefunline#3}% }% - \def#2{\dodefunx#1}% - \def#3% + \def#2{% + % First, check whether we are in the right environment: + \checkenv#1% + % + % As in \startdefun, allow line break if we have multiple x headers + % in a row. It's not a great place, though. + \ifnum\lastpenalty=10002 \penalty3000 \else \defunpenalty=10002 \fi + % + \doingtypefnfalse % distinguish typed functions from all else + \parseargusing\activeparens{\printdefunline#3}% + }% + \def#3% definition of \deffooheader follows } \newif\ifdoingtypefn % doing typed function? @@ -7639,7 +8021,7 @@ % @deftypefnnewline on|off says whether the return type of typed functions % are printed on their own line. This affects @deftypefn, @deftypefun, % @deftypeop, and @deftypemethod. -% +% \parseargdef\deftypefnnewline{% \def\temp{#1}% \ifx\temp\onword @@ -7655,74 +8037,51 @@ \fi\fi } -% \dosubind {index}{topic}{subtopic} -% -% If SUBTOPIC is present, precede it with a space, and call \doind. -% (At some time during the 20th century, this made a two-level entry in an -% index such as the operation index. Nobody seemed to notice the change in -% behaviour though.) -\def\dosubind#1#2#3{% - \def\thirdarg{#3}% - \ifx\thirdarg\empty - \doind{#1}{#2}% - \else - \doind{#1}{#2\space#3}% - \fi -} - % Untyped functions: % @deffn category name args -\makedefun{deffn}{\deffngeneral{}} - -% @deffn category class name args -\makedefun{defop}#1 {\defopon{#1\ \putwordon}} - -% \defopon {category on}class name args -\def\defopon#1#2 {\deffngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} } +\makedefun{deffn}#1 #2 #3\endheader{% + \doind{fn}{\code{#2}}% + \printdefname{#1}{}{#2}\magicamp\defunargs{#3\unskip}% +} -% \deffngeneral {subind}category name args -% -\def\deffngeneral#1#2 #3 #4\endheader{% - \dosubind{fn}{\code{#3}}{#1}% - \defname{#2}{}{#3}\magicamp\defunargs{#4\unskip}% +% @defop category class name args +\makedefun{defop}#1 {\defopheaderx{#1\ \putwordon}} +\def\defopheaderx#1#2 #3 #4\endheader{% + \doind{fn}{\code{#3}\space\putwordon\ \code{#2}}% + \printdefname{#1\ \code{#2}}{}{#3}\magicamp\defunargs{#4\unskip}% } % Typed functions: % @deftypefn category type name args -\makedefun{deftypefn}{\deftypefngeneral{}} +\makedefun{deftypefn}#1 #2 #3 #4\endheader{% + \doind{fn}{\code{#3}}% + \doingtypefntrue + \printdefname{#1}{#2}{#3}\defunargs{#4\unskip}% +} % @deftypeop category class type name args -\makedefun{deftypeop}#1 {\deftypeopon{#1\ \putwordon}} - -% \deftypeopon {category on}class type name args -\def\deftypeopon#1#2 {\deftypefngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} } - -% \deftypefngeneral {subind}category type name args -% -\def\deftypefngeneral#1#2 #3 #4 #5\endheader{% - \dosubind{fn}{\code{#4}}{#1}% +\makedefun{deftypeop}#1 {\deftypeopheaderx{#1\ \putwordon}} +\def\deftypeopheaderx#1#2 #3 #4 #5\endheader{% + \doind{fn}{\code{#4}\space\putwordon\ \code{#1\ \code{#2}}}% \doingtypefntrue - \defname{#2}{#3}{#4}\defunargs{#5\unskip}% + \printdefname{#1\ \code{#2}}{#3}{#4}\defunargs{#5\unskip}% } % Typed variables: % @deftypevr category type var args -\makedefun{deftypevr}{\deftypecvgeneral{}} +\makedefun{deftypevr}#1 #2 #3 #4\endheader{% + \doind{vr}{\code{#3}}% + \printdefname{#1}{#2}{#3}\defunargs{#4\unskip}% +} % @deftypecv category class type var args -\makedefun{deftypecv}#1 {\deftypecvof{#1\ \putwordof}} - -% \deftypecvof {category of}class type var args -\def\deftypecvof#1#2 {\deftypecvgeneral{\putwordof\ \code{#2}}{#1\ \code{#2}} } - -% \deftypecvgeneral {subind}category type var args -% -\def\deftypecvgeneral#1#2 #3 #4 #5\endheader{% - \dosubind{vr}{\code{#4}}{#1}% - \defname{#2}{#3}{#4}\defunargs{#5\unskip}% +\makedefun{deftypecv}#1 {\deftypecvheaderx{#1\ \putwordof}} +\def\deftypecvheaderx#1#2 #3 #4 #5\endheader{% + \doind{vr}{\code{#4}\space\putwordof\ \code{#2}}% + \printdefname{#1\ \code{#2}}{#3}{#4}\defunargs{#5\unskip}% } % Untyped variables: @@ -7731,17 +8090,15 @@ \makedefun{defvr}#1 {\deftypevrheader{#1} {} } % @defcv category class var args -\makedefun{defcv}#1 {\defcvof{#1\ \putwordof}} - -% \defcvof {category of}class var args -\def\defcvof#1#2 {\deftypecvof{#1}#2 {} } +\makedefun{defcv}#1 {\defcvheaderx{#1\ \putwordof}} +\def\defcvheaderx#1#2 {\deftypecvheaderx{#1}#2 {} } % Types: % @deftp category name args \makedefun{deftp}#1 #2 #3\endheader{% \doind{tp}{\code{#2}}% - \defname{#1}{}{#2}\defunargs{#3\unskip}% + \printdefname{#1}{}{#2}\defunargs{#3\unskip}% } % Remaining @defun-like shortcuts: @@ -7752,19 +8109,19 @@ \makedefun{defvar}{\defvrheader{\putwordDefvar} } \makedefun{defopt}{\defvrheader{\putwordDefopt} } \makedefun{deftypevar}{\deftypevrheader{\putwordDefvar} } -\makedefun{defmethod}{\defopon\putwordMethodon} -\makedefun{deftypemethod}{\deftypeopon\putwordMethodon} -\makedefun{defivar}{\defcvof\putwordInstanceVariableof} -\makedefun{deftypeivar}{\deftypecvof\putwordInstanceVariableof} +\makedefun{defmethod}{\defopheaderx\putwordMethodon} +\makedefun{deftypemethod}{\deftypeopheaderx\putwordMethodon} +\makedefun{defivar}{\defcvheaderx\putwordInstanceVariableof} +\makedefun{deftypeivar}{\deftypecvheaderx\putwordInstanceVariableof} -% \defname, which formats the name of the @def (not the args). +% \printdefname, which formats the name of the @def (not the args). % #1 is the category, such as "Function". % #2 is the return type, if any. % #3 is the function name. % % We are followed by (but not passed) the arguments, if any. % -\def\defname#1#2#3{% +\def\printdefname#1#2#3{% \par % Get the values of \leftskip and \rightskip as they were outside the @def... \advance\leftskip by -\defbodyindent @@ -7774,9 +8131,7 @@ \rettypeownlinefalse \ifdoingtypefn % doing a typed function specifically? % then check user option for putting return type on its own line: - \expandafter\ifx\csname SETtxideftypefnnl\endcsname\relax \else - \rettypeownlinetrue - \fi + \ifflagclear{txideftypefnnl}{}{\rettypeownlinetrue}% \fi % % How we'll format the category name. Putting it in brackets helps @@ -7820,6 +8175,8 @@ \tolerance=10000 \hbadness=10000 \exdentamount=\defbodyindent {% + \def\^^M{}% for line continuation + % % defun fonts. We use typewriter by default (used to be bold) because: % . we're printing identifiers, they should be in tt in principle. % . in languages with many accents, such as Czech or French, it's @@ -7834,37 +8191,33 @@ \tclose{\temp}% typeset the return type \ifrettypeownline % put return type on its own line; prohibit line break following: - \hfil\vadjust{\nobreak}\break + \hfil\vadjust{\nobreak}\break \else \space % type on same line, so just followed by a space \fi \fi % no return type #3% output function name }% - {\rm\enskip}% hskip 0.5 em of \rmfont + \ifflagclear{txidefnamenospace}{% + {\rm\enskip}% hskip 0.5 em of \rmfont + }{}% % - \boldbrax + \parenbrackglyphs % arguments will be output next, if any. } -% Print arguments in slanted roman (not ttsl), inconsistently with using -% tt for the name. This is because literal text is sometimes needed in -% the argument list (groff manual), and ttsl and tt are not very -% distinguishable. Prevent hyphenation at `-' chars. -% +% Print arguments. Use slanted for @def*, typewriter for @deftype*. \def\defunargs#1{% - % use sl by default (not ttsl), - % tt for the names. - \df \sl \hyphenchar\font=0 - % - % On the other hand, if an argument has two dashes (for instance), we - % want a way to get ttsl. We used to recommend @var for that, so - % leave the code in, but it's strange for @var to lead to typewriter. - % Nowadays we recommend @code, since the difference between a ttsl hyphen - % and a tt hyphen is pretty tiny. @code also disables ?` !`. - \def\var##1{{\setregularquotes\ttslanted{##1}}}% - #1% - \sl\hyphenchar\font=45 + \bgroup + \def\^^M{}% for line continuation + \df \ifdoingtypefn \tt \else \sl \fi + \ifflagclear{txicodevaristt}{}% + % use \ttsl for @var in both @def* and @deftype*. + % the kern prevents an italic correction at end, which appears + % too much for ttsl. + {\def\var##1{{\setregularquotes \ttsl ##1\kern 0pt }}}% + #1% + \egroup } % We want ()&[] to print specially on the defun line. @@ -7879,57 +8232,40 @@ \let\lparen = ( \let\rparen = ) % Be sure that we always have a definition for `(', etc. For example, -% if the fn name has parens in it, \boldbrax will not be in effect yet, -% so TeX would otherwise complain about undefined control sequence. +% if the fn name has parens in it, \parenbrackglyphs will not be in +% effect yet, so TeX would otherwise complain about undefined control +% sequence. { \activeparens - \global\let(=\lparen \global\let)=\rparen - \global\let[=\lbrack \global\let]=\rbrack - \global\let& = \& + \gdef\defcharsdefault{% + \let(=\lparen \let)=\rparen + \let[=\lbrack \let]=\rbrack + \let& = \&% + } + \globaldefs=1 \defcharsdefault - \gdef\boldbrax{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb} + \gdef\parenbrackglyphs{\let(=\opnr\let)=\cpnr\let[=\lbrb\let]=\rbrb} \gdef\magicamp{\let&=\amprm} } \let\ampchar\& -\newcount\parencount - -% If we encounter &foo, then turn on ()-hacking afterwards -\newif\ifampseen -\def\amprm#1 {\ampseentrue{\bf\ }} - -\def\parenfont{% - \ifampseen - % At the first level, print parens in roman, - % otherwise use the default font. - \ifnum \parencount=1 \rm \fi - \else - % The \sf parens (in \boldbrax) actually are a little bolder than - % the contained text. This is especially needed for [ and ] . - \sf - \fi -} -\def\infirstlevel#1{% - \ifampseen - \ifnum\parencount=1 - #1% - \fi - \fi -} -\def\bfafterword#1 {#1 \bf} +\def\amprm#1 {{\rm\ }} +\newcount\parencount +% opening and closing parentheses in roman font \def\opnr{% + \ptexslash % italic correction \global\advance\parencount by 1 - {\parenfont(}% - \infirstlevel \bfafterword + {\sf(}% } -\def\clnr{% - {\parenfont)}% - \infirstlevel \sl +\def\cpnr{% + \ptexslash % italic correction + {\sf)}% \global\advance\parencount by -1 } \newcount\brackcount +% left and right square brackets in bold font \def\lbrb{% \global\advance\brackcount by 1 {\bf[}% @@ -7971,24 +8307,17 @@ } \fi -\let\E=\expandafter - % Used at the time of macro expansion. % Argument is macro body with arguments substituted \def\scanmacro#1{% \newlinechar`\^^M - % expand the expansion of \eatleadingcr twice to maybe remove a leading - % newline (and \else and \fi tokens), then call \eatspaces on the result. - \def\xeatspaces##1{% - \E\E\E\E\E\E\E\eatspaces\E\E\E\E\E\E\E{\eatleadingcr##1% - }}% - \def\xempty##1{}% + \def\xeatspaces##1{\eatleadingcrthen\eatspaces{##1}}% % % Process the macro body under the current catcode regime. \scantokens{#1@comment}% % % The \comment is to remove the \newlinechar added by \scantokens, and - % can be noticed by \parsearg. Note \c isn't used because this means cedilla + % can be noticed by \parsearg. Note \c isn't used because this means cedilla % in math mode. } @@ -8035,10 +8364,12 @@ \unbrace{\gdef\trim@@@ #1 } #2@{#1} } -{\catcode`\^^M=\other% -\gdef\eatleadingcr#1{\if\noexpand#1\noexpand^^M\else\E#1\fi}}% -% Warning: this won't work for a delimited argument -% or for an empty argument +% Trim a single leading ^^M off a string, then call #1 +{\catcode`\^^M=\active \catcode`\Q=3% +\gdef\eatleadingcrthen #1#2{\eatlcra #1Q#2Q^^MQ}% +\gdef\eatlcra #1#2Q^^M{\eatlcrb #1#2Q}% +\gdef\eatlcrb #1Q#2Q#3Q{#1{#2}}% +} % Trim a single trailing ^^M off a string. {\catcode`\^^M=\other \catcode`\Q=3% @@ -8069,24 +8400,17 @@ \catcode`\_=\other \catcode`\|=\other \catcode`\~=\other - \passthroughcharstrue -} - -\def\scanargctxt{% used for copying and captions, not macros. - \scanctxt \catcode`\@=\other - \catcode`\\=\other \catcode`\^^M=\other + \catcode`\\=\active + \passthroughcharstrue } -\def\macrobodyctxt{% used for @macro definitions +\def\macrobodyctxt{% used for @macro definitions and @copying \scanctxt \catcode`\ =\other - \catcode`\@=\other \catcode`\{=\other \catcode`\}=\other - \catcode`\^^M=\other - \usembodybackslash } % Used when scanning braced macro arguments. Note, however, that catcode @@ -8095,14 +8419,10 @@ \def\macroargctxt{% \scanctxt \catcode`\ =\active - \catcode`\@=\other - \catcode`\^^M=\other - \catcode`\\=\active } \def\macrolineargctxt{% used for whole-line arguments without braces \scanctxt - \catcode`\@=\other \catcode`\{=\other \catcode`\}=\other } @@ -8146,7 +8466,7 @@ \global\expandafter\let\csname ismacro.\the\macname\endcsname=1% \addtomacrolist{\the\macname}% \fi - \begingroup \macrobodyctxt + \begingroup \macrobodyctxt \usembodybackslash \ifrecursive \expandafter\parsermacbody \else \expandafter\parsemacbody \fi} @@ -8161,8 +8481,6 @@ \let\commondummyword\unmacrodo \xdef\macrolist{\macrolist}% \endgroup - \else - \errmessage{Macro #1 not defined}% \fi } @@ -8187,6 +8505,10 @@ % is #, then the preceding argument is delimited by % an opening brace, and that opening brace is not consumed. +% Make @ a letter, so that we can make private-to-Texinfo macro names. +\edef\texiatcatcode{\the\catcode`\@} +\catcode `@=11\relax + % Parse the optional {params} list to @macro or @rmacro. % Set \paramno to the number of arguments, % and \paramlist to a parameter text for the macro (e.g. #1,#2,#3 for a @@ -8194,19 +8516,18 @@ % list to some hook where the argument is to be expanded. If there are % less than 10 arguments that hook is to be replaced by ##N where N % is the position in that list, that is to say the macro arguments are to be -% defined `a la TeX in the macro body. +% defined `a la TeX in the macro body. % % That gets used by \mbodybackslash (above). % % If there are 10 or more arguments, a different technique is used: see -% \parsemmanyargdef. +% \parsemmanyargdef@@. % \def\parsemargdef#1;{% \paramno=0\def\paramlist{}% \let\hash\relax % \hash is redefined to `#' later to get it into definitions \let\xeatspaces\relax - \let\xempty\relax \parsemargdefxxx#1,;,% \ifnum\paramno<10\relax\else \paramno0\relax @@ -8218,29 +8539,25 @@ \else \let\next=\parsemargdefxxx \advance\paramno by 1 \expandafter\edef\csname macarg.\eatspaces{#1}\endcsname - {\xeatspaces{\hash\the\paramno\noexpand\xempty{}}}% + {\xeatspaces{\hash\the\paramno}}% \edef\paramlist{\paramlist\hash\the\paramno,}% \fi\next} -% the \xempty{} is to give \eatleadingcr an argument in the case of an -% empty macro argument. % \parsemacbody, \parsermacbody % % Read recursive and nonrecursive macro bodies. (They're different since % rec and nonrec macros end differently.) -% -% We are in \macrobodyctxt, and the \xdef causes backslashshes in the macro +% +% We are in \macrobodyctxt, and the \xdef causes backslashes in the macro % body to be transformed. -% Set \macrobody to the body of the macro, and call \defmacro. +% Set \macrobody to the body of the macro, and call \macrodef. % +\catcode `\@\texiatcatcode {\catcode`\ =\other\long\gdef\parsemacbody#1@end macro{% -\xdef\macrobody{\eatcr{#1}}\endgroup\defmacro}}% +\xdef\macrobody{\eatcr{#1}}\endgroup\macrodef}}% {\catcode`\ =\other\long\gdef\parsermacbody#1@end rmacro{% -\xdef\macrobody{\eatcr{#1}}\endgroup\defmacro}}% - -% Make @ a letter, so that we can make private-to-Texinfo macro names. -\edef\texiatcatcode{\the\catcode`\@} -\catcode `@=11\relax +\xdef\macrobody{\eatcr{#1}}\endgroup\macrodef}}% +\catcode `\@=11\relax %%%%%%%%%%%%%% Code for > 10 arguments only %%%%%%%%%%%%%%%%%% @@ -8263,7 +8580,7 @@ % twice the \macarg.BLAH macros does not cost too much processing power. \def\parsemmanyargdef@@#1,{% \if#1;\let\next=\relax - \else + \else \let\next=\parsemmanyargdef@@ \edef\tempb{\eatspaces{#1}}% \expandafter\def\expandafter\tempa @@ -8348,7 +8665,7 @@ % Replace arguments by their values in the macro body, and place the result % in macro \@tempa. -% +% \def\macvalstoargs@{% % To do this we use the property that token registers that are \the'ed % within an \edef expand only once. So we are going to place all argument @@ -8372,9 +8689,9 @@ \expandafter\def\expandafter\@tempa\expandafter{\@tempc}% } -% Define the named-macro outside of this group and then close this group. -% -\def\macargexpandinbody@{% +% Define the named-macro outside of this group and then close this group. +% +\def\macargexpandinbody@{% \expandafter \endgroup \macargdeflist@ @@ -8412,7 +8729,7 @@ } % Trailing missing arguments are set to empty. -% +% \def\setemptyargvalues@{% \ifx\paramlist\nilm@ \let\next\macargexpandinbody@ @@ -8455,60 +8772,59 @@ % \xdef is used so that macro definitions will survive the file % they're defined in: @include reads the file inside a group. % -\def\defmacro{% +\def\macrodef{% \let\hash=##% convert placeholders to macro parameter chars \ifnum\paramno=1 - \def\xeatspaces##1{##1}% - % This removes the pair of braces around the argument. We don't - % use \eatspaces, because this can cause ends of lines to be lost - % when the argument to \eatspaces is read, leading to line-based - % commands like "@itemize" not being read correctly. + \long\def\xeatspaces##1{##1}% + % We don't use \xeatspaces for single-argument macros, because we + % want to keep ends of lines. This definition removes \xeatspaces + % when \macrobody is expanded below. \else - \let\xeatspaces\relax % suppress expansion + \def\xeatspaces{\string\xeatspaces}% + % This expands \xeatspaces as a sequence of character tokens, which + % stops \scantokens inserting an extra space after the control sequence. \fi \ifcase\paramno % 0 \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup + \begingroup \noexpand\spaceisspace - \noexpand\endlineisspace + \noexpand\ignoreactivenewline \noexpand\expandafter % skip any whitespace after the macro name. \expandafter\noexpand\csname\the\macname @@@\endcsname}% \expandafter\xdef\csname\the\macname @@@\endcsname{% - \egroup + \endgroup \noexpand\scanmacro{\macrobody}}% \or % 1 \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup + \begingroup \noexpand\braceorline \expandafter\noexpand\csname\the\macname @@@\endcsname}% \expandafter\xdef\csname\the\macname @@@\endcsname##1{% - \egroup + \endgroup \noexpand\scanmacro{\macrobody}% }% \else % at most 9 \ifnum\paramno<10\relax % @MACNAME sets the context for reading the macro argument - % @MACNAME@@ gets the argument, processes backslashes and appends a + % @MACNAME@@ gets the argument, processes backslashes and appends a % comma. % @MACNAME@@@ removes braces surrounding the argument list. % @MACNAME@@@@ scans the macro body with arguments substituted. \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup + \begingroup \noexpand\expandafter % This \expandafter skip any spaces after the \noexpand\macroargctxt % macro before we change the catcode of space. \noexpand\expandafter \expandafter\noexpand\csname\the\macname @@\endcsname}% \expandafter\xdef\csname\the\macname @@\endcsname##1{% - \noexpand\passargtomacro - \expandafter\noexpand\csname\the\macname @@@\endcsname{##1,}}% + \noexpand\passargtomacro + \expandafter\noexpand\csname\the\macname @@@\endcsname{##1,}}% \expandafter\xdef\csname\the\macname @@@\endcsname##1{% - \expandafter\noexpand\csname\the\macname @@@@\endcsname ##1}% - \expandafter\expandafter - \expandafter\xdef - \expandafter\expandafter - \csname\the\macname @@@@\endcsname\paramlist{% - \egroup\noexpand\scanmacro{\macrobody}}% + \expandafter\noexpand\csname\the\macname @@@@\endcsname ##1}% + \expandaftergroup{\expandafter\xdef\csname\the\macname @@@@\endcsname}% + \paramlist{% + \endgroup\noexpand\scanmacro{\macrobody}}% \else % 10 or more: \expandafter\xdef\csname\the\macname\endcsname{% \noexpand\getargvals@{\the\macname}{\argl}% @@ -8520,6 +8836,16 @@ \catcode `\@\texiatcatcode\relax % end private-to-Texinfo catcodes +% utility definition to avoid excessive use of \expandafter. call +% as \expandaftergroup{CONTENT}\WORD to expand \WORD exactly once and remove +% braces around CONTENT. +\def\expandaftergroup#1#2{% + \expandafter\expandaftergroupx\expandafter{#2}{#1}% +} +\def\expandaftergroupx#1#2{% + #2#1% +} + \def\norecurse#1{\bgroup\cslet{#1}{macsave.#1}} @@ -8533,11 +8859,11 @@ % Call #1 with a list of tokens #2, with any doubled backslashes in #2 % compressed to one. % -% This implementation works by expansion, and not execution (so we cannot use -% \def or similar). This reduces the risk of this failing in contexts where -% complete expansion is done with no execution (for example, in writing out to +% This implementation works by expansion, and not execution (so we cannot use +% \def or similar). This reduces the risk of this failing in contexts where +% complete expansion is done with no execution (for example, in writing out to % an auxiliary file for an index entry). -% +% % State is kept in the input stream: the argument passed to % @look_ahead, @gobble_and_check_finish and @add_segment is % @@ -8559,11 +8885,11 @@ % #3 - NEXT_TOKEN % #4 used to look ahead % -% If the next token is not a backslash, process the rest of the argument; +% If the next token is not a backslash, process the rest of the argument; % otherwise, remove the next token. @gdef@look_ahead#1!#2#3#4{% @ifx#4\% - @expandafter@gobble_and_check_finish + @expandafter@gobble_and_check_finish @else @expandafter@add_segment @fi#1!{#2}#4#4% @@ -8587,9 +8913,9 @@ % #3 - NEXT_TOKEN % #4 is input stream until next backslash % -% Input stream is either at the start of the argument, or just after a -% backslash sequence, either a lone backslash, or a doubled backslash. -% NEXT_TOKEN contains the first token in the input stream: if it is \finish, +% Input stream is either at the start of the argument, or just after a +% backslash sequence, either a lone backslash, or a doubled backslash. +% NEXT_TOKEN contains the first token in the input stream: if it is \finish, % finish; otherwise, append to ARG_RESULT the segment of the argument up until % the next backslash. PENDING_BACKSLASH contains a backslash to represent % a backslash just before the start of the input stream that has not been @@ -8601,13 +8927,13 @@ % append the pending backslash to the result, followed by the next segment @expandafter@is_fi@look_ahead#1#2#4!{\}@fi % this @fi is discarded by @look_ahead. - % we can't get rid of it with \expandafter because we don't know how + % we can't get rid of it with \expandafter because we don't know how % long #4 is. } % #1 - THE_MACRO % #2 - ARG_RESULT -% #3 discards the res of the conditional in @add_segment, and @is_fi ends the +% #3 discards the res of the conditional in @add_segment, and @is_fi ends the % conditional. @gdef@call_the_macro#1#2!#3@fi{@is_fi #1{#2}} @@ -8619,7 +8945,7 @@ % for reading the argument (slightly different in the two cases). Then, % to read the argument, in the whole-line case, it then calls the regular % \parsearg MAC; in the lbrace case, it calls \passargtomacro MAC. -% +% \def\braceorline#1{\let\macnamexxx=#1\futurelet\nchar\braceorlinexxx} \def\braceorlinexxx{% \ifx\nchar\bgroup @@ -8630,6 +8956,74 @@ \fi \macnamexxx} +% @linemacro + +\parseargdef\linemacro{% + \getargs{#1}% now \macname is the macname and \argl the arglist + \ifx\argl\empty + \paramno=0 + \let\hash\relax + \def\paramlist{\hash 1\endlinemacro}% + \else + \expandafter\linegetparamlist\argl;% + \fi + \begingroup \macrobodyctxt \usembodybackslash + \parselinemacrobody +} + +% Build up \paramlist which will be used as the parameter text for the macro. +% At the end it will be like "#1 #2 #3\endlinemacro". +\def\linegetparamlist#1;{% + \paramno=0\def\paramlist{}% + \let\hash\relax + \linegetparamlistxxx#1,;,% +} +\def\linegetparamlistxxx#1,{% + \if#1;\let\next=\linegetparamlistxxxx + \else \let\next=\linegetparamlistxxx + \advance\paramno by 1 + \expandafter\edef\csname macarg.\eatspaces{#1}\endcsname + {\hash\the\paramno}% + \edef\paramlist{\paramlist\hash\the\paramno\space}% + \fi\next} +\def\linegetparamlistxxxx{% + \expandafter\fixparamlist\paramlist\fixparamlist +} +% Replace final space token +\def\fixparamlist#1 \fixparamlist{% + \def\paramlist{#1\endlinemacro}% +} + +% Read the body of the macro, replacing backslash-surrounded variables +% +{\catcode`\ =\other\long\gdef\parselinemacrobody#1@end linemacro{% +\xdef\macrobody{#1}% +\endgroup +\linemacrodef +}} + +% Make the definition +\def\linemacrodef{% + \let\hash=##% + \expandafter\xdef\csname\the\macname\endcsname{% + \bgroup + \noexpand\parsearg + \expandafter\noexpand\csname\the\macname @@\endcsname + } + \expandafter\xdef\csname\the\macname @@\endcsname##1{% + \egroup + \expandafter\noexpand + \csname\the\macname @@@\endcsname##1\noexpand\endlinemacro + } + \expandaftergroup{\expandafter\xdef\csname\the\macname @@@\endcsname}% + \paramlist{% + \newlinechar=13 % split \macrobody into lines + \noexpand\scantokens{\macrobody}% + } +} + + + % @alias. % We need some trickery to remove the optional spaces around the equal % sign. Make them active and then expand them all to nothing. @@ -8673,7 +9067,7 @@ % Used so that the @top node doesn't have to be wrapped in an @ifnottex % conditional. -% \doignore goes to more effort to skip nested conditionals but we don't need +% \doignore goes to more effort to skip nested conditionals but we don't need % that here. \def\omittopnode{% \ifx\lastnode\wordTop @@ -8681,9 +9075,11 @@ } \def\wordTop{Top} -% Until the next @node or @bye command, divert output to a box that is not -% output. -\def\ignorenode{\setbox\dummybox\vbox\bgroup\def\node{\egroup\node}% +% Until the next @node, @part or @bye command, divert output to a box that +% is not output. +\def\ignorenode{\setbox\dummybox\vbox\bgroup +\def\part{\egroup\part}% +\def\node{\egroup\node}% \ignorenodebye } @@ -8695,14 +9091,24 @@ \let\lastnode=\empty % Write a cross-reference definition for the current node. #1 is the -% type (Ynumbered, Yappendix, Ynothing). +% type (Ynumbered, Yappendix, Ynothing). #2 is the section title. % -\def\donoderef#1{% +\def\donoderef#1#2{% \ifx\lastnode\empty\else - \setref{\lastnode}{#1}% + \setref{\lastnode}{#1}{#2}% \global\let\lastnode=\empty + \setnodeseenonce \fi } +\def\setnodeseenonce{ + \global\nodeseentrue + \let\setnodeseenonce\relax +} + +% @nodedescription, @nodedescriptionblock - do nothing for TeX +\parseargdef\nodedescription{} +\def\nodedescriptionblock{\doignore{nodedescriptionblock}} + % @anchor{NAME} -- define xref target at arbitrary point. % @@ -8710,21 +9116,28 @@ % \def\savesf{\relax \ifhmode \savesfregister=\spacefactor \fi} \def\restoresf{\relax \ifhmode \spacefactor=\savesfregister \fi} -\def\anchor#1{\savesf \setref{#1}{Ynothing}\restoresf \ignorespaces} - -% \setref{NAME}{SNT} defines a cross-reference point NAME (a node or an -% anchor), which consists of three parts: -% 1) NAME-title - the current sectioning name taken from \currentsection, -% or the anchor name. -% 2) NAME-snt - section number and type, passed as the SNT arg, or -% empty for anchors. +\def\anchor#1{% + \savesf \setref{#1}{Yanchor}{#1}\restoresf \ignorespaces +} + +% @namedanchor{NAME, XREFNAME} -- define xref target at arbitrary point +% with label text for cross-references to it. +\def\namedanchor#1{\donamedanchor#1\finish}% +\def\donamedanchor#1,#2\finish{% + \savesf \setref{#1}{Yanchor}{\ignorespaces #2\unskip}\restoresf \ignorespaces +} + +% \setref{NAME}{SNT}{TITLE} defines a cross-reference point NAME (a node +% or an anchor), which consists of three parts: +% 1) NAME-title - the current sectioning name +% 2) NAME-snt - section number and type, passed as the SNT arg. % 3) NAME-pg - the page number. % % This is called from \donoderef, \anchor, and \dofloat. In the case of % floats, there is an additional part, which is not written here: % 4) NAME-lof - the text as it should appear in a @listoffloats. % -\def\setref#1#2{% +\def\setref#1#2#3{% \pdfmkdest{#1}% \iflinks {% @@ -8736,7 +9149,7 @@ \write\auxfile{@xrdef{#1-% #1 of \setref, expanded by the \edef ##1}{##2}}% these are parameters of \writexrdef }% - \toks0 = \expandafter{\currentsection}% + \toks0 = {#3}% \immediate \writexrdef{title}{\the\toks0 }% \immediate \writexrdef{snt}{\csname #2\endcsname}% \Ynumbered etc. \safewhatsit{\writexrdef{pg}{\folio}}% will be written later, at \shipout @@ -8748,7 +9161,7 @@ % automatically in xrefs, if the third arg is not explicitly specified. % This was provided as a "secret" @set xref-automatic-section-title % variable, now it's official. -% +% \parseargdef\xrefautomaticsectiontitle{% \def\temp{#1}% \ifx\temp\onword @@ -8764,7 +9177,7 @@ \fi\fi } -% +% % @xref, @pxref, and @ref generate cross-references. For \xrefX, #1 is % the node name, #2 the name of the Info cross-reference, #3 the printed % node name, #4 the name of the Info file, #5 the name of the printed @@ -8785,118 +9198,12 @@ \def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup \unsepspaces % - % Get args without leading/trailing spaces. - \def\printedrefname{\ignorespaces #3}% - \setbox\printedrefnamebox = \hbox{\printedrefname\unskip}% - % + \getprintedrefname{#1}{#3}{#5}% \def\infofilename{\ignorespaces #4}% \setbox\infofilenamebox = \hbox{\infofilename\unskip}% % - \def\printedmanual{\ignorespaces #5}% - \setbox\printedmanualbox = \hbox{\printedmanual\unskip}% - % - % If the printed reference name (arg #3) was not explicitly given in - % the @xref, figure out what we want to use. - \ifdim \wd\printedrefnamebox = 0pt - % No printed node name was explicitly given. - \expandafter\ifx\csname SETxref-automatic-section-title\endcsname \relax - % Not auto section-title: use node name inside the square brackets. - \def\printedrefname{\ignorespaces #1}% - \else - % Auto section-title: use chapter/section title inside - % the square brackets if we have it. - \ifdim \wd\printedmanualbox > 0pt - % It is in another manual, so we don't have it; use node name. - \def\printedrefname{\ignorespaces #1}% - \else - \ifhavexrefs - % We (should) know the real title if we have the xref values. - \def\printedrefname{\refx{#1-title}}% - \else - % Otherwise just copy the Info node name. - \def\printedrefname{\ignorespaces #1}% - \fi% - \fi - \fi - \fi - % - % Make link in pdf output. - \ifpdf - % For pdfTeX and LuaTeX - {\indexnofonts - \makevalueexpandable - \turnoffactive - % This expands tokens, so do it after making catcode changes, so _ - % etc. don't get their TeX definitions. This ignores all spaces in - % #4, including (wrongly) those in the middle of the filename. - \getfilename{#4}% - % - % This (wrongly) does not take account of leading or trailing - % spaces in #1, which should be ignored. - \setpdfdestname{#1}% - % - \ifx\pdfdestname\empty - \def\pdfdestname{Top}% no empty targets - \fi - % - \leavevmode - \startlink attr{/Border [0 0 0]}% - \ifnum\filenamelength>0 - goto file{\the\filename.pdf} name{\pdfdestname}% - \else - goto name{\pdfmkpgn{\pdfdestname}}% - \fi - }% - \setcolor{\linkcolor}% - \else - \ifx\XeTeXrevision\thisisundefined - \else - % For XeTeX - {\indexnofonts - \makevalueexpandable - \turnoffactive - % This expands tokens, so do it after making catcode changes, so _ - % etc. don't get their TeX definitions. This ignores all spaces in - % #4, including (wrongly) those in the middle of the filename. - \getfilename{#4}% - % - % This (wrongly) does not take account of leading or trailing - % spaces in #1, which should be ignored. - \setpdfdestname{#1}% - % - \ifx\pdfdestname\empty - \def\pdfdestname{Top}% no empty targets - \fi - % - \leavevmode - \ifnum\filenamelength>0 - % With default settings, - % XeTeX (xdvipdfmx) replaces link destination names with integers. - % In this case, the replaced destination names of - % remote PDFs are no longer known. In order to avoid a replacement, - % you can use xdvipdfmx's command line option `-C 0x0010'. - % If you use XeTeX 0.99996+ (TeX Live 2016+), - % this command line option is no longer necessary - % because we can use the `dvipdfmx:config' special. - \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A - << /S /GoToR /F (\the\filename.pdf) /D (\pdfdestname) >> >>}% - \else - \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A - << /S /GoTo /D (\pdfdestname) >> >>}% - \fi - }% - \setcolor{\linkcolor}% - \fi - \fi - {% - % Have to otherify everything special to allow the \csname to - % include an _ in the xref name, etc. - \indexnofonts - \turnoffactive - \def\value##1{##1}% - \expandafter\global\expandafter\let\expandafter\Xthisreftitle - \csname XR#1-title\endcsname - }% + \startxreflink{#1}{#4}% + \getrefx{#1-title}\Xthisreftitle % % Float references are printed completely differently: "Figure 1.2" % instead of "[somenode], p.3". \iffloat distinguishes them by @@ -8929,31 +9236,32 @@ % Cross-manual reference with a printed manual name. % \crossmanualxref{\cite{\printedmanual\unskip}}% - % \else\ifdim \wd\infofilenamebox > 0pt % Cross-manual reference with only an info filename (arg 4), no % printed manual name (arg 5). This is essentially the same as % the case above; we output the filename, since we have nothing else. % \crossmanualxref{\code{\infofilename\unskip}}% - % \else % Reference within this manual. % - % Only output a following space if the -snt ref is nonempty, as the ref - % will be empty for @unnumbered and @anchor. - \setbox2 = \hbox{\ignorespaces \refx{#1-snt}}% - \ifdim \wd2 > 0pt \refx{#1-snt}\space\fi + % Only output a following space if the -snt ref is nonempty, as is + % the case for @unnumbered and @anchor. + \getrefx{#1-snt}\tmp + \ifx\tmp\empty\else + \ifx\tmp\Yanchor\else + \tmp\space + \fi + \fi % % output the `[mynode]' via the macro below so it can be overridden. \xrefprintnodename\printedrefname % - \expandafter\ifx\csname SETtxiomitxrefpg\endcsname\relax - % But we always want a comma and a space: - ,\space - % + \ifflagclear{txiomitxrefpg}{% + % We always want a comma + ,% % output the `page 3'. - \turnoffactive \putwordpage\tie\refx{#1-pg}% + \turnoffactive \putpageref{#1}% % Add a , if xref followed by a space \if\space\noexpand\tokenafterxref ,% \else\ifx\ \tokenafterxref ,% @TAB @@ -8963,27 +9271,118 @@ \tokenafterxref ,% @NL \else\ifx\tie\tokenafterxref ,% @tie \fi\fi\fi\fi\fi\fi - \fi + }{}% \fi\fi \fi - \endlink -\endgroup} + \endlink +\endgroup} + +% \getprintedrefname{NODE}{LABEL}{MANUAL} +% - set \printedrefname and \printedmanual +% +\def\getprintedrefname#1#2#3{% + % Get args without leading/trailing spaces. + \def\printedrefname{\ignorespaces #2}% + \setbox\printedrefnamebox = \hbox{\printedrefname\unskip}% + % + \def\printedmanual{\ignorespaces #3}% + \setbox\printedmanualbox = \hbox{\printedmanual\unskip}% + % + % If the printed reference name (arg #2) was not explicitly given in + % the @xref, figure out what we want to use. + \ifdim \wd\printedrefnamebox = 0pt + % No printed node name was explicitly given. + \expandafter\ifx\csname SETxref-automatic-section-title\endcsname \relax + % Not auto section-title: use node name inside the square brackets. + \def\printedrefname{\ignorespaces #1}% + \else + % Auto section-title: use chapter/section title inside + % the square brackets if we have it. + \ifdim \wd\printedmanualbox > 0pt + % It is in another manual, so we don't have it; use node name. + \def\printedrefname{\ignorespaces #1}% + \else + \ifhavexrefs + % We (should) know the real title if we have the xref values. + \def\printedrefname{\refx{#1-title}}% + \else + % Otherwise just copy the Info node name. + \def\printedrefname{\ignorespaces #1}% + \fi + \fi + \fi + \fi +} + +% \startxreflink{NODE}{FILE} - start link in pdf output. +\def\startxreflink#1#2{% + \ifpdforxetex + % For pdfTeX and LuaTeX + {\indexnofonts + \makevalueexpandable + \turnoffactive + % This expands tokens, so do it after making catcode changes, so _ + % etc. don't get their TeX definitions. This ignores all spaces in + % #2, including (wrongly) those in the middle of the filename. + \getfilename{#2}% + % + % This (wrongly) does not take account of leading or trailing + % spaces in #1, which should be ignored. + \setpdfdestname{#1}% + % + \ifx\pdfdestname\empty + \def\pdfdestname{Top}% no empty targets + \fi + % + \leavevmode + \ifpdf + \startlink attr{/Border [0 0 0]}% + \ifnum\filenamelength>0 + goto file{\the\filename.pdf} name{\pdfdestname}% + \else + goto name{\pdfdestname}% + \fi + \else % XeTeX + \ifnum\filenamelength>0 + % With default settings, + % XeTeX (xdvipdfmx) replaces link destination names with integers. + % In this case, the replaced destination names of + % remote PDFs are no longer known. In order to avoid a replacement, + % you can use xdvipdfmx's command line option `-C 0x0010'. + % If you use XeTeX 0.99996+ (TeX Live 2016+), + % this command line option is no longer necessary + % because we can use the `dvipdfmx:config' special. + \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A + << /S /GoToR /F (\the\filename.pdf) /D (\pdfdestname) >> >>}% + \else + \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A + << /S /GoTo /D (\pdfdestname) >> >>}% + \fi + \fi + }% + \setcolor{\linkcolor}% + \fi +} + +% can be overridden in translation files +\def\putpageref#1{% + \space\putwordpage\tie\refx{#1-pg}} % Output a cross-manual xref to #1. Used just above (twice). -% +% % Only include the text "Section ``foo'' in" if the foo is neither % missing or Top. Thus, @xref{,,,foo,The Foo Manual} outputs simply % "see The Foo Manual", the idea being to refer to the whole manual. -% +% % But, this being TeX, we can't easily compare our node name against the % string "Top" while ignoring the possible spaces before and after in % the input. By adding the arbitrary 7sp below, we make it much less % likely that a real node name would have the same width as "Top" (e.g., % in a monospaced font). Hopefully it will never happen in practice. -% +% % For the same basic reason, we retypeset the "Top" at every % reference, since the current font is indeterminate. -% +% \def\crossmanualxref#1{% \setbox\toprefbox = \hbox{Top\kern7sp}% \setbox2 = \hbox{\ignorespaces \printedrefname \unskip \kern7sp}% @@ -9002,10 +9401,26 @@ % \def\xrefprintnodename#1{[#1]} +% @link{NODENAME, LABEL, MANUAL} - create a "plain" link, with no +% page number. Not useful if printed on paper. +% +\def\link#1{\linkX[#1,,,]} +\def\linkX[#1,#2,#3,#4]{% + \begingroup + \unsepspaces + \getprintedrefname{#1}{#2}{#3}% + \startxreflink{#1}{#3}% + \printedrefname + \endlink + \endgroup +} + + % Things referred to by \setref. % \def\Ynothing{} \def\Yomitfromtoc{} +\def\Yanchor{\isanchor} \let\isanchor\relax \def\Ynumbered{% \ifnum\secno=0 \putwordChapter@tie \the\chapno @@ -9032,14 +9447,7 @@ % \refx{NAME} - reference a cross-reference string named NAME. \def\refx#1{% - \requireauxfile - {% - \indexnofonts - \turnoffactive - \def\value##1{##1}% - \expandafter\global\expandafter\let\expandafter\thisrefX - \csname XR#1\endcsname - }% + \getrefx{#1}\thisrefX \ifx\thisrefX\relax % If not defined, say something at least. \angleleft un\-de\-fined\angleright @@ -9060,9 +9468,20 @@ \fi } -% This is the macro invoked by entries in the aux file. Define a control -% sequence for a cross-reference target (we prepend XR to the control sequence -% name to avoid collisions). The value is the page number. If this is a float +% Set #2 to xref string #1 +\def\getrefx#1#2{% + \requireauxfile + {% + \indexnofonts + \turnoffactive + \def\value##1{##1}% + \expandafter\global\expandafter\let\expandafter#2\csname XR#1\endcsname + }% +} + +% This is the macro invoked by entries in the aux file. Define a control +% sequence for a cross-reference target (we prepend XR to the control sequence +% name to avoid collisions). The value is the page number. If this is a float % type, we have more work to do. % \def\xrdef#1#2{% @@ -9078,10 +9497,10 @@ \bgroup \expandafter\gdef\csname XR\safexrefname\endcsname{#2}% \egroup - % We put the \gdef inside a group to avoid the definitions building up on - % TeX's save stack, which can cause it to run out of space for aux files with + % We put the \gdef inside a group to avoid the definitions building up on + % TeX's save stack, which can cause it to run out of space for aux files with % thousands of lines. \gdef doesn't use the save stack, but \csname does - % when it defines an unknown control sequence as \relax. + % when it defines an unknown control sequence as \relax. % % Was that xref control sequence that we just defined for a float? \expandafter\iffloat\csname XR\safexrefname\endcsname @@ -9102,6 +9521,7 @@ \expandafter\xdef\csname floatlist\iffloattype\endcsname{\the\toks0 {\safexrefname}}% \fi + \ignorespaces % ignore ends of line in aux file } % If working on a large document in chapters, it is convenient to @@ -9124,12 +9544,14 @@ % Read the last existing aux file, if any. No error if none exists. % \def\tryauxfile{% + \ifxetex\xetexpreauxfile\fi \openin 1 \jobname.aux \ifeof 1 \else \readdatafile{aux}% \global\havexrefstrue \fi \closein 1 + \ifxetex\xetexpostauxfile\fi } \def\setupdatafile{% @@ -9212,7 +9634,10 @@ % Auto-number footnotes. Otherwise like plain. \gdef\footnote{% \global\advance\footnoteno by \@ne - \edef\thisfootno{$^{\the\footnoteno}$}% + % + % Output for the footnote marker. If we are immediately after another + % footnote, output a comma and small space first. + \edef\thisfootno{$^{\ifnum\lastpenalty=3 ,\mskip 1mu \fi\the\footnoteno}$}% % % In case the footnote comes at the end of a sentence, preserve the % extra spacing after we do the footnote number. @@ -9221,19 +9646,25 @@ % % Remove inadvertent blank space before typesetting the footnote number. \unskip - \thisfootno\@sf + % + % \scriptspace is 0.5pt by default and gives excessive space before the + % comma if we have multiple footnote markers in a row. + \bgroup\scriptspace=0pt + \thisfootno\@sf + \egroup \dofootnote }% -% Don't bother with the trickery in plain.tex to not require the -% footnote text as a parameter. Our footnotes don't need to be so general. -% -% Oh yes, they do; otherwise, @ifset (and anything else that uses -% \parseargline) fails inside footnotes because the tokens are fixed when -% the footnote is read. --karl, 16nov96. +% marker for immediately after a footnote marker +\gdef\footnoteendmarker{\penalty3 } + +% Do not require the footnote text as a parameter; otherwise, @ifset +% (and anything else that uses \parseargline) fails inside footnotes +% because the tokens are fixed when the footnote is read. % \gdef\dofootnote{% \insert\footins\bgroup + \aftergroup\footnoteendmarker % % Nested footnotes are not supported in TeX, that would take a lot % more work. (\startsavinginserts does not suffice.) @@ -9264,14 +9695,14 @@ % Hang the footnote text off the number. Use \everypar in case the % footnote extends for more than one paragraph. \everypar = {\hang}% - \textindent{\thisfootno}% + \textindent{$^{\the\footnoteno}$}% % % Don't crash into the line above the footnote text. Since this % expands into a box, it must come within the paragraph, lest it % provide a place where TeX can split the footnote. \footstrut % - % Invoke rest of plain TeX footnote routine. + % Eat opening brace and invoke rest of plain TeX footnote routine. \futurelet\next\fo@t } }%end \catcode `\@=11 @@ -9380,6 +9811,12 @@ \imagexxx #1,,,,,\finish \fi } + +% Approximate height of a line in the standard text font. +\newdimen\capheight +\setbox0=\vbox{\tenrm H} +\capheight=\ht0 + % % Arguments to @image: % #1 is (mandatory) image filename; we tack on .eps extension. @@ -9392,39 +9829,39 @@ \catcode`\^^M = 5 % in case we're inside an example \normalturnoffactive % allow _ et al. in names \makevalueexpandable - % If the image is by itself, center it. \ifvmode \imagevmodetrue - \else \ifx\centersub\centerV - % for @center @image, we need a vbox so we can have our vertical space - \imagevmodetrue - \vbox\bgroup % vbox has better behavior than vtop herev - \fi\fi - % - \ifimagevmode - \nobreak\medskip + \medskip % Usually we'll have text after the image which will insert % \parskip glue, so insert it here too to equalize the space % above and below. - \nobreak\vskip\parskip - \nobreak + \vskip\parskip + % + % Place image in a \vtop for a top page margin that is (close to) correct, + % as \topskip glue is relative to the first baseline. + \vtop\bgroup \kern -\capheight \vskip-\parskip \fi % - % Leave vertical mode so that indentation from an enclosing - % environment such as @quotation is respected. - % However, if we're at the top level, we don't want the - % normal paragraph indentation. - % On the other hand, if we are in the case of @center @image, we don't - % want to start a paragraph, which will create a hsize-width box and - % eradicate the centering. - \ifx\centersub\centerV \else \imageindent \fi + \ifx\centersub\centerV + % For @center @image, enter vertical mode and add vertical space + % Enter an extra \parskip because @center doesn't add space itself. + \vbox\bgroup\vskip\parskip\medskip\vskip\parskip + \else + % Enter horizontal mode so that indentation from an enclosing + % environment such as @quotation is respected. + % However, if we're at the top level, we don't want the + % normal paragraph indentation. + \imageindent + \fi % % Output the image. \ifpdf % For pdfTeX and LuaTeX <= 0.80 \dopdfimage{#1}{#2}{#3}% \else - \ifx\XeTeXrevision\thisisundefined + \ifxetex + \doxeteximage{#1}{#2}{#3}% + \else % For epsf.tex % \epsfbox itself resets \epsf?size at each figure. \setbox0 = \hbox{\ignorespaces #2}% @@ -9432,16 +9869,17 @@ \setbox0 = \hbox{\ignorespaces #3}% \ifdim\wd0 > 0pt \epsfysize=#3\relax \fi \epsfbox{#1.eps}% - \else - % For XeTeX - \doxeteximage{#1}{#2}{#3}% \fi \fi % \ifimagevmode + \egroup \medskip % space after a standalone image \fi - \ifx\centersub\centerV \egroup \fi + \ifx\centersub\centerV % @center @image + \medskip + \egroup % close \vbox + \fi \endgroup} @@ -9508,14 +9946,15 @@ \global\advance\floatno by 1 % {% - % This magic value for \currentsection is output by \setref as the - % XREFLABEL-title value. \xrefX uses it to distinguish float + % This magic value for the third argument of \setref is output as + % the XREFLABEL-title value. \xrefX uses it to distinguish float % labels (which have a completely different output format) from % node and anchor labels. And \xrdef uses it to construct the % lists of floats. % - \edef\currentsection{\floatmagic=\safefloattype}% - \setref{\floatlabel}{Yfloat}% + \edef\tmp{\noexpand\setref{\noexpand\floatlabel}{Yfloat}% + {\floatmagic=\safefloattype}}% + \tmp }% \fi % @@ -9608,8 +10047,8 @@ % \def\caption{\docaption\thiscaption} \def\shortcaption{\docaption\thisshortcaption} -\def\docaption{\checkenv\float \bgroup\scanargctxt\defcaption} -\def\defcaption#1#2{\egroup \def#1{#2}} +\def\docaption{\checkenv\float \bgroup\scanctxt\docaptionz} +\def\docaptionz#1#2{\egroup \def#1{#2}} % The parameter is the control sequence identifying the counter we are % going to use. Create it if it doesn't exist and assign it to \floatno. @@ -9637,7 +10076,7 @@ % #1 is the control sequence we are passed; we expand into a conditional % which is true if #1 represents a float ref. That is, the magic -% \currentsection value which we \setref above. +% value which we passed to \setref above. % \def\iffloat#1{\expandafter\doiffloat#1==\finish} % @@ -9694,6 +10133,7 @@ \toksA = \expandafter{\csname XR#1-lof\endcsname}% % % use the same \entry macro we use to generate the TOC and index. + \let\entry\entryinternal \edef\writeentry{\noexpand\entry{\the\toksA}{\csname XR#1-pg\endcsname}}% \writeentry }} @@ -9729,8 +10169,18 @@ \gdef\documentlanguagetrywithoutunderscore#1_#2\finish{% \openin 1 txi-#1.tex \ifeof 1 - \errhelp = \nolanghelp - \errmessage{Cannot read language file txi-#1.tex}% + \def\lang{#1}% + \def\enword{en}% + \ifx\lang\enword + % for English only, keep on going rather than issuing a fatal error + % message, as txi-en.tex likely doesn't contain any changes from the + % defaults. note that this is a problem if we already loaded another + % language file and want to switch back to English. + \message{Cannot read language file txi-#1.tex}% + \else + \errhelp = \nolanghelp + \errmessage{Cannot read language file txi-#1.tex}% + \fi \else \globaldefs = 1 % everything in the txi-LL files needs to persist \input txi-#1.tex @@ -9776,35 +10226,40 @@ \newif\iftxinativeunicodecapable \newif\iftxiusebytewiseio -\ifx\XeTeXrevision\thisisundefined - \ifx\luatexversion\thisisundefined - \txinativeunicodecapablefalse - \txiusebytewiseiotrue - \else +\ifxetex + \txinativeunicodecapabletrue + \txiusebytewiseiofalse +\else + \ifluatex \txinativeunicodecapabletrue \txiusebytewiseiofalse + \else + \txinativeunicodecapablefalse + \txiusebytewiseiotrue \fi -\else - \txinativeunicodecapabletrue - \txiusebytewiseiofalse \fi +\let\xetexpreauxfile\relax +\let\xetexpostauxfile\relax + % Set I/O by bytes instead of UTF-8 sequence for XeTeX and LuaTex % for non-UTF-8 (byte-wise) encodings. % \def\setbytewiseio{% - \ifx\XeTeXrevision\thisisundefined - \else - \XeTeXdefaultencoding "bytes" % For subsequent files to be read - \XeTeXinputencoding "bytes" % For document root file - % Unfortunately, there seems to be no corresponding XeTeX command for - % output encoding. This is a problem for auxiliary index and TOC files. - % The only solution would be perhaps to write out @U{...} sequences in - % place of non-ASCII characters. + \ifxetex + % For document root file + \XeTeXinputencoding "bytes" + % + % Setting for subsequent files to be read with @include. + \XeTeXdefaultencoding "bytes" + % + % Use UTF-8 for reading auxiliary index and TOC files, which are + % always output in UTF-8 with XeTeX. + \def\xetexpreauxfile{\XeTeXdefaultencoding "UTF-8"}% + \def\xetexpostauxfile{\XeTeXdefaultencoding "bytes"}% \fi - \ifx\luatexversion\thisisundefined - \else + \ifluatex \directlua{ local utf8_char, byte, gsub = unicode.utf8.char, string.byte, string.gsub local function convert_char (char) @@ -9898,12 +10353,10 @@ % For native Unicode handling (XeTeX and LuaTeX) \nativeunicodechardefs \else - % For treating UTF-8 as byte sequences (TeX, eTeX and pdfTeX) + % For treating UTF-8 as byte sequences (TeX, eTeX and pdfTeX). + % Since we already invoke \utfeightchardefs at the top level, + % making non-ascii chars active is sufficient. \setnonasciicharscatcode\active - % since we already invoked \utfeightchardefs at the top level - % (below), do not re-invoke it, otherwise our check for duplicated - % definitions gets triggered. Making non-ascii chars active is - % sufficient. \fi % \else @@ -9915,8 +10368,7 @@ \fi % lattwo \fi % ascii % - \ifx\XeTeXrevision\thisisundefined - \else + \ifxetex \ifx \declaredencoding \utfeight \else \ifx \declaredencoding \ascii @@ -9928,7 +10380,6 @@ \fi } -% emacs-page % A message to be logged when using a character that isn't available % the default font encoding (OT1). % @@ -9937,12 +10388,6 @@ % Take account of \c (plain) vs. \, (Texinfo) difference. \def\cedilla#1{\ifx\c\ptexc\c{#1}\else\,{#1}\fi} -% First, make active non-ASCII characters in order for them to be -% correctly categorized when TeX reads the replacement text of -% macros containing the character definitions. -\setnonasciicharscatcode\active -% - \def\gdefchar#1#2{% \gdef#1{% \ifpassthroughchars @@ -9952,8 +10397,14 @@ \fi }} +\begingroup + +% Make non-ASCII characters active for defining the character definition +% macros. +\setnonasciicharscatcode\active + % Latin1 (ISO-8859-1) character definitions. -\def\latonechardefs{% +\gdef\latonechardefs{% \gdefchar^^a0{\tie} \gdefchar^^a1{\exclamdown} \gdefchar^^a2{{\tcfont \char162}} % cent @@ -10058,7 +10509,7 @@ } % Latin9 (ISO-8859-15) encoding character definitions. -\def\latninechardefs{% +\gdef\latninechardefs{% % Encoding is almost identical to Latin1. \latonechardefs % @@ -10073,7 +10524,7 @@ } % Latin2 (ISO-8859-2) character definitions. -\def\lattwochardefs{% +\gdef\lattwochardefs{% \gdefchar^^a0{\tie} \gdefchar^^a1{\ogonek{A}} \gdefchar^^a2{\u{}} @@ -10091,7 +10542,7 @@ \gdefchar^^ae{\v Z} \gdefchar^^af{\dotaccent Z} % - \gdefchar^^b0{\textdegree{}} + \gdefchar^^b0{\textdegree} \gdefchar^^b1{\ogonek{a}} \gdefchar^^b2{\ogonek{ }} \gdefchar^^b3{\l} @@ -10177,6 +10628,8 @@ \gdefchar^^ff{\dotaccent{}} } +\endgroup % active chars + % UTF-8 character definitions. % % This code to support UTF-8 is based on LaTeX's utf8.def, with some @@ -10198,11 +10651,15 @@ \gdef\UTFviiiDefined#1{% \ifx #1\relax - \message{\linenumber Unicode char \string #1 not defined for Texinfo}% + \ifutfviiidefinedwarning + \message{\linenumber Unicode char \string #1 not defined for Texinfo}% + \fi \else \expandafter #1% \fi } +\newif\ifutfviiidefinedwarning +\utfviiidefinedwarningtrue % Give non-ASCII bytes the active definitions for processing UTF-8 sequences \begingroup @@ -10212,8 +10669,8 @@ % Loop from \countUTFx to \countUTFy, performing \UTFviiiTmp % substituting ~ and $ with a character token of that value. - \def\UTFviiiLoop{% - \global\catcode\countUTFx\active + \gdef\UTFviiiLoop{% + \catcode\countUTFx\active \uccode`\~\countUTFx \uccode`\$\countUTFx \uppercase\expandafter{\UTFviiiTmp}% @@ -10221,7 +10678,7 @@ \ifnum\countUTFx < \countUTFy \expandafter\UTFviiiLoop \fi} - + % % For bytes other than the first in a UTF-8 sequence. Not expected to % be expanded except when writing to auxiliary files. \countUTFx = "80 @@ -10255,6 +10712,16 @@ \else\expandafter\UTFviiiFourOctets\expandafter$\fi }}% \UTFviiiLoop + % + % for pdftex only, used to expand ASCII to UTF-16BE. + \gdef\asciitounicode{% + \countUTFx = "20 + \countUTFy = "80 + \def\UTFviiiTmp{% + \def~{\nullbyte $}}% + \UTFviiiLoop + } + {\catcode0=11 \gdef\nullbyte{^^00}}% \endgroup \def\globallet{\global\let} % save some \expandafter's below @@ -10271,7 +10738,7 @@ \uppercase{.} \endgroup \else - \errhelp = \EMsimple + \errhelp = \EMsimple \errmessage{Unicode character U+#1 not supported, sorry}% \fi \else @@ -10279,8 +10746,8 @@ \fi } -% These macros are used here to construct the name of a control -% sequence to be defined. +% These macros are used here to construct the names of macros +% that expand to the definitions for UTF-8 sequences. \def\UTFviiiTwoOctetsName#1#2{% \csname u8:#1\string #2\endcsname}% \def\UTFviiiThreeOctetsName#1#2#3{% @@ -10288,6 +10755,35 @@ \def\UTFviiiFourOctetsName#1#2#3#4{% \csname u8:#1\string #2\string #3\string #4\endcsname}% +% generate UTF-16 from codepoint +\def\utfsixteentotoks#1#2{% + \countUTFz = "#2\relax + \ifnum \countUTFz > 65535 + % doesn't work for codepoints > U+FFFF + % we don't define glyphs for any of these anyway, so it doesn't matter + #1={U+#2}% + \else + \countUTFx = \countUTFz + \divide\countUTFx by 256 + \countUTFy = \countUTFx + \multiply\countUTFx by 256 + \advance\countUTFz by -\countUTFx + \uccode`,=\countUTFy + \uccode`;=\countUTFz + \ifnum\countUTFy = 0 + \uppercase{#1={\nullbyte\string;}}% + \else\ifnum\countUTFz = 0 + \uppercase{#1={\string,\nullbyte}}% + \else + \uppercase{#1={\string,\string;}}% + \fi\fi + % NB \uppercase cannot insert a null byte + \fi +} + +\newif\ifutfbytespdf +\utfbytespdffalse + % For UTF-8 byte sequences (TeX, e-TeX and pdfTeX), % provide a definition macro to replace a Unicode character; % this gets used by the @U command @@ -10304,19 +10800,23 @@ \countUTFz = "#1\relax \begingroup \parseXMLCharref - - % Give \u8:... its definition. The sequence of seven \expandafter's - % expands after the \gdef three times, e.g. % + % Completely expand \UTFviiiTmp, which looks like: % 1. \UTFviiTwoOctetsName B1 B2 % 2. \csname u8:B1 \string B2 \endcsname % 3. \u8: B1 B2 (a single control sequence token) + \xdef\UTFviiiTmp{\UTFviiiTmp}% % - \expandafter\expandafter - \expandafter\expandafter - \expandafter\expandafter - \expandafter\gdef \UTFviiiTmp{#2}% - % + \ifpdf + \toksA={#2}% + \utfsixteentotoks\toksB{#1}% + \expandafter\xdef\UTFviiiTmp{% + \noexpand\ifutfbytespdf\noexpand\utfbytes{\the\toksB}% + \noexpand\else\the\toksA\noexpand\fi}% + \else + \expandafter\gdef\UTFviiiTmp{#2}% + \fi + % \expandafter\ifx\csname uni:#1\endcsname \relax \else \message{Internal error, already defined: #1}% \fi @@ -10325,12 +10825,13 @@ \expandafter\globallet\csname uni:#1\endcsname \UTFviiiTmp \endgroup} % - % Given the value in \countUTFz as a Unicode code point, set \UTFviiiTmp - % to the corresponding UTF-8 sequence. + % Given the value in \countUTFz as a Unicode code point, set + % \UTFviiiTmp to one of the \UTVviii*OctetsName macros followed by + % the corresponding UTF-8 sequence. \gdef\parseXMLCharref{% - \ifnum\countUTFz < "A0\relax + \ifnum\countUTFz < "20\relax \errhelp = \EMsimple - \errmessage{Cannot define Unicode char value < 00A0}% + \errmessage{Cannot define Unicode char value < 0020}% \else\ifnum\countUTFz < "800\relax \parseUTFviiiA,% \parseUTFviiiB C\UTFviiiTwoOctetsName.,% @@ -10355,7 +10856,7 @@ \divide\countUTFz by 64 \countUTFy = \countUTFz % Save to be the future value of \countUTFz. \multiply\countUTFz by 64 - + % \countUTFz is now \countUTFx with the last 5 bits cleared. Subtract % in order to get the last five bits. \advance\countUTFx by -\countUTFz @@ -10385,12 +10886,22 @@ \catcode"#1=\other } +% Suppress ligature creation from adjacent characters. +\ifluatex + % Braces do not suppress ligature creation in LuaTeX, e.g. in of{}fice + % to suppress the "ff" ligature. Using a kern appears to be the only + % workaround. + \def\nolig{\kern0pt{}} +\else + \def\nolig{{}} +\fi + % https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_M % U+0000..U+007F = https://en.wikipedia.org/wiki/Basic_Latin_(Unicode_block) % U+0080..U+00FF = https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block) % U+0100..U+017F = https://en.wikipedia.org/wiki/Latin_Extended-A % U+0180..U+024F = https://en.wikipedia.org/wiki/Latin_Extended-B -% +% % Many of our renditions are less than wonderful, and all the missing % characters are available somewhere. Loading the necessary fonts % awaits user request. We can't truly support Unicode without @@ -10400,6 +10911,103 @@ % least make most of the characters not bomb out. % \def\unicodechardefs{% + \DeclareUnicodeCharacter{0020}{ } % space + \DeclareUnicodeCharacter{0021}{\char"21 }% % space to terminate number + \DeclareUnicodeCharacter{0022}{\char"22 }% + \DeclareUnicodeCharacter{0023}{\char"23 }% + \DeclareUnicodeCharacter{0024}{\char"24 }% + \DeclareUnicodeCharacter{0025}{\char"25 }% + \DeclareUnicodeCharacter{0026}{\char"26 }% + \DeclareUnicodeCharacter{0027}{\char"27 }% + \DeclareUnicodeCharacter{0028}{\char"28 }% + \DeclareUnicodeCharacter{0029}{\char"29 }% + \DeclareUnicodeCharacter{002A}{\char"2A }% + \DeclareUnicodeCharacter{002B}{\char"2B }% + \DeclareUnicodeCharacter{002C}{\char"2C }% + \DeclareUnicodeCharacter{002D}{\char"2D }% + \DeclareUnicodeCharacter{002E}{\char"2E }% + \DeclareUnicodeCharacter{002F}{\char"2F }% + \DeclareUnicodeCharacter{0030}{0}% + \DeclareUnicodeCharacter{0031}{1}% + \DeclareUnicodeCharacter{0032}{2}% + \DeclareUnicodeCharacter{0033}{3}% + \DeclareUnicodeCharacter{0034}{4}% + \DeclareUnicodeCharacter{0035}{5}% + \DeclareUnicodeCharacter{0036}{6}% + \DeclareUnicodeCharacter{0037}{7}% + \DeclareUnicodeCharacter{0038}{8}% + \DeclareUnicodeCharacter{0039}{9}% + \DeclareUnicodeCharacter{003A}{\char"3A }% + \DeclareUnicodeCharacter{003B}{\char"3B }% + \DeclareUnicodeCharacter{003C}{\char"3C }% + \DeclareUnicodeCharacter{003D}{\char"3D }% + \DeclareUnicodeCharacter{003E}{\char"3E }% + \DeclareUnicodeCharacter{003F}{\char"3F }% + \DeclareUnicodeCharacter{0040}{\char"40 }% + \DeclareUnicodeCharacter{0041}{A}% + \DeclareUnicodeCharacter{0042}{B}% + \DeclareUnicodeCharacter{0043}{C}% + \DeclareUnicodeCharacter{0044}{D}% + \DeclareUnicodeCharacter{0045}{E}% + \DeclareUnicodeCharacter{0046}{F}% + \DeclareUnicodeCharacter{0047}{G}% + \DeclareUnicodeCharacter{0048}{H}% + \DeclareUnicodeCharacter{0049}{I}% + \DeclareUnicodeCharacter{004A}{J}% + \DeclareUnicodeCharacter{004B}{K}% + \DeclareUnicodeCharacter{004C}{L}% + \DeclareUnicodeCharacter{004D}{M}% + \DeclareUnicodeCharacter{004E}{N}% + \DeclareUnicodeCharacter{004F}{O}% + \DeclareUnicodeCharacter{0050}{P}% + \DeclareUnicodeCharacter{0051}{Q}% + \DeclareUnicodeCharacter{0052}{R}% + \DeclareUnicodeCharacter{0053}{S}% + \DeclareUnicodeCharacter{0054}{T}% + \DeclareUnicodeCharacter{0055}{U}% + \DeclareUnicodeCharacter{0056}{V}% + \DeclareUnicodeCharacter{0057}{W}% + \DeclareUnicodeCharacter{0058}{X}% + \DeclareUnicodeCharacter{0059}{Y}% + \DeclareUnicodeCharacter{005A}{Z}% + \DeclareUnicodeCharacter{005B}{\char"5B }% + \DeclareUnicodeCharacter{005C}{\char"5C }% + \DeclareUnicodeCharacter{005D}{\char"5D }% + \DeclareUnicodeCharacter{005E}{\char"5E }% + \DeclareUnicodeCharacter{005F}{\char"5F }% + \DeclareUnicodeCharacter{0060}{\char"60 }% + \DeclareUnicodeCharacter{0061}{a}% + \DeclareUnicodeCharacter{0062}{b}% + \DeclareUnicodeCharacter{0063}{c}% + \DeclareUnicodeCharacter{0064}{d}% + \DeclareUnicodeCharacter{0065}{e}% + \DeclareUnicodeCharacter{0066}{f}% + \DeclareUnicodeCharacter{0067}{g}% + \DeclareUnicodeCharacter{0068}{h}% + \DeclareUnicodeCharacter{0069}{i}% + \DeclareUnicodeCharacter{006A}{j}% + \DeclareUnicodeCharacter{006B}{k}% + \DeclareUnicodeCharacter{006C}{l}% + \DeclareUnicodeCharacter{006D}{m}% + \DeclareUnicodeCharacter{006E}{n}% + \DeclareUnicodeCharacter{006F}{o}% + \DeclareUnicodeCharacter{0070}{p}% + \DeclareUnicodeCharacter{0071}{q}% + \DeclareUnicodeCharacter{0072}{r}% + \DeclareUnicodeCharacter{0073}{s}% + \DeclareUnicodeCharacter{0074}{t}% + \DeclareUnicodeCharacter{0075}{u}% + \DeclareUnicodeCharacter{0076}{v}% + \DeclareUnicodeCharacter{0077}{w}% + \DeclareUnicodeCharacter{0078}{x}% + \DeclareUnicodeCharacter{0079}{y}% + \DeclareUnicodeCharacter{007A}{z}% + \DeclareUnicodeCharacter{007B}{\char"7B }% + \DeclareUnicodeCharacter{007C}{\char"7C }% + \DeclareUnicodeCharacter{007D}{\char"7D }% + \DeclareUnicodeCharacter{007E}{\char"7E }% + % \DeclareUnicodeCharacter{007F}{} % DEL + % \DeclareUnicodeCharacter{00A0}{\tie}% \DeclareUnicodeCharacter{00A1}{\exclamdown}% \DeclareUnicodeCharacter{00A2}{{\tcfont \char162}}% 0242=cent @@ -10417,7 +11025,7 @@ \DeclareUnicodeCharacter{00AE}{\registeredsymbol{}}% \DeclareUnicodeCharacter{00AF}{\={ }}% % - \DeclareUnicodeCharacter{00B0}{\ringaccent{ }}% + \DeclareUnicodeCharacter{00B0}{\textdegree}% \DeclareUnicodeCharacter{00B1}{\ensuremath\pm}% \DeclareUnicodeCharacter{00B2}{$^2$}% \DeclareUnicodeCharacter{00B3}{$^3$}% @@ -10899,11 +11507,14 @@ \DeclareUnicodeCharacter{1EF8}{\~Y}% \DeclareUnicodeCharacter{1EF9}{\~y}% % + % Exotic spaces + \DeclareUnicodeCharacter{2007}{\hphantom{0}}% + % % Punctuation \DeclareUnicodeCharacter{2013}{--}% \DeclareUnicodeCharacter{2014}{---}% - \DeclareUnicodeCharacter{2018}{\quoteleft{}}% - \DeclareUnicodeCharacter{2019}{\quoteright{}}% + \DeclareUnicodeCharacter{2018}{\quoteleft\nolig}% + \DeclareUnicodeCharacter{2019}{\quoteright\nolig}% \DeclareUnicodeCharacter{201A}{\quotesinglbase{}}% \DeclareUnicodeCharacter{201C}{\quotedblleft{}}% \DeclareUnicodeCharacter{201D}{\quotedblright{}}% @@ -10918,7 +11529,7 @@ % \DeclareUnicodeCharacter{20AC}{\euro{}}% % - \DeclareUnicodeCharacter{2192}{\expansion{}}% + \DeclareUnicodeCharacter{2192}{\arrow}% \DeclareUnicodeCharacter{21D2}{\result{}}% % % Mathematical symbols @@ -10938,7 +11549,7 @@ \DeclareUnicodeCharacter{2287}{\ensuremath\supseteq}% % \DeclareUnicodeCharacter{2016}{\ensuremath\Vert}% - \DeclareUnicodeCharacter{2032}{\ensuremath\prime}% + \DeclareUnicodeCharacter{2032}{\ensuremath{^\prime}}% \DeclareUnicodeCharacter{210F}{\ensuremath\hbar}% \DeclareUnicodeCharacter{2111}{\ensuremath\Im}% \DeclareUnicodeCharacter{2113}{\ensuremath\ell}% @@ -11061,6 +11672,25 @@ % \global\mathchardef\checkmark="1370% actually the square root sign \DeclareUnicodeCharacter{2713}{\ensuremath\checkmark}% + % + % These are all the combining accents. We need these empty definitions + % at present for the sake of PDF outlines. + \DeclareUnicodeCharacter{0300}{}% + \DeclareUnicodeCharacter{0301}{}% + \DeclareUnicodeCharacter{0302}{}% + \DeclareUnicodeCharacter{0303}{}% + \DeclareUnicodeCharacter{0305}{}% + \DeclareUnicodeCharacter{0306}{}% + \DeclareUnicodeCharacter{0307}{}% + \DeclareUnicodeCharacter{0308}{}% + \DeclareUnicodeCharacter{030A}{}% + \DeclareUnicodeCharacter{030B}{}% + \DeclareUnicodeCharacter{030C}{}% + \DeclareUnicodeCharacter{0323}{}% + \DeclareUnicodeCharacter{0327}{}% + \DeclareUnicodeCharacter{0328}{}% + \DeclareUnicodeCharacter{0331}{}% + \DeclareUnicodeCharacter{0361}{}% }% end of \unicodechardefs % UTF-8 byte sequence (pdfTeX) definitions (replacing and @U command) @@ -11081,24 +11711,26 @@ % provide a definition macro to replace/pass-through a Unicode character % \def\DeclareUnicodeCharacterNative#1#2{% - \catcode"#1=\active - \def\dodeclareunicodecharacternative##1##2##3{% + \ifnum"#1>"7F % only make non-ASCII chars active + \catcode"#1=\active + \def\dodeclareunicodecharacternative##1##2##3{% + \begingroup + \uccode`\~="##2\relax + \uppercase{\gdef~}{% + \ifpassthroughchars + ##1% + \else + ##3% + \fi + } + \endgroup + } \begingroup - \uccode`\~="##2\relax - \uppercase{\gdef~}{% - \ifpassthroughchars - ##1% - \else - ##3% - \fi - } + \uccode`\.="#1\relax + \uppercase{\def\UTFNativeTmp{.}}% + \expandafter\dodeclareunicodecharacternative\UTFNativeTmp{#1}{#2}% \endgroup - } - \begingroup - \uccode`\.="#1\relax - \uppercase{\def\UTFNativeTmp{.}}% - \expandafter\dodeclareunicodecharacternative\UTFNativeTmp{#1}{#2}% - \endgroup + \fi } % Native Unicode handling (XeTeX and LuaTeX) character replacing definition. @@ -11127,14 +11759,14 @@ \relax } -% Define all Unicode characters we know about. This makes UTF-8 the default -% input encoding and allows @U to work. +% Define all Unicode characters we know about \iftxinativeunicodecapable \nativeunicodechardefsatu \else \utfeightchardefs \fi + \message{formatting,} \newdimen\defaultparindent \defaultparindent = 15pt @@ -11181,13 +11813,9 @@ % \vsize = #1\relax \advance\vsize by \topskip - \outervsize = \vsize - \advance\outervsize by 2\topandbottommargin \txipageheight = \vsize % \hsize = #2\relax - \outerhsize = \hsize - \advance\outerhsize by 0.5in \txipagewidth = \hsize % \normaloffset = #4\relax @@ -11201,12 +11829,12 @@ \pdfhorigin = 1 true in \pdfvorigin = 1 true in \else - \ifx\XeTeXrevision\thisisundefined - \special{papersize=#8,#7}% - \else + \ifxetex \pdfpageheight #7\relax \pdfpagewidth #8\relax % XeTeX does not have \pdfhorigin and \pdfvorigin. + \else + \special{papersize=#8,#7}% \fi \fi % @@ -11244,23 +11872,6 @@ \defbodyindent = .5cm }} -% Use @smallerbook to reset parameters for 6x9 trim size. -% (Just testing, parameters still in flux.) -\def\smallerbook{{\globaldefs = 1 - \parskip = 1.5pt plus 1pt - \textleading = 12pt - % - \internalpagesizes{7.4in}{4.8in}% - {-.2in}{-.4in}% - {0pt}{14pt}% - {9in}{6in}% - % - \lispnarrowing = 0.25in - \tolerance = 700 - \contentsrightmargin = 0pt - \defbodyindent = .4cm -}} - % Use @afourpaper to print on European A4 paper. \def\afourpaper{{\globaldefs = 1 \parskip = 3pt plus 2pt minus 1pt @@ -11294,7 +11905,7 @@ \textleading = 12.5pt % \internalpagesizes{160mm}{120mm}% - {\voffset}{\hoffset}% + {\voffset}{-11.4mm}% {\bindingoffset}{8pt}% {210mm}{148mm}% % @@ -11373,9 +11984,138 @@ \hfuzz = 1pt +\message{microtype,} + +% protrusion, from Thanh's protcode.tex. +\def\mtsetprotcode#1{% + \rpcode#1`\!=200 \rpcode#1`\,=700 \rpcode#1`\-=700 \rpcode#1`\.=700 + \rpcode#1`\;=500 \rpcode#1`\:=500 \rpcode#1`\?=200 + \rpcode#1`\'=700 + \rpcode#1 34=500 % '' + \rpcode#1 123=300 % -- + \rpcode#1 124=200 % --- + \rpcode#1`\)=50 \rpcode#1`\A=50 \rpcode#1`\F=50 \rpcode#1`\K=50 + \rpcode#1`\L=50 \rpcode#1`\T=50 \rpcode#1`\V=50 \rpcode#1`\W=50 + \rpcode#1`\X=50 \rpcode#1`\Y=50 \rpcode#1`\k=50 \rpcode#1`\r=50 + \rpcode#1`\t=50 \rpcode#1`\v=50 \rpcode#1`\w=50 \rpcode#1`\x=50 + \rpcode#1`\y=50 + % + \lpcode#1`\`=700 + \lpcode#1 92=500 % `` + \lpcode#1`\(=50 \lpcode#1`\A=50 \lpcode#1`\J=50 \lpcode#1`\T=50 + \lpcode#1`\V=50 \lpcode#1`\W=50 \lpcode#1`\X=50 \lpcode#1`\Y=50 + \lpcode#1`\v=50 \lpcode#1`\w=50 \lpcode#1`\x=50 \lpcode#1`\y=0 + % + \mtadjustprotcode#1\relax +} + +\newcount\countC +\def\mtadjustprotcode#1{% + \countC=0 + \loop + \ifcase\lpcode#1\countC\else + \mtadjustcp\lpcode#1\countC + \fi + \ifcase\rpcode#1\countC\else + \mtadjustcp\rpcode#1\countC + \fi + \advance\countC 1 + \ifnum\countC < 256 \repeat +} + +\newcount\countB +\def\mtadjustcp#1#2#3{% + \setbox\boxA=\hbox{% + \ifx#2\font\else#2\fi + \char#3}% + \countB=\wd\boxA + \multiply\countB #1#2#3\relax + \divide\countB \fontdimen6 #2\relax + #1#2#3=\countB\relax +} + +\ifxetex % XeTeX + \mtsetprotcode\textrm + \def\mtfontexpand#1{} +\else + \ifluatex % LuaTeX + \mtsetprotcode\textrm + \def\mtfontexpand#1{\expandglyphsinfont#1 20 20 1\relax} + \else + \ifpdf % pdfTeX + \mtsetprotcode\textrm + \def\mtfontexpand#1{\pdffontexpand#1 20 20 1 autoexpand\relax} + \else % TeX + \def\mtfontexpand#1{} + \fi + \fi +\fi + + +\newif\ifmicrotype + +\def\microtypeON{% + \microtypetrue + % + \ifxetex % XeTeX + \XeTeXprotrudechars=2 + \else + \ifluatex % LuaTeX + \adjustspacing=2 + \protrudechars=2 + \else + \ifpdf % pdfTeX + \pdfadjustspacing=2 + \pdfprotrudechars=2 + \fi + \fi + \fi + % + \mtfontexpand\textrm + \mtfontexpand\textsl + \mtfontexpand\textbf +} + +\def\microtypeOFF{% + \microtypefalse + % + \ifxetex % XeTeX + \XeTeXprotrudechars=0 + \else + \ifluatex % LuaTeX + \adjustspacing=0 + \protrudechars=0 + \else + \ifpdf % pdfTeX + \pdfadjustspacing=0 + \pdfprotrudechars=0 + \fi + \fi + \fi +} + +\microtypeOFF + +\parseargdef\microtype{% + \def\txiarg{#1}% + \ifx\txiarg\onword + \microtypeON + \else\ifx\txiarg\offword + \microtypeOFF + \else + \errhelp = \EMsimple + \errmessage{Unknown @microtype option `\txiarg', must be on|off}% + \fi\fi +} + + \message{and turning on texinfo input format.} +% Make UTF-8 the default encoding. +\documentencodingzzz{UTF-8} + \def^^L{\par} % remove \outer, so ^L can appear in an @comment +\catcode`\^^K = 10 % treat vertical tab as whitespace % DEL is a comment character, in case @c does not suffice. \catcode`\^^? = 14 @@ -11391,23 +12131,6 @@ \catcode`\|=\other \def\normalverticalbar{|} \catcode`\~=\other \def\normaltilde{~} -% This macro is used to make a character print one way in \tt -% (where it can probably be output as-is), and another way in other fonts, -% where something hairier probably needs to be done. -% -% #1 is what to print if we are indeed using \tt; #2 is what to print -% otherwise. Since all the Computer Modern typewriter fonts have zero -% interword stretch (and shrink), and it is reasonable to expect all -% typewriter fonts to have this, we can check that font parameter. -% -\def\ifusingtt#1#2{\ifdim \fontdimen3\font=0pt #1\else #2\fi} - -% Same as above, but check for italic font. Actually this also catches -% non-italic slanted fonts since it is impossible to distinguish them from -% italic fonts. But since this is only used by $ and it uses \sl anyway -% this is not a problem. -\def\ifusingit#1#2{\ifdim \fontdimen1\font>0pt #1\else #2\fi} - % Set catcodes for Texinfo file % Active characters for printing the wanted glyph. @@ -11442,7 +12165,7 @@ \def\texinfochars{% \let< = \activeless \let> = \activegtr - \let~ = \activetilde + \let~ = \activetilde \let^ = \activehat \setregularquotes \let\b = \strong @@ -11453,23 +12176,32 @@ % Used sometimes to turn off (effectively) the active characters even after % parsing them. \def\turnoffactive{% - \normalturnoffactive + \passthroughcharstrue + \let-=\normaldash + \let"=\normaldoublequote + \let$=\normaldollar %$ font-lock fix + \let+=\normalplus + \let<=\normalless + \let>=\normalgreater + \let^=\normalcaret + \let_=\normalunderscore + \let|=\normalverticalbar + \let~=\normaltilde \otherbackslash + \setregularquotes + \unsepspaces } -\catcode`\@=0 +% If a .fmt file is being used, characters that might appear in a file +% name cannot be active until we have parsed the command line. +% So turn them off again, and have \loadconf turn them back on. +\catcode`+=\other \catcode`\_=\other + % \backslashcurfont outputs one backslash character in current font, % as in \char`\\. \global\chardef\backslashcurfont=`\\ -% \realbackslash is an actual character `\' with catcode other. -{\catcode`\\=\other @gdef@realbackslash{\}} - -% In Texinfo, backslash is an active character; it prints the backslash -% in fixed width font. -\catcode`\\=\active % @ for escape char from now on. - % Print a typewriter backslash. For math mode, we can't simply use % \backslashcurfont: the story here is that in math mode, the \char % of \backslashcurfont ends up printing the roman \ from the math symbol @@ -11479,109 +12211,125 @@ % ignored family value; char position "5C). We can't use " for the % usual hex value because it has already been made active. -@def@ttbackslash{{@tt @ifmmode @mathchar29020 @else @backslashcurfont @fi}} -@let@backslashchar = @ttbackslash % @backslashchar{} is for user documents. - -% \otherbackslash defines an active \ to be a literal `\' character with -% catcode other. -@gdef@otherbackslash{@let\=@realbackslash} - -% Same as @turnoffactive except outputs \ as {\tt\char`\\} instead of -% the literal character `\'. -% -{@catcode`- = @active - @gdef@normalturnoffactive{% - @passthroughcharstrue - @let-=@normaldash - @let"=@normaldoublequote - @let$=@normaldollar %$ font-lock fix - @let+=@normalplus - @let<=@normalless - @let>=@normalgreater - @let^=@normalcaret - @let_=@normalunderscore - @let|=@normalverticalbar - @let~=@normaltilde - @let\=@ttbackslash - @setregularquotes - @unsepspaces - } -} +\def\ttbackslash{{\tt \ifmmode \mathchar29020 \else \backslashcurfont \fi}} +\let\backslashchar = \ttbackslash % \backslashchar{} is for user documents. -% If a .fmt file is being used, characters that might appear in a file -% name cannot be active until we have parsed the command line. -% So turn them off again, and have @fixbackslash turn them back on. -@catcode`+=@other @catcode`@_=@other - -% \enablebackslashhack - allow file to begin `\input texinfo' -% -% If a .fmt file is being used, we don't want the `\input texinfo' to show up. -% That is what \eatinput is for; after that, the `\' should revert to printing -% a backslash. -% If the file did not have a `\input texinfo', then it is turned off after -% the first line; otherwise the first `\' in the file would cause an error. -% This is used on the very last line of this file, texinfo.tex. -% We also use @c to call @fixbackslash, in case ends of lines are hidden. -{ -@catcode`@^=7 -@catcode`@^^M=13@gdef@enablebackslashhack{% - @global@let\ = @eatinput% - @catcode`@^^M=13% - @def@c{@fixbackslash@c}% - % Definition for the newline at the end of this file. - @def ^^M{@let^^M@secondlinenl}% - % Definition for a newline in the main Texinfo file. - @gdef @secondlinenl{@fixbackslash}% - % In case the first line has a whole-line command on it - @let@originalparsearg@parsearg - @def@parsearg{@fixbackslash@originalparsearg} +% These are made active for url-breaking, so need +% active definitions as the normal characters. +\def\normaldot{.} +\def\normalquest{?} +\def\normalslash{/} + +% \newlinesloadsconf - call \loadconf as soon as possible in the +% file, e.g. at the first newline. +% +{\catcode`\^=7 +\catcode`\^^M=13 +\gdef\newlineloadsconf{% + \catcode`\^^M=13 % + \newlineloadsconfzz% +} +\gdef\newlineloadsconfzz#1^^M{% + \def\c{\loadconf\c}% + % Definition for the first newline read in the file + \def ^^M{\loadconf}% + % In case the first line has a whole-line or environment command on it + \let\originalparsearg\parsearg% + \def\parsearg{\loadconf\originalparsearg}% + % + % \startenvironment is in the expansion of commands defined with \envdef + \let\originalstartenvironment\startenvironment% + \def\startenvironment{\loadconf\startenvironment}% }} -{@catcode`@^=7 @catcode`@^^M=13% -@gdef@eatinput input texinfo#1^^M{@fixbackslash}} % Emergency active definition of newline, in case an active newline token % appears by mistake. -{@catcode`@^=7 @catcode13=13% -@gdef@enableemergencynewline{% - @gdef^^M{% - @par% - %@par% +{\catcode`\^=7 \catcode13=13% +\gdef\enableemergencynewline{% + \gdef^^M{% + \par% + %\par% }}} -@gdef@fixbackslash{% - @ifx\@eatinput @let\ = @ttbackslash @fi - @catcode13=5 % regular end of line - @enableemergencynewline - @let@c=@comment - @let@parsearg@originalparsearg +% \loadconf gets called at the beginning of every Texinfo file. +% If texinfo.cnf is present on the system, read it. Useful for site-wide +% @afourpaper, etc. Not opening texinfo.cnf directly in texinfo.tex +% makes it possible to make a format file for Texinfo. +% +\gdef\loadconf{% + \relax % Terminate the filename if running as "tex '&texinfo' FILE.texi". + % + % Turn off the definitions that trigger \loadconf + \everyjobreset + \catcode13=5 % regular end of line + \enableemergencynewline + \let\c=\comment + \let\parsearg\originalparsearg + \let\startenvironment\originalstartenvironment + % % Also turn back on active characters that might appear in the input % file name, in case not using a pre-dumped format. - @catcode`+=@active - @catcode`@_=@active - % - % If texinfo.cnf is present on the system, read it. - % Useful for site-wide @afourpaper, etc. This macro, @fixbackslash, gets - % called at the beginning of every Texinfo file. Not opening texinfo.cnf - % directly in this file, texinfo.tex, makes it possible to make a format - % file for Texinfo. + \catcode`+=\active + \catcode`\_=\active % - @openin 1 texinfo.cnf - @ifeof 1 @else @input texinfo.cnf @fi - @closein 1 + \openin 1 texinfo.cnf + \ifeof 1 \else \input texinfo.cnf \fi + \closein 1 } +% Redefine some control sequences to be controlled by the \ifdummies +% and \ifindexnofonts switches. Do this at the end so that the control +% sequences are all defined. +\definedummies + + + + +\catcode`\@=0 + +% \realbackslash is an actual character `\' with catcode other. +{\catcode`\\=\other @gdef@realbackslash{\}} + +% In Texinfo, backslash is an active character; it prints the backslash +% in fixed width font. +\catcode`\\=\active % @ for escape char from now on. + +@let\ = @ttbackslash + +% If in a .fmt file, print the version number. +% \eatinput stops the `\input texinfo' from showing up. +% After that, `\' should revert to printing a backslash. +% Turn on active characters that we couldn't do earlier because +% they might have appeared in the input file name. +% +@everyjob{@message{[Texinfo version @texinfoversion]}% + @global@let\ = @eatinput + @catcode`+=@active @catcode`@_=@active} + +{@catcode`@^=7 @catcode`@^^M=13% +@gdef@eatinput input texinfo#1^^M{@loadconf}} + +@def@everyjobreset{@ifx\@eatinput @let\ = @ttbackslash @fi} + +% \otherbackslash defines an active \ to be a literal `\' character with +% catcode other. +@gdef@otherbackslash{@let\=@realbackslash} + +% Same as @turnoffactive except outputs \ as {\tt\char`\\} instead of +% the literal character `\'. +% +{@catcode`- = @active + @gdef@normalturnoffactive{% + @turnoffactive + @let\=@ttbackslash + } +} % Say @foo, not \foo, in error messages. @escapechar = `@@ -% These (along with & and #) are made active for url-breaking, so need -% active definitions as the normal characters. -@def@normaldot{.} -@def@normalquest{?} -@def@normalslash{/} - % These look ok in all fonts, so just make them not special. % @hashchar{} gets its own user-level command, because of #line. @catcode`@& = @other @def@normalamp{&} @@ -11596,17 +12344,11 @@ @c Do this last of all since we use ` in the previous @catcode assignments. @catcode`@'=@active @catcode`@`=@active -@setregularquotes @c Local variables: -@c eval: (add-hook 'before-save-hook 'time-stamp) -@c page-delimiter: "^\\\\message\\|emacs-page" -@c time-stamp-start: "def\\\\texinfoversion{" -@c time-stamp-format: "%:y-%02m-%02d.%02H" -@c time-stamp-end: "}" +@c eval: (add-hook 'before-save-hook 'time-stamp nil t) +@c time-stamp-pattern: "texinfoversion{%Y-%02m-%02d.%02H}" +@c page-delimiter: "^\\\\message" @c End: -@c vim:sw=2: - -@enablebackslashhack - +@newlineloadsconf diff --git a/deps/libffi/doc/version.texi b/deps/libffi/doc/version.texi index dc281e38e0f6..c9adde9c03f9 100644 --- a/deps/libffi/doc/version.texi +++ b/deps/libffi/doc/version.texi @@ -1,4 +1,4 @@ -@set UPDATED 8 August 2026 -@set UPDATED-MONTH August 2026 -@set EDITION 3.8.0 -@set VERSION 3.8.0 +@set UPDATED 14 November 2026 +@set UPDATED-MONTH November 2026 +@set EDITION 3.8.1 +@set VERSION 3.8.1 diff --git a/deps/libffi/fficonfig.h.in b/deps/libffi/fficonfig.h.in index 0b35a6be073c..78c52d934035 100644 --- a/deps/libffi/fficonfig.h.in +++ b/deps/libffi/fficonfig.h.in @@ -71,10 +71,10 @@ /* Define if you support more than one size of the long double type */ #undef HAVE_LONG_DOUBLE_VARIANT -/* Define to 1 if you have the `memcpy' function. */ +/* Define to 1 if you have the 'memcpy' function. */ #undef HAVE_MEMCPY -/* Define to 1 if you have the `memfd_create' function. */ +/* Define to 1 if you have the 'memfd_create' function. */ #undef HAVE_MEMFD_CREATE /* Define if .eh_frame sections should be read-only. */ @@ -134,16 +134,16 @@ /* Define to the version of this package. */ #undef PACKAGE_VERSION -/* The size of `double', as computed by sizeof. */ +/* The size of 'double', as computed by sizeof. */ #undef SIZEOF_DOUBLE -/* The size of `long double', as computed by sizeof. */ +/* The size of 'long double', as computed by sizeof. */ #undef SIZEOF_LONG_DOUBLE -/* The size of `size_t', as computed by sizeof. */ +/* The size of 'size_t', as computed by sizeof. */ #undef SIZEOF_SIZE_T -/* Define to 1 if all of the C90 standard headers exist (not just the ones +/* Define to 1 if all of the C89 standard headers exist (not just the ones required in a freestanding environment). This macro is provided for backward compatibility; new code need not use it. */ #undef STDC_HEADERS diff --git a/deps/libffi/generate-headers.py b/deps/libffi/generate-headers.py index fb58edf17b66..b17dadff0801 100644 --- a/deps/libffi/generate-headers.py +++ b/deps/libffi/generate-headers.py @@ -7,8 +7,8 @@ from pathlib import Path -LIBFFI_VERSION = '3.8.0' -LIBFFI_VERSION_NUMBER = '30800' +LIBFFI_VERSION = '3.8.1' +LIBFFI_VERSION_NUMBER = '30801' def normalize_arch(target_arch): aliases = { diff --git a/deps/libffi/include/Makefile.in b/deps/libffi/include/Makefile.in index 8851d33a6f98..fa38efaf444d 100644 --- a/deps/libffi/include/Makefile.in +++ b/deps/libffi/include/Makefile.in @@ -1,7 +1,7 @@ -# Makefile.in generated by automake 1.16.5 from Makefile.am. +# Makefile.in generated by automake 1.18.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994-2021 Free Software Foundation, Inc. +# Copyright (C) 1994-2025 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -70,6 +70,8 @@ am__make_running_with_option = \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +am__rm_f = rm -f $(am__rm_f_notfound) +am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ @@ -155,10 +157,9 @@ am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ - test -z "$$files" \ - || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ - || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ - $(am__cd) "$$dir" && rm -f $$files; }; \ + { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__installdirs = "$(DESTDIR)$(includedir)" HEADERS = $(nodist_include_HEADERS) $(noinst_HEADERS) @@ -282,8 +283,10 @@ ac_ct_READELF = @ac_ct_READELF@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ +am__xargs_n = @am__xargs_n@ ax_enable_builddir_sed = @ax_enable_builddir_sed@ bindir = @bindir@ build = @build@ @@ -452,6 +455,7 @@ cscopelist-am: $(am__tagged_files) distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am @@ -516,9 +520,9 @@ mostlyclean-generic: clean-generic: distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) - -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) + -$(am__rm_f) $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) + -$(am__rm_f) $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -611,3 +615,10 @@ uninstall-am: uninstall-nodist_includeHEADERS # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: + +# Tell GNU make to disable its built-in pattern rules. +%:: %,v +%:: RCS/%,v +%:: RCS/% +%:: s.% +%:: SCCS/s.% diff --git a/deps/libffi/install-sh b/deps/libffi/install-sh index ec298b537402..1d8d96696466 100755 --- a/deps/libffi/install-sh +++ b/deps/libffi/install-sh @@ -1,7 +1,7 @@ #!/bin/sh # install - install a program, script, or datafile -scriptversion=2020-11-14.01; # UTC +scriptversion=2025-06-18.21; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the @@ -124,9 +124,9 @@ it's up to you to specify -f if you want it. If -S is not specified, no backups are attempted. -Email bug reports to bug-automake@gnu.org. -Automake home page: https://www.gnu.org/software/automake/ -" +Report bugs to . +GNU Automake home page: . +General help using GNU software: ." while test $# -ne 0; do case $1 in @@ -170,7 +170,7 @@ while test $# -ne 0; do -T) is_target_a_directory=never;; - --version) echo "$0 $scriptversion"; exit $?;; + --version) echo "$0 (GNU Automake) $scriptversion"; exit $?;; --) shift break;; @@ -345,7 +345,7 @@ do ' 0 # Because "mkdir -p" follows existing symlinks and we likely work - # directly in world-writeable /tmp, make sure that the '$tmpdir' + # directly in world-writable /tmp, make sure that the '$tmpdir' # directory is successfully created first before we actually test # 'mkdir -p'. if (umask $mkdir_umask && @@ -353,7 +353,7 @@ do exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1 then if test -z "$dir_arg" || { - # Check for POSIX incompatibilities with -m. + # Check for POSIX incompatibility with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. @@ -533,9 +533,9 @@ do done # Local variables: -# eval: (add-hook 'before-save-hook 'time-stamp) +# eval: (add-hook 'before-save-hook 'time-stamp nil t) # time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-format: "%Y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: diff --git a/deps/libffi/libtool-version b/deps/libffi/libtool-version index 814c6e21d925..5b9d55999538 100644 --- a/deps/libffi/libtool-version +++ b/deps/libffi/libtool-version @@ -26,4 +26,4 @@ # release, then set age to 0. # # CURRENT:REVISION:AGE -13:0:5 +13:1:5 diff --git a/deps/libffi/ltmain.sh b/deps/libffi/ltmain.sh index 977e5237bb01..22edd1403fb4 100755 --- a/deps/libffi/ltmain.sh +++ b/deps/libffi/ltmain.sh @@ -2,11 +2,11 @@ ## DO NOT EDIT - This file generated from ./build-aux/ltmain.in ## by inline-source v2019-02-19.15 -# libtool (GNU libtool) 2.4.7 +# libtool (GNU libtool) 2.5.4 # Provide generalized library-building support services. # Written by Gordon Matzigkeit , 1996 -# Copyright (C) 1996-2019, 2021-2022 Free Software Foundation, Inc. +# Copyright (C) 1996-2019, 2021-2024 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. @@ -31,8 +31,8 @@ PROGRAM=libtool PACKAGE=libtool -VERSION="2.4.7 Debian-2.4.7-7build1" -package_revision=2.4.7 +VERSION="2.5.4 Debian-2.5.4-9" +package_revision=2.5.4 ## ------ ## @@ -64,7 +64,7 @@ package_revision=2.4.7 # libraries, which are installed to $pkgauxdir. # Set a version string for this script. -scriptversion=2019-02-19.15; # UTC +scriptversion=2024-12-01.17; # UTC # General shell script boiler plate, and helper functions. # Written by Gary V. Vaughan, 2004 @@ -72,11 +72,11 @@ scriptversion=2019-02-19.15; # UTC # This is free software. There is NO warranty; not even for # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # -# Copyright (C) 2004-2019, 2021 Bootstrap Authors +# Copyright (C) 2004-2019, 2021, 2023-2024 Bootstrap Authors # # This file is dual licensed under the terms of the MIT license -# , and GPL version 2 or later -# . You must apply one of +# , and GPL version 2 or later +# . You must apply one of # these licenses when using or redistributing this software or any of # the files within it. See the URLs above, or the file `LICENSE` # included in the Bootstrap distribution for the full license texts. @@ -143,7 +143,7 @@ nl=' ' IFS="$sp $nl" -# There are apparently some retarded systems that use ';' as a PATH separator! +# There are apparently some systems that use ';' as a PATH separator! if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { @@ -572,15 +572,16 @@ func_require_term_colors () # --------------------- # Append VALUE onto the existing contents of VAR. + # _G_HAVE_PLUSEQ_OP # Can be empty, in which case the shell is probed, "yes" if += is - # useable or anything else if it does not work. - if test -z "$_G_HAVE_PLUSEQ_OP" && \ - __PLUSEQ_TEST="a" && \ - __PLUSEQ_TEST+=" b" 2>/dev/null && \ - test "a b" = "$__PLUSEQ_TEST"; then - _G_HAVE_PLUSEQ_OP=yes - fi + # usable or anything else if it does not work. +if test -z "$_G_HAVE_PLUSEQ_OP" && \ + __PLUSEQ_TEST="a" && \ + __PLUSEQ_TEST+=" b" 2>/dev/null && \ + test "a b" = "$__PLUSEQ_TEST"; then + _G_HAVE_PLUSEQ_OP=yes +fi if test yes = "$_G_HAVE_PLUSEQ_OP" then @@ -727,7 +728,7 @@ eval 'func_dirname () # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. -# value retuned in "$func_basename_result" +# value returned in "$func_basename_result" # For efficiency, we do not delegate to the functions above but instead # duplicate the functionality here. eval 'func_dirname_and_basename () @@ -885,7 +886,7 @@ func_mkdir_p () # While some portion of DIR does not yet exist... while test ! -d "$_G_directory_path"; do # ...make a list in topmost first order. Use a colon delimited - # list incase some portion of path contains whitespace. + # list in case some portion of path contains whitespace. _G_dir_list=$_G_directory_path:$_G_dir_list # If the last portion added has no slash in it, the list is done @@ -1524,11 +1525,11 @@ func_lt_ver () # This is free software. There is NO warranty; not even for # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # -# Copyright (C) 2010-2019, 2021 Bootstrap Authors +# Copyright (C) 2010-2019, 2021, 2023-2024 Bootstrap Authors # # This file is dual licensed under the terms of the MIT license -# , and GPL version 2 or later -# . You must apply one of +# , and GPL version 2 or later +# . You must apply one of # these licenses when using or redistributing this software or any of # the files within it. See the URLs above, or the file `LICENSE` # included in the Bootstrap distribution for the full license texts. @@ -2205,7 +2206,30 @@ func_version () # End: # Set a version string. -scriptversion='(GNU libtool) 2.4.7' +scriptversion='(GNU libtool) 2.5.4' + +# func_version +# ------------ +# Echo version message to standard output and exit. +func_version () +{ + $debug_cmd + + year=`date +%Y` + + cat < +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. + +Originally written by Gordon Matzigkeit, 1996 +(See AUTHORS for complete contributor listing) +EOF + + exit $? +} # func_echo ARG... @@ -2228,18 +2252,6 @@ func_echo () } -# func_warning ARG... -# ------------------- -# Libtool warnings are not categorized, so override funclib.sh -# func_warning with this simpler definition. -func_warning () -{ - $debug_cmd - - $warning_func ${1+"$@"} -} - - ## ---------------- ## ## Options parsing. ## ## ---------------- ## @@ -2251,19 +2263,23 @@ usage='$progpath [OPTION]... [MODE-ARG]...' # Short help message in response to '-h'. usage_message="Options: - --config show all configuration variables - --debug enable verbose shell tracing - -n, --dry-run display commands without modifying any files - --features display basic configuration information and exit - --mode=MODE use operation mode MODE - --no-warnings equivalent to '-Wnone' - --preserve-dup-deps don't remove duplicate dependency libraries - --quiet, --silent don't print informational messages - --tag=TAG use configuration variables from tag TAG - -v, --verbose print more informational messages than default - --version print version information - -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] - -h, --help, --help-all print short, long, or detailed help message + --config show all configuration variables + --debug enable verbose shell tracing + -n, --dry-run display commands without modifying any files + --features display basic configuration information + --finish use operation '--mode=finish' + --mode=MODE use operation mode MODE + --no-finish don't update shared library cache + --no-quiet, --no-silent print default informational messages + --no-warnings equivalent to '-Wnone' + --preserve-dup-deps don't remove duplicate dependency libraries + --quiet, --silent don't print informational messages + --reorder-cache=DIRS reorder shared library cache for preferred DIRS + --tag=TAG use configuration variables from tag TAG + -v, --verbose print more informational messages than default + --version print version information + -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] + -h, --help, --help-all print short, long, or detailed help message " # Additional text appended to 'usage_message' in response to '--help'. @@ -2296,13 +2312,13 @@ include the following information: compiler: $LTCC compiler flags: $LTCFLAGS linker: $LD (gnu? $with_gnu_ld) - version: $progname $scriptversion Debian-2.4.7-7build1 + version: $progname $scriptversion Debian-2.5.4-9 automake: `($AUTOMAKE --version) 2>/dev/null |$SED 1q` autoconf: `($AUTOCONF --version) 2>/dev/null |$SED 1q` Report bugs to . -GNU libtool home page: . -General help using GNU software: ." +GNU libtool home page: . +General help using GNU software: ." exit 0 } @@ -2492,8 +2508,11 @@ libtool_options_prep () opt_dry_run=false opt_help=false opt_mode= + opt_reorder_cache=false opt_preserve_dup_deps=false opt_quiet=false + opt_finishing=true + opt_warning= nonopt= preserve_args= @@ -2585,14 +2604,18 @@ libtool_parse_options () clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error - *) func_error "invalid argument for $_G_opt" + *) func_error "invalid argument '$1' for $_G_opt" exit_cmd=exit - break ;; esac shift ;; + --no-finish) + opt_finishing=false + func_append preserve_args " $_G_opt" + ;; + --no-silent|--no-quiet) opt_quiet=false func_append preserve_args " $_G_opt" @@ -2608,6 +2631,24 @@ libtool_parse_options () func_append preserve_args " $_G_opt" ;; + --reorder-cache) + opt_reorder_cache=true + shared_lib_dirs=$1 + if test -n "$shared_lib_dirs"; then + case $1 in + # Must begin with /: + /*) ;; + + # Catch anything else as an error (relative paths) + *) func_error "invalid argument '$1' for $_G_opt" + func_error "absolute paths are required for $_G_opt" + exit_cmd=exit + ;; + esac + fi + shift + ;; + --silent|--quiet) opt_quiet=: opt_verbose=false @@ -2644,6 +2685,18 @@ libtool_parse_options () func_add_hook func_parse_options libtool_parse_options +# func_warning ARG... +# ------------------- +# Libtool warnings are not categorized, so override funclib.sh +# func_warning with this simpler definition. +func_warning () +{ + if $opt_warning; then + $debug_cmd + $warning_func ${1+"$@"} + fi +} + # libtool_validate_options [ARG]... # --------------------------------- @@ -2660,10 +2713,10 @@ libtool_validate_options () # preserve --debug test : = "$debug_cmd" || func_append preserve_args " --debug" - case $host in + case $host_os in # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452 # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788 - *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*) + cygwin* | mingw* | windows* | pw32* | cegcc* | solaris2* | os2*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; @@ -2995,7 +3048,7 @@ EOF # func_convert_core_file_wine_to_w32 ARG # Helper function used by file name conversion functions when $build is *nix, -# and $host is mingw, cygwin, or some other w32 environment. Relies on a +# and $host is mingw, windows, cygwin, or some other w32 environment. Relies on a # correctly configured wine environment available, with the winepath program # in $build's $PATH. # @@ -3027,9 +3080,10 @@ func_convert_core_file_wine_to_w32 () # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and -# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly -# configured wine environment available, with the winepath program in $build's -# $PATH. Assumes ARG has no leading or trailing path separator characters. +# $host is mingw, windows, cygwin, or some other w32 environment. Relies on a +# correctly configured wine environment available, with the winepath program +# in $build's $PATH. Assumes ARG has no leading or trailing path separator +# characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. @@ -3172,6 +3226,15 @@ func_convert_path_front_back_pathsep () # end func_convert_path_front_back_pathsep +# func_convert_delimited_path PATH ORIG_DELIMITER NEW_DELIMITER +# Replaces a delimiter for a given path. +func_convert_delimited_path () +{ + converted_path=`$ECHO "$1" | $SED "s#$2#$3#g"` +} +# end func_convert_delimited_path + + ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## @@ -3506,6 +3569,65 @@ func_dll_def_p () } +# func_reorder_shared_lib_cache DIRS +# Reorder the shared library cache by unconfiguring previous shared library cache +# and configuring preferred search directories before previous search directories. +# Previous shared library cache: /usr/lib /usr/local/lib +# Preferred search directories: /tmp/testing +# Reordered shared library cache: /tmp/testing /usr/lib /usr/local/lib +func_reorder_shared_lib_cache () +{ + $debug_cmd + + case $host_os in + openbsd*) + get_search_directories=`PATH="$PATH:/sbin" ldconfig -r | $GREP "search directories" | $SED "s#.*search directories:\ ##g"` + func_convert_delimited_path "$get_search_directories" ':' '\ ' + save_search_directories=$converted_path + func_convert_delimited_path "$1" ':' '\ ' + + # Ensure directories exist + for dir in $converted_path; do + # Ensure each directory is an absolute path + case $dir in + /*) ;; + *) func_error "Directory '$dir' is not an absolute path" + exit $EXIT_FAILURE ;; + esac + # Ensure no trailing slashes + func_stripname '' '/' "$dir" + dir=$func_stripname_result + if test -d "$dir"; then + if test -n "$preferred_search_directories"; then + preferred_search_directories="$preferred_search_directories $dir" + else + preferred_search_directories=$dir + fi + else + func_error "Directory '$dir' does not exist" + exit $EXIT_FAILURE + fi + done + + PATH="$PATH:/sbin" ldconfig -U $save_search_directories + PATH="$PATH:/sbin" ldconfig -m $preferred_search_directories $save_search_directories + get_search_directories=`PATH="$PATH:/sbin" ldconfig -r | $GREP "search directories" | $SED "s#.*search directories:\ ##g"` + func_convert_delimited_path "$get_search_directories" ':' '\ ' + reordered_search_directories=$converted_path + + $ECHO "Original: $save_search_directories" + $ECHO "Reordered: $reordered_search_directories" + exit $EXIT_SUCCESS + ;; + *) + func_error "--reorder-cache is not supported for host_os=$host_os." + exit $EXIT_FAILURE + ;; + esac +} +# end func_reorder_shared_lib_cache + + # func_mode_compile arg... func_mode_compile () { @@ -3684,7 +3806,7 @@ func_mode_compile () # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in - cygwin* | mingw* | pw32* | os2* | cegcc*) + cygwin* | mingw* | windows* | pw32* | os2* | cegcc*) pic_mode=default ;; esac @@ -4078,6 +4200,12 @@ if $opt_help; then fi +# If option '--reorder-cache', reorder the shared library cache and exit. +if $opt_reorder_cache; then + func_reorder_shared_lib_cache $shared_lib_dirs +fi + + # func_mode_execute arg... func_mode_execute () { @@ -4262,7 +4390,7 @@ func_mode_finish () fi fi - if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs" && $opt_finishing; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. @@ -4287,6 +4415,12 @@ func_mode_finish () for libdir in $libdirs; do $ECHO " $libdir" done + if test "false" = "$opt_finishing"; then + echo + echo "NOTE: finish_cmds were not executed during testing, so you must" + echo "manually run ldconfig to add a given test directory, LIBDIR, to" + echo "the search path for generated executables." + fi echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" @@ -4523,8 +4657,15 @@ func_mode_install () func_append dir "$objdir" if test -n "$relink_command"; then + # Strip any trailing slash from the destination. + func_stripname '' '/' "$libdir" + destlibdir=$func_stripname_result + + func_stripname '' '/' "$destdir" + s_destdir=$func_stripname_result + # Determine the prefix the user has applied to our future dir. - inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` + inst_prefix_dir=`$ECHO "X$s_destdir" | $Xsed -e "s%$destlibdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that @@ -4561,7 +4702,7 @@ func_mode_install () 'exit $?' tstripme=$stripme case $host_os in - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) case $realname in *.dll.a) tstripme= @@ -4674,7 +4815,7 @@ func_mode_install () # Do a test to see if this is really a libtool program. case $host in - *cygwin* | *mingw*) + *cygwin* | *mingw* | *windows*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result @@ -4902,7 +5043,7 @@ extern \"C\" { $RM $export_symbols eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in - *cygwin* | *mingw* | *cegcc* ) + *cygwin* | *mingw* | *windows* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; @@ -4914,7 +5055,7 @@ extern \"C\" { eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in - *cygwin* | *mingw* | *cegcc* ) + *cygwin* | *mingw* | *windows* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; @@ -4928,7 +5069,7 @@ extern \"C\" { func_basename "$dlprefile" name=$func_basename_result case $host in - *cygwin* | *mingw* | *cegcc* ) + *cygwin* | *mingw* | *windows* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" @@ -4954,8 +5095,16 @@ extern \"C\" { eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 - eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | - $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" + case $host in + i[3456]86-*-mingw32*) + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | + $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" + ;; + *) + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | + $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/__nm_//' >> '$nlist'" + ;; + esac } else # not an import lib $opt_dry_run || { @@ -5103,7 +5252,7 @@ static const void *lt_preloaded_setup() { # Transform the symbol file into the correct name. symfileobj=$output_objdir/${my_outputname}S.$objext case $host in - *cygwin* | *mingw* | *cegcc* ) + *cygwin* | *mingw* | *windows* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` @@ -5179,7 +5328,7 @@ func_win32_libid () *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | - $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then + $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64|pe-aarch64)' >/dev/null; then case $nm_interface in "MS dumpbin") if func_cygming_ms_implib_p "$1" || @@ -5446,7 +5595,7 @@ func_extract_archives () # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to -# incorporate the script contents within a cygwin/mingw +# incorporate the script contents within a cygwin/mingw/windows # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. @@ -5454,7 +5603,7 @@ func_extract_archives () # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory where it is stored is -# the $objdir directory. This is a cygwin/mingw-specific +# the $objdir directory. This is a cygwin/mingw/windows-specific # behavior. func_emit_wrapper () { @@ -5579,7 +5728,7 @@ func_exec_program_core () " case $host in # Backslashes separate directories on plain windows - *-*-mingw | *-*-os2* | *-cegcc*) + *-*-mingw* | *-*-windows* | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir\\\\\$program\" 1>&2 @@ -5647,7 +5796,7 @@ func_exec_program () file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done - # Usually 'no', except on cygwin/mingw when embedded into + # Usually 'no', except on cygwin/mingw/windows when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then @@ -5779,7 +5928,7 @@ EOF #endif #include #include -#ifdef _MSC_VER +#if defined _WIN32 && !defined __GNUC__ # include # include # include @@ -5804,7 +5953,7 @@ EOF /* declarations of non-ANSI functions */ #if defined __MINGW32__ # ifdef __STRICT_ANSI__ -int _putenv (const char *); +_CRTIMP int __cdecl _putenv (const char *); # endif #elif defined __CYGWIN__ # ifdef __STRICT_ANSI__ @@ -6002,7 +6151,7 @@ main (int argc, char *argv[]) { EOF case $host in - *mingw* | *cygwin* ) + *mingw* | *windows* | *cygwin* ) # make stdout use "unix" line endings echo " setmode(1,_O_BINARY);" ;; @@ -6021,7 +6170,7 @@ EOF { /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX namespace, but it is not one of the ones we know about and - have already dealt with, above (inluding dump-script), then + have already dealt with, above (including dump-script), then report an error. Otherwise, targets might begin to believe they are allowed to use options in the LTWRAPPER_OPTION_PREFIX namespace. The first time any user complains about this, we'll @@ -6105,7 +6254,7 @@ EOF EOF case $host_os in - mingw*) + mingw* | windows*) cat <<"EOF" { char* p; @@ -6147,7 +6296,7 @@ EOF EOF case $host_os in - mingw*) + mingw* | windows*) cat <<"EOF" /* execv doesn't actually work on mingw as expected on unix */ newargz = prepare_spawn (newargz); @@ -6566,7 +6715,7 @@ lt_update_lib_path (const char *name, const char *value) EOF case $host_os in - mingw*) + mingw* | windows*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). @@ -6741,7 +6890,7 @@ func_mode_link () $debug_cmd case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + *-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # what system we are compiling for in order to pass an extra @@ -6765,6 +6914,7 @@ func_mode_link () finalize_command=$nonopt compile_rpath= + compile_rpath_tail= finalize_rpath= compile_shlibpath= finalize_shlibpath= @@ -6805,10 +6955,12 @@ func_mode_link () xrpath= perm_rpath= temp_rpath= + temp_rpath_tail= thread_safe=no vinfo= vinfo_number=no weak_libs= + rpath_arg= single_module=$wl-single_module func_infer_tag $base_compile @@ -7071,7 +7223,7 @@ func_mode_link () case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) - func_fatal_error "only absolute run-paths are allowed" + func_fatal_error "argument to -rpath is not absolute: $arg" ;; esac if test rpath = "$prev"; then @@ -7247,7 +7399,7 @@ func_mode_link () ;; esac case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + *-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; @@ -7267,7 +7419,7 @@ func_mode_link () -l*) if test X-lc = "X$arg" || test X-lm = "X$arg"; then case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) + *-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; @@ -7275,7 +7427,7 @@ func_mode_link () # These systems don't actually have a C library (as such) test X-lc = "X$arg" && continue ;; - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*) + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-midnightbsd*) # Do not include libc due to us having libc/libc_r. test X-lc = "X$arg" && continue ;; @@ -7295,7 +7447,7 @@ func_mode_link () esac elif test X-lc_r = "X$arg"; then case $host in - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*) + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-midnightbsd*) # Do not include libc_r directly, use -pthread flag. continue ;; @@ -7318,7 +7470,8 @@ func_mode_link () # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. - -model|-arch|-isysroot|--sysroot) + # -q