chore(ext/node): reorg node compat test CI check (#29893)

This PR reorganizes the node compat test CI check.

Now we don't copy (or modify) tests from the vendored dir
(`tests/node_compat/runner/suite`), instead run them directly.

There seem currently 1.4K test cases which pass without modification in
all OSes. The list of such test files are now stored in
`tests/node_compat/config.toml`, and `tests/node_compat/test.ts` run
them as `Deno.test` cases.

(Note: `config.toml` is created by this script:
https://github.com/denoland/node_test_viewer/blob/main/get_consistently_passing_test_names_as_toml.ts.
It checks the daily node compat test runs for the last 10 days, and
retrieves consistently passing test cases.)

closes #29857
This commit is contained in:
Yoshiya Hinosawa 2025-06-27 21:06:18 +09:00 committed by GitHub
parent 9026234a23
commit c73b91318b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
1248 changed files with 1484 additions and 104069 deletions

View file

@ -479,7 +479,7 @@ const ci = {
},
{
...submoduleStep("./tests/node_compat/runner/suite"),
if: "matrix.job == 'lint' && matrix.os == 'linux'",
if: "matrix.job == 'test'",
},
{
...submoduleStep("./cli/bench/testdata/lsp_benchdata"),
@ -711,12 +711,6 @@ const ci = {
run:
"deno run --allow-read --allow-env --allow-sys ./tools/jsdoc_checker.js",
},
{
name: "node_compat/setup.ts --check",
if: "matrix.job == 'lint' && matrix.os == 'linux'",
run:
"deno run --allow-write --allow-read --allow-run=git ./tests/node_compat/runner/setup.ts --check",
},
{
name: "Check tracing build",
if:

View file

@ -163,7 +163,7 @@ jobs:
if: '!(matrix.skip) && (matrix.wpt)'
- name: Clone submodule ./tests/node_compat/runner/suite
run: git submodule update --init --recursive --depth=1 -- ./tests/node_compat/runner/suite
if: '!(matrix.skip) && (matrix.job == ''lint'' && matrix.os == ''linux'')'
if: '!(matrix.skip) && (matrix.job == ''test'')'
- name: Clone submodule ./cli/bench/testdata/lsp_benchdata
run: git submodule update --init --recursive --depth=1 -- ./cli/bench/testdata/lsp_benchdata
if: '!(matrix.skip) && (matrix.job == ''bench'')'
@ -419,9 +419,6 @@ jobs:
- name: jsdoc_checker.js
if: '!(matrix.skip) && (matrix.job == ''lint'')'
run: deno run --allow-read --allow-env --allow-sys ./tools/jsdoc_checker.js
- name: node_compat/setup.ts --check
if: '!(matrix.skip) && (matrix.job == ''lint'' && matrix.os == ''linux'')'
run: deno run --allow-write --allow-read --allow-run=git ./tests/node_compat/runner/setup.ts --check
- name: Check tracing build
if: '!(matrix.skip) && (matrix.job == ''test'' && matrix.profile == ''debug'' && matrix.os == ''linux'' && matrix.arch == ''x86_64'')'
run: cargo check -p deno --features=lsp-tracing

1
.gitmodules vendored
View file

@ -10,6 +10,7 @@
path = tests/node_compat/runner/suite
url = https://github.com/denoland/node_test.git
shallow = true
ignore = untracked
[submodule "cli/bench/testdata/lsp_benchdata"]
path = cli/bench/testdata/lsp_benchdata
url = https://github.com/denoland/deno_lsp_benchdata.git

View file

@ -0,0 +1,26 @@
# Node compat test directory
This directory includes the tools for running Node.js test cases directly in
Deno.
- ./runner/suite/ - vendored Node.js test cases (git submodule at
https://github.com/denoland/node_test)
- ./config.toml - has the list of passing Node.js test cases
- ./test.ts - The script entrypoint of node compat test.
If you run single node.js test case, use the command:
```
./tools/node_compat_tests.js --filter <name of test file>
```
## Add test case entry to CI check
If you fixed some Node.js compabitility and some test cases started passing,
then add those cases to `config.toml`. The items listed in there are checked in
CI check.
## Daily test viewer
To see the latest test results of all test cases, visit this site
https://node-test-viewer.deno.dev/results/latest

View file

@ -1,130 +1,4 @@
// Copyright 2018-2025 the Deno authors. MIT license.
import { partition } from "@std/collections/partition";
import { join } from "@std/path";
import * as JSONC from "@std/jsonc";
import { walk } from "@std/fs/walk";
import { relative } from "@std/path/posix/relative";
/**
* The test suite matches the folders inside the `test` folder inside the
* node repo
*
* Each test suite contains a list of files (which can be paths
* or a regex to match) that will be pulled from the node repo
*/
type TestSuites = Record<string, string[]>;
interface Config {
/** Ignored files won't regenerated by the update script */
ignore: TestSuites;
/**
* The files that will be run by the test suite
*
* The files to be generated with the update script must be listed here as well,
* but they won't be regenerated if they are listed in the `ignore` configuration
*/
tests: TestSuites;
windowsIgnore: TestSuites;
darwinIgnore: TestSuites;
}
export const config: Config = JSONC.parse(
await Deno.readTextFile(new URL("./config.jsonc", import.meta.url)),
) as unknown as Config;
export const ignoreList = Object.entries(config.ignore).reduce(
(total: RegExp[], [suite, paths]) => {
paths.forEach((path) => total.push(new RegExp(join(suite, path))));
return total;
},
[],
);
export function getPathsFromTestSuites(suites: TestSuites): string[] {
const testPaths: string[] = [];
for (const [dir, paths] of Object.entries(suites)) {
if (
["parallel", "internet", "pummel", "sequential", "pseudo-tty"].includes(
dir,
)
) {
for (const path of paths) {
testPaths.push(join(dir, path));
}
}
}
return testPaths;
}
const PARALLEL_PATTERN = /^parallel[\/\\]/;
export function partitionParallelTestPaths(
testPaths: string[],
): { parallel: string[]; sequential: string[] } {
const partitions = partition(testPaths, (p) => !!p.match(PARALLEL_PATTERN));
return { parallel: partitions[0], sequential: partitions[1] };
}
export const NODE_IGNORED_TEST_DIRS = [
"addons",
"async-hooks",
"cctest",
"common",
"doctool",
"embedding",
"fixtures",
"fuzzers",
"js-native-api",
"node-api",
"overlapped-checker",
"report",
"testpy",
"tick-processor",
"tools",
"v8-updates",
"wasi",
"wpt",
];
export const VENDORED_NODE_TEST = new URL(
"./runner/suite/test/",
import.meta.url,
);
export const NODE_COMPAT_TEST_DEST_URL = new URL(
"./test/",
import.meta.url,
);
export async function getNodeTests(): Promise<string[]> {
const paths: string[] = [];
const rootPath = VENDORED_NODE_TEST.href.slice(7);
for await (
const item of walk(VENDORED_NODE_TEST, { exts: [".js"] })
) {
const path = relative(rootPath, item.path);
if (NODE_IGNORED_TEST_DIRS.every((dir) => !path.startsWith(dir))) {
paths.push(path);
}
}
return paths.sort();
}
export async function getDenoTests() {
const paths: string[] = [];
const rootPath = NODE_COMPAT_TEST_DEST_URL.href.slice(7);
for await (
const item of walk(NODE_COMPAT_TEST_DEST_URL, { exts: [".js"] })
) {
const path = relative(rootPath, item.path);
paths.push(path);
}
return paths.sort();
}
let testSerialId = 0;
const cwd = new URL(".", import.meta.url);
/** Checks if the test file uses `node:test` module */
export function usesNodeTestModule(testSource: string): boolean {
@ -145,67 +19,6 @@ export const TEST_ARGS = [
"--unstable-detect-cjs",
];
export async function runNodeCompatTestCase(
testCase: string,
signal?: AbortSignal,
) {
const v8Flags = ["--stack-size=4000"];
const nodeOptions = [] as string[];
const testSource = await Deno.readTextFile(testCase);
const envVars: Record<string, string> = {};
const knownGlobals: string[] = [];
parseFlags(testSource).forEach((flag) => {
switch (flag) {
case "--expose_externalize_string":
v8Flags.push("--expose-externalize-string");
knownGlobals.push(
"createExternalizableString",
"createExternalizableTwoByteString",
);
break;
case "--expose-gc":
v8Flags.push("--expose-gc");
knownGlobals.push("gc");
break;
case "--no-warnings":
nodeOptions.push("--no-warnings");
break;
case "--pending-deprecation":
nodeOptions.push("--pending-deprecation");
break;
case "--allow-natives-syntax":
v8Flags.push("--allow-natives-syntax");
break;
default:
break;
}
});
if (knownGlobals.length > 0) {
envVars["NODE_TEST_KNOWN_GLOBALS"] = knownGlobals.join(",");
}
const usesNodeTest = usesNodeTestModule(testSource);
const args = [
...(usesNodeTest ? TEST_ARGS : RUN_ARGS),
"--v8-flags=" + v8Flags.join(),
testCase,
];
// Pipe stdout in order to output each test result as Deno.test output
// That way the tests will respect the `--quiet` option when provided
return new Deno.Command(Deno.execPath(), {
args,
env: {
TEST_SERIAL_ID: String(testSerialId++),
NODE_OPTIONS: nodeOptions.join(" "),
...envVars,
},
cwd,
stdout: "piped",
stderr: "piped",
signal,
}).spawn();
}
/** Parses the special "Flags:"" syntax in Node.js test files */
export function parseFlags(source: string): string[] {
const line = /^\/\/ Flags: (.+)$/um.exec(source);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,3 +0,0 @@
{
"type": "commonjs"
}

View file

@ -23,7 +23,7 @@ import {
} from "./common.ts";
// The timeout ms for single test execution. If a single test didn't finish in this timeout milliseconds, the test is considered as failure
const TIMEOUT = 2000;
const TIMEOUT = 5000;
const testDirUrl = new URL("runner/suite/test/", import.meta.url).href;
const IS_CI = !!Deno.env.get("CI");
@ -153,15 +153,17 @@ function getFlags(source: string): [string[], string[]] {
return [v8Flags, nodeOptions];
}
let testSerialId = 0;
/**
* Run a single node test file. Retries 3 times on WouldBlock error.
*
* @param testPath Relative path to the test file
* @param testPath Relative path from test/ dir of Node.js (e.g. "parallel/test-assert.js").
*/
async function runSingle(
export async function runSingle(
testPath: string,
retry = 0,
): Promise<NodeTestFileReport> {
testSerialId++;
let cmd: Deno.ChildProcess | undefined;
const testPath_ = "tests/node_compat/runner/suite/test/" + testPath;
let usesNodeTest = false;
@ -183,6 +185,7 @@ async function runSingle(
NODE_SKIP_FLAG_CHECK: "1",
NODE_OPTIONS: nodeOptions.join(" "),
NO_COLOR: "1",
TEST_SERIAL_ID: String(testSerialId),
},
stdout: "piped",
stderr: "piped",
@ -334,14 +337,14 @@ async function main() {
return true;
}
reports[term] = { result: NodeTestFileResult.SKIP };
reports[term] = { result: NodeTestFileResult.SKIP, usesNodeTest: false };
return false;
});
parallel = parallel.filter((term) => {
if (term.includes(filterTerm)) {
return true;
}
reports[term] = { result: NodeTestFileResult.SKIP };
reports[term] = { result: NodeTestFileResult.SKIP, usesNodeTest: false };
return false;
});
console.log(

View file

@ -1 +0,0 @@
versions

View file

@ -1,50 +0,0 @@
# Tools for Node.js compatibility work
We run
[native Node.js test cases](https://github.com/nodejs/node/tree/main/test)
against our Node.js compatibility feature.
This directory includes the tools for downloading, setting up, and updating the
Node.js compat testing in Deno repository.
- `//tests/node_compat/runner/setup.ts`
- This script sets up the Node.js compat tests.
- `//tests/node_compat/runner/versions/`
- Node.js source tarballs and extracted test cases are stored here.
- `//tests/node_compat/config.jsonc`
- This json file stores the settings about which Node.js compat test to run
with Deno.
- `//tests/node_compat/test`
- The actual test cases are stored here.
## Steps to add new test cases from Node.js test cases
1. Update `tests` property of `//tests/node_compat/config.jsonc`. For example,
if you want to add `test/parallel/test-foo.js` from Node.js test cases, then
add `test-foo.js` entry in `tests.parallel` array property in `config.jsonc`
1. Run `deno task setup` in `tests/node_compat/runner` dir.
The above command copies the updated items from Node.js tarball to the Deno
source tree.
Ideally Deno should pass the Node.js compat tests without modification, but if
you need to modify it, then add that item in `ignore` property of
`config.jsonc`. Then `setup.ts` doesn't overwrite the modified Node.js test
cases anymore.
If the test needs to be ignored in particular platform, then add them in
`${platform}Ignore` property of `config.jsonc`
## Run Node.js test cases
Node.js compat tests are run as part of `cargo test` command. If you want to run
only the Node.js compat test cases you can use the command
`cargo test node_compat`. If you want to run specific tests you can use the
command `deno task test` (in `tests/node_compat/runner` dir). For example, if
you want to run all test files which contains `buffer` in filename you can use
the command:
```shellsession
/path/to/deno/tests/node_compat/runner
$ deno task test buffer
```

File diff suppressed because it is too large Load diff

View file

@ -1,72 +0,0 @@
// Copyright 2018-2025 the Deno authors. MIT license.
// deno-lint-ignore-file no-console
import { deadline } from "@std/async/deadline";
import { ensureDir } from "@std/fs/ensure-dir";
import { copy } from "@std/fs/copy";
import { withoutAll } from "@std/collections/without-all";
import {
getDenoTests,
getNodeTests,
NODE_COMPAT_TEST_DEST_URL,
runNodeCompatTestCase,
VENDORED_NODE_TEST,
} from "../common.ts";
import { fromFileUrl } from "@std/path/from-file-url";
/** The timeout ms for single test execution. If a single test didn't finish in this timeout milliseconds, the test is considered as failure */
const TIMEOUT = 2000;
async function main() {
const remainingTests = withoutAll(await getNodeTests(), await getDenoTests());
console.log(`Remaining tests: ${remainingTests.length}`);
const success = [] as string[];
let i = 0;
Deno.addSignalListener("SIGINT", () => {
console.log(`Success: ${success.length}`);
for (const testPath of success) {
console.log(testPath);
}
Deno.exit(1);
});
for (const testPath of remainingTests) {
i++;
const source = new URL(testPath, VENDORED_NODE_TEST);
const dest = new URL(testPath, NODE_COMPAT_TEST_DEST_URL);
await ensureDir(new URL(".", dest));
await copy(source, dest);
const num = String(i).padStart(4, " ");
try {
const cp = await runNodeCompatTestCase(
fromFileUrl(dest),
AbortSignal.timeout(TIMEOUT),
);
const result = await deadline(cp.output(), TIMEOUT + 1000);
if (result.code === 0) {
console.log(`${num} %cPASS`, "color: green", testPath);
success.push(testPath);
} else {
console.log(`${num} %cFAIL`, "color: red", testPath);
}
} catch (e) {
if (e instanceof DOMException && e.name === "TimeoutError") {
console.log(`${num} %cFAIL`, "color: red", testPath);
} else {
console.log(`Unexpected Error`, e);
}
} finally {
await Deno.remove(dest);
}
}
console.log(`Success: ${success.length}`);
for (const testPath of success) {
console.log(testPath);
}
Deno.exit(0);
}
await main();

View file

@ -1,137 +0,0 @@
#!/usr/bin/env -S deno run --allow-read=. --allow-write=. --allow-run=git --config=tests/config/deno.json
// Copyright 2018-2025 the Deno authors. MIT license.
// deno-lint-ignore-file no-console
/** This copies the test files according to the config file `tests/node_compat/config.jsonc` */
import { walk } from "@std/fs/walk";
import { SEPARATOR } from "@std/path/constants";
import { ensureFile } from "@std/fs/ensure-file";
import { writeAll } from "@std/io/write-all";
import { withoutAll } from "@std/collections/without-all";
import { version } from "./suite/node_version.ts";
import {
config,
getDenoTests,
getNodeTests,
ignoreList,
NODE_COMPAT_TEST_DEST_URL,
VENDORED_NODE_TEST,
} from "../common.ts";
const encoder = new TextEncoder();
const NODE_VERSION = version;
async function updateToDo() {
using file = await Deno.open(new URL("./TODO.md", import.meta.url), {
write: true,
create: true,
truncate: true,
});
const nodeTests = await getNodeTests();
const portedTests = await getDenoTests();
const remainingTests = withoutAll(nodeTests, portedTests);
const numPorted = portedTests.length;
const numMissing = remainingTests.length;
const numTotal = nodeTests.length;
const portedPercentage = (numPorted / numTotal * 100).toFixed(2);
const remainingPercentage = (numMissing / numTotal * 100).toFixed(2);
await file.write(encoder.encode(`<!-- deno-fmt-ignore-file -->
# Remaining Node Tests
${numPorted} tests out of ${numTotal} have been ported from Node ${NODE_VERSION} (${portedPercentage}% ported, ${remainingPercentage}% remaining).
NOTE: This file should not be manually edited. Please edit \`tests/node_compat/config.json\` and run \`deno task setup\` in \`tests/node_compat/runner\` dir instead.
`));
for (const test of remainingTests) {
await file.write(
encoder.encode(
`- [${test}](https://github.com/nodejs/node/tree/v${NODE_VERSION}/test/${test})\n`,
),
);
}
}
async function clearTests() {
console.log("Cleaning up previous tests");
for await (
const file of walk(NODE_COMPAT_TEST_DEST_URL, {
includeDirs: false,
skip: ignoreList,
})
) {
await Deno.remove(file.path);
}
}
/** Checks if file has entry in config.json */
function hasEntry(file: string, suite: string) {
return Array.isArray(config.tests[suite]) &&
config.tests[suite].includes(file);
}
async function copyTests() {
console.log("Copying test files...");
for await (const entry of walk(VENDORED_NODE_TEST, { skip: ignoreList })) {
const fragments = entry.path.split(SEPARATOR);
// suite is the directory name after test/. For example, if the file is
// "node_compat/node/test/fixtures/policy/main.mjs"
// then suite is "fixtures/policy"
const suite = fragments.slice(fragments.indexOf("node_compat") + 4, -1)
.join("/");
if (!hasEntry(entry.name, suite)) {
continue;
}
const dest = new URL(`${suite}/${entry.name}`, NODE_COMPAT_TEST_DEST_URL);
await ensureFile(dest);
const destFile = await Deno.open(dest, {
create: true,
truncate: true,
write: true,
});
const srcFile = await Deno.open(
new URL(`${suite}/${entry.name}`, VENDORED_NODE_TEST),
);
// Add header to js files
if (dest.pathname.endsWith("js")) {
await writeAll(
destFile,
encoder.encode(`// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node ${NODE_VERSION}
// This file is automatically generated by \`tests/node_compat/runner/setup.ts\`. Do not modify this file manually.
`),
);
}
await srcFile.readable.pipeTo(destFile.writable);
}
}
// main
await clearTests();
await copyTests();
await updateToDo();
if (Deno.args[0] === "--check") {
const cmd = new Deno.Command("git", {
args: ["status", "-s", "tests/node_compat/test"],
});
const { stdout } = await cmd.output();
if (stdout.length > 0) {
console.log("The following files have been changed:");
console.log(new TextDecoder().decode(stdout));
Deno.exit(1);
}
}

View file

@ -1,154 +1,62 @@
// Copyright 2018-2025 the Deno authors. MIT license.
// deno-lint-ignore-file no-console
/**
* This script will run the test files specified in the configuration file.
*
* Each test file will be run independently (in a separate process as this is
* what Node.js is doing) and we wait until it completes. If the process reports
* an abnormal code, the test is reported and the test suite will fail
* immediately.
*
* Some tests check for presence of certain `process.exitCode`.
* Some tests depends on directories/files created by other tests - they must
* all share the same working directory.
*/
import { magenta } from "@std/fmt/colors";
import { parse } from "@std/toml";
import { runSingle } from "./run_all_test_unmodified.ts";
import { assert } from "@std/assert";
import { partition } from "@std/collections/partition";
import { pooledMap } from "@std/async/pool";
import { dirname, fromFileUrl, join } from "@std/path";
import { assertEquals, fail } from "@std/assert";
import { distinct } from "@std/collections";
import {
config,
getPathsFromTestSuites,
partitionParallelTestPaths,
runNodeCompatTestCase,
} from "./common.ts";
// If the test case is invoked like
// deno test -A tests/node_compat/test.ts -- <test-names>
// Use the <test-names> as filters
const filters = Deno.args;
const hasFilters = filters.length > 0;
const toolsPath = dirname(fromFileUrl(import.meta.url));
const testPaths = partitionParallelTestPaths(
getPathsFromTestSuites(config.tests).concat(
getPathsFromTestSuites(config.ignore),
),
);
testPaths.sequential = distinct(testPaths.sequential);
testPaths.parallel = distinct(testPaths.parallel);
// This is a placeholder for the future extension of the config file.
// deno-lint-ignore ban-types
type SingleFileConfig = {};
type Config = {
tests: Record<string, SingleFileConfig>;
};
const windowsIgnorePaths = new Set(
getPathsFromTestSuites(config.windowsIgnore),
);
const darwinIgnorePaths = new Set(
getPathsFromTestSuites(config.darwinIgnore),
const configFile = await Deno.readTextFile(
new URL("./config.toml", import.meta.url),
).then(parse);
const [sequentialTests, parallelTests] = partition(
Object.entries((configFile as Config).tests),
([testName]) => testName.startsWith("sequential/"),
);
const decoder = new TextDecoder();
async function runTest(t: Deno.TestContext, path: string): Promise<void> {
// If filter patterns are given and any pattern doesn't match
// to the file path, then skip the case
if (
filters.length > 0 &&
filters.every((pattern) => !path.includes(pattern))
) {
return;
async function run(name: string) {
const result = await runSingle(name);
let msg = "";
const error = result.error;
if (error && "message" in error) {
msg = error.message;
} else if (error && "stderr" in error) {
msg = error.stderr;
} else if (error && "timeout" in error) {
msg = `Timed out after ${error.timeout}ms`;
}
const ignore =
(Deno.build.os === "windows" && windowsIgnorePaths.has(path)) ||
(Deno.build.os === "darwin" && darwinIgnorePaths.has(path));
await t.step({
name: `Node.js compatibility "${path}"`,
ignore,
sanitizeOps: false,
sanitizeResources: false,
sanitizeExit: false,
fn: async () => {
const testCase = join(toolsPath, "test", path);
const command = await runNodeCompatTestCase(testCase);
const warner = setTimeout(() => {
console.error(`Test is running slow: ${testCase}`);
}, 2 * 60_000);
const killer = setTimeout(() => {
console.error(
`Test ran far too long, terminating with extreme prejudice: ${testCase}`,
);
command.kill();
}, 10 * 60_000);
const { code, stdout, stderr } = await command.output();
clearTimeout(warner);
clearTimeout(killer);
assert(result.result === "pass", `Test "${name}" failed: ${msg}`);
}
if (code !== 0) {
// If the test case failed, show the stdout, stderr, and instruction
// for repeating the single test case.
if (stdout.length) {
console.log(decoder.decode(stdout));
}
const stderrOutput = decoder.decode(stderr);
const repeatCmd = magenta(
`./target/debug/deno test --config tests/config/deno.json -A tests/node_compat/test.ts -- ${path}`,
);
const msg = `"${magenta(path)}" failed:
${stderrOutput}
You can repeat only this test with the command:
${repeatCmd}
`;
console.log(msg);
fail(msg);
} else if (hasFilters) {
// Even if the test case is successful, shows the stdout and stderr
// when test case filtering is specified.
if (stdout.length) console.log(decoder.decode(stdout));
if (stderr.length) console.log(decoder.decode(stderr));
}
},
for (const [name, _testConfig] of sequentialTests) {
Deno.test("Node compat: " + name, async () => {
await run(name);
});
}
Deno.test("Node.js compatibility", async (t) => {
for (const path of testPaths.sequential) {
await runTest(t, path);
}
const testPool = pooledMap(
Deno.test("Node compat: parallel tests", async (t) => {
const iter = pooledMap(
navigator.hardwareConcurrency,
testPaths.parallel,
(path) => runTest(t, path),
parallelTests,
([name, _testConfig]) =>
t.step({
name,
fn: () => run(name),
sanitizeExit: false,
sanitizeOps: false,
sanitizeResources: false,
}),
);
const testCases = [];
for await (const testCase of testPool) {
testCases.push(testCase);
for await (const _ of iter) {
// Just iterate through the results to ensure all tests are run
}
await Promise.all(testCases);
});
function checkConfigTestFilesOrder(testFileLists: Array<string[]>) {
for (const testFileList of testFileLists) {
const sortedTestList = JSON.parse(JSON.stringify(testFileList));
sortedTestList.sort((a: string, b: string) =>
a.toLowerCase().localeCompare(b.toLowerCase())
);
assertEquals(
testFileList,
sortedTestList,
"File names in `config.json` are not correct order.",
);
}
}
if (!hasFilters) {
Deno.test("checkConfigTestFilesOrder", function () {
checkConfigTestFilesOrder([
...Object.keys(config.ignore).map((suite) => config.ignore[suite]),
...Object.keys(config.tests).map((suite) => config.tests[suite]),
]);
});
}

View file

@ -1,143 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const cp = require('child_process');
const { spawnSync } = require('child_process');
// This is a sibling test to test/addons/uv-handle-leak.
const bindingPath = path.resolve(
__dirname, '..', 'addons', 'uv-handle-leak', 'build',
`${common.buildType}/binding.node`);
if (!fs.existsSync(bindingPath))
common.skip('binding not built yet');
if (process.argv[2] === 'child') {
const { Worker } = require('worker_threads');
// The worker thread loads and then unloads `bindingPath`. Because of this the
// symbols in `bindingPath` are lost when the worker thread quits, but the
// number of open handles in the worker thread's event loop is assessed in the
// main thread afterwards, and the names of the callbacks associated with the
// open handles is retrieved at that time as well. Thus, we require
// `bindingPath` here so that the symbols and their names survive the life
// cycle of the worker thread.
require(bindingPath);
new Worker(`
const binding = require(${JSON.stringify(bindingPath)});
binding.leakHandle();
binding.leakHandle(0);
binding.leakHandle(0x42);
`, { eval: true });
} else {
const child = cp.spawnSync(process.execPath, [__filename, 'child']);
const stderr = child.stderr.toString();
assert.strictEqual(child.stdout.toString(), '');
const lines = stderr.split('\n');
let state = 'initial';
// Parse output that is formatted like this:
// uv loop at [0x559b65ed5770] has open handles:
// [0x7f2de0018430] timer (active)
// Close callback: 0x7f2df31de220 CloseCallback(uv_handle_s*) [...]
// Data: 0x7f2df33df140 example_instance [...]
// (First field): 0x7f2df33dedc0 vtable for ExampleOwnerClass [...]
// [0x7f2de000b870] timer
// Close callback: 0x7f2df31de220 CloseCallback(uv_handle_s*) [...]
// Data: (nil)
// [0x7f2de000b910] timer
// Close callback: 0x7f2df31de220 CloseCallback(uv_handle_s*) [...]
// Data: 0x42
// uv loop at [0x559b65ed5770] has 3 open handles in total
function isGlibc() {
try {
const lddOut = spawnSync('ldd', [process.execPath]).stdout;
const libcInfo = lddOut.toString().split('\n').map(
(line) => line.match(/libc\.so.+=>\s*(\S+)\s/)).filter((info) => info);
if (libcInfo.length === 0)
return false;
const nmOut = spawnSync('nm', ['-D', libcInfo[0][1]]).stdout;
if (/gnu_get_libc_version/.test(nmOut))
return true;
} catch {
return false;
}
}
if (!(common.isFreeBSD ||
common.isAIX ||
common.isIBMi ||
(common.isLinux && !isGlibc()) ||
common.isWindows)) {
assert(stderr.includes('ExampleOwnerClass'), stderr);
assert(stderr.includes('CloseCallback'), stderr);
assert(stderr.includes('example_instance'), stderr);
}
while (lines.length > 0) {
const line = lines.shift().trim();
if (line.length === 0) {
continue; // Skip empty lines.
}
switch (state) {
case 'initial':
assert.match(line, /^uv loop at \[.+\] has open handles:$/);
state = 'handle-start';
break;
case 'handle-start':
if (/^uv loop at \[.+\] has \d+ open handles in total$/.test(line)) {
state = 'source-line';
break;
}
assert.match(line, /^\[.+\] timer( \(active\))?$/);
state = 'close-callback';
break;
case 'close-callback':
assert.match(line, /^Close callback:/);
state = 'data';
break;
case 'data':
assert.match(line, /^Data: .+$/);
state = 'maybe-first-field';
break;
case 'maybe-first-field':
if (!/^\(First field\)/.test(line)) {
lines.unshift(line);
}
state = 'handle-start';
break;
case 'source-line':
assert.match(line, /CheckedUvLoopClose/);
state = 'assertion-failure';
break;
case 'assertion-failure':
assert.match(line, /Assertion failed:/);
state = 'done';
break;
case 'done':
break;
}
}
assert.strictEqual(state, 'done');
}

View file

@ -1,20 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
if (!common.enoughTestMem)
common.skip('Insufficient memory for async_hooks benchmark test');
const runBenchmark = require('../common/benchmark');
runBenchmark('async_hooks');

View file

@ -1,21 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
if (!common.enoughTestMem)
common.skip('Insufficient memory for HTTP benchmark test');
// Because the http benchmarks use hardcoded ports, this should be in sequential
// rather than parallel to make sure it does not conflict with tests that choose
// random available ports.
const runBenchmark = require('../common/benchmark');
runBenchmark('http', { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });

View file

@ -1,23 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
if (!common.enoughTestMem)
common.skip('Insufficient memory for HTTP/2 benchmark test');
// Because the http benchmarks use hardcoded ports, this should be in sequential
// rather than parallel to make sure it does not conflict with tests that choose
// random available ports.
const runBenchmark = require('../common/benchmark');
runBenchmark('http2', { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });

View file

@ -1,24 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
if (!common.enoughTestMem)
common.skip('Insufficient memory for TLS benchmark test');
// Because the TLS benchmarks use hardcoded ports, this should be in sequential
// rather than parallel to make sure it does not conflict with tests that choose
// random available ports.
const runBenchmark = require('../common/benchmark');
runBenchmark('tls', { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });

View file

@ -1,21 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
if (!common.enoughTestMem)
common.skip('Insufficient memory for Worker benchmark test');
// Because the worker benchmarks can run on different threads,
// this should be in sequential rather than parallel to make sure
// it does not conflict with tests that choose random available ports.
const runBenchmark = require('../common/benchmark');
runBenchmark('worker', { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });

View file

@ -1,163 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const assert = require('assert');
const { spawnSync, execFileSync } = require('child_process');
const common = require('./');
const util = require('util');
// Workaround for Windows Server 2008R2
// When CMD is used to launch a process and CMD is killed too quickly, the
// process can stay behind running in suspended state, never completing.
function cleanupStaleProcess(filename) {
if (!common.isWindows) {
return;
}
process.once('beforeExit', () => {
const basename = filename.replace(/.*[/\\]/g, '');
try {
execFileSync(`${process.env.SystemRoot}\\System32\\wbem\\WMIC.exe`, [
'process',
'where',
`commandline like '%${basename}%child'`,
'delete',
'/nointeractive',
]);
} catch {
// Ignore failures, there might not be any stale process to clean up.
}
});
}
// This should keep the child process running long enough to expire
// the timeout.
const kExpiringChildRunTime = common.platformTimeout(20 * 1000);
const kExpiringParentTimer = 1;
assert(kExpiringChildRunTime > kExpiringParentTimer);
function logAfterTime(time) {
setTimeout(() => {
// The following console statements are part of the test.
console.log('child stdout');
console.error('child stderr');
}, time);
}
function checkOutput(str, check) {
if ((check instanceof RegExp && !check.test(str)) ||
(typeof check === 'string' && check !== str)) {
return { passed: false, reason: `did not match ${util.inspect(check)}` };
}
if (typeof check === 'function') {
try {
check(str);
} catch (error) {
return {
passed: false,
reason: `did not match expectation, checker throws:\n${util.inspect(error)}`,
};
}
}
return { passed: true };
}
function expectSyncExit(caller, spawnArgs, {
status,
signal,
stderr: stderrCheck,
stdout: stdoutCheck,
trim = false,
}) {
const child = spawnSync(...spawnArgs);
const failures = [];
let stderrStr, stdoutStr;
if (status !== undefined && child.status !== status) {
failures.push(`- process terminated with status ${child.status}, expected ${status}`);
}
if (signal !== undefined && child.signal !== signal) {
failures.push(`- process terminated with signal ${child.signal}, expected ${signal}`);
}
function logAndThrow() {
const tag = `[process ${child.pid}]:`;
console.error(`${tag} --- stderr ---`);
console.error(stderrStr === undefined ? child.stderr.toString() : stderrStr);
console.error(`${tag} --- stdout ---`);
console.error(stdoutStr === undefined ? child.stdout.toString() : stdoutStr);
console.error(`${tag} status = ${child.status}, signal = ${child.signal}`);
const error = new Error(`${failures.join('\n')}`);
if (spawnArgs[2]) {
error.options = spawnArgs[2];
}
let command = spawnArgs[0];
if (Array.isArray(spawnArgs[1])) {
command += ' ' + spawnArgs[1].join(' ');
}
error.command = command;
Error.captureStackTrace(error, caller);
throw error;
}
// If status and signal are not matching expectations, fail early.
if (failures.length !== 0) {
logAndThrow();
}
if (stderrCheck !== undefined) {
stderrStr = child.stderr.toString();
const { passed, reason } = checkOutput(trim ? stderrStr.trim() : stderrStr, stderrCheck);
if (!passed) {
failures.push(`- stderr ${reason}`);
}
}
if (stdoutCheck !== undefined) {
stdoutStr = child.stdout.toString();
const { passed, reason } = checkOutput(trim ? stdoutStr.trim() : stdoutStr, stdoutCheck);
if (!passed) {
failures.push(`- stdout ${reason}`);
}
}
if (failures.length !== 0) {
logAndThrow();
}
return { child, stderr: stderrStr, stdout: stdoutStr };
}
function spawnSyncAndExit(...args) {
const spawnArgs = args.slice(0, args.length - 1);
const expectations = args[args.length - 1];
return expectSyncExit(spawnSyncAndExit, spawnArgs, expectations);
}
function spawnSyncAndExitWithoutError(...args) {
return expectSyncExit(spawnSyncAndExitWithoutError, [...args], {
status: 0,
signal: null,
});
}
function spawnSyncAndAssert(...args) {
const expectations = args.pop();
return expectSyncExit(spawnSyncAndAssert, [...args], {
status: 0,
signal: null,
...expectations,
});
}
module.exports = {
cleanupStaleProcess,
logAfterTime,
kExpiringChildRunTime,
kExpiringParentTimer,
spawnSyncAndAssert,
spawnSyncAndExit,
spawnSyncAndExitWithoutError,
};

View file

@ -1,35 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const assert = require('assert');
const kLimit = Symbol('limit');
const kCallback = Symbol('callback');
const common = require('./');
class Countdown {
constructor(limit, cb) {
assert.strictEqual(typeof limit, 'number');
assert.strictEqual(typeof cb, 'function');
this[kLimit] = limit;
this[kCallback] = common.mustCall(cb);
}
dec() {
assert(this[kLimit] > 0, 'Countdown expired');
if (--this[kLimit] === 0)
this[kCallback]();
return this[kLimit];
}
get remaining() {
return this[kLimit];
}
}
module.exports = Countdown;

View file

@ -1,171 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
if (!common.hasCrypto) {
common.skip('missing crypto');
}
const assert = require('assert');
const crypto = require('crypto');
const {
createSign,
createVerify,
publicEncrypt,
privateDecrypt,
sign,
verify,
} = crypto;
// The values below (modp2/modp2buf) are for a 1024 bits long prime from
// RFC 2412 E.2, see https://tools.ietf.org/html/rfc2412. */
const modp2buf = Buffer.from([
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f,
0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b,
0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67,
0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22,
0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95,
0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d,
0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51,
0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6,
0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff,
0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb,
0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b,
0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
]);
// Asserts that the size of the given key (in chars or bytes) is within 10% of
// the expected size.
function assertApproximateSize(key, expectedSize) {
const u = typeof key === 'string' ? 'chars' : 'bytes';
const min = Math.floor(0.9 * expectedSize);
const max = Math.ceil(1.1 * expectedSize);
assert(key.length >= min,
`Key (${key.length} ${u}) is shorter than expected (${min} ${u})`);
assert(key.length <= max,
`Key (${key.length} ${u}) is longer than expected (${max} ${u})`);
}
// Tests that a key pair can be used for encryption / decryption.
function testEncryptDecrypt(publicKey, privateKey) {
const message = 'Hello Node.js world!';
const plaintext = Buffer.from(message, 'utf8');
for (const key of [publicKey, privateKey]) {
const ciphertext = publicEncrypt(key, plaintext);
const received = privateDecrypt(privateKey, ciphertext);
assert.strictEqual(received.toString('utf8'), message);
}
}
// Tests that a key pair can be used for signing / verification.
function testSignVerify(publicKey, privateKey) {
const message = Buffer.from('Hello Node.js world!');
function oldSign(algo, data, key) {
return createSign(algo).update(data).sign(key);
}
function oldVerify(algo, data, key, signature) {
return createVerify(algo).update(data).verify(key, signature);
}
for (const signFn of [sign, oldSign]) {
const signature = signFn('SHA256', message, privateKey);
for (const verifyFn of [verify, oldVerify]) {
for (const key of [publicKey, privateKey]) {
const okay = verifyFn('SHA256', message, key, signature);
assert(okay);
}
}
}
}
// Constructs a regular expression for a PEM-encoded key with the given label.
function getRegExpForPEM(label, cipher) {
const head = `\\-\\-\\-\\-\\-BEGIN ${label}\\-\\-\\-\\-\\-`;
const rfc1421Header = cipher == null ? '' :
`\nProc-Type: 4,ENCRYPTED\nDEK-Info: ${cipher},[^\n]+\n`;
const body = '([a-zA-Z0-9\\+/=]{64}\n)*[a-zA-Z0-9\\+/=]{1,64}';
const end = `\\-\\-\\-\\-\\-END ${label}\\-\\-\\-\\-\\-`;
return new RegExp(`^${head}${rfc1421Header}\n${body}\n${end}\n$`);
}
const pkcs1PubExp = getRegExpForPEM('RSA PUBLIC KEY');
const pkcs1PrivExp = getRegExpForPEM('RSA PRIVATE KEY');
const pkcs1EncExp = (cipher) => getRegExpForPEM('RSA PRIVATE KEY', cipher);
const spkiExp = getRegExpForPEM('PUBLIC KEY');
const pkcs8Exp = getRegExpForPEM('PRIVATE KEY');
const pkcs8EncExp = getRegExpForPEM('ENCRYPTED PRIVATE KEY');
const sec1Exp = getRegExpForPEM('EC PRIVATE KEY');
const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
// Synthesize OPENSSL_VERSION_NUMBER format with the layout 0xMNN00PPSL
const opensslVersionNumber = (major = 0, minor = 0, patch = 0) => {
assert(major >= 0 && major <= 0xf);
assert(minor >= 0 && minor <= 0xff);
assert(patch >= 0 && patch <= 0xff);
return (major << 28) | (minor << 20) | (patch << 4);
};
let OPENSSL_VERSION_NUMBER;
const hasOpenSSL = (major = 0, minor = 0, patch = 0) => {
if (!common.hasCrypto) return false;
if (OPENSSL_VERSION_NUMBER === undefined) {
const regexp = /(?<m>\d+)\.(?<n>\d+)\.(?<p>\d+)/;
const { m, n, p } = process.versions.openssl.match(regexp).groups;
OPENSSL_VERSION_NUMBER = opensslVersionNumber(m, n, p);
}
return OPENSSL_VERSION_NUMBER >= opensslVersionNumber(major, minor, patch);
};
let opensslCli = null;
module.exports = {
modp2buf,
assertApproximateSize,
testEncryptDecrypt,
testSignVerify,
pkcs1PubExp,
pkcs1PrivExp,
pkcs1EncExp, // used once
spkiExp,
pkcs8Exp, // used once
pkcs8EncExp, // used once
sec1Exp,
sec1EncExp,
hasOpenSSL,
get hasOpenSSL3() {
return hasOpenSSL(3);
},
// opensslCli defined lazily to reduce overhead of spawnSync
get opensslCli() {
if (opensslCli !== null) return opensslCli;
if (process.config.variables.node_shared_openssl) {
// Use external command
opensslCli = 'openssl';
} else {
const path = require('path');
// Use command built from sources included in Node.js repository
opensslCli = path.join(path.dirname(process.execPath), 'openssl-cli');
}
if (exports.isWindows) opensslCli += '.exe';
const { spawnSync } = require('child_process');
const opensslCmd = spawnSync(opensslCli, ['version']);
if (opensslCmd.status !== 0 || opensslCmd.error !== undefined) {
// OpenSSL command cannot be executed
opensslCli = false;
}
return opensslCli;
},
};

View file

@ -1,348 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const assert = require('assert');
const os = require('os');
const { isIP } = require('net');
const types = {
A: 1,
AAAA: 28,
NS: 2,
CNAME: 5,
SOA: 6,
PTR: 12,
MX: 15,
TXT: 16,
ANY: 255,
CAA: 257,
};
const classes = {
IN: 1,
};
// Naïve DNS parser/serializer.
function readDomainFromPacket(buffer, offset) {
assert.ok(offset < buffer.length);
const length = buffer[offset];
if (length === 0) {
return { nread: 1, domain: '' };
} else if ((length & 0xC0) === 0) {
offset += 1;
const chunk = buffer.toString('ascii', offset, offset + length);
// Read the rest of the domain.
const { nread, domain } = readDomainFromPacket(buffer, offset + length);
return {
nread: 1 + length + nread,
domain: domain ? `${chunk}.${domain}` : chunk,
};
}
// Pointer to another part of the packet.
assert.strictEqual(length & 0xC0, 0xC0);
// eslint-disable-next-line @stylistic/js/space-infix-ops, @stylistic/js/space-unary-ops
const pointeeOffset = buffer.readUInt16BE(offset) &~ 0xC000;
return {
nread: 2,
domain: readDomainFromPacket(buffer, pointeeOffset),
};
}
function parseDNSPacket(buffer) {
assert.ok(buffer.length > 12);
const parsed = {
id: buffer.readUInt16BE(0),
flags: buffer.readUInt16BE(2),
};
const counts = [
['questions', buffer.readUInt16BE(4)],
['answers', buffer.readUInt16BE(6)],
['authorityAnswers', buffer.readUInt16BE(8)],
['additionalRecords', buffer.readUInt16BE(10)],
];
let offset = 12;
for (const [ sectionName, count ] of counts) {
parsed[sectionName] = [];
for (let i = 0; i < count; ++i) {
const { nread, domain } = readDomainFromPacket(buffer, offset);
offset += nread;
const type = buffer.readUInt16BE(offset);
const rr = {
domain,
cls: buffer.readUInt16BE(offset + 2),
};
offset += 4;
for (const name in types) {
if (types[name] === type)
rr.type = name;
}
if (sectionName !== 'questions') {
rr.ttl = buffer.readInt32BE(offset);
const dataLength = buffer.readUInt16BE(offset);
offset += 6;
switch (type) {
case types.A:
assert.strictEqual(dataLength, 4);
rr.address = `${buffer[offset + 0]}.${buffer[offset + 1]}.` +
`${buffer[offset + 2]}.${buffer[offset + 3]}`;
break;
case types.AAAA:
assert.strictEqual(dataLength, 16);
rr.address = buffer.toString('hex', offset, offset + 16)
.replace(/(.{4}(?!$))/g, '$1:');
break;
case types.TXT:
{
let position = offset;
rr.entries = [];
while (position < offset + dataLength) {
const txtLength = buffer[offset];
rr.entries.push(buffer.toString('utf8',
position + 1,
position + 1 + txtLength));
position += 1 + txtLength;
}
assert.strictEqual(position, offset + dataLength);
break;
}
case types.MX:
{
rr.priority = buffer.readInt16BE(buffer, offset);
offset += 2;
const { nread, domain } = readDomainFromPacket(buffer, offset);
rr.exchange = domain;
assert.strictEqual(nread, dataLength);
break;
}
case types.NS:
case types.CNAME:
case types.PTR:
{
const { nread, domain } = readDomainFromPacket(buffer, offset);
rr.value = domain;
assert.strictEqual(nread, dataLength);
break;
}
case types.SOA:
{
const mname = readDomainFromPacket(buffer, offset);
const rname = readDomainFromPacket(buffer, offset + mname.nread);
rr.nsname = mname.domain;
rr.hostmaster = rname.domain;
const trailerOffset = offset + mname.nread + rname.nread;
rr.serial = buffer.readUInt32BE(trailerOffset);
rr.refresh = buffer.readUInt32BE(trailerOffset + 4);
rr.retry = buffer.readUInt32BE(trailerOffset + 8);
rr.expire = buffer.readUInt32BE(trailerOffset + 12);
rr.minttl = buffer.readUInt32BE(trailerOffset + 16);
assert.strictEqual(trailerOffset + 20, dataLength);
break;
}
default:
throw new Error(`Unknown RR type ${rr.type}`);
}
offset += dataLength;
}
parsed[sectionName].push(rr);
assert.ok(offset <= buffer.length);
}
}
assert.strictEqual(offset, buffer.length);
return parsed;
}
function writeIPv6(ip) {
const parts = ip.replace(/^:|:$/g, '').split(':');
const buf = Buffer.alloc(16);
let offset = 0;
for (const part of parts) {
if (part === '') {
offset += 16 - 2 * (parts.length - 1);
} else {
buf.writeUInt16BE(parseInt(part, 16), offset);
offset += 2;
}
}
return buf;
}
function writeDomainName(domain) {
return Buffer.concat(domain.split('.').map((label) => {
assert(label.length < 64);
return Buffer.concat([
Buffer.from([label.length]),
Buffer.from(label, 'ascii'),
]);
}).concat([Buffer.alloc(1)]));
}
function writeDNSPacket(parsed) {
const buffers = [];
const kStandardResponseFlags = 0x8180;
buffers.push(new Uint16Array([
parsed.id,
parsed.flags ?? kStandardResponseFlags,
parsed.questions?.length,
parsed.answers?.length,
parsed.authorityAnswers?.length,
parsed.additionalRecords?.length,
]));
for (const q of parsed.questions) {
assert(types[q.type]);
buffers.push(writeDomainName(q.domain));
buffers.push(new Uint16Array([
types[q.type],
q.cls === undefined ? classes.IN : q.cls,
]));
}
for (const rr of [].concat(parsed.answers,
parsed.authorityAnswers,
parsed.additionalRecords)) {
if (!rr) continue;
assert(types[rr.type]);
buffers.push(writeDomainName(rr.domain));
buffers.push(new Uint16Array([
types[rr.type],
rr.cls === undefined ? classes.IN : rr.cls,
]));
buffers.push(new Int32Array([rr.ttl]));
const rdLengthBuf = new Uint16Array(1);
buffers.push(rdLengthBuf);
switch (rr.type) {
case 'A':
rdLengthBuf[0] = 4;
buffers.push(new Uint8Array(rr.address.split('.')));
break;
case 'AAAA':
rdLengthBuf[0] = 16;
buffers.push(writeIPv6(rr.address));
break;
case 'TXT': {
const total = rr.entries.map((s) => s.length).reduce((a, b) => a + b);
// Total length of all strings + 1 byte each for their lengths.
rdLengthBuf[0] = rr.entries.length + total;
for (const txt of rr.entries) {
buffers.push(new Uint8Array([Buffer.byteLength(txt)]));
buffers.push(Buffer.from(txt));
}
break;
}
case 'MX':
rdLengthBuf[0] = 2;
buffers.push(new Uint16Array([rr.priority]));
// fall through
case 'NS':
case 'CNAME':
case 'PTR':
{
const domain = writeDomainName(rr.exchange || rr.value);
rdLengthBuf[0] += domain.length;
buffers.push(domain);
break;
}
case 'SOA':
{
const mname = writeDomainName(rr.nsname);
const rname = writeDomainName(rr.hostmaster);
rdLengthBuf[0] = mname.length + rname.length + 20;
buffers.push(mname, rname);
buffers.push(new Uint32Array([
rr.serial, rr.refresh, rr.retry, rr.expire, rr.minttl,
]));
break;
}
case 'CAA':
{
rdLengthBuf[0] = 5 + rr.issue.length + 2;
buffers.push(Buffer.from([Number(rr.critical)]));
buffers.push(Buffer.from([Number(5)]));
buffers.push(Buffer.from('issue' + rr.issue));
break;
}
default:
throw new Error(`Unknown RR type ${rr.type}`);
}
}
return Buffer.concat(buffers.map((typedArray) => {
const buf = Buffer.from(typedArray.buffer,
typedArray.byteOffset,
typedArray.byteLength);
if (os.endianness() === 'LE') {
if (typedArray.BYTES_PER_ELEMENT === 2) buf.swap16();
if (typedArray.BYTES_PER_ELEMENT === 4) buf.swap32();
}
return buf;
}));
}
const mockedErrorCode = 'ENOTFOUND';
const mockedSysCall = 'getaddrinfo';
function errorLookupMock(code = mockedErrorCode, syscall = mockedSysCall) {
return function lookupWithError(hostname, dnsopts, cb) {
const err = new Error(`${syscall} ${code} ${hostname}`);
err.code = code;
err.errno = code;
err.syscall = syscall;
err.hostname = hostname;
cb(err);
};
}
function createMockedLookup(...addresses) {
addresses = addresses.map((address) => ({ address: address, family: isIP(address) }));
// Create a DNS server which replies with a AAAA and a A record for the same host
return function lookup(hostname, options, cb) {
if (options.all === true) {
process.nextTick(() => {
cb(null, addresses);
});
return;
}
process.nextTick(() => {
cb(null, addresses[0].address, addresses[0].family);
});
};
}
module.exports = {
types,
classes,
writeDNSPacket,
parseDNSPacket,
errorLookupMock,
mockedErrorCode,
mockedSysCall,
createMockedLookup,
};

View file

@ -1,55 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 20.11.1
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const { Duplex } = require('stream');
const assert = require('assert');
const kCallback = Symbol('Callback');
const kOtherSide = Symbol('Other');
class DuplexSocket extends Duplex {
constructor() {
super();
this[kCallback] = null;
this[kOtherSide] = null;
}
_read() {
const callback = this[kCallback];
if (callback) {
this[kCallback] = null;
callback();
}
}
_write(chunk, encoding, callback) {
assert.notStrictEqual(this[kOtherSide], null);
assert.strictEqual(this[kOtherSide][kCallback], null);
if (chunk.length === 0) {
process.nextTick(callback);
} else {
this[kOtherSide].push(chunk);
this[kOtherSide][kCallback] = callback;
}
}
_final(callback) {
this[kOtherSide].on('end', callback);
this[kOtherSide].push(null);
}
}
function makeDuplexPair() {
const clientSide = new DuplexSocket();
const serverSide = new DuplexSocket();
clientSide[kOtherSide] = serverSide;
serverSide[kOtherSide] = clientSide;
return { clientSide, serverSide };
}
module.exports = makeDuplexPair;

View file

@ -1,66 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const path = require('path');
const fs = require('fs');
const { pathToFileURL } = require('url');
const fixturesDir = path.join(__dirname, '..', 'fixtures');
function fixturesPath(...args) {
return path.join(fixturesDir, ...args);
}
function fixturesFileURL(...args) {
return pathToFileURL(fixturesPath(...args));
}
function readFixtureSync(args, enc) {
if (Array.isArray(args))
return fs.readFileSync(fixturesPath(...args), enc);
return fs.readFileSync(fixturesPath(args), enc);
}
function readFixtureKey(name, enc) {
return fs.readFileSync(fixturesPath('keys', name), enc);
}
function readFixtureKeys(enc, ...names) {
return names.map((name) => readFixtureKey(name, enc));
}
// This should be in sync with test/fixtures/utf8_test_text.txt.
// We copy them here as a string because this is supposed to be used
// in fs API tests.
const utf8TestText = '永和九年,嵗在癸丑,暮春之初,會於會稽山隂之蘭亭,脩稧事也。' +
'羣賢畢至,少長咸集。此地有崇山峻領,茂林脩竹;又有清流激湍,' +
'暎帶左右。引以為流觴曲水,列坐其次。雖無絲竹管弦之盛,一觴一詠,' +
'亦足以暢敘幽情。是日也,天朗氣清,恵風和暢;仰觀宇宙之大,' +
'俯察品類之盛;所以遊目騁懐,足以極視聽之娛,信可樂也。夫人之相與,' +
'俯仰一世,或取諸懐抱,悟言一室之內,或因寄所託,放浪形骸之外。' +
'雖趣舎萬殊,靜躁不同,當其欣扵所遇,暫得扵己,怏然自足,' +
'不知老之將至。及其所之既惓,情隨事遷,感慨係之矣。向之所欣,' +
'俛仰之閒以為陳跡,猶不能不以之興懐;況脩短隨化,終期扵盡。' +
'古人云:「死生亦大矣。」豈不痛哉!每攬昔人興感之由,若合一契,' +
'未嘗不臨文嗟悼,不能喻之扵懐。固知一死生為虛誕,齊彭殤為妄作。' +
'後之視今,亦由今之視昔,悲夫!故列敘時人,錄其所述,雖世殊事異,' +
'所以興懐,其致一也。後之攬者,亦將有感扵斯文。';
module.exports = {
fixturesDir,
path: fixturesPath,
fileURL: fixturesFileURL,
readSync: readFixtureSync,
readKey: readFixtureKey,
readKeys: readFixtureKeys,
utf8TestText,
get utf8TestTextPath() {
return fixturesPath('utf8_test_text.txt');
},
};

View file

@ -1,39 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
// Hijack stdout and stderr
const stdWrite = {};
function hijackStdWritable(name, listener) {
const stream = process[name];
const _write = stdWrite[name] = stream.write;
stream.writeTimes = 0;
stream.write = function(data, callback) {
try {
listener(data);
} catch (e) {
process.nextTick(() => { throw e; });
}
_write.call(stream, data, callback);
stream.writeTimes++;
};
}
function restoreWritable(name) {
process[name].write = stdWrite[name];
delete process[name].writeTimes;
}
module.exports = {
hijackStdout: hijackStdWritable.bind(null, 'stdout'),
hijackStderr: hijackStdWritable.bind(null, 'stderr'),
restoreStdout: restoreWritable.bind(null, 'stdout'),
restoreStderr: restoreWritable.bind(null, 'stderr'),
};

View file

@ -1,534 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
/**
* This file is meant as a replacement for the original common/index.js
*
* That file has a lot of node functionality not currently supported, so this is a lite
* version of that file, which most tests should be able to use
*/
'use strict';
const assert = require("assert");
const { spawn } = require('child_process');
const path = require("path");
const util = require("util");
const tmpdir = require("./tmpdir");
function platformTimeout(ms) {
return ms;
}
let localhostIPv4 = null;
let knownGlobals = [
AbortSignal,
addEventListener,
alert,
atob,
btoa,
Buffer,
caches,
clearImmediate,
close,
closed,
confirm,
console,
createImageBitmap,
crypto,
Deno,
dispatchEvent,
EventSource,
fetch,
getParent,
global,
global.clearInterval,
global.clearTimeout,
global.setInterval,
global.setTimeout,
localStorage,
location,
name,
navigator,
onload,
onunload,
process,
prompt,
queueMicrotask,
removeEventListener,
reportError,
sessionStorage,
setImmediate,
];
if (global.AbortController)
knownGlobals.push(global.AbortController);
if (global.gc) {
knownGlobals.push(global.gc);
}
if (global.performance) {
knownGlobals.push(global.performance);
}
if (global.PerformanceMark) {
knownGlobals.push(global.PerformanceMark);
}
if (global.PerformanceMeasure) {
knownGlobals.push(global.PerformanceMeasure);
}
if (global.structuredClone) {
knownGlobals.push(global.structuredClone);
}
function allowGlobals(...allowlist) {
knownGlobals = knownGlobals.concat(allowlist);
}
if (process.env.NODE_TEST_KNOWN_GLOBALS !== '0') {
if (process.env.NODE_TEST_KNOWN_GLOBALS) {
const knownFromEnv = process.env.NODE_TEST_KNOWN_GLOBALS.split(',').map((name) => global[name]);
allowGlobals(...knownFromEnv);
}
function leakedGlobals() {
const leaked = [];
for (const val in global) {
if (!knownGlobals.includes(global[val])) {
leaked.push(val);
}
}
return leaked;
}
process.on('exit', function() {
const leaked = leakedGlobals();
if (leaked.length > 0) {
assert.fail(`Unexpected global(s) found: ${leaked.join(', ')}`);
}
});
}
function _expectWarning(name, expected, code) {
if (typeof expected === 'string') {
expected = [[expected, code]];
} else if (!Array.isArray(expected)) {
expected = Object.entries(expected).map(([a, b]) => [b, a]);
} else if (expected.length !== 0 && !Array.isArray(expected[0])) {
expected = [[expected[0], expected[1]]];
}
// Deprecation codes are mandatory, everything else is not.
if (name === 'DeprecationWarning') {
expected.forEach(([_, code]) => assert(code, `Missing deprecation code: ${expected}`));
}
return mustCall((warning) => {
const [ message, code ] = expected.shift();
assert.strictEqual(warning.name, name);
if (typeof message === 'string') {
assert.strictEqual(warning.message, message);
} else {
assert.match(warning.message, message);
}
assert.strictEqual(warning.code, code);
}, expected.length);
}
let catchWarning;
// Accepts a warning name and description or array of descriptions or a map of
// warning names to description(s) ensures a warning is generated for each
// name/description pair.
// The expected messages have to be unique per `expectWarning()` call.
function expectWarning(nameOrMap, expected, code) {
if (catchWarning === undefined) {
catchWarning = {};
process.on('warning', (warning) => {
if (!catchWarning[warning.name]) {
throw new TypeError(
`"${warning.name}" was triggered without being expected.\n` +
util.inspect(warning)
);
}
catchWarning[warning.name](warning);
});
}
if (typeof nameOrMap === 'string') {
catchWarning[nameOrMap] = _expectWarning(nameOrMap, expected, code);
} else {
Object.keys(nameOrMap).forEach((name) => {
catchWarning[name] = _expectWarning(name, nameOrMap[name]);
});
}
}
/**
* Useful for testing expected internal/error objects
*
* @param {Error} error
*/
function expectsError(validator, exact) {
/**
* @param {Error} error
*/
return mustCall((...args) => {
if (args.length !== 1) {
// Do not use `assert.strictEqual()` to prevent `inspect` from
// always being called.
assert.fail(`Expected one argument, got ${util.inspect(args)}`);
}
const error = args.pop();
const descriptor = Object.getOwnPropertyDescriptor(error, 'message');
// The error message should be non-enumerable
assert.strictEqual(descriptor.enumerable, false);
assert.throws(() => { throw error; }, validator);
return true;
}, exact);
}
const noop = () => {};
/**
* @param {Function} fn
* @param {number} exact
*/
function mustCall(fn, exact) {
return _mustCallInner(fn, exact, "exact");
}
function mustCallAtLeast(fn, minimum) {
return _mustCallInner(fn, minimum, 'minimum');
}
function mustSucceed(fn, exact) {
return mustCall(function(err, ...args) {
assert.ifError(err);
if (typeof fn === 'function')
return fn.apply(this, args);
}, exact);
}
const mustCallChecks = [];
/**
* @param {number} exitCode
*/
function runCallChecks(exitCode) {
if (exitCode !== 0) return;
const failed = mustCallChecks.filter(function (context) {
if ("minimum" in context) {
context.messageSegment = `at least ${context.minimum}`;
return context.actual < context.minimum;
}
context.messageSegment = `exactly ${context.exact}`;
return context.actual !== context.exact;
});
failed.forEach(function (context) {
console.log(
"Mismatched %s function calls. Expected %s, actual %d.",
context.name,
context.messageSegment,
context.actual,
);
console.log(context.stack.split("\n").slice(2).join("\n"));
});
if (failed.length) process.exit(1);
}
/**
* @param {Function} fn
* @param {"exact" | "minimum"} field
*/
function _mustCallInner(fn, criteria = 1, field) {
// @ts-ignore
if (process._exiting) {
throw new Error("Cannot use common.mustCall*() in process exit handler");
}
if (typeof fn === "number") {
criteria = fn;
fn = noop;
} else if (fn === undefined) {
fn = noop;
}
if (typeof criteria !== "number") {
throw new TypeError(`Invalid ${field} value: ${criteria}`);
}
let context;
if (field === "exact") {
context = {
exact: criteria,
actual: 0,
stack: util.inspect(new Error()),
name: fn.name || "<anonymous>",
};
} else {
context = {
minimum: criteria,
actual: 0,
stack: util.inspect(new Error()),
name: fn.name || "<anonymous>",
};
}
// Add the exit listener only once to avoid listener leak warnings
if (mustCallChecks.length === 0) process.on("exit", runCallChecks);
mustCallChecks.push(context);
return function () {
context.actual++;
return fn.apply(this, arguments);
};
}
/**
* @param {string=} msg
*/
function mustNotCall(msg) {
/**
* @param {any[]} args
*/
return function mustNotCall(...args) {
const argsInfo = args.length > 0
? `\ncalled with arguments: ${args.map(util.inspect).join(", ")}`
: "";
assert.fail(
`${msg || "function should not have been called"} at unknown` +
argsInfo,
);
};
}
const _mustNotMutateObjectDeepProxies = new WeakMap();
function mustNotMutateObjectDeep(original) {
// Return primitives and functions directly. Primitives are immutable, and
// proxied functions are impossible to compare against originals, e.g. with
// `assert.deepEqual()`.
if (original === null || typeof original !== 'object') {
return original;
}
const cachedProxy = _mustNotMutateObjectDeepProxies.get(original);
if (cachedProxy) {
return cachedProxy;
}
const _mustNotMutateObjectDeepHandler = {
__proto__: null,
defineProperty(target, property, descriptor) {
assert.fail(`Expected no side effects, got ${inspect(property)} ` +
'defined');
},
deleteProperty(target, property) {
assert.fail(`Expected no side effects, got ${inspect(property)} ` +
'deleted');
},
get(target, prop, receiver) {
return mustNotMutateObjectDeep(Reflect.get(target, prop, receiver));
},
preventExtensions(target) {
assert.fail('Expected no side effects, got extensions prevented on ' +
inspect(target));
},
set(target, property, value, receiver) {
assert.fail(`Expected no side effects, got ${inspect(value)} ` +
`assigned to ${inspect(property)}`);
},
setPrototypeOf(target, prototype) {
assert.fail(`Expected no side effects, got set prototype to ${prototype}`);
}
};
const proxy = new Proxy(original, _mustNotMutateObjectDeepHandler);
_mustNotMutateObjectDeepProxies.set(original, proxy);
return proxy;
}
// A helper function to simplify checking for ERR_INVALID_ARG_TYPE output.
function invalidArgTypeHelper(input) {
if (input == null) {
return ` Received ${input}`;
}
if (typeof input === "function") {
return ` Received function ${input.name}`;
}
if (typeof input === "object") {
if (input.constructor && input.constructor.name) {
return ` Received an instance of ${input.constructor.name}`;
}
return ` Received ${util.inspect(input, { depth: -1 })}`;
}
let inspected = util.inspect(input, { colors: false });
if (inspected.length > 25) {
inspected = `${inspected.slice(0, 25)}...`;
}
return ` Received type ${typeof input} (${inspected})`;
}
const isWindows = process.platform === 'win32';
const isAIX = process.platform === 'aix';
const isSunOS = process.platform === 'sunos';
const isFreeBSD = process.platform === 'freebsd';
const isOpenBSD = process.platform === 'openbsd';
const isLinux = process.platform === 'linux';
const isMacOS = process.platform === 'darwin';
/**
* Tests from older versions of Node.js still use `isOSX` to check for macOS.
* Let's keep it for compatibility until all tests are updated.
* @deprecated Use `isMacOS` instead.
*/
const isOSX = isMacOS;
const isDumbTerminal = process.env.TERM === 'dumb';
function skipIfDumbTerminal() {
if (isDumbTerminal) {
skip('skipping - dumb terminal');
}
}
function printSkipMessage(msg) {
console.log(`1..0 # Skipped: ${msg}`);
}
function skip(msg) {
printSkipMessage(msg);
process.exit(0);
}
const PIPE = (() => {
const localRelative = path.relative(process.cwd(), `${tmpdir.path}/`);
const pipePrefix = isWindows ? "\\\\.\\pipe\\" : localRelative;
const pipeName = `node-test.${process.pid}.sock`;
return path.join(pipePrefix, pipeName);
})();
function getArrayBufferViews(buf) {
const { buffer, byteOffset, byteLength } = buf;
const out = [];
const arrayBufferViews = [
Int8Array,
Uint8Array,
Uint8ClampedArray,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array,
DataView,
];
for (const type of arrayBufferViews) {
const { BYTES_PER_ELEMENT = 1 } = type;
if (byteLength % BYTES_PER_ELEMENT === 0) {
out.push(new type(buffer, byteOffset, byteLength / BYTES_PER_ELEMENT));
}
}
return out;
}
function getBufferSources(buf) {
return [...getArrayBufferViews(buf), new Uint8Array(buf).buffer];
}
const pwdCommand = isWindows ?
['cmd.exe', ['/d', '/c', 'cd']] :
['pwd', []];
function spawnPromisified(...args) {
let stderr = '';
let stdout = '';
const child = spawn(...args);
child.stderr.setEncoding('utf8');
child.stderr.on('data', (data) => { stderr += data; });
child.stdout.setEncoding('utf8');
child.stdout.on('data', (data) => { stdout += data; });
return new Promise((resolve, reject) => {
child.on('close', (code, signal) => {
resolve({
code,
signal,
stderr,
stdout,
});
});
child.on('error', (code, signal) => {
reject({
code,
signal,
stderr,
stdout,
});
});
});
}
module.exports = {
allowGlobals,
defaultAutoSelectFamilyAttemptTimeout: 2500,
expectsError,
expectWarning,
getArrayBufferViews,
getBufferSources,
hasCrypto: true,
hasIntl: true,
hasMultiLocalhost() {
return false;
},
invalidArgTypeHelper,
mustCall,
mustCallAtLeast,
mustNotCall,
mustNotMutateObjectDeep,
mustSucceed,
PIPE,
platformTimeout,
printSkipMessage,
pwdCommand,
skipIfDumbTerminal,
spawnPromisified,
isDumbTerminal,
isWindows,
isAIX,
isSunOS,
isFreeBSD,
isOpenBSD,
isLinux,
isMacOS,
isOSX,
isMainThread: true, // TODO(f3n67u): replace with `worker_thread.isMainThread` when `worker_thread` implemented
skip,
get hasIPv6() {
const iFaces = require('os').networkInterfaces();
const re = isWindows ? /Loopback Pseudo-Interface/ : /lo/;
return Object.keys(iFaces).some((name) => {
return re.test(name) &&
iFaces[name].some(({ family }) => family === 'IPv6');
});
},
get localhostIPv4() {
if (localhostIPv4 !== null) return localhostIPv4;
if (localhostIPv4 === null) localhostIPv4 = '127.0.0.1';
return localhostIPv4;
},
get PORT() {
return 12346;
},
};

View file

@ -1,103 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const common = require('./index.js');
const {
allowGlobals,
buildType,
canCreateSymLink,
childShouldThrowAndAbort,
enoughTestMem,
escapePOSIXShell,
expectsError,
expectWarning,
getArrayBufferViews,
getBufferSources,
getTTYfd,
hasCrypto,
hasIntl,
hasIPv6,
isAIX,
isAlive,
isFreeBSD,
isIBMi,
isInsideDirWithUnusualChars,
isLinux,
isOpenBSD,
isMacOS,
isSunOS,
isWindows,
localIPv6Hosts,
mustCall,
mustCallAtLeast,
mustNotCall,
mustNotMutateObjectDeep,
mustSucceed,
nodeProcessAborted,
parseTestFlags,
PIPE,
platformTimeout,
printSkipMessage,
runWithInvalidFD,
skip,
skipIf32Bits,
skipIfEslintMissing,
skipIfInspectorDisabled,
spawnPromisified,
} = common;
const getPort = () => common.PORT;
export {
allowGlobals,
buildType,
canCreateSymLink,
childShouldThrowAndAbort,
createRequire,
enoughTestMem,
escapePOSIXShell,
expectsError,
expectWarning,
getArrayBufferViews,
getBufferSources,
getPort,
getTTYfd,
hasCrypto,
hasIntl,
hasIPv6,
isAIX,
isAlive,
isFreeBSD,
isIBMi,
isInsideDirWithUnusualChars,
isLinux,
isOpenBSD,
isMacOS,
isSunOS,
isWindows,
localIPv6Hosts,
mustCall,
mustCallAtLeast,
mustNotCall,
mustNotMutateObjectDeep,
mustSucceed,
nodeProcessAborted,
parseTestFlags,
PIPE,
platformTimeout,
printSkipMessage,
runWithInvalidFD,
skip,
skipIf32Bits,
skipIfEslintMissing,
skipIfInspectorDisabled,
spawnPromisified,
};

View file

@ -1,68 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 18.12.0
// This file is automatically generated by "node/_tools/setup.ts". Do not modify this file manually
'use strict';
// Utilities for internet-related tests
const addresses = {
// A generic host that has registered common DNS records,
// supports both IPv4 and IPv6, and provides basic HTTP/HTTPS services
INET_HOST: 'nodejs.org',
// A host that provides IPv4 services
INET4_HOST: 'nodejs.org',
// A host that provides IPv6 services
INET6_HOST: 'nodejs.org',
// An accessible IPv4 IP,
// defaults to the Google Public DNS IPv4 address
INET4_IP: '8.8.8.8',
// An accessible IPv6 IP,
// defaults to the Google Public DNS IPv6 address
INET6_IP: '2001:4860:4860::8888',
// An invalid host that cannot be resolved
// See https://tools.ietf.org/html/rfc2606#section-2
INVALID_HOST: 'something.invalid',
// A host with MX records registered
MX_HOST: 'nodejs.org',
// On some systems, .invalid returns a server failure/try again rather than
// record not found. Use this to guarantee record not found.
NOT_FOUND: 'come.on.fhqwhgads.test',
// A host with SRV records registered
// TODO(kt3k): Temporarily use _caldav._tcp.google.com instead of
// _jabber._tcp.google.com, which currently doesn't respond
// SRV_HOST: '_jabber._tcp.google.com',
SRV_HOST: '_caldav._tcp.google.com',
// A host with PTR records registered
PTR_HOST: '8.8.8.8.in-addr.arpa',
// A host with NAPTR records registered
NAPTR_HOST: 'sip2sip.info',
// A host with SOA records registered
SOA_HOST: 'nodejs.org',
// A host with CAA record registered
CAA_HOST: 'google.com',
// A host with CNAME records registered
CNAME_HOST: 'blog.nodejs.org',
// A host with NS records registered
NS_HOST: 'nodejs.org',
// A host with TXT records registered
TXT_HOST: 'nodejs.org',
// An accessible IPv4 DNS server
DNS4_SERVER: '8.8.8.8',
// An accessible IPv4 DNS server
DNS6_SERVER: '2001:4860:4860::8888'
};
for (const key of Object.keys(addresses)) {
const envName = `NODE_TEST_${key}`;
if (process.env[envName]) {
addresses[key] = process.env[envName];
}
}
module.exports = {
addresses
};

View file

@ -1,113 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const { spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('url');
const { isMainThread } = require('worker_threads');
const isUnixLike = process.platform !== 'win32';
let escapePOSIXShell;
function rmSync(pathname, useSpawn) {
if (useSpawn) {
if (isUnixLike) {
escapePOSIXShell ??= require('./index.js').escapePOSIXShell;
for (let i = 0; i < 3; i++) {
const { status } = spawnSync(...escapePOSIXShell`rm -rf "${pathname}"`);
if (status === 0) {
break;
}
}
} else {
spawnSync(
process.execPath,
[
'-e',
`fs.rmSync(${JSON.stringify(pathname)}, { maxRetries: 3, recursive: true, force: true });`,
],
);
}
} else {
fs.rmSync(pathname, { maxRetries: 3, recursive: true, force: true });
}
}
const testRoot = process.env.NODE_TEST_DIR ?
fs.realpathSync(process.env.NODE_TEST_DIR) : path.resolve(__dirname, '..');
// Using a `.` prefixed name, which is the convention for "hidden" on POSIX,
// gets tools to ignore it by default or by simple rules, especially eslint.
const tmpdirName = '.tmp.' +
(process.env.TEST_SERIAL_ID || process.env.TEST_THREAD_ID || '0');
const tmpPath = path.join(testRoot, tmpdirName);
let firstRefresh = true;
function refresh(useSpawn = false) {
rmSync(tmpPath, useSpawn);
fs.mkdirSync(tmpPath);
if (firstRefresh) {
firstRefresh = false;
// Clean only when a test uses refresh. This allows for child processes to
// use the tmpdir and only the parent will clean on exit.
process.on('exit', () => {
return onexit(useSpawn);
});
}
}
function onexit(useSpawn) {
// Change directory to avoid possible EBUSY
if (isMainThread)
process.chdir(testRoot);
try {
rmSync(tmpPath, useSpawn);
} catch (e) {
console.error('Can\'t clean tmpdir:', tmpPath);
const files = fs.readdirSync(tmpPath);
console.error('Files blocking:', files);
if (files.some((f) => f.startsWith('.nfs'))) {
// Warn about NFS "silly rename"
console.error('Note: ".nfs*" might be files that were open and ' +
'unlinked but not closed.');
console.error('See http://nfs.sourceforge.net/#faq_d2 for details.');
}
console.error();
throw e;
}
}
function resolve(...paths) {
return path.resolve(tmpPath, ...paths);
}
function hasEnoughSpace(size) {
const { bavail, bsize } = fs.statfsSync(tmpPath);
return bavail >= Math.ceil(size / bsize);
}
function fileURL(...paths) {
// When called without arguments, add explicit trailing slash
const fullPath = path.resolve(tmpPath + path.sep, ...paths);
return pathToFileURL(fullPath);
}
module.exports = {
fileURL,
hasEnoughSpace,
path: tmpPath,
refresh,
resolve,
};

View file

@ -1,19 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const { mustNotCall, mustCall } = require('../common');
Object.defineProperties(Object.prototype, {
then: {
set: mustNotCall('set %Object.prototype%.then'),
get: mustNotCall('get %Object.prototype%.then'),
},
});
import('data:text/javascript,').then(mustCall());

View file

@ -1,29 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
const tmpdir = require('../common/tmpdir');
const assert = require('node:assert');
const fs = require('node:fs/promises');
tmpdir.refresh();
const target = tmpdir.fileURL(`${Math.random()}.mjs`);
(async () => {
await assert.rejects(import(target), { code: 'ERR_MODULE_NOT_FOUND' });
await fs.writeFile(target, 'export default "actual target"\n');
const moduleRecord = await import(target);
await fs.rm(target);
assert.strictEqual(await import(target), moduleRecord);
})().then(common.mustCall());

View file

@ -1,17 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const { cache } = require;
Object.keys(cache).forEach((key) => {
delete cache[key];
});
// Require the same module again triggers the crash
require('../common');

View file

@ -1,54 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
// This test ensures that JavaScript file that includes
// a reserved Windows word can be loaded as ESM module
const common = require('../common');
const tmpdir = require('../common/tmpdir');
const assert = require('assert');
const fs = require('fs').promises;
const path = require('path');
const imp = (file) => {
return import(path.relative(__dirname, file).replace(/\\/g, '/'));
};
(async () => {
tmpdir.refresh();
const rel = (file) => tmpdir.resolve(file);
{ // Load a single script
const file = rel('con.mjs');
await fs.writeFile(file, 'export default "ok"');
assert.strictEqual((await imp(file)).default, 'ok');
await fs.unlink(file);
}
{ // Load a module
const entry = rel('entry.mjs');
const nmDir = rel('node_modules');
const mDir = rel('node_modules/con');
const pkg = rel('node_modules/con/package.json');
const script = rel('node_modules/con/index.mjs');
await fs.writeFile(entry, 'export {default} from "con"');
await fs.mkdir(nmDir);
await fs.mkdir(mDir);
await fs.writeFile(pkg, '{"main":"index.mjs"}');
await fs.writeFile(script, 'export default "ok"');
assert.strictEqual((await imp(entry)).default, 'ok');
await fs.unlink(script);
await fs.unlink(pkg);
await fs.rmdir(mDir);
await fs.rmdir(nmDir);
await fs.unlink(entry);
}
})().then(common.mustCall());

View file

@ -1,41 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const assert = require('assert');
const { compileFunction } = require('node:vm');
const min = -2147483648;
const max = 2147483647;
compileFunction('', [], { lineOffset: min, columnOffset: min });
compileFunction('', [], { lineOffset: max, columnOffset: max });
assert.throws(
() => {
compileFunction('', [], { lineOffset: min - 1, columnOffset: max });
},
{
code: 'ERR_OUT_OF_RANGE',
name: 'RangeError',
message: /The value of "options\.lineOffset" is out of range/,
}
);
assert.throws(
() => {
compileFunction('', [], { lineOffset: min, columnOffset: min - 1 });
},
{
code: 'ERR_OUT_OF_RANGE',
name: 'RangeError',
message: /The value of "options\.columnOffset" is out of range/,
}
);

View file

@ -1,30 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
console.log('hello, world!');

View file

@ -1,53 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
const c = require('./b/c');
console.error('load fixtures/a.js');
var string = 'A';
exports.SomeClass = c.SomeClass;
exports.A = function() {
return string;
};
exports.C = function() {
return c.C();
};
exports.D = function() {
return c.D();
};
exports.number = 42;
process.on('exit', function() {
string = 'A done';
});

View file

@ -1,8 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 20.11.1
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
module.exports = 'perhaps I work';

View file

@ -1,8 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
setInterval(function() {}, 9999);

View file

@ -1,13 +0,0 @@
const assert = require("assert");
const debug = require('util').debuglog('test');
const process = require("process");
function onmessage(m) {
debug("CHILD got message:", m);
assert.ok(m.hello);
process.removeListener("message", onmessage);
}
process.on("message", onmessage);
// TODO(kt3k): Uncomment the below when the ipc features are ready
// process.send({ foo: 'bar' });

View file

@ -1,36 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
const exec = require('child_process').exec;
[0, 1].forEach(function(i) {
exec('ls', function(err, stdout, stderr) {
console.log(i);
throw new Error('hello world');
});
});

View file

@ -1,41 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 18.12.1
// This file is automatically generated by "node/_tools/setup.ts". Do not modify this file manually
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
const common = require('../common');
const assert = require('assert');
process.stdout.write('hello world\r\n');
// TODO(PolarETech): process.openStdin() is not yet implemented.
// Use process.stdin instead.
var stdin = process.stdin;
// var stdin = process.openStdin();
stdin.on('data', function(data) {
process.stdout.write(data.toString());
});

File diff suppressed because one or more lines are too long

View file

@ -1,29 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
process.exit(process.argv[2] || 1);

View file

@ -1,11 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
const util = require('node:util');
const assert = require('node:assert');
assert.ok(util.getCallSites().length > 1);
process.stdout.write(util.getCallSites()[0].scriptName);

View file

@ -1,23 +0,0 @@
-----BEGIN CERTIFICATE-----
MIID6DCCAtCgAwIBAgIUFH02wcL3Qgben6tfIibXitsApCYwDQYJKoZIhvcNAQEL
BQAwejELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQswCQYDVQQHDAJTRjEPMA0G
A1UECgwGSm95ZW50MRAwDgYDVQQLDAdOb2RlLmpzMQwwCgYDVQQDDANjYTExIDAe
BgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMCAXDTIyMDkwMzIxNDAzN1oY
DzIyOTYwNjE3MjE0MDM3WjB9MQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExCzAJ
BgNVBAcMAlNGMQ8wDQYDVQQKDAZKb3llbnQxEDAOBgNVBAsMB05vZGUuanMxDzAN
BgNVBAMMBmFnZW50MTEgMB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcw
ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDUVjIK+yDTgnCT3CxChO0E
37q9VuHdrlKeKLeQzUJW2yczSfNzX/0zfHpjY+zKWie39z3HCJqWxtiG2wxiOI8c
3WqWOvzVmdWADlh6EfkIlg+E7VC6JaKDA+zabmhPvnuu3JzogBMnsWl68lCXzuPx
deQAmEwNtqjrh74DtM+Ud0ulb//Ixjxo1q3rYKu+aaexSramuee6qJta2rjrB4l8
B/bU+j1mDf9XQQfSjo9jRnp4hiTFdBl2k+lZzqE2L/rhu6EMjA2IhAq/7xA2MbLo
9cObVUin6lfoo5+JKRgT9Fp2xEgDOit+2EA/S6oUfPNeLSVUqmXOSWlXlwlb9Nxr
AgMBAAGjYTBfMF0GCCsGAQUFBwEBBFEwTzAjBggrBgEFBQcwAYYXaHR0cDovL29j
c3Aubm9kZWpzLm9yZy8wKAYIKwYBBQUHMAKGHGh0dHA6Ly9jYS5ub2RlanMub3Jn
L2NhLmNlcnQwDQYJKoZIhvcNAQELBQADggEBAMM0mBBjLMt9pYXePtUeNO0VTw9y
FWCM8nAcAO2kRNwkJwcsispNpkcsHZ5o8Xf5mpCotdvziEWG1hyxwU6nAWyNOLcN
G0a0KUfbMO3B6ZYe1GwPDjXaQnv75SkAdxgX5zOzca3xnhITcjUUGjQ0fbDfwFV5
ix8mnzvfXjDONdEznVa7PFcN6QliFUMwR/h8pCRHtE5+a10OSPeJSrGG+FtrGnRW
G1IJUv6oiGF/MvWCr84REVgc1j78xomGANJIu2hN7bnD1nEMON6em8IfnDOUtynV
9wfWTqiQYD5Zifj6WcGa0aAHMuetyFG4lIfMAHmd3gaKpks7j9l26LwRPvI=
-----END CERTIFICATE-----

View file

@ -1,27 +0,0 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA1FYyCvsg04Jwk9wsQoTtBN+6vVbh3a5Snii3kM1CVtsnM0nz
c1/9M3x6Y2Psylont/c9xwialsbYhtsMYjiPHN1qljr81ZnVgA5YehH5CJYPhO1Q
uiWigwPs2m5oT757rtyc6IATJ7FpevJQl87j8XXkAJhMDbao64e+A7TPlHdLpW//
yMY8aNat62CrvmmnsUq2prnnuqibWtq46weJfAf21Po9Zg3/V0EH0o6PY0Z6eIYk
xXQZdpPpWc6hNi/64buhDIwNiIQKv+8QNjGy6PXDm1VIp+pX6KOfiSkYE/RadsRI
AzorfthAP0uqFHzzXi0lVKplzklpV5cJW/TcawIDAQABAoIBAAvbtHfAhpjJVBgt
15rvaX04MWmZjIugzKRgib/gdq/7FTlcC+iJl85kSUF7tyGl30n62MxgwqFhAX6m
hQ6HMhbelrFFIhGbwbyhEHfgwROlrcAysKt0pprCgVvBhrnNXYLqdyjU3jz9P3LK
TY3s0/YMK2uNFdI+PTjKH+Z9Foqn9NZUnUonEDepGyuRO7fLeccWJPv2L4CR4a/5
ku4VbDgVpvVSVRG3PSVzbmxobnpdpl52og+T7tPx1cLnIknPtVljXPWtZdfekh2E
eAp2KxCCHOKzzG3ItBKsVu0woeqEpy8JcoO6LbgmEoVnZpgmtQClbBgef8+i+oGE
BgW9nmECgYEA8gA63QQuZOUC56N1QXURexN2PogF4wChPaCTFbQSJXvSBkQmbqfL
qRSD8P0t7GOioPrQK6pDwFf4BJB01AvkDf8Z6DxxOJ7cqIC7LOwDupXocWX7Q0Qk
O6cwclBVsrDZK00v60uRRpl/a39GW2dx7IiQDkKQndLh3/0TbMIWHNcCgYEA4J6r
yinZbLpKw2+ezhi4B4GT1bMLoKboJwpZVyNZZCzYR6ZHv+lS7HR/02rcYMZGoYbf
n7OHwF4SrnUS7vPhG4g2ZsOhKQnMvFSQqpGmK1ZTuoKGAevyvtouhK/DgtLWzGvX
9fSahiq/UvfXs/z4M11q9Rv9ztPCmG1cwSEHlo0CgYEAogQNZJK8DMhVnYcNpXke
7uskqtCeQE/Xo06xqkIYNAgloBRYNpUYAGa/vsOBz1UVN/kzDUi8ezVp0oRz8tLT
J5u2WIi+tE2HJTiqF3UbOfvK1sCT64DfUSCpip7GAQ/tFNRkVH8PD9kMOYfILsGe
v+DdsO5Xq5HXrwHb02BNNZkCgYBsl8lt33WiPx5OBfS8pu6xkk+qjPkeHhM2bKZs
nkZlS9j0KsudWGwirN/vkkYg8zrKdK5AQ0dqFRDrDuasZ3N5IA1M+V88u+QjWK7o
B6pSYVXxYZDv9OZSpqC+vUrEQLJf+fNakXrzSk9dCT1bYv2Lt6ox/epix7XYg2bI
Z/OHMQKBgQC2FUGhlndGeugTJaoJ8nhT/0VfRUX/h6sCgSerk5qFr/hNCBV4T022
x0NDR2yLG6MXyqApJpG6rh3QIDElQoQCNlI3/KJ6JfEfmqrLLN2OigTvA5sE4fGU
Dp/ha8OQAx95EwXuaG7LgARduvOIK3x8qi8KsZoUGJcg2ywurUbkWA==
-----END RSA PRIVATE KEY-----

View file

@ -1,22 +0,0 @@
-----BEGIN CERTIFICATE-----
MIIDlDCCAnygAwIBAgIUSrFsjf1qfQ0t/KvfnEsOksatAikwDQYJKoZIhvcNAQEL
BQAwejELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQswCQYDVQQHDAJTRjEPMA0G
A1UECgwGSm95ZW50MRAwDgYDVQQLDAdOb2RlLmpzMQwwCgYDVQQDDANjYTExIDAe
BgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMCAXDTIyMDkwMzIxNDAzN1oY
DzIyOTYwNjE3MjE0MDM3WjB6MQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExCzAJ
BgNVBAcMAlNGMQ8wDQYDVQQKDAZKb3llbnQxEDAOBgNVBAsMB05vZGUuanMxDDAK
BgNVBAMMA2NhMTEgMB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDNvf4OGGep+ak+4DNjbuNgy0S/
AZPxahEFp4gpbcvsi9YLOPZ31qpilQeQf7d27scIZ02Qx1YBAzljxELB8H/ZxuYS
cQK0s+DNP22xhmgwMWznO7TezkHP5ujN2UkbfbUpfUxGFgncXeZf9wR7yFWppeHi
RWNBOgsvY7sTrS12kXjWGjqntF7xcEDHc7h+KyF6ZjVJZJCnP6pJEQ+rUjd51eCZ
Xt4WjowLnQiCS1VKzXiP83a++Ma1BKKkUitTR112/Uwd5eGoiByhmLzb/BhxnHJN
07GXjhlMItZRm/jfbZsx1mwnNOO3tx4r08l+DaqkinIadvazs+1ugCaKQn8xAgMB
AAGjEDAOMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFqG0RXURDam
56x5accdg9sY5zEGP5VQhkK3ZDc2NyNNa25rwvrjCpO+e0OSwKAmm4aX6iIf2woY
wF2f9swWYzxn9CG4fDlUA8itwlnHxupeL4fGMTYb72vf31plUXyBySRsTwHwBloc
F7KvAZpYYKN9EMH1S/267By6H2I33BT/Ethv//n8dSfmuCurR1kYRaiOC4PVeyFk
B3sj8TtolrN0y/nToWUhmKiaVFnDx3odQ00yhmxR3t21iB7yDkko6D8Vf2dVC4j/
YYBVprXGlTP/hiYRLDoP20xKOYznx5cvHPJ9p+lVcOZUJsJj/Iy750+2n5UiBmXt
lz88C25ucKA=
-----END CERTIFICATE-----

View file

@ -1,9 +0,0 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl83yoBp5JDhe/lcDMxqY
lsuZ52v1RiTnzwbAlYOVqKCRzfZwBcqi8aFdFsocLyHR4SIHE19i+AR0WvuAdM2+
LLURytNmZJyb4qJyuJAX2vpO0OA82rFt7pSwk1zy1QSs1vUEsxOFrpbdewV+rklM
twaa/zbpOgeCWtyZxaXUmJiW1j+eZETjRQWWDwl6+0/JOocxB3HrxRPz1IuiFPiy
osMhh+SlwFM0WzLam2S5/6xAJhAcZr/8//rIQMIkRPLPUagYvqVXcKlncOomzZGz
Oxt4+AjMnwJOxDqRn+ZaESK1VgeF61WFm9hEOrHfS34kPRsKpRWMNNOjFKOp8aBL
TQIDAQAB
-----END PUBLIC KEY-----

View file

@ -1 +0,0 @@
MIICUzCCATswggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCXzfKgGnkkOF7+VwMzGpiWy5nna/VGJOfPBsCVg5WooJHN9nAFyqLxoV0WyhwvIdHhIgcTX2L4BHRa+4B0zb4stRHK02ZknJvionK4kBfa+k7Q4DzasW3ulLCTXPLVBKzW9QSzE4Wult17BX6uSUy3Bpr/Nuk6B4Ja3JnFpdSYmJbWP55kRONFBZYPCXr7T8k6hzEHcevFE/PUi6IU+LKiwyGH5KXAUzRbMtqbZLn/rEAmEBxmv/z/+shAwiRE8s9RqBi+pVdwqWdw6ibNkbM7G3j4CMyfAk7EOpGf5loRIrVWB4XrVYWb2EQ6sd9LfiQ9GwqlFYw006MUo6nxoEtNAgMBAAEWE3RoaXMtaXMtYS1jaGFsbGVuZ2UwDQYJKoZIhvcNAQELBQADggEBAHUw1UoZjG7TCb/JhFo5p8XIFeizGEwYoqttBoVTQ+MeCfnNoLLeAyId0atb2jPnYsI25Z/PHHV1N9t0L/NelY3rZC/Z00Wx8IGeslnGXXbqwnp36Umb0r2VmxTr8z1QaToGyOQXp4Xor9qbQFoANIivyVUYsuqJ1FnDJCC/jBPo4IWiQbTst331v2fiVdV+/XUh9AIjcm4085b65HjFwLxDeWhbgAZ+UfhqBbTVA1K8uUqS8e3gbeaNstZvnclxZ3PlHSk8v1RdIG4e5ThTOwPH5u/7KKeafn9SwgY/Q8KqaVfHHCv1IeVlijamjnyFhWc35kGlBUNgLOnWAOE3GsM=

View file

@ -1 +0,0 @@
UzCCATswggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC33FiIiiexwLe/P8DZx5HsqFlmUO7/lvJ7necJVNwqdZ3ax5jpQB0p6uxfqeOvzcN3k5V7UFb/Am+nkSNZMAZhsWzCU2Z4Pjh50QYz3f0Hour7/yIGStOLyYY3hgLK2K8TbhgjQPhdkw9+QtKlpvbL8fLgONAoGrVOFnRQGcr70iFffsm79mgZhKVMgYiHPJqJgGHvCtkGg9zMgS7p63+Q3ZWedtFS2RhMX3uCBy/mH6EOlRCNBbRmA4xxNzyf5GQaki3T+Iz9tOMjdPP+CwV2LqEdylmBuik8vrfTb3qIHLKKBAI8lXN26wWtA3kN4L7NP+cbKlCRlqctvhmylLH1AgMBAAEWE3RoaXMtaXMtYS1jaGFsbGVuZ2UwDQYJKoZIhvcNAQEEBQADggEBAIozmeW1kfDfAVwRQKileZGLRGCD7AjdHLYEe16xTBPve8Af1bDOyuWsAm4qQLYA4FAFROiKeGqxCtIErEvm87/09tCfF1My/1Uj+INjAk39DK9J9alLlTsrwSgd1lb3YlXY7TyitCmh7iXLo4pVhA2chNA3njiMq3CUpSvGbpzrESL2dv97lv590gUD988wkTDVyYsf0T8+X0Kww3AgPWGji+2f2i5/jTfD/s1lK1nqi7ZxFm0pGZoy1MJ51SCEy7Y82ajroI+5786nC02mo9ak7samca4YDZOoxN4d3tax4B/HDF5dqJSm1/31xYLDTfujCM5FkSjRc4m6hnriEkc=

View file

@ -1,17 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
var t = 1;
var k = 1;
console.log('A message', 5);
while (t > 0) {
if (t++ === 1000) {
t = 0;
console.log(`Outputted message #${k++}`);
}
}
process.exit(55);

View file

@ -1,20 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
const spawn = require('child_process').spawn,
path = require('path'),
childPath = path.join(__dirname, 'child-process-persistent.js');
var child = spawn(process.execPath, [ childPath ], {
detached: true,
stdio: 'ignore'
});
console.log(child.pid);
child.unref();

View file

@ -1,33 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
const assert = require('assert');
var n = parseInt(process.argv[2]);
process.stdout.write('c'.repeat(n));

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

View file

@ -1 +0,0 @@
永和九年,嵗在癸丑,暮春之初,會於會稽山隂之蘭亭,脩稧事也。羣賢畢至,少長咸集。此地有崇山峻領,茂林脩竹;又有清流激湍,暎帶左右。引以為流觴曲水,列坐其次。雖無絲竹管弦之盛,一觴一詠,亦足以暢敘幽情。是日也,天朗氣清,恵風和暢;仰觀宇宙之大,俯察品類之盛;所以遊目騁懐,足以極視聽之娛,信可樂也。夫人之相與,俯仰一世,或取諸懐抱,悟言一室之內,或因寄所託,放浪形骸之外。雖趣舎萬殊,靜躁不同,當其欣扵所遇,暫得扵己,怏然自足,不知老之將至。及其所之既惓,情隨事遷,感慨係之矣。向之所欣,俛仰之閒以為陳跡,猶不能不以之興懐;況脩短隨化,終期扵盡。古人云:「死生亦大矣。」豈不痛哉!每攬昔人興感之由,若合一契,未嘗不臨文嗟悼,不能喻之扵懐。固知一死生為虛誕,齊彭殤為妄作。後之視今,亦由今之視昔,悲夫!故列敘時人,錄其所述,雖世殊事異,所以興懐,其致一也。後之攬者,亦將有感扵斯文。

View file

@ -1,8 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
require('new-buffer-cjs');

View file

@ -1,8 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
import 'new-buffer-esm'

View file

@ -1,8 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
new Buffer(10);

View file

@ -1,3 +0,0 @@
{
"main": "index.js"
}

View file

@ -1,9 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
import { Buffer } from 'node:buffer';
new Buffer(10);

View file

@ -1,4 +0,0 @@
{
"main": "index.js",
"type": "module"
}

View file

@ -1 +0,0 @@
xyz

View file

@ -1,76 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
// Verify that non-ASCII hostnames are handled correctly as IDNA 2008.
//
// * Tests will fail with NXDOMAIN when UTF-8 leaks through to a getaddrinfo()
// that doesn't support IDNA at all.
//
// * "straße.de" will resolve to the wrong address when the resolver supports
// only IDNA 2003 (e.g., glibc until 2.28) because it encodes it wrong.
const { mustCall } = require('../common');
const assert = require('assert');
const dns = require('dns');
const { addresses } = require('../common/internet');
const fixture = {
hostname: 'straße.de',
expectedAddress: '81.169.145.78',
dnsServer: addresses.DNS4_SERVER,
family: 4,
};
// Explicitly use well-behaved DNS servers that are known to be able to resolve
// the query (which is a.k.a xn--strae-oqa.de).
dns.setServers([fixture.dnsServer]);
dns.lookup(
fixture.hostname,
{ family: fixture.family },
mustCall((err, address) => {
if (err && err.errno === 'ESERVFAIL') {
assert.ok(err.message.includes('queryA ESERVFAIL straße.de'));
return;
}
assert.ifError(err);
assert.strictEqual(address, fixture.expectedAddress);
}),
);
dns.promises.lookup(fixture.hostname, { family: fixture.family })
.then(({ address }) => {
assert.strictEqual(address, fixture.expectedAddress);
}, (err) => {
if (err && err.errno === 'ESERVFAIL') {
assert.ok(err.message.includes('queryA ESERVFAIL straße.de'));
} else {
throw err;
}
}).finally(mustCall());
dns.resolve4(fixture.hostname, mustCall((err, addresses) => {
if (err && err.errno === 'ESERVFAIL') {
assert.ok(err.message.includes('queryA ESERVFAIL straße.de'));
return;
}
assert.ifError(err);
assert.deepStrictEqual(addresses, [fixture.expectedAddress]);
}));
const p = new dns.promises.Resolver().resolve4(fixture.hostname);
p.then((addresses) => {
assert.deepStrictEqual(addresses, [fixture.expectedAddress]);
}, (err) => {
if (err && err.errno === 'ESERVFAIL') {
assert.ok(err.message.includes('queryA ESERVFAIL straße.de'));
} else {
throw err;
}
}).finally(mustCall());

View file

@ -1,61 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const common = require('../common');
const dns = require('dns');
const dnsPromises = dns.promises;
const { addresses } = require('../common/internet');
const assert = require('assert');
assert.rejects(
dnsPromises.lookup(addresses.NOT_FOUND, {
hints: 0,
family: 0,
all: false,
}),
{
code: 'ENOTFOUND',
message: `getaddrinfo ENOTFOUND ${addresses.NOT_FOUND}`,
},
).then(common.mustCall());
assert.rejects(
dnsPromises.lookup(addresses.NOT_FOUND, {
hints: 0,
family: 0,
all: true,
}),
{
code: 'ENOTFOUND',
message: `getaddrinfo ENOTFOUND ${addresses.NOT_FOUND}`,
},
).then(common.mustCall());
dns.lookup(addresses.NOT_FOUND, {
hints: 0,
family: 0,
all: true,
}, common.mustCall((error) => {
assert.strictEqual(error.code, 'ENOTFOUND');
assert.strictEqual(
error.message,
`getaddrinfo ENOTFOUND ${addresses.NOT_FOUND}`,
);
assert.strictEqual(error.syscall, 'getaddrinfo');
assert.strictEqual(error.hostname, addresses.NOT_FOUND);
}));
assert.throws(
() => dnsPromises.lookup(addresses.NOT_FOUND, {
family: 'ipv4',
all: 'all',
}),
{ code: 'ERR_INVALID_ARG_VALUE' },
);

View file

@ -1,49 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
const assert = require('assert');
const dnsPromises = require('dns').promises;
// Error when rrtype is invalid.
{
const rrtype = 'DUMMY';
assert.throws(
() => dnsPromises.resolve('example.org', rrtype),
{
code: 'ERR_INVALID_ARG_VALUE',
name: 'TypeError',
message: `The argument 'rrtype' is invalid. Received '${rrtype}'`,
},
);
}
// Error when rrtype is a number.
{
const rrtype = 0;
assert.throws(
() => dnsPromises.resolve('example.org', rrtype),
{
code: 'ERR_INVALID_ARG_TYPE',
name: 'TypeError',
message: 'The "rrtype" argument must be of type string. ' +
`Received type ${typeof rrtype} (${rrtype})`,
},
);
}
// Setting rrtype to undefined should work like resolve4.
{
(async function() {
const rrtype = undefined;
const result = await dnsPromises.resolve('example.org', rrtype);
assert.ok(result !== undefined);
assert.ok(result.length > 0);
})().then(common.mustCall());
}

View file

@ -1,35 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const dns = require('dns');
// Should not segfault.
// Ref: https://github.com/nodejs/node-v0.x-archive/issues/6244
dns.resolve4('127.0.0.1', common.mustCall());

View file

@ -1,25 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
// We don't care about `err` in the callback function of `dns.resolve4`. We just
// want to test whether `dns.setServers` that is run after `resolve4` will cause
// a crash or not. If it doesn't crash, the test succeeded.
const common = require('../common');
const { addresses } = require('../common/internet');
const dns = require('dns');
dns.resolve4(
addresses.INET4_HOST,
common.mustCall(function(/* err, nameServers */) {
dns.setServers([ addresses.DNS4_SERVER ]);
}));
// Test https://github.com/nodejs/node/issues/14734
dns.resolve4(addresses.INET4_HOST, common.mustCall());

View file

@ -1,46 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const { addresses } = require('../common/internet');
if (!common.hasCrypto)
common.skip('missing crypto');
const https = require('https');
const http = require('http');
https.get(`https://${addresses.INET_HOST}/`, common.mustCall((res) => {
res.resume();
}));
http.get(`http://${addresses.INET_HOST}/`, common.mustCall((res) => {
res.resume();
}));

View file

@ -1,38 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
require('../common');
process.maxTickDepth = 10;
let i = 20;
process.nextTick(function f() {
console.error(`tick ${i}`);
if (i-- > 0)
process.nextTick(f);
});

View file

@ -1,19 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const util = require('util');
const err = new Error('foo\nbar');
console.log(util.inspect({ err, nested: { err } }, { compact: true }));
console.log(util.inspect({ err, nested: { err } }, { compact: false }));
err.foo = 'bar';
console.log(util.inspect(err, { compact: true, breakLength: 5 }));

View file

@ -1,22 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 20.11.1
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
// This test ensures Math functions don't fail with an "illegal instruction"
// error on ARM devices (primarily on the Raspberry Pi 1)
// See https://github.com/nodejs/node/issues/1376
// and https://code.google.com/p/v8/issues/detail?id=4019
// Iterate over all Math functions
Object.getOwnPropertyNames(Math).forEach((functionName) => {
if (!/[A-Z]/.test(functionName)) {
// The function names don't have capital letters.
Math[functionName](-0.5);
}
});

View file

@ -1,244 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
const assert = require('assert');
// Run all tests in parallel and check their outcome at the end.
const promises = [];
// Thenable object without `catch` method,
// shouldn't be considered as a valid Thenable
const invalidThenable = {
then: (fulfill, reject) => {
fulfill();
},
};
// Function that returns a Thenable function,
// a function with `catch` and `then` methods attached,
// shouldn't be considered as a valid Thenable.
const invalidThenableFunc = () => {
function f() {}
f.then = (fulfill, reject) => {
fulfill();
};
f.catch = () => {};
return f;
};
// Test assert.rejects() and assert.doesNotReject() by checking their
// expected output and by verifying that they do not work sync
// Check `assert.rejects`.
{
const rejectingFn = async () => assert.fail();
const errObj = {
code: 'ERR_ASSERTION',
name: 'AssertionError',
message: 'Failed'
};
// `assert.rejects` accepts a function or a promise
// or a thenable as first argument.
promises.push(assert.rejects(rejectingFn, errObj));
promises.push(assert.rejects(rejectingFn(), errObj));
const validRejectingThenable = {
then: (fulfill, reject) => {
reject({ code: 'FAIL' });
},
catch: () => {}
};
promises.push(assert.rejects(validRejectingThenable, { code: 'FAIL' }));
// `assert.rejects` should not accept thenables that
// use a function as `obj` and that have no `catch` handler.
promises.push(assert.rejects(
assert.rejects(invalidThenable, {}),
{
code: 'ERR_INVALID_ARG_TYPE'
})
);
promises.push(assert.rejects(
assert.rejects(invalidThenableFunc, {}),
{
code: 'ERR_INVALID_RETURN_VALUE'
})
);
const err = new Error('foobar');
const validate = () => { return 'baz'; };
promises.push(assert.rejects(
() => assert.rejects(Promise.reject(err), validate),
{
message: 'The "validate" validation function is expected to ' +
"return \"true\". Received 'baz'\n\nCaught error:\n\n" +
'Error: foobar',
code: 'ERR_ASSERTION',
actual: err,
expected: validate,
name: 'AssertionError',
operator: 'rejects',
}
));
}
{
const handler = (err) => {
assert(err instanceof assert.AssertionError,
`${err.name} is not instance of AssertionError`);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.message,
'Missing expected rejection (mustNotCall).');
assert.strictEqual(err.operator, 'rejects');
assert.ok(!err.stack.includes('at Function.rejects'));
return true;
};
let promise = assert.rejects(async () => {}, common.mustNotCall());
promises.push(assert.rejects(promise, common.mustCall(handler)));
promise = assert.rejects(() => {}, common.mustNotCall());
promises.push(assert.rejects(promise, {
name: 'TypeError',
code: 'ERR_INVALID_RETURN_VALUE',
// FIXME(JakobJingleheimer): This should match on key words, like /Promise/ and /undefined/.
message: 'Expected instance of Promise to be returned ' +
'from the "promiseFn" function but got undefined.'
}));
promise = assert.rejects(Promise.resolve(), common.mustNotCall());
promises.push(assert.rejects(promise, common.mustCall(handler)));
}
{
const THROWN_ERROR = new Error();
promises.push(assert.rejects(() => {
throw THROWN_ERROR;
}, {}).catch(common.mustCall((err) => {
assert.strictEqual(err, THROWN_ERROR);
})));
}
promises.push(assert.rejects(
assert.rejects('fail', {}),
{
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "promiseFn" argument must be of type function or an ' +
"instance of Promise. Received type string ('fail')"
}
));
{
const handler = (generated, actual, err) => {
assert.strictEqual(err.generatedMessage, generated);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.actual, actual);
assert.strictEqual(err.operator, 'rejects');
assert.match(err.stack, /rejects/);
return true;
};
const err = new Error();
promises.push(assert.rejects(
assert.rejects(Promise.reject(null), { code: 'FOO' }),
handler.bind(null, true, null)
));
promises.push(assert.rejects(
assert.rejects(Promise.reject(5), { code: 'FOO' }, 'AAAAA'),
handler.bind(null, false, 5)
));
promises.push(assert.rejects(
assert.rejects(Promise.reject(err), { code: 'FOO' }, 'AAAAA'),
handler.bind(null, false, err)
));
}
// Check `assert.doesNotReject`.
{
// `assert.doesNotReject` accepts a function or a promise
// or a thenable as first argument.
/* eslint-disable no-restricted-syntax */
let promise = assert.doesNotReject(() => new Map(), common.mustNotCall());
promises.push(assert.rejects(promise, {
message: 'Expected instance of Promise to be returned ' +
'from the "promiseFn" function but got an instance of Map.',
code: 'ERR_INVALID_RETURN_VALUE',
name: 'TypeError'
}));
promises.push(assert.doesNotReject(async () => {}));
promises.push(assert.doesNotReject(Promise.resolve()));
// `assert.doesNotReject` should not accept thenables that
// use a function as `obj` and that have no `catch` handler.
const validFulfillingThenable = {
then: (fulfill, reject) => {
fulfill();
},
catch: () => {}
};
promises.push(assert.doesNotReject(validFulfillingThenable));
promises.push(assert.rejects(
assert.doesNotReject(invalidThenable),
{
code: 'ERR_INVALID_ARG_TYPE'
})
);
promises.push(assert.rejects(
assert.doesNotReject(invalidThenableFunc),
{
code: 'ERR_INVALID_RETURN_VALUE'
})
);
const handler1 = (err) => {
assert(err instanceof assert.AssertionError,
`${err.name} is not instance of AssertionError`);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.message, 'Failed');
return true;
};
const handler2 = (err) => {
assert(err instanceof assert.AssertionError,
`${err.name} is not instance of AssertionError`);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.message,
'Got unwanted rejection.\nActual message: "Failed"');
assert.strictEqual(err.operator, 'doesNotReject');
assert.ok(err.stack);
assert.ok(!err.stack.includes('at Function.doesNotReject'));
return true;
};
const rejectingFn = async () => assert.fail();
promise = assert.doesNotReject(rejectingFn, common.mustCall(handler1));
promises.push(assert.rejects(promise, common.mustCall(handler2)));
promise = assert.doesNotReject(rejectingFn(), common.mustCall(handler1));
promises.push(assert.rejects(promise, common.mustCall(handler2)));
promise = assert.doesNotReject(() => assert.fail(), common.mustNotCall());
promises.push(assert.rejects(promise, common.mustCall(handler1)));
promises.push(assert.rejects(
assert.doesNotReject(123),
{
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "promiseFn" argument must be of type ' +
'function or an instance of Promise. Received type number (123)'
}
));
/* eslint-enable no-restricted-syntax */
}
// Make sure all async code gets properly executed.
Promise.all(promises).then(common.mustCall());

View file

@ -1,55 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
// Do not read filesystem when creating AssertionError messages for code in
// builtin modules.
require('../common');
const assert = require('assert');
const EventEmitter = require('events');
const e = new EventEmitter();
e.on('hello', assert);
if (process.argv[2] !== 'child') {
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
const { spawnSync } = require('child_process');
let threw = false;
try {
e.emit('hello', false);
} catch (err) {
const frames = err.stack.split('\n');
const [, filename, line, column] = frames[1].match(/\((.+):(\d+):(\d+)\)/);
// Spawn a child process to avoid the error having been cached in the assert
// module's `errorCache` Map.
const { output, status, error } =
spawnSync(process.execPath,
[process.argv[1], 'child', filename, line, column],
{ cwd: tmpdir.path, env: process.env });
assert.ifError(error);
assert.strictEqual(status, 0, `Exit code: ${status}\n${output}`);
threw = true;
}
assert.ok(threw);
} else {
const { writeFileSync } = require('fs');
const [, , , filename, line, column] = process.argv;
const data = `${'\n'.repeat(line - 1)}${' '.repeat(column - 1)}` +
'ok(failed(badly));';
writeFileSync(filename, data);
assert.throws(
() => e.emit('hello', false),
{
message: 'false == true'
}
);
}

View file

@ -1,81 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const { hasCrypto } = require('../common');
const { test } = require('node:test');
const assert = require('assert');
// Turn off no-restricted-properties because we are testing deepEqual!
/* eslint-disable no-restricted-properties */
// Disable colored output to prevent color codes from breaking assertion
// message comparisons. This should only be an issue when process.stdout
// is a TTY.
if (process.stdout.isTTY)
process.env.NODE_DISABLE_COLORS = '1';
test('', { skip: !hasCrypto }, () => {
// See https://github.com/nodejs/node/issues/10258
{
const date = new Date('2016');
function FakeDate() {}
FakeDate.prototype = Date.prototype;
const fake = new FakeDate();
assert.notDeepEqual(date, fake);
assert.notDeepEqual(fake, date);
// For deepStrictEqual we check the runtime type,
// then reveal the fakeness of the fake date
assert.throws(
() => assert.deepStrictEqual(date, fake),
{
message: 'Expected values to be strictly deep-equal:\n' +
'+ actual - expected\n' +
'\n' +
'+ 2016-01-01T00:00:00.000Z\n' +
'- Date {}\n'
}
);
assert.throws(
() => assert.deepStrictEqual(fake, date),
{
message: 'Expected values to be strictly deep-equal:\n' +
'+ actual - expected\n' +
'\n' +
'+ Date {}\n' +
'- 2016-01-01T00:00:00.000Z\n'
}
);
}
{ // At the moment global has its own type tag
const fakeGlobal = {};
Object.setPrototypeOf(fakeGlobal, Object.getPrototypeOf(globalThis));
for (const prop of Object.keys(globalThis)) {
fakeGlobal[prop] = global[prop];
}
assert.notDeepEqual(fakeGlobal, globalThis);
// Message will be truncated anyway, don't validate
assert.throws(() => assert.deepStrictEqual(fakeGlobal, globalThis),
assert.AssertionError);
}
{ // At the moment process has its own type tag
const fakeProcess = {};
Object.setPrototypeOf(fakeProcess, Object.getPrototypeOf(process));
for (const prop of Object.keys(process)) {
fakeProcess[prop] = process[prop];
}
assert.notDeepEqual(fakeProcess, process);
// Message will be truncated anyway, don't validate
assert.throws(() => assert.deepStrictEqual(fakeProcess, process),
assert.AssertionError);
}
});
/* eslint-enable */

View file

@ -1,77 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Flags: --no-warnings
'use strict';
const { expectWarning } = require('../common');
const assert = require('assert');
const { test } = require('node:test');
expectWarning(
'DeprecationWarning',
'assert.fail() with more than one argument is deprecated. ' +
'Please use assert.strictEqual() instead or only pass a message.',
'DEP0094'
);
test('Two args only, operator defaults to "!="', () => {
assert.throws(() => {
assert.fail('first', 'second');
}, {
code: 'ERR_ASSERTION',
name: 'AssertionError',
message: '\'first\' != \'second\'',
operator: '!=',
actual: 'first',
expected: 'second',
generatedMessage: true
});
});
test('Three args', () => {
assert.throws(() => {
assert.fail('ignored', 'ignored', 'another custom message');
}, {
code: 'ERR_ASSERTION',
name: 'AssertionError',
message: 'another custom message',
operator: 'fail',
actual: 'ignored',
expected: 'ignored',
generatedMessage: false
});
});
test('Three args with custom Error', () => {
assert.throws(() => {
assert.fail(typeof 1, 'object', new TypeError('another custom message'));
}, {
name: 'TypeError',
message: 'another custom message'
});
});
test('No third arg (but a fourth arg)', () => {
assert.throws(() => {
assert.fail('first', 'second', undefined, 'operator');
}, {
code: 'ERR_ASSERTION',
name: 'AssertionError',
message: '\'first\' operator \'second\'',
operator: 'operator',
actual: 'first',
expected: 'second'
});
});
test('The stackFrameFunction should exclude the foo frame', () => {
assert.throws(
function foo() { assert.fail('first', 'second', 'message', '!==', foo); },
(err) => !/^\s*at\sfoo\b/m.test(err.stack)
);
});

View file

@ -1,57 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const assert = require('assert');
const { test } = require('node:test');
test('No args', () => {
assert.throws(
() => { assert.fail(); },
{
code: 'ERR_ASSERTION',
name: 'AssertionError',
message: 'Failed',
operator: 'fail',
actual: undefined,
expected: undefined,
generatedMessage: true,
stack: /Failed/
}
);
});
test('One arg = message', () => {
assert.throws(() => {
assert.fail('custom message');
}, {
code: 'ERR_ASSERTION',
name: 'AssertionError',
message: 'custom message',
operator: 'fail',
actual: undefined,
expected: undefined,
generatedMessage: false
});
});
test('One arg = Error', () => {
assert.throws(() => {
assert.fail(new TypeError('custom message'));
}, {
name: 'TypeError',
message: 'custom message'
});
});
test('Object prototype get', () => {
Object.prototype.get = () => { throw new Error('failed'); };
assert.throws(() => assert.fail(''), { code: 'ERR_ASSERTION' });
delete Object.prototype.get;
});

View file

@ -1,111 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const assert = require('assert');
const { test } = require('node:test');
test('Test that assert.ifError has the correct stack trace of both stacks', () => {
let err;
// Create some random error frames.
(function a() {
(function b() {
(function c() {
err = new Error('test error');
})();
})();
})();
const msg = err.message;
const stack = err.stack;
(function x() {
(function y() {
(function z() {
let threw = false;
try {
assert.ifError(err);
} catch (e) {
assert.strictEqual(e.message,
'ifError got unwanted exception: test error');
assert.strictEqual(err.message, msg);
assert.strictEqual(e.actual, err);
assert.strictEqual(e.actual.stack, stack);
assert.strictEqual(e.expected, null);
assert.strictEqual(e.operator, 'ifError');
threw = true;
}
assert(threw);
})();
})();
})();
});
test('General ifError tests', () => {
assert.throws(
() => {
const error = new Error();
error.stack = 'Error: containing weird stack\nYes!\nI am part of a stack.';
assert.ifError(error);
},
(error) => {
assert(!error.stack.includes('Yes!'));
return true;
}
);
assert.throws(
() => assert.ifError(new TypeError()),
{
message: 'ifError got unwanted exception: TypeError'
}
);
assert.throws(
() => assert.ifError({ stack: false }),
{
message: 'ifError got unwanted exception: { stack: false }'
}
);
assert.throws(
() => assert.ifError({ constructor: null, message: '' }),
{
message: 'ifError got unwanted exception: '
}
);
assert.throws(
() => { assert.ifError(false); },
{
message: 'ifError got unwanted exception: false'
}
);
});
test('Should not throw', () => {
assert.ifError(null);
assert.ifError();
assert.ifError(undefined);
});
test('https://github.com/nodejs/node-v0.x-archive/issues/2893', () => {
let threw = false;
try {
// eslint-disable-next-line no-restricted-syntax
assert.throws(() => {
assert.ifError(null);
});
} catch (e) {
threw = true;
assert.strictEqual(e.message, 'Missing expected exception.');
assert(!e.stack.includes('throws'), e);
}
assert(threw);
});

File diff suppressed because it is too large Load diff

View file

@ -1,18 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const { AsyncResource } = require('async_hooks');
try {
new AsyncResource('foo').runInAsyncScope(() => { throw new Error('bar'); });
} catch {
// Continue regardless of error.
}
// Should abort (fail the case) if async id is not matching.

View file

@ -1,24 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
// Test that passing thisArg to runInAsyncScope() works.
const common = require('../common');
const assert = require('assert');
const { AsyncResource } = require('async_hooks');
const thisArg = {};
const res = new AsyncResource('fhqwhgads');
function callback() {
assert.strictEqual(this, thisArg);
}
res.runInAsyncScope(common.mustCall(callback), thisArg);

View file

@ -1,24 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
const assert = require('assert');
const { AsyncLocalStorage } = require('async_hooks');
[1, false, '', {}, []].forEach((i) => {
assert.throws(() => AsyncLocalStorage.bind(i), {
code: 'ERR_INVALID_ARG_TYPE'
});
});
const fn = common.mustCall(AsyncLocalStorage.bind(() => 123));
assert.strictEqual(fn(), 123);
const fn2 = AsyncLocalStorage.bind(common.mustCall((arg) => assert.strictEqual(arg, 'test')));
fn2('test');

View file

@ -1,42 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const assert = require('assert');
const vm = require('vm');
const { AsyncLocalStorage } = require('async_hooks');
// Regression test for https://github.com/nodejs/node/issues/38781
const context = vm.createContext({
AsyncLocalStorage,
assert
});
vm.runInContext(`
const storage = new AsyncLocalStorage()
async function test() {
return storage.run({ test: 'vm' }, async () => {
assert.strictEqual(storage.getStore().test, 'vm');
await 42;
assert.strictEqual(storage.getStore().test, 'vm');
});
}
test()
`, context);
const storage = new AsyncLocalStorage();
async function test() {
return storage.run({ test: 'main context' }, async () => {
assert.strictEqual(storage.getStore().test, 'main context');
await 42;
assert.strictEqual(storage.getStore().test, 'main context');
});
}
test();

View file

@ -1,22 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
const { AsyncLocalStorage } = require('async_hooks');
// Regression test for: https://github.com/nodejs/node/issues/34556
const als = new AsyncLocalStorage();
const done = common.mustCall();
function run(count) {
if (count !== 0) return als.run({}, run, --count);
done();
}
run(1000);

View file

@ -1,72 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
const Countdown = require('../common/countdown');
const assert = require('assert');
const { AsyncLocalStorage } = require('async_hooks');
const http = require('http');
const cls = new AsyncLocalStorage();
const NUM_CLIENTS = 10;
// Run multiple clients that receive data from a server
// in multiple chunks, in a single non-closure function.
// Use the AsyncLocalStorage (ALS) APIs to maintain the context
// and data download. Make sure that individual clients
// receive their respective data, with no conflicts.
// Set up a server that sends large buffers of data, filled
// with cardinal numbers, increasing per request
let index = 0;
const server = http.createServer((q, r) => {
// Send a large chunk as response, otherwise the data
// may be sent in a single chunk, and the callback in the
// client may be called only once, defeating the purpose of test
r.end((index++ % 10).toString().repeat(1024 * 1024));
});
const countdown = new Countdown(NUM_CLIENTS, () => {
server.close();
});
server.listen(0, common.mustCall(() => {
for (let i = 0; i < NUM_CLIENTS; i++) {
cls.run(new Map(), common.mustCall(() => {
const options = { port: server.address().port };
const req = http.get(options, common.mustCall((res) => {
const store = cls.getStore();
store.set('data', '');
// Make ondata and onend non-closure
// functions and fully dependent on ALS
res.setEncoding('utf8');
res.on('data', ondata);
res.on('end', common.mustCall(onend));
}));
req.end();
}));
}
}));
// Accumulate the current data chunk with the store data
function ondata(d) {
const store = cls.getStore();
assert.notStrictEqual(store, undefined);
let chunk = store.get('data');
chunk += d;
store.set('data', chunk);
}
// Retrieve the store data, and test for homogeneity
function onend() {
const store = cls.getStore();
assert.notStrictEqual(store, undefined);
const data = store.get('data');
assert.strictEqual(data, data[0].repeat(data.length));
countdown.dec();
}

View file

@ -1,23 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
const common = require('../common');
const { strictEqual } = require('assert');
const { AsyncLocalStorage } = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();
const runInAsyncScope =
asyncLocalStorage.run(123, common.mustCall(() => AsyncLocalStorage.snapshot()));
const result =
asyncLocalStorage.run(321, common.mustCall(() => {
return runInAsyncScope(() => {
return asyncLocalStorage.getStore();
});
}));
strictEqual(result, 123);

View file

@ -1,14 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const assert = require('assert');
// https://github.com/nodejs/node/issues/21219
assert.strictEqual(Atomics.wake, undefined);

View file

@ -1,40 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
require('../common');
const assert = require('assert');
let exception = null;
try {
eval('"\\uc/ef"');
} catch (e) {
exception = e;
}
assert(exception instanceof SyntaxError);

View file

@ -1,34 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const { mustNotCall } = require('../common');
process.on('beforeExit', mustNotCall('exit should not allow this to occur'));
process.exit();

View file

@ -1,291 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 18.12.1
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const {
BlockList,
SocketAddress,
} = require('net');
const assert = require('assert');
const util = require('util');
{
const blockList = new BlockList();
[1, [], {}, null, 1n, undefined, null].forEach((i) => {
assert.throws(() => blockList.addAddress(i), {
code: 'ERR_INVALID_ARG_TYPE'
});
});
[1, [], {}, null, 1n, null].forEach((i) => {
assert.throws(() => blockList.addAddress('1.1.1.1', i), {
code: 'ERR_INVALID_ARG_TYPE'
});
});
assert.throws(() => blockList.addAddress('1.1.1.1', 'foo'), {
code: 'ERR_INVALID_ARG_VALUE'
});
[1, [], {}, null, 1n, undefined, null].forEach((i) => {
assert.throws(() => blockList.addRange(i), {
code: 'ERR_INVALID_ARG_TYPE'
});
assert.throws(() => blockList.addRange('1.1.1.1', i), {
code: 'ERR_INVALID_ARG_TYPE'
});
});
[1, [], {}, null, 1n, null].forEach((i) => {
assert.throws(() => blockList.addRange('1.1.1.1', '1.1.1.2', i), {
code: 'ERR_INVALID_ARG_TYPE'
});
});
assert.throws(() => blockList.addRange('1.1.1.1', '1.1.1.2', 'foo'), {
code: 'ERR_INVALID_ARG_VALUE'
});
}
{
const blockList = new BlockList();
blockList.addAddress('1.1.1.1');
blockList.addAddress('8592:757c:efae:4e45:fb5d:d62a:0d00:8e17', 'ipv6');
blockList.addAddress('::ffff:1.1.1.2', 'ipv6');
assert(blockList.check('1.1.1.1'));
assert(!blockList.check('1.1.1.1', 'ipv6'));
assert(!blockList.check('8592:757c:efae:4e45:fb5d:d62a:0d00:8e17'));
assert(blockList.check('8592:757c:efae:4e45:fb5d:d62a:0d00:8e17', 'ipv6'));
assert(blockList.check('::ffff:1.1.1.1', 'ipv6'));
assert(blockList.check('::ffff:1.1.1.1', 'IPV6'));
assert(blockList.check('1.1.1.2'));
assert(!blockList.check('1.2.3.4'));
assert(!blockList.check('::1', 'ipv6'));
}
{
const blockList = new BlockList();
const sa1 = new SocketAddress({ address: '1.1.1.1' });
const sa2 = new SocketAddress({
address: '8592:757c:efae:4e45:fb5d:d62a:0d00:8e17',
family: 'ipv6'
});
const sa3 = new SocketAddress({ address: '1.1.1.2' });
blockList.addAddress(sa1);
blockList.addAddress(sa2);
blockList.addAddress('::ffff:1.1.1.2', 'ipv6');
assert(blockList.check('1.1.1.1'));
assert(blockList.check(sa1));
assert(!blockList.check('1.1.1.1', 'ipv6'));
assert(!blockList.check('8592:757c:efae:4e45:fb5d:d62a:0d00:8e17'));
assert(blockList.check('8592:757c:efae:4e45:fb5d:d62a:0d00:8e17', 'ipv6'));
assert(blockList.check(sa2));
assert(blockList.check('::ffff:1.1.1.1', 'ipv6'));
assert(blockList.check('::ffff:1.1.1.1', 'IPV6'));
assert(blockList.check('1.1.1.2'));
assert(blockList.check(sa3));
assert(!blockList.check('1.2.3.4'));
assert(!blockList.check('::1', 'ipv6'));
}
{
const blockList = new BlockList();
blockList.addRange('1.1.1.1', '1.1.1.10');
blockList.addRange('::1', '::f', 'ipv6');
assert(!blockList.check('1.1.1.0'));
for (let n = 1; n <= 10; n++)
assert(blockList.check(`1.1.1.${n}`));
assert(!blockList.check('1.1.1.11'));
assert(!blockList.check('::0', 'ipv6'));
for (let n = 0x1; n <= 0xf; n++) {
assert(blockList.check(`::${n.toString(16)}`, 'ipv6'),
`::${n.toString(16)} check failed`);
}
assert(!blockList.check('::10', 'ipv6'));
}
{
const blockList = new BlockList();
const sa1 = new SocketAddress({ address: '1.1.1.1' });
const sa2 = new SocketAddress({ address: '1.1.1.10' });
const sa3 = new SocketAddress({ address: '::1', family: 'ipv6' });
const sa4 = new SocketAddress({ address: '::f', family: 'ipv6' });
blockList.addRange(sa1, sa2);
blockList.addRange(sa3, sa4);
assert(!blockList.check('1.1.1.0'));
for (let n = 1; n <= 10; n++)
assert(blockList.check(`1.1.1.${n}`));
assert(!blockList.check('1.1.1.11'));
assert(!blockList.check('::0', 'ipv6'));
for (let n = 0x1; n <= 0xf; n++) {
assert(blockList.check(`::${n.toString(16)}`, 'ipv6'),
`::${n.toString(16)} check failed`);
}
assert(!blockList.check('::10', 'ipv6'));
}
{
const blockList = new BlockList();
blockList.addSubnet('1.1.1.0', 16);
blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');
assert(blockList.check('1.1.0.1'));
assert(blockList.check('1.1.1.1'));
assert(!blockList.check('1.2.0.1'));
assert(blockList.check('::ffff:1.1.0.1', 'ipv6'));
assert(blockList.check('8592:757c:efae:4e45:f::', 'ipv6'));
assert(blockList.check('8592:757c:efae:4e45::f', 'ipv6'));
assert(!blockList.check('8592:757c:efae:4f45::f', 'ipv6'));
}
{
const blockList = new BlockList();
const sa1 = new SocketAddress({ address: '1.1.1.0' });
const sa2 = new SocketAddress({ address: '1.1.1.1' });
blockList.addSubnet(sa1, 16);
blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');
assert(blockList.check('1.1.0.1'));
assert(blockList.check(sa2));
assert(!blockList.check('1.2.0.1'));
assert(blockList.check('::ffff:1.1.0.1', 'ipv6'));
assert(blockList.check('8592:757c:efae:4e45:f::', 'ipv6'));
assert(blockList.check('8592:757c:efae:4e45::f', 'ipv6'));
assert(!blockList.check('8592:757c:efae:4f45::f', 'ipv6'));
}
{
const blockList = new BlockList();
blockList.addAddress('1.1.1.1');
blockList.addRange('10.0.0.1', '10.0.0.10');
blockList.addSubnet('8592:757c:efae:4e45::', 64, 'IpV6'); // Case insensitive
// const rulesCheck = [
// 'Subnet: IPv6 8592:757c:efae:4e45::/64',
// 'Range: IPv4 10.0.0.1-10.0.0.10',
// 'Address: IPv4 1.1.1.1',
// ];
// assert.deepStrictEqual(blockList.rules, rulesCheck);
assert(blockList.check('1.1.1.1'));
assert(blockList.check('10.0.0.5'));
assert(blockList.check('::ffff:10.0.0.5', 'ipv6'));
assert(blockList.check('8592:757c:efae:4e45::f', 'ipv6'));
assert(!blockList.check('123.123.123.123'));
assert(!blockList.check('8592:757c:efaf:4e45:fb5d:d62a:0d00:8e17', 'ipv6'));
assert(!blockList.check('::ffff:123.123.123.123', 'ipv6'));
}
{
// This test validates boundaries of non-aligned CIDR bit prefixes
const blockList = new BlockList();
blockList.addSubnet('10.0.0.0', 27);
blockList.addSubnet('8592:757c:efaf::', 51, 'ipv6');
for (let n = 0; n <= 31; n++)
assert(blockList.check(`10.0.0.${n}`));
assert(!blockList.check('10.0.0.32'));
assert(blockList.check('8592:757c:efaf:0:0:0:0:0', 'ipv6'));
assert(blockList.check('8592:757c:efaf:1fff:ffff:ffff:ffff:ffff', 'ipv6'));
assert(!blockList.check('8592:757c:efaf:2fff:ffff:ffff:ffff:ffff', 'ipv6'));
}
{
// Regression test for https://github.com/nodejs/node/issues/39074
const blockList = new BlockList();
blockList.addRange('10.0.0.2', '10.0.0.10');
// IPv4 checks against IPv4 range.
assert(blockList.check('10.0.0.2'));
assert(blockList.check('10.0.0.10'));
assert(!blockList.check('192.168.0.3'));
assert(!blockList.check('2.2.2.2'));
assert(!blockList.check('255.255.255.255'));
// IPv6 checks against IPv4 range.
assert(blockList.check('::ffff:0a00:0002', 'ipv6'));
assert(blockList.check('::ffff:0a00:000a', 'ipv6'));
assert(!blockList.check('::ffff:c0a8:0003', 'ipv6'));
assert(!blockList.check('::ffff:0202:0202', 'ipv6'));
assert(!blockList.check('::ffff:ffff:ffff', 'ipv6'));
}
{
const blockList = new BlockList();
assert.throws(() => blockList.addRange('1.1.1.2', '1.1.1.1'), /ERR_INVALID_ARG_VALUE/);
}
{
const blockList = new BlockList();
assert.throws(() => blockList.addSubnet(1), /ERR_INVALID_ARG_TYPE/);
assert.throws(() => blockList.addSubnet('1.1.1.1', ''),
/ERR_INVALID_ARG_TYPE/);
assert.throws(() => blockList.addSubnet('1.1.1.1', NaN), /ERR_OUT_OF_RANGE/);
assert.throws(() => blockList.addSubnet('', 1, 1), /ERR_INVALID_ARG_TYPE/);
assert.throws(() => blockList.addSubnet('', 1, ''), /ERR_INVALID_ARG_VALUE/);
assert.throws(() => blockList.addSubnet('1.1.1.1', -1, 'ipv4'),
/ERR_OUT_OF_RANGE/);
assert.throws(() => blockList.addSubnet('1.1.1.1', 33, 'ipv4'),
/ERR_OUT_OF_RANGE/);
assert.throws(() => blockList.addSubnet('::', -1, 'ipv6'),
/ERR_OUT_OF_RANGE/);
assert.throws(() => blockList.addSubnet('::', 129, 'ipv6'),
/ERR_OUT_OF_RANGE/);
}
{
const blockList = new BlockList();
assert.throws(() => blockList.check(1), /ERR_INVALID_ARG_TYPE/);
assert.throws(() => blockList.check('', 1), /ERR_INVALID_ARG_TYPE/);
}
{
const blockList = new BlockList();
const ret = util.inspect(blockList, { depth: -1 });
assert.strictEqual(ret, '[BlockList]');
}
{
const blockList = new BlockList();
const ret = util.inspect(blockList, { depth: null });
assert(ret.includes('rules: []'));
}
{
// Test for https://github.com/nodejs/node/issues/43360
const blocklist = new BlockList();
blocklist.addSubnet('1.1.1.1', 32, 'ipv4');
assert(blocklist.check('1.1.1.1'));
assert(!blocklist.check('1.1.1.2'));
assert(!blocklist.check('2.3.4.5'));
}

View file

@ -1,46 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const { strictEqual, throws } = require('assert');
const buffer = require('buffer');
// Exported on the global object
strictEqual(globalThis.atob, buffer.atob);
strictEqual(globalThis.btoa, buffer.btoa);
// Throws type error on no argument passed
throws(() => buffer.atob(), /TypeError/);
throws(() => buffer.btoa(), /TypeError/);
strictEqual(atob(' '), '');
strictEqual(atob(' Y\fW\tJ\njZ A=\r= '), 'abcd');
strictEqual(atob(null), '\x9Eée');
strictEqual(atob(NaN), '5£');
strictEqual(atob(Infinity), '"wâ\x9E+r');
strictEqual(atob(true), '¶»\x9E');
strictEqual(atob(1234), '×mø');
strictEqual(atob([]), '');
strictEqual(atob({ toString: () => '' }), '');
strictEqual(atob({ [Symbol.toPrimitive]: () => '' }), '');
throws(() => atob(Symbol()), /TypeError/);
[
undefined, false, () => {}, {}, [1],
0, 1, 0n, 1n, -Infinity,
'a', 'a\n\n\n', '\ra\r\r', ' a ', '\t\t\ta', 'a\f\f\f', '\ta\r \n\f',
].forEach((value) =>
// See #2 - https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
throws(() => atob(value), {
constructor: DOMException,
name: 'InvalidCharacterError',
code: 5,
}));

File diff suppressed because it is too large Load diff

View file

@ -1,159 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const assert = require('assert');
const LENGTH = 16;
const ab = new ArrayBuffer(LENGTH);
const dv = new DataView(ab);
const ui = new Uint8Array(ab);
const buf = Buffer.from(ab);
assert.ok(buf instanceof Buffer);
assert.strictEqual(buf.parent, buf.buffer);
assert.strictEqual(buf.buffer, ab);
assert.strictEqual(buf.length, ab.byteLength);
buf.fill(0xC);
for (let i = 0; i < LENGTH; i++) {
assert.strictEqual(ui[i], 0xC);
ui[i] = 0xF;
assert.strictEqual(buf[i], 0xF);
}
buf.writeUInt32LE(0xF00, 0);
buf.writeUInt32BE(0xB47, 4);
buf.writeDoubleLE(3.1415, 8);
assert.strictEqual(dv.getUint32(0, true), 0xF00);
assert.strictEqual(dv.getUint32(4), 0xB47);
assert.strictEqual(dv.getFloat64(8, true), 3.1415);
// Now test protecting users from doing stupid things
assert.throws(function() {
function AB() { }
Object.setPrototypeOf(AB, ArrayBuffer);
Object.setPrototypeOf(AB.prototype, ArrayBuffer.prototype);
Buffer.from(new AB());
}, {
code: 'ERR_INVALID_ARG_TYPE',
name: 'TypeError',
message: 'The first argument must be of type string or an instance of ' +
'Buffer, ArrayBuffer, or Array or an Array-like Object. Received ' +
'an instance of AB'
});
// Test the byteOffset and length arguments
{
const ab = new Uint8Array(5);
ab[0] = 1;
ab[1] = 2;
ab[2] = 3;
ab[3] = 4;
ab[4] = 5;
const buf = Buffer.from(ab.buffer, 1, 3);
assert.strictEqual(buf.length, 3);
assert.strictEqual(buf[0], 2);
assert.strictEqual(buf[1], 3);
assert.strictEqual(buf[2], 4);
buf[0] = 9;
assert.strictEqual(ab[1], 9);
assert.throws(() => Buffer.from(ab.buffer, 6), {
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
name: 'RangeError',
message: '"offset" is outside of buffer bounds'
});
assert.throws(() => Buffer.from(ab.buffer, 3, 6), {
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
name: 'RangeError',
message: '"length" is outside of buffer bounds'
});
}
// Test the deprecated Buffer() version also
{
const ab = new Uint8Array(5);
ab[0] = 1;
ab[1] = 2;
ab[2] = 3;
ab[3] = 4;
ab[4] = 5;
const buf = Buffer(ab.buffer, 1, 3);
assert.strictEqual(buf.length, 3);
assert.strictEqual(buf[0], 2);
assert.strictEqual(buf[1], 3);
assert.strictEqual(buf[2], 4);
buf[0] = 9;
assert.strictEqual(ab[1], 9);
assert.throws(() => Buffer(ab.buffer, 6), {
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
name: 'RangeError',
message: '"offset" is outside of buffer bounds'
});
assert.throws(() => Buffer(ab.buffer, 3, 6), {
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
name: 'RangeError',
message: '"length" is outside of buffer bounds'
});
}
{
// If byteOffset is not numeric, it defaults to 0.
const ab = new ArrayBuffer(10);
const expected = Buffer.from(ab, 0);
assert.deepStrictEqual(Buffer.from(ab, 'fhqwhgads'), expected);
assert.deepStrictEqual(Buffer.from(ab, NaN), expected);
assert.deepStrictEqual(Buffer.from(ab, {}), expected);
assert.deepStrictEqual(Buffer.from(ab, []), expected);
// If byteOffset can be converted to a number, it will be.
assert.deepStrictEqual(Buffer.from(ab, [1]), Buffer.from(ab, 1));
// If byteOffset is Infinity, throw.
assert.throws(() => {
Buffer.from(ab, Infinity);
}, {
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
name: 'RangeError',
message: '"offset" is outside of buffer bounds'
});
}
{
// If length is not numeric, it defaults to 0.
const ab = new ArrayBuffer(10);
const expected = Buffer.from(ab, 0, 0);
assert.deepStrictEqual(Buffer.from(ab, 0, 'fhqwhgads'), expected);
assert.deepStrictEqual(Buffer.from(ab, 0, NaN), expected);
assert.deepStrictEqual(Buffer.from(ab, 0, {}), expected);
assert.deepStrictEqual(Buffer.from(ab, 0, []), expected);
// If length can be converted to a number, it will be.
assert.deepStrictEqual(Buffer.from(ab, 0, [1]), Buffer.from(ab, 0, 1));
// If length is Infinity, throw.
assert.throws(() => {
Buffer.from(ab, 0, Infinity);
}, {
code: 'ERR_BUFFER_OUT_OF_BOUNDS',
name: 'RangeError',
message: '"length" is outside of buffer bounds'
});
}
// Test an array like entry with the length set to NaN.
assert.deepStrictEqual(Buffer.from({ length: NaN }), Buffer.alloc(0));

View file

@ -1,53 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
require('../common');
const assert = require('assert');
// ASCII conversion in node.js simply masks off the high bits,
// it doesn't do transliteration.
assert.strictEqual(Buffer.from('hérité').toString('ascii'), 'hC)ritC)');
// 71 characters, 78 bytes. The character is a triple-byte sequence.
const input = 'Cest, graphiquement, la réunion dun accent aigu ' +
'et dun accent grave.';
const expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' +
'db\u0000\u0019un accent aigu et db\u0000\u0019un ' +
'accent grave.';
const buf = Buffer.from(input);
for (let i = 0; i < expected.length; ++i) {
assert.strictEqual(buf.slice(i).toString('ascii'), expected.slice(i));
// Skip remainder of multi-byte sequence.
if (input.charCodeAt(i) > 65535) ++i;
if (input.charCodeAt(i) > 127) ++i;
}

View file

@ -1,45 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
// Flags: --expose-internals
'use strict';
require('../common');
const assert = require('assert');
const { internalBinding } = require('internal/test/binding');
const { arrayBufferViewHasBuffer } = internalBinding('util');
// All ABs in Deno are not on heap.
const tests = [
{ length: 0, expectOnHeap: false },
{ length: 48, expectOnHeap: false },
{ length: 96, expectOnHeap: false },
{ length: 1024, expectOnHeap: false },
];
for (const { length, expectOnHeap } of tests) {
const arrays = [
new Uint8Array(length),
new Uint16Array(length / 2),
new Uint32Array(length / 4),
new Float32Array(length / 4),
new Float64Array(length / 8),
Buffer.alloc(length),
Buffer.allocUnsafeSlow(length),
// Buffer.allocUnsafe() is missing because it may use pooled allocations.
];
for (const array of arrays) {
const isOnHeap = !arrayBufferViewHasBuffer(array);
assert.strictEqual(isOnHeap, expectOnHeap,
`mismatch: ${isOnHeap} vs ${expectOnHeap} ` +
`for ${array.constructor.name}, length = ${length}`);
// Consistency check: Accessing .buffer should create it.
array.buffer; // eslint-disable-line no-unused-expressions
assert(arrayBufferViewHasBuffer(array));
}
}

View file

@ -1,55 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const assert = require('assert');
// Test hex strings and bad hex strings
{
const buf = Buffer.alloc(4);
assert.strictEqual(buf.length, 4);
assert.deepStrictEqual(buf, Buffer.from([0, 0, 0, 0]));
assert.strictEqual(buf.write('abcdxx', 0, 'hex'), 2);
assert.deepStrictEqual(buf, Buffer.from([0xab, 0xcd, 0x00, 0x00]));
assert.strictEqual(buf.toString('hex'), 'abcd0000');
assert.strictEqual(buf.write('abcdef01', 0, 'hex'), 4);
assert.deepStrictEqual(buf, Buffer.from([0xab, 0xcd, 0xef, 0x01]));
assert.strictEqual(buf.toString('hex'), 'abcdef01');
const copy = Buffer.from(buf.toString('hex'), 'hex');
assert.strictEqual(buf.toString('hex'), copy.toString('hex'));
}
{
const buf = Buffer.alloc(5);
assert.strictEqual(buf.write('abcdxx', 1, 'hex'), 2);
assert.strictEqual(buf.toString('hex'), '00abcd0000');
}
{
const buf = Buffer.alloc(4);
assert.deepStrictEqual(buf, Buffer.from([0, 0, 0, 0]));
assert.strictEqual(buf.write('xxabcd', 0, 'hex'), 0);
assert.deepStrictEqual(buf, Buffer.from([0, 0, 0, 0]));
assert.strictEqual(buf.write('xxab', 1, 'hex'), 0);
assert.deepStrictEqual(buf, Buffer.from([0, 0, 0, 0]));
assert.strictEqual(buf.write('cdxxab', 0, 'hex'), 1);
assert.deepStrictEqual(buf, Buffer.from([0xcd, 0, 0, 0]));
}
{
const buf = Buffer.alloc(256);
for (let i = 0; i < 256; i++)
buf[i] = i;
const hex = buf.toString('hex');
assert.deepStrictEqual(Buffer.from(hex, 'hex'), buf);
const badHex = `${hex.slice(0, 256)}xx${hex.slice(256, 510)}`;
assert.deepStrictEqual(Buffer.from(badHex, 'hex'), buf.slice(0, 128));
}

View file

@ -1,62 +0,0 @@
// deno-fmt-ignore-file
// deno-lint-ignore-file
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// Taken from Node 23.9.0
// This file is automatically generated by `tests/node_compat/runner/setup.ts`. Do not modify this file manually.
'use strict';
require('../common');
const assert = require('assert');
const buf = Buffer.allocUnsafe(8);
['LE', 'BE'].forEach(function(endianness) {
// Should allow simple BigInts to be written and read
let val = 123456789n;
buf[`writeBigInt64${endianness}`](val, 0);
let rtn = buf[`readBigInt64${endianness}`](0);
assert.strictEqual(val, rtn);
// Should allow INT64_MAX to be written and read
val = 0x7fffffffffffffffn;
buf[`writeBigInt64${endianness}`](val, 0);
rtn = buf[`readBigInt64${endianness}`](0);
assert.strictEqual(val, rtn);
// Should read and write a negative signed 64-bit integer
val = -123456789n;
buf[`writeBigInt64${endianness}`](val, 0);
assert.strictEqual(val, buf[`readBigInt64${endianness}`](0));
// Should read and write an unsigned 64-bit integer
val = 123456789n;
buf[`writeBigUInt64${endianness}`](val, 0);
assert.strictEqual(val, buf[`readBigUInt64${endianness}`](0));
// Should throw a RangeError upon INT64_MAX+1 being written
assert.throws(function() {
const val = 0x8000000000000000n;
buf[`writeBigInt64${endianness}`](val, 0);
}, RangeError);
// Should throw a RangeError upon UINT64_MAX+1 being written
assert.throws(function() {
const val = 0x10000000000000000n;
buf[`writeBigUInt64${endianness}`](val, 0);
}, {
code: 'ERR_OUT_OF_RANGE',
message: 'The value of "value" is out of range. It must be ' +
'>= 0n and < 2n ** 64n. Received 18_446_744_073_709_551_616n'
});
// Should throw a TypeError upon invalid input
assert.throws(function() {
buf[`writeBigInt64${endianness}`]('bad', 0);
}, TypeError);
// Should throw a TypeError upon invalid input
assert.throws(function() {
buf[`writeBigUInt64${endianness}`]('bad', 0);
}, TypeError);
});

Some files were not shown because too many files have changed in this diff Show more