diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98a432c13d..32e436b8f1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,6 +45,11 @@ jobs: - name: Checkout uses: actions/checkout@v4 + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version-file: .nvmrc + - name: Restore build cache id: build-cache uses: actions/cache@v4 @@ -401,11 +406,11 @@ jobs: run: | opam exec -- node packages/playground-bundling/scripts/generate_cmijs.js opam exec -- dune build --profile browser - cp ./_build/default/compiler/jsoo/jsoo_playground_main.bc.js playground/compiler.js + cp ./_build/default/compiler/jsoo/jsoo_playground_main.bc.js playground/compiler.cjs - name: Test playground compiler if: matrix.build_playground - run: node playground/playground_test.js + run: node playground/playground_test.cjs - name: Upload playground compiler to CDN if: ${{ matrix.build_playground && startsWith(github.ref, 'refs/tags/v') }} diff --git a/.github/workflows/get_artifact_dir_name.js b/.github/workflows/get_artifact_dir_name.js index 28e245bb5c..9ad465b6a4 100644 --- a/.github/workflows/get_artifact_dir_name.js +++ b/.github/workflows/get_artifact_dir_name.js @@ -1,10 +1,10 @@ -const fs = require("fs"); -const os = require("os"); +import * as fs from "node:fs"; +import * as os from "node:os"; -const { dirName: artifactDirName } = require("../../cli/bin_path.js"); +import { platformName } from "#cli/bins"; // Pass artifactDirName to subsequent GitHub actions fs.appendFileSync( process.env.GITHUB_ENV, - `artifact_dir_name=${artifactDirName}${os.EOL}`, + `artifact_dir_name=${platformName}${os.EOL}`, ); diff --git a/.github/workflows/prepare_package_upload.js b/.github/workflows/prepare_package_upload.js index b94e20153e..680b58b7ae 100644 --- a/.github/workflows/prepare_package_upload.js +++ b/.github/workflows/prepare_package_upload.js @@ -1,7 +1,8 @@ -const fs = require("fs"); -const os = require("os"); +import * as fs from "node:fs"; +import * as os from "node:os"; + +import packageSpec from "rescript/package.json" with { type: "json" }; -const packageSpec = require("rescript/package.json"); const { version } = packageSpec; const commitHash = process.argv[2] || process.env.GITHUB_SHA; diff --git a/.gitignore b/.gitignore index e50efa90c8..f672ecca61 100644 --- a/.gitignore +++ b/.gitignore @@ -72,7 +72,7 @@ playground/stdlib/ playground/*.cmj playground/*.cmi playground/.netrc -playground/compiler.js +playground/compiler.*js rewatch/target/ rewatch/rewatch @@ -88,3 +88,5 @@ tests/analysis_tests/**/*.bs.js !.yarn/releases !.yarn/sdks !.yarn/versions + +*.tsbuildinfo diff --git a/.yarnrc.yml b/.yarnrc.yml index aa89ff6467..5a86a6195d 100644 --- a/.yarnrc.yml +++ b/.yarnrc.yml @@ -3,3 +3,5 @@ yarnPath: .yarn/releases/yarn-4.7.0.cjs nodeLinker: node-modules nmMode: hardlinks-global + +defaultSemverRangePrefix: "" diff --git a/CHANGELOG.md b/CHANGELOG.md index d503c99bb6..070d0df456 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ #### :house: Internal - Remove `Stdlib_Char` module for now. https://github.com/rescript-lang/rescript/pull/7367 +- Convert internal JavaScript codebase into ESM, ReScript package itself is now ESM (`"type": "module"`). https://github.com/rescript-lang/rescript/pull/6899 # 12.0.0-alpha.10 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0fcea01340..c94e799ddc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -263,7 +263,7 @@ $ node ### Testing the Playground bundle -Run `node playground/playground_test.js` for a quick sanity check to see if all the build artifacts are working together correctly. When releasing the playground bundle, the test will always be executed before publishing to catch regressions. +Run `node playground/playground_test.cjs` for a quick sanity check to see if all the build artifacts are working together correctly. When releasing the playground bundle, the test will always be executed before publishing to catch regressions. ### Working on the Playground JS API @@ -273,7 +273,7 @@ Whenever you are modifying any files in the ReScript compiler, or in the `jsoo_p make playground # optionally run your test / arbitrary node script to verify your changes -node playground/playground_test.js +node playground/playground_test.cjs ``` ### Publishing the Playground Bundle on our KeyCDN diff --git a/Makefile b/Makefile index 0b54c0bfb8..5f6677fc31 100644 --- a/Makefile +++ b/Makefile @@ -61,7 +61,7 @@ artifacts: lib # Builds the core playground bundle (without the relevant cmijs files for the runtime) playground: dune build --profile browser - cp ./_build/default/compiler/jsoo/jsoo_playground_main.bc.js playground/compiler.js + cp ./_build/default/compiler/jsoo/jsoo_playground_main.bc.js playground/compiler.cjs # Creates all the relevant core and third party cmij files to side-load together with the playground bundle playground-cmijs: artifacts @@ -70,7 +70,7 @@ playground-cmijs: artifacts # Builds the playground, runs some e2e tests and releases the playground to the # CDN (requires KEYCDN_USER and KEYCDN_PASSWORD set in the env variables) playground-release: playground playground-cmijs - node playground/playground_test.js + node playground/playground_test.cjs sh playground/upload_bundle.sh format: @@ -86,7 +86,7 @@ clean-rewatch: cargo clean --manifest-path rewatch/Cargo.toml && rm -f rewatch/rewatch clean: - (cd runtime && ../cli/rescript clean) + (cd runtime && ../cli/rescript.js clean) dune clean clean-all: clean clean-gentype clean-rewatch diff --git a/analysis/examples/example-project/types.json b/analysis/examples/example-project/types.json index 904cdf616e..00f8bce969 100644 --- a/analysis/examples/example-project/types.json +++ b/analysis/examples/example-project/types.json @@ -8,6 +8,6 @@ } ], "custom": [ - {"module": "Belt_HashMapInt", "path": [], "name": "t", "args": 1} + { "module": "Belt_HashMapInt", "path": [], "name": "t", "args": 1 } ] -} \ No newline at end of file +} diff --git a/analysis/examples/larger-project/.watchmanconfig b/analysis/examples/larger-project/.watchmanconfig deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/biome.json b/biome.json index 0d166ac261..aef80be170 100644 --- a/biome.json +++ b/biome.json @@ -1,5 +1,5 @@ { - "$schema": "https://biomejs.dev/schemas/1.8.3/schema.json", + "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", "vcs": { "enabled": true, "clientKind": "git", @@ -7,10 +7,28 @@ "useIgnoreFile": true }, "linter": { - "enabled": false + "enabled": true, + "rules": { + "recommended": true, + "style": { + "useTemplate": "off" + }, + "nursery": { + "noCommonJs": "error" + }, + "suspicious": { + "noAssignInExpressions": "warn" + }, + "correctness": { + "useImportExtensions": "error", + "noUndeclaredDependencies": "error", + "noUnusedImports": "error", + "noUnusedVariables": "warn" + } + } }, "organizeImports": { - "enabled": false + "enabled": true }, "formatter": { "enabled": true, @@ -19,24 +37,7 @@ "indentWidth": 2, "lineEnding": "lf", "lineWidth": 80, - "attributePosition": "auto", - "ignore": [ - ".yarn/**", - "tests/build_tests/**", - "tests/tests/**", - "tests/tools_tests/**", - "tests/analysis_tests/**", - "tests/docstring_tests/**", - "analysis/examples/**", - "analysis/reanalyze/examples/**", - "lib/**", - "ninja/**", - "playground/**", - "**/*.bs.js", - "**/*.res.js", - "**/*.gen.ts*", - "package.json" - ] + "attributePosition": "auto" }, "javascript": { "formatter": { @@ -50,5 +51,27 @@ "quoteStyle": "double", "attributePosition": "auto" } + }, + "files": { + "ignore": [ + ".yarn/**", + "tests/analysis_tests/**/src/**", + "tests/build_tests/**/src/**", + "tests/docstring_tests/**", + "tests/gentype_tests/**", + "tests/tests/**/src/**", + "tests/tools_tests/**/src/**", + "analysis/examples/**/src/**", + "lib/es6/**", + "lib/js/**", + "ninja/**", + "packages/**", + "playground/**", + "*.bs.js", + "*.res.js", + "*.res.mjs", + "*.gen.ts*", + "package.json" + ] } } diff --git a/cli/bin_path.js b/cli/bin_path.js deleted file mode 100644 index 727e233da0..0000000000 --- a/cli/bin_path.js +++ /dev/null @@ -1,59 +0,0 @@ -//@ts-check - -const path = require("path"); - -/** - * @type{string} - * - * For compatibility reasons, if the architecture is x64, omit it from the bin directory name. - * So we'll have "darwin", "linux" and "win32" for x64 arch, - * but "darwinarm64" and "linuxarm64" for arm64 arch. - * Also, we do not have Windows ARM binaries yet. But the x64 binaries do work on Windows 11 ARM. - * So omit the architecture for Windows, too. - */ -const binDirName = - process.arch === "x64" || process.platform === "win32" - ? process.platform - : process.platform + process.arch; - -/** - * - * @type{string} - */ -const binAbsolutePath = path.join(__dirname, "..", binDirName); - -/** - * @type{string} - */ -const bsc_exe = path.join(binAbsolutePath, "bsc.exe"); - -/** - * @type{string} - */ -const ninja_exe = path.join(binAbsolutePath, "ninja.exe"); - -/** - * @type{string} - */ -const rescript_exe = path.join(binAbsolutePath, "rescript.exe"); - -/** - * @type{string} - */ -const rescript_tools_exe = path.join(binAbsolutePath, "rescript-tools.exe"); - -/** - * @type{string} - */ -const rescript_editor_analysis_exe = path.join( - binAbsolutePath, - "rescript-editor-analysis.exe", -); - -exports.dirName = binDirName; -exports.absolutePath = binAbsolutePath; -exports.bsc_exe = bsc_exe; -exports.ninja_exe = ninja_exe; -exports.rescript_exe = rescript_exe; -exports.rescript_tools_exe = rescript_tools_exe; -exports.rescript_editor_analysis_exe = rescript_editor_analysis_exe; diff --git a/cli/bsc b/cli/bsc deleted file mode 100755 index 6294212188..0000000000 --- a/cli/bsc +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node -"use strict"; - -var child_process = require("child_process"); -var { bsc_exe } = require("./bin_path"); - -var delegate_args = process.argv.slice(2); - -try { - child_process.execFileSync(bsc_exe, delegate_args, { stdio: "inherit" }); -} catch (e) { - if (e.code === "ENOENT") { - console.error(String(e)); - } - process.exit(2); -} diff --git a/cli/bsc.js b/cli/bsc.js new file mode 100755 index 0000000000..711ccc17dd --- /dev/null +++ b/cli/bsc.js @@ -0,0 +1,18 @@ +#!/usr/bin/env node + +// @ts-check + +import { execFileSync } from "node:child_process"; + +import { bsc_exe } from "./common/bins.js"; + +const delegate_args = process.argv.slice(2); + +try { + execFileSync(bsc_exe, delegate_args, { stdio: "inherit" }); +} catch (e) { + if (e.code === "ENOENT") { + console.error(String(e)); + } + process.exit(2); +} diff --git a/cli/rescript_arg.js b/cli/common/args.js similarity index 68% rename from cli/rescript_arg.js rename to cli/common/args.js index 3bfdc1283e..471a6430d5 100644 --- a/cli/rescript_arg.js +++ b/cli/common/args.js @@ -1,4 +1,5 @@ -//@ts-check +// @ts-check + class StringBuilder { constructor() { this.val = ""; @@ -13,23 +14,32 @@ class StringBuilder { return this; } } -class ArgError extends Error {} + +export class ArgError extends Error {} /** - * * @param {string} s */ -function bad_arg(s) { +export function bad_arg(s) { throw new ArgError(s); } /** - * @typedef {{val : string}} stringref - * @typedef {{val : boolean}} boolref - * @typedef {{kind:"Unit_call",data : ()=>void } | {kind : "Unit_set", data : boolref}} unit_action - * @typedef {{kind:"String_call",data:(s : string)=>void} | {kind : "String_set",data: stringref}} string_action - * @typedef {{kind:"Unit",data : unit_action } | {kind:"String", data: string_action}} action - * @typedef {Array<[string,action,string]>} specs + * @typedef {{ val: string }} stringref + * @typedef {{ val: boolean }} boolref + * @typedef {( + * | { kind: "Unit_call", data: () => void } + * | { kind: "Unit_set", data: boolref } + * )} unit_action + * @typedef {( + * | { kind: "String_call", data: (s: string) => void } + * | { kind: "String_set", data: stringref } + * )} string_action + * @typedef {( + * | { kind: "Unit", data: unit_action } + * | { kind: "String", data: string_action} + * )} action + * @typedef {Array<[string, action, string]>} specs * @param {StringBuilder} b * @param {string} usage * @param {specs} specs @@ -39,33 +49,32 @@ function usage_b(b, usage, specs) { if (specs.length === 0) { return; } - b.add(`\nOptions:\n`); - var max_col = 0; - for (let [key] of specs) { + b.add("\nOptions:\n"); + let max_col = 0; + for (const [key] of specs) { if (key.length > max_col) { max_col = key.length; } } for (let i = 0; i < specs.length; i++) { - let [key, _, doc] = specs[i]; + const [key, _, doc] = specs[i]; if (!doc.startsWith("*internal*")) { b.add(" ") .add(key) .add(" ".repeat(max_col - key.length + 2)); let cur = 0; - let doc_length = doc.length; + const doc_length = doc.length; while (cur < doc_length) { if (cur !== 0) { b.add("\n").add(" ".repeat(max_col + 4)); } - let i = doc.indexOf("\n", cur); + const i = doc.indexOf("\n", cur); if (i < 0) { b.add(doc.substring(cur)); break; - } else { - b.add(doc.substr(cur, i - cur)); - cur = i + 1; } + b.add(doc.substring(cur, i - cur)); + cur = i + 1; } b.add("\n"); } @@ -73,13 +82,16 @@ function usage_b(b, usage, specs) { } /** - * @typedef { {kind : "Unknown"; data:string} | {kind:"Missing";data:string}} error + * @typedef {( + * | { kind: "Unknown", data:string } + * | { kind: "Missing", data:string } + * )} error * @param {string} usage * @param {error} error * @param {specs} specs */ function stop_raise(usage, error, specs) { - var b = new StringBuilder(); + const b = new StringBuilder(); switch (error.kind) { case "Unknown": if (["-help", "--help", "-h"].includes(error.data)) { @@ -89,23 +101,24 @@ function stop_raise(usage, error, specs) { } else { b.add(`Unknown option "${error.data}".\n'`); } + break; case "Missing": b.add(`Option "${error.data}" needs an argument.\n'`); + break; } usage_b(b, usage, specs); bad_arg(b.val); } /** - * * @param {string} usage * @param {Array} argv * @param {specs} specs - * @param {(args:Array)=>void} annofun + * @param {(args: Array) => void} annofun * @param {number} start * @param {number} finish */ -function parse_exn( +export function parse_exn( usage, argv, specs, @@ -114,15 +127,15 @@ function parse_exn( // first 3 are [node, rescript, subcommand] finish = argv.length, ) { - var current = start; - var list = []; + let current = start; + const list = []; while (current < finish) { - let s = argv[current]; + const s = argv[current]; ++current; if (s !== "" && s[0] === "-") { - var out = specs.find(([flag]) => flag === s); + const out = specs.find(([flag]) => flag === s); if (out !== undefined) { - let [_, action] = out; + const [_, action] = out; switch (action.kind) { case "Unit": switch (action.data.kind) { @@ -139,7 +152,7 @@ function parse_exn( if (current >= finish) { stop_raise(usage, { kind: "Missing", data: s }, specs); } else { - let arg = argv[current]; + const arg = argv[current]; ++current; switch (action.data.kind) { case "String_call": @@ -161,6 +174,3 @@ function parse_exn( } annofun(list); } -exports.bad_arg = bad_arg; -exports.parse_exn = parse_exn; -exports.ArgError = ArgError; diff --git a/cli/common/bins.js b/cli/common/bins.js new file mode 100644 index 0000000000..7472466062 --- /dev/null +++ b/cli/common/bins.js @@ -0,0 +1,37 @@ +// @ts-check + +import * as path from "node:path"; + +/** + * For compatibility reasons, if the architecture is x64, omit it from the bin directory name. + * So we'll have "darwin", "linux" and "win32" for x64 arch, + * but "darwinarm64" and "linuxarm64" for arm64 arch. + * Also, we do not have Windows ARM binaries yet. But the x64 binaries do work on Windows 11 ARM. + * So omit the architecture for Windows, too. + */ +export const platformName = + process.arch === "x64" || process.platform === "win32" + ? process.platform + : process.platform + process.arch; + +export const platformDir = path.resolve( + import.meta.dirname, + "..", + "..", + platformName, +); + +export const bsc_exe = path.join(platformDir, "bsc.exe"); + +export const ninja_exe = path.join(platformDir, "ninja.exe"); + +export const rescript_exe = path.join(platformDir, "rescript.exe"); + +export const rescript_tools_exe = path.join(platformDir, "rescript-tools.exe"); + +export const rescript_editor_analysis_exe = path.join( + platformDir, + "rescript-editor-analysis.exe", +); + +export const rewatch_exe = path.join(platformDir, "rewatch.exe"); diff --git a/cli/rescript_bsb.js b/cli/common/bsb.js similarity index 77% rename from cli/rescript_bsb.js rename to cli/common/bsb.js index 294979ddd1..8f229f1aa7 100644 --- a/cli/rescript_bsb.js +++ b/cli/common/bsb.js @@ -1,10 +1,13 @@ -//@ts-check +// @ts-check -const fs = require("fs"); -const path = require("path"); -var os = require("os"); -const child_process = require("child_process"); -const { rescript_exe } = require("./bin_path"); +import * as child_process from "node:child_process"; +import * as fs from "node:fs"; +import { createServer } from "node:http"; +import * as os from "node:os"; +import * as path from "node:path"; +import { WebSocket } from "#lib/minisocket"; + +import { rescript_exe } from "./bins.js"; const cwd = process.cwd(); const lockFileName = path.join(cwd, ".bsb.lock"); @@ -25,7 +28,7 @@ const lockFileName = path.join(cwd, ".bsb.lock"); * @type {child_process.ChildProcess | null} */ let ownerProcess = null; -function releaseBuild() { +export function releaseBuild() { if (ownerProcess) { ownerProcess.kill("SIGHUP"); try { @@ -45,24 +48,23 @@ function releaseBuild() { function acquireBuild(args, options) { if (ownerProcess) { return null; - } else { - try { - ownerProcess = child_process.spawn(rescript_exe, args, { - stdio: "inherit", - ...options, - }); - fs.writeFileSync(lockFileName, ownerProcess.pid.toString(), { - encoding: "utf8", - flag: "wx", - mode: 0o664, - }); - } catch (err) { - if (err.code === "EEXIST") { - console.warn(lockFileName, "already exists, try later"); - } else console.log(err); - } - return ownerProcess; } + try { + ownerProcess = child_process.spawn(rescript_exe, args, { + stdio: "inherit", + ...options, + }); + fs.writeFileSync(lockFileName, ownerProcess.pid.toString(), { + encoding: "utf8", + flag: "wx", + mode: 0o664, + }); + } catch (err) { + if (err.code === "EEXIST") { + console.warn(lockFileName, "already exists, try later"); + } else console.log(err); + } + return ownerProcess; } /** @@ -99,19 +101,20 @@ function delegate(args, maybeOnClose) { /** * @param {Array} args */ -function info(args) { +export function info(args) { delegate(["info", ...args]); } /** * @param {Array} args */ -function clean(args) { +export function clean(args) { delegate(["clean", ...args]); } -const shouldColorizeError = process.stderr.isTTY || process.env.FORCE_COLOR == "1"; -const shouldColorize = process.stdout.isTTY || process.env.FORCE_COLOR == "1"; +const shouldColorizeError = + process.stderr.isTTY || process.env.FORCE_COLOR === "1"; +const shouldColorize = process.stdout.isTTY || process.env.FORCE_COLOR === "1"; /** * @type {[number,number]} @@ -129,12 +132,12 @@ function updateFinishTime() { * @param {number} [code] */ function logFinishCompiling(code) { - let log = `>>>> Finish compiling`; + let log = ">>>> Finish compiling"; if (code) { - log = log + " (exit: " + code + ")"; + log = `${log} (exit: ${code})`; } if (shouldColorize) { - log = "\x1b[36m" + log + "\x1b[0m"; + log = `\x1b[36m${log}\x1b[0m`; } if (code) { console.log(log); @@ -145,9 +148,9 @@ function logFinishCompiling(code) { function logStartCompiling() { updateStartTime(); - let log = `>>>> Start compiling`; + let log = ">>>> Start compiling"; if (shouldColorize) { - log = "\x1b[36m" + log + "\x1b[0m"; + log = `\x1b[36m${log}\x1b[0m`; } console.log(log); } @@ -164,9 +167,8 @@ function exitProcess() { function getProjectFiles(file) { if (fs.existsSync(file)) { return JSON.parse(fs.readFileSync(file, "utf8")); - } else { - return { dirs: [], generated: [] }; } + return { dirs: [], generated: [] }; } /** @@ -189,7 +191,7 @@ function watch(args) { const sourcedirs = path.join("lib", "bs", ".sourcedirs.json"); - var LAST_SUCCESS_BUILD_STAMP = 0; + let LAST_SUCCESS_BUILD_STAMP = 0; let LAST_BUILD_START = 0; let LAST_FIRED_EVENT = 0; @@ -211,20 +213,20 @@ function watch(args) { const verbose = args.includes("-verbose"); const dlog = verbose ? console.log : () => {}; - var wsParamIndex = args.indexOf("-ws"); + const wsParamIndex = args.indexOf("-ws"); if (wsParamIndex > -1) { - var hostAndPortNumber = (args[wsParamIndex + 1] || "").split(":"); + const hostAndPortNumber = (args[wsParamIndex + 1] || "").split(":"); /** * @type {number} */ - var portNumber; + let portNumber; if (hostAndPortNumber.length === 1) { - portNumber = parseInt(hostAndPortNumber[0]); + portNumber = Number.parseInt(hostAndPortNumber[0]); } else { webSocketHost = hostAndPortNumber[0]; - portNumber = parseInt(hostAndPortNumber[1]); + portNumber = Number.parseInt(hostAndPortNumber[1]); } - if (!isNaN(portNumber)) { + if (!Number.isNaN(portNumber)) { webSocketPort = portNumber; } withWebSocket = true; @@ -237,12 +239,12 @@ function watch(args) { function notifyClients() { wsClients = wsClients.filter(x => !x.closed && !x.socket.destroyed); - var wsClientsLen = wsClients.length; + const wsClientsLen = wsClients.length; dlog(`Alive sockets number: ${wsClientsLen}`); - var data = '{"LAST_SUCCESS_BUILD_STAMP":' + LAST_SUCCESS_BUILD_STAMP + "}"; - for (var i = 0; i < wsClientsLen; ++i) { + const data = JSON.stringify({ LAST_SUCCESS_BUILD_STAMP }); + for (let i = 0; i < wsClientsLen; i++) { // in reverse order, the last pushed get notified earlier - var client = wsClients[wsClientsLen - i - 1]; + const client = wsClients[wsClientsLen - i - 1]; if (!client.closed) { client.sendText(data); } @@ -250,22 +252,20 @@ function watch(args) { } function setUpWebSocket() { - var WebSocket = require("../lib/minisocket.js").MiniWebSocket; - var id = setInterval(notifyClients, 3000); - require("http") - .createServer() - .on("upgrade", function (req, socket, upgradeHead) { + const _id = setInterval(notifyClients, 3000); + createServer() + .on("upgrade", (req, socket, upgradeHead) => { dlog("connection opened"); - var ws = new WebSocket(req, socket, upgradeHead); - socket.on("error", function (err) { + const ws = new WebSocket(req, socket, upgradeHead); + socket.on("error", err => { dlog(`Socket Error ${err}`); }); wsClients.push(ws); }) - .on("error", function (err) { + .on("error", err => { // @ts-ignore if (err !== undefined && err.code === "EADDRINUSE") { - var error = shouldColorize ? `\x1b[1;31mERROR:\x1b[0m` : `ERROR:`; + const error = shouldColorize ? "\x1b[1;31mERROR:\x1b[0m" : "ERROR:"; console.error(`${error} The websocket port number ${webSocketPort} is in use. Please pick a different one using the \`-ws [host:]port\` flag from bsb.`); } else { @@ -280,31 +280,26 @@ Please pick a different one using the \`-ws [host:]port\` flag from bsb.`); * @param {ProjectFiles} projectFiles */ function watchBuild(projectFiles) { - var watchFiles = projectFiles.dirs; + const watchFiles = projectFiles.dirs; watchGenerated = projectFiles.generated; // close and remove all unused watchers - watchers = watchers.filter(function (watcher) { + watchers = watchers.filter(watcher => { if (watcher.dir === resConfig) { return true; - } else if (watchFiles.indexOf(watcher.dir) < 0) { + } + if (watchFiles.indexOf(watcher.dir) < 0) { dlog(`${watcher.dir} is no longer watched`); watcher.watcher.close(); return false; - } else { - return true; } + return true; }); // adding new watchers - for (var i = 0; i < watchFiles.length; ++i) { - var dir = watchFiles[i]; - if ( - !watchers.find(function (watcher) { - return watcher.dir === dir; - }) - ) { + for (const dir of watchFiles) { + if (!watchers.find(watcher => watcher.dir === dir)) { dlog(`watching dir ${dir} now`); - var watcher = fs.watch(dir, onChange); + const watcher = fs.watch(dir, onChange); watchers.push({ dir: dir, watcher: watcher }); } else { // console.log(dir, 'already watched') @@ -360,7 +355,7 @@ Please pick a different one using the \`-ws [host:]port\` flag from bsb.`); function outputError(error, highlight) { if (shouldColorizeError && highlight) { process.stderr.write( - error.replace(highlight, "\x1b[1;31m" + highlight + "\x1b[0m"), + error.replace(highlight, `\x1b[1;31m${highlight}\x1b[0m`), ); } else { process.stderr.write(error); @@ -379,9 +374,8 @@ Please pick a different one using the \`-ws [host:]port\` flag from bsb.`); if (reasonsToRebuild.length === 0) { dlog("No need to rebuild"); return; - } else { - dlog(`Rebuilding since ${reasonsToRebuild}`); } + dlog(`Rebuilding since ${reasonsToRebuild}`); let p; if ( (p = acquireBuild(rescriptWatchBuildArgs, { @@ -389,7 +383,7 @@ Please pick a different one using the \`-ws [host:]port\` flag from bsb.`); })) ) { logStartCompiling(); - p.on("data", function (s) { + p.on("data", s => { outputError(s, "ninja: error"); }) .once("exit", buildFinishedCallback) @@ -407,7 +401,7 @@ Please pick a different one using the \`-ws [host:]port\` flag from bsb.`); dlog( `Acquire lock failed, do the build later ${depth} : ${reasonsToRebuild}`, ); - const waitTime = Math.pow(2, depth) * 40; + const waitTime = 2 ** depth * 40; setTimeout(() => { build(Math.min(depth + 1, 5)); }, waitTime); @@ -420,9 +414,9 @@ Please pick a different one using the \`-ws [host:]port\` flag from bsb.`); * @param {string | null} reason */ function onChange(event, reason) { - var eventTime = Date.now(); - var timeDiff = eventTime - LAST_BUILD_START; - var eventDiff = eventTime - LAST_FIRED_EVENT; + const eventTime = Date.now(); + const timeDiff = eventTime - LAST_BUILD_START; + const eventDiff = eventTime - LAST_FIRED_EVENT; dlog(`Since last build: ${timeDiff} -- ${eventDiff}`); if (timeDiff < 5 || eventDiff < 5) { // for 5ms, we could think that the ninja not get @@ -482,7 +476,7 @@ Please pick a different one using the \`-ws [host:]port\` flag from bsb.`); /** * @param {Array} args */ -function build(args) { +export function build(args) { // We want to show the compile time for build // But bsb might show a help message when --help or invalid arguments are passed // We don't want to show the compile time in that case @@ -506,8 +500,3 @@ function build(args) { } delegate(["build", ...args]); } - -exports.releaseBuild = releaseBuild; -exports.info = info; -exports.clean = clean; -exports.build = build; diff --git a/cli/rescript-tools b/cli/rescript-tools deleted file mode 100755 index a4d5ae21ae..0000000000 --- a/cli/rescript-tools +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env node -//@ts-check -"use strict"; - -const path = require("path"); -const child_process = require("child_process"); - -const { absolutePath: binAbsolutePath } = require("./bin_path"); -const rewatchExe = path.join(binAbsolutePath, "rescript-tools.exe"); - -const args = process.argv.slice(2); - -child_process.spawnSync(rewatchExe, args, { stdio: "inherit" }); diff --git a/cli/rescript-tools.js b/cli/rescript-tools.js new file mode 100755 index 0000000000..a5f8e6f0eb --- /dev/null +++ b/cli/rescript-tools.js @@ -0,0 +1,11 @@ +#!/usr/bin/env node + +// @ts-check + +import * as child_process from "node:child_process"; + +import { rescript_tools_exe } from "./common/bins.js"; + +const args = process.argv.slice(2); + +child_process.spawnSync(rescript_tools_exe, args, { stdio: "inherit" }); diff --git a/cli/rescript b/cli/rescript.js similarity index 67% rename from cli/rescript rename to cli/rescript.js index 831b0c1207..83bcfef05d 100755 --- a/cli/rescript +++ b/cli/rescript.js @@ -1,26 +1,30 @@ #!/usr/bin/env node -//@ts-check -"use strict"; -/** - * This script is supposed to be running in project root directory - * It matters since we need read .sourcedirs(location) - * and its content are file/directories with regard to project root - */ +// @ts-check -var { bsc_exe, rescript_exe } = require("./bin_path.js"); -var bsb = require("./rescript_bsb.js"); +// This script is supposed to be running in project root directory +// It matters since we need read .sourcedirs(location) +// and its content are file/directories with regard to project root -var cwd = process.cwd(); +import * as tty from "node:tty"; +import packageJson from "rescript/package.json" with { type: "json" }; + +import { bsc_exe, rescript_exe } from "./common/bins.js"; +import * as bsb from "./common/bsb.js"; + +const cwd = process.cwd(); process.env.BSB_PROJECT_ROOT = cwd; if (process.env.FORCE_COLOR === undefined) { - if (require("tty").isatty(1)) { + if (tty.isatty(1)) { process.env.FORCE_COLOR = "1"; process.env.NINJA_ANSI_FORCED = "1"; } } else { - if (process.env.FORCE_COLOR === "1" && process.env.NINJA_ANSI_FORCED === undefined) { + if ( + process.env.FORCE_COLOR === "1" && + process.env.NINJA_ANSI_FORCED === undefined + ) { process.env.NINJA_ANSI_FORCED = "1"; } if (process.argv.includes("-verbose")) { @@ -76,19 +80,20 @@ try { const args = process.argv.slice(2); const argPatterns = { - help: ['help', '-h', '-help', '--help'], - version: ['version', '-v', '-version', '--version'], + help: ["help", "-h", "-help", "--help"], + version: ["version", "-v", "-version", "--version"], }; const helpArgIndex = args.findIndex(arg => argPatterns.help.includes(arg)); const firstPositionalArgIndex = args.findIndex(arg => !arg.startsWith("-")); -if (helpArgIndex !== -1 && (firstPositionalArgIndex === -1 || helpArgIndex <= firstPositionalArgIndex)) { +if ( + helpArgIndex !== -1 && + (firstPositionalArgIndex === -1 || helpArgIndex <= firstPositionalArgIndex) +) { console.log(helpMessage); - } else if (argPatterns.version.includes(args[0])) { - console.log(require("../package.json").version); - + console.log(packageJson.version); } else if (firstPositionalArgIndex !== -1) { const subcmd = args[firstPositionalArgIndex]; const subcmdArgs = args.slice(firstPositionalArgIndex + 1); @@ -107,25 +112,17 @@ if (helpArgIndex !== -1 && (firstPositionalArgIndex === -1 || helpArgIndex <= fi break; } case "format": { - require("./rescript_format.js").main( - subcmdArgs, - rescript_exe, - bsc_exe - ); + const mod = await import("./rescript/format.js"); + await mod.main(subcmdArgs, rescript_exe, bsc_exe); break; } case "dump": { - require("./rescript_dump.js").main( - subcmdArgs, - rescript_exe, - bsc_exe - ); + const mod = await import("./rescript/dump.js"); + mod.main(subcmdArgs, rescript_exe, bsc_exe); break; } default: { - console.error( - `Error: Unknown command "${subcmd}".\n${helpMessage}` - ); + console.error(`Error: Unknown command "${subcmd}".\n${helpMessage}`); process.exit(2); } } diff --git a/cli/rescript_dump.js b/cli/rescript/dump.js similarity index 69% rename from cli/rescript_dump.js rename to cli/rescript/dump.js index 0aa46d4b44..bd1201e354 100644 --- a/cli/rescript_dump.js +++ b/cli/rescript/dump.js @@ -1,22 +1,26 @@ -//@ts-check -var arg = require("./rescript_arg.js"); -var dump_usage = `Usage: rescript dump [target] +// @ts-check + +import * as child_process from "node:child_process"; +import * as path from "node:path"; + +import * as arg from "#cli/args"; + +const dump_usage = `Usage: rescript dump [target] \`rescript dump\` dumps the information for the target `; -var child_process = require("child_process"); -var path = require("path"); + /** * @type {arg.specs} */ -var specs = []; +const specs = []; /** * @param {string[]} argv * @param {string} rescript_exe * @param {string} bsc_exe */ -function main(argv, rescript_exe, bsc_exe) { - var target; +export function main(argv, rescript_exe, bsc_exe) { + let target; arg.parse_exn(dump_usage, argv, specs, xs => { if (xs.length !== 1) { arg.bad_arg(`Expect only one target, ${xs.length} found`); @@ -24,13 +28,13 @@ function main(argv, rescript_exe, bsc_exe) { target = xs[0]; }); - var { ext } = path.parse(target); + const { ext } = path.parse(target); if (ext !== ".cmi") { console.error("Only .cmi target allowed"); process.exit(2); } - var output = child_process.spawnSync(rescript_exe, ["build", "--", target], { + let output = child_process.spawnSync(rescript_exe, ["build", "--", target], { encoding: "utf-8", }); if (output.status !== 0) { @@ -47,5 +51,3 @@ function main(argv, rescript_exe, bsc_exe) { process.exit(2); } } - -exports.main = main; diff --git a/cli/rescript_format.js b/cli/rescript/format.js similarity index 76% rename from cli/rescript_format.js rename to cli/rescript/format.js index 0873b95bbb..072d340d76 100644 --- a/cli/rescript_format.js +++ b/cli/rescript/format.js @@ -1,36 +1,41 @@ -//@ts-check -var os = require("os"); -var arg = require("./rescript_arg.js"); +// @ts-check -var format_usage = `Usage: rescript format [files] +import * as child_process from "node:child_process"; +import * as crypto from "node:crypto"; +import * as fs from "node:fs"; +import * as asyncFs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { promisify } from "node:util"; + +import * as arg from "#cli/args"; + +const asyncExecFile = promisify(child_process.execFile); + +const format_usage = `Usage: rescript format [files] \`rescript format\` formats the current directory `; -var child_process = require("child_process"); -var util = require("util"); -var asyncExecFile = util.promisify(child_process.execFile); -var path = require("path"); -var fs = require("fs"); -var asyncFs = fs.promises; + /** * @type {arg.stringref} */ -var stdin = { val: undefined }; +const stdin = { val: "" }; /** * @type {arg.boolref} */ -var format = { val: undefined }; +const format = { val: false }; /** * @type {arg.boolref} */ -var check = { val: undefined }; +const check = { val: false }; /** * @type{arg.specs} */ -var specs = [ +const specs = [ [ "-stdin", { kind: "String", data: { kind: "String_set", data: stdin } }, @@ -48,8 +53,8 @@ the formatted code to stdout in ReScript syntax`, "Check formatting for file or the whole project. Use `-all` to check the whole project", ], ]; -var formattedStdExtensions = [".res", ".resi"]; -var formattedFileExtensions = [".res", ".resi"]; +const formattedStdExtensions = [".res", ".resi"]; +const formattedFileExtensions = [".res", ".resi"]; /** * @@ -59,17 +64,17 @@ function hasExtension(extensions) { /** * @param {string} x */ - var pred = x => extensions.some(ext => x.endsWith(ext)); + const pred = x => extensions.some(ext => x.endsWith(ext)); return pred; } async function readStdin() { - var stream = process.stdin; + const stream = process.stdin; const chunks = []; for await (const chunk of stream) chunks.push(chunk); return Buffer.concat(chunks).toString("utf8"); } -const numThreads = os.cpus().length; +const _numThreads = os.cpus().length; /** * Splits an array into smaller chunks of a specified size. @@ -112,7 +117,7 @@ async function formatFiles(files, bsc_exe, isSupportedFile, checkFormatting) { const { stdout } = await asyncExecFile(bsc_exe, flags); if (check.val) { const original = await asyncFs.readFile(file, "utf-8"); - if (original != stdout) { + if (original !== stdout) { console.error("[format check]", file); incorrectlyFormattedFiles++; } @@ -125,7 +130,7 @@ async function formatFiles(files, bsc_exe, isSupportedFile, checkFormatting) { process.exit(2); } if (incorrectlyFormattedFiles > 0) { - if (incorrectlyFormattedFiles == 1) { + if (incorrectlyFormattedFiles === 1) { console.error("The file listed above needs formatting"); } else { console.error( @@ -141,25 +146,25 @@ async function formatFiles(files, bsc_exe, isSupportedFile, checkFormatting) { * @param {string} rescript_exe * @param {string} bsc_exe */ -async function main(argv, rescript_exe, bsc_exe) { - var isSupportedFile = hasExtension(formattedFileExtensions); - var isSupportedStd = hasExtension(formattedStdExtensions); +export async function main(argv, rescript_exe, bsc_exe) { + const isSupportedFile = hasExtension(formattedFileExtensions); + const isSupportedStd = hasExtension(formattedStdExtensions); try { /** * @type {string[]} */ - var files = []; + let files = []; arg.parse_exn(format_usage, argv, specs, xs => { files = xs; }); - var format_project = format.val; - var use_stdin = stdin.val; + const format_project = format.val; + const use_stdin = stdin.val; // Only -check arg // Require: -all or path to a file - if (check.val && !format_project && files.length == 0) { + if (check.val && !format_project && files.length === 0) { console.error( "format check require path to a file or use `-all` to check the whole project", ); @@ -173,7 +178,7 @@ async function main(argv, rescript_exe, bsc_exe) { } // -all // TODO: check the rest arguments - var output = child_process.spawnSync( + const output = child_process.spawnSync( rescript_exe, ["info", "-list-files"], { @@ -193,17 +198,15 @@ async function main(argv, rescript_exe, bsc_exe) { process.exit(2); } if (isSupportedStd(use_stdin)) { - var crypto = require("crypto"); - var os = require("os"); - var filename = path.join( + const randomHex = crypto.randomBytes(8).toString("hex"); + const basename = path.basename(use_stdin); + const filename = path.join( os.tmpdir(), - "rescript_" + - crypto.randomBytes(8).toString("hex") + - path.parse(use_stdin).base, + `rescript_${randomHex}${basename}`, ); - (async function () { - var content = await readStdin(); - var fd = fs.openSync(filename, "wx", 0o600); // Avoid overwriting existing file + (async () => { + const content = await readStdin(); + const fd = fs.openSync(filename, "wx", 0o600); // Avoid overwriting existing file fs.writeFileSync(fd, content, "utf8"); fs.closeSync(fd); process.addListener("exit", () => fs.unlinkSync(filename)); @@ -232,8 +235,7 @@ async function main(argv, rescript_exe, bsc_exe) { files = fs.readdirSync(process.cwd()).filter(isSupportedFile); } - for (let i = 0; i < files.length; ++i) { - let file = files[i]; + for (const file of files) { if (!isSupportedStd(file)) { console.error(`Don't know what do with ${file}`); console.error(`Supported extensions: ${formattedFileExtensions}`); @@ -251,4 +253,3 @@ async function main(argv, rescript_exe, bsc_exe) { } } } -exports.main = main; diff --git a/cli/rewatch b/cli/rewatch deleted file mode 100755 index 269daac37f..0000000000 --- a/cli/rewatch +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env node -//@ts-check -"use strict"; - -const path = require("path"); -const child_process = require("child_process"); - -const { absolutePath: binAbsolutePath } = require("./bin_path"); -const rewatchExe = path.join(binAbsolutePath, "rewatch.exe"); - -const args = process.argv.slice(2); - -child_process.spawnSync(rewatchExe, args, { stdio: "inherit" }); diff --git a/cli/rewatch.js b/cli/rewatch.js new file mode 100755 index 0000000000..41377a387f --- /dev/null +++ b/cli/rewatch.js @@ -0,0 +1,10 @@ +#!/usr/bin/env node + +// @ts-check + +import * as child_process from "node:child_process"; +import { rewatch_exe } from "./common/bins.js"; + +const args = process.argv.slice(2); + +child_process.spawnSync(rewatch_exe, args, { stdio: "inherit" }); diff --git a/jsconfig.json b/jsconfig.json deleted file mode 100644 index 5ac7dffc06..0000000000 --- a/jsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "compilerOptions": { - "alwaysStrict": true, - "noImplicitAny": true, - // , "strictNullChecks": true - "target": "es2018", - // target need be set up - // otherwise some method is missing - "module": "nodenext", - // setup to understand commonjs module - - "moduleResolution": "nodenext" - } -} diff --git a/lib/bstracing b/lib/bstracing index 2a365a6052..ad45f72c11 100755 --- a/lib/bstracing +++ b/lib/bstracing @@ -1,10 +1,10 @@ #!/usr/bin/env node -"use strict"; -//@ts-check -const fs = require("fs"); -const readline = require("readline"); -const path = require("path"); +// @ts-check + +import * as fs from "node:fs"; +import * as readline from "node:readline"; +import * as path from "node:path"; /** * @@ -13,8 +13,8 @@ const path = require("path"); * @param {()=>void} finish */ function processEntry(file, lineCb, finish) { - let input = fs.createReadStream(file); - input.on("error", function (error) { + const input = fs.createReadStream(file); + input.on("error", (error) => { console.error(error.message); console.error( "make sure you are running after bsb building and in the top directory" @@ -23,7 +23,7 @@ function processEntry(file, lineCb, finish) { }); const rl = readline.createInterface({ input: input, - crlfDelay: Infinity, + crlfDelay: Number.POSITIVE_INFINITY, }); rl.on("line", lineCb); @@ -121,7 +121,7 @@ const colors = [ "cq_build_attempt_failed", ]; -let allocated = new Map(); +const allocated = new Map(); function getColorName(obj, cat) { obj.cat = cat; @@ -139,9 +139,9 @@ function getColorName(obj, cat) { * @param {Interval} target */ function category(target, obj) { - let targets = target.targets; + const targets = target.targets; if (targets.length === 1) { - let curTar = targets[0]; + const curTar = targets[0]; if (curTar.endsWith(".d")) { getColorName(obj, "dep"); } else if (curTar.endsWith(".mlast") || curTar.endsWith(".mliast")) { @@ -174,13 +174,13 @@ function readIntervals(file, showAll, outputFile) { processEntry( file, (line) => { - let lineTrim = line.trim(); + const lineTrim = line.trim(); if (lineTrim.startsWith("#")) { return; } let [start, end, _, name, cmdHash] = lineTrim.split("\t"); - cmdHash += "/" + end; + cmdHash += `/${end}`; if (+end < lastEndSeen) { // This is a guess // it could be wrong, when there's multiple small compilation @@ -199,12 +199,12 @@ function readIntervals(file, showAll, outputFile) { ).targets.push(name); }, () => { - let sorted = [...targets.values()].sort((a, b) => { + const sorted = [...targets.values()].sort((a, b) => { return a.start - b.start; }); - let jsonArray = []; - let threads = new Threads(); - for (let target of sorted) { + const jsonArray = []; + const threads = new Threads(); + for (const target of sorted) { jsonArray.push( category(target, { ph: "X", @@ -221,38 +221,38 @@ function readIntervals(file, showAll, outputFile) { } ); } -let logName = ".ninja_log"; +const logName = ".ninja_log"; /** * @type {string} */ -var file; +let file; /** * * @param ps {string[]} */ function tryLocation(ps) { - for (let p of ps) { - let log = path.join(p, logName); + for (const p of ps) { + const log = path.join(p, logName); if (fs.existsSync(log)) { file = log; return; } } console.error( - `no .ninja_log found in specified paths, make sure you set bstracing to the proper directory` + "no .ninja_log found in specified paths, make sure you set bstracing to the proper directory" ); process.exit(2); } let showAll = false; -let curDate = new Date(); +const curDate = new Date(); let outputFile = `tracing_${curDate.getHours()}_${curDate.getMinutes()}_${curDate.getSeconds()}.json`; { - let index = process.argv.indexOf(`-C`); + let index = process.argv.indexOf("-C"); if (index >= 0) { - let p = process.argv[index + 1]; + const p = process.argv[index + 1]; tryLocation([p, path.join(p, "lib", "bs")]); } else { tryLocation([".", path.join("lib", "bs")]); @@ -260,7 +260,7 @@ let outputFile = `tracing_${curDate.getHours()}_${curDate.getMinutes()}_${curDat if (process.argv.includes("-all")) { showAll = true; } - index = process.argv.indexOf(`-o`); + index = process.argv.indexOf("-o"); if (index >= 0) { outputFile = process.argv[index + 1]; } diff --git a/lib/es6/RescriptTools.js b/lib/es6/RescriptTools.js index 68a040855e..84f6ade54b 100644 --- a/lib/es6/RescriptTools.js +++ b/lib/es6/RescriptTools.js @@ -1,13 +1,9 @@ -import * as Bin_pathJs from "../../cli/bin_path.js"; - -let binaryPath = Bin_pathJs.rescript_tools_exe; let Docgen; export { Docgen, - binaryPath, } -/* binaryPath Not a pure module */ +/* No side effect */ diff --git a/lib/js/RescriptTools.js b/lib/js/RescriptTools.js index cefe75eb6f..064bdaddf4 100644 --- a/lib/js/RescriptTools.js +++ b/lib/js/RescriptTools.js @@ -1,11 +1,7 @@ 'use strict'; -let Bin_pathJs = require("../../cli/bin_path.js"); - -let binaryPath = Bin_pathJs.rescript_tools_exe; let Docgen; exports.Docgen = Docgen; -exports.binaryPath = binaryPath; -/* binaryPath Not a pure module */ +/* No side effect */ diff --git a/lib/minisocket.js b/lib/minisocket.js index 780a53e0a0..45c9ca0676 100644 --- a/lib/minisocket.js +++ b/lib/minisocket.js @@ -1,93 +1,93 @@ +import * as crypto from "node:crypto"; -var crypto = require("crypto"); -var KEY_SUFFIX = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; +const KEY_SUFFIX = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; function hashWebSocketKey(key) { - var sha1 = crypto.createHash("sha1"); - sha1.update(key + KEY_SUFFIX, "ascii"); - return sha1.digest("base64"); + const sha1 = crypto.createHash("sha1"); + sha1.update(key + KEY_SUFFIX, "ascii"); + return sha1.digest("base64"); } /** - * Limitations: the current implementation does not + * Limitations: the current implementation does not * care about what the client send: * - we don't know `ws.close` only know `socket.closed` which is later so it has a latency * - ping pong protocol */ // http://tools.ietf.org/html/rfc6455#section-5.2 -var opcodes = { - TEXT: 1, - BINARY: 2, - CLOSE: 8, - PING: 9, - PONG: 10 +const opcodes = { + TEXT: 1, + BINARY: 2, + CLOSE: 8, + PING: 9, + PONG: 10, }; /** - * - * @param {number} opcode - * @param {Buffer} payload + * + * @param {number} opcode + * @param {Buffer} payload */ function encodeMessage(opcode, payload) { - var buf; // Buffer type - var b1 = 0x80 | opcode; - // always send message as one frame (fin) + let buf; // Buffer type + const b1 = 0x80 | opcode; + // always send message as one frame (fin) - // second byte: maks and length part 1 - // followed by 0, 2, or 8 additional bytes of continued length - var b2 = 0; - // server does not mask frames - var length = payload.length; - if (length < 126) { - buf = Buffer.allocUnsafe(payload.length + 2 + 0); - // zero extra bytes - b2 |= length; - buf.writeUInt8(b1, 0); - buf.writeUInt8(b2, 1); - payload.copy(buf, 2); - } else if (length < (1 << 16)) { - buf = Buffer.allocUnsafe(payload.length + 2 + 2); - // two bytes extra - b2 |= 126; - buf.writeUInt8(b1, 0); - buf.writeUInt8(b2, 1); - // add two byte length - buf.writeUInt16BE(length, 2); - payload.copy(buf, 4); - } else { - buf = Buffer.allocUnsafe(payload.length + 2 + 8); - // eight bytes extra - b2 |= 127; - buf.writeUInt8(b1, 0); - buf.writeUInt8(b2, 1); - // add eight byte length - // note: this implementation cannot handle lengths greater than 2^32 - // the 32 bit length is prefixed with 0x0000 - buf.writeUInt32BE(0, 2); - buf.writeUInt32BE(length, 6); - payload.copy(buf, 10); - } - return buf; -}; + // second byte: maks and length part 1 + // followed by 0, 2, or 8 additional bytes of continued length + let b2 = 0; + // server does not mask frames + const length = payload.length; + if (length < 126) { + buf = Buffer.allocUnsafe(payload.length + 2 + 0); + // zero extra bytes + b2 |= length; + buf.writeUInt8(b1, 0); + buf.writeUInt8(b2, 1); + payload.copy(buf, 2); + } else if (length < 1 << 16) { + buf = Buffer.allocUnsafe(payload.length + 2 + 2); + // two bytes extra + b2 |= 126; + buf.writeUInt8(b1, 0); + buf.writeUInt8(b2, 1); + // add two byte length + buf.writeUInt16BE(length, 2); + payload.copy(buf, 4); + } else { + buf = Buffer.allocUnsafe(payload.length + 2 + 8); + // eight bytes extra + b2 |= 127; + buf.writeUInt8(b1, 0); + buf.writeUInt8(b2, 1); + // add eight byte length + // note: this implementation cannot handle lengths greater than 2^32 + // the 32 bit length is prefixed with 0x0000 + buf.writeUInt32BE(0, 2); + buf.writeUInt32BE(length, 6); + payload.copy(buf, 10); + } + return buf; +} + +const upgradeHeader = + "HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nsec-websocket-accept: "; -var upgradeHeader = 'HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nsec-websocket-accept: ' -class MiniWebSocket { - constructor(req, socket, upgradeHead) { - this.socket = socket; - this.closed = false; - var self = this; - var key = hashWebSocketKey(req.headers["sec-websocket-key"]) +export class WebSocket { + constructor(req, socket, _upgradeHead) { + this.socket = socket; + this.closed = false; + const key = hashWebSocketKey(req.headers["sec-websocket-key"]); - // http://tools.ietf.org/html/rfc6455#section-4.2.2 - socket.write( upgradeHeader + key + '\r\n\r\n'); - socket.on("close", function (hadError) { - if (!self.closed) { - self.closed = true; - } - }); - }; - sendText(obj) { - this.socket.write(encodeMessage(opcodes.TEXT,Buffer.from(obj, "utf8"))) - }; + // http://tools.ietf.org/html/rfc6455#section-4.2.2 + socket.write(`${upgradeHeader + key}\r\n\r\n`); + socket.on("close", _hadError => { + if (!this.closed) { + this.closed = true; + } + }); + } + sendText(obj) { + this.socket.write(encodeMessage(opcodes.TEXT, Buffer.from(obj, "utf8"))); + } } -exports.MiniWebSocket = MiniWebSocket \ No newline at end of file diff --git a/lib_dev/README.md b/lib_dev/README.md new file mode 100644 index 0000000000..b742ebf514 --- /dev/null +++ b/lib_dev/README.md @@ -0,0 +1,19 @@ +# Libraries for development + +This is a place for development purposes libraries. + +You can use modules here by `#dev/*` + +e.g. in `scripts` or `tests`: + +```js +import { setup } from '#dev/process'; + +const { execBuild } = setup(import.meta.url); + +// Execute ReScript in the current file location. +await execBuild({ stdio: "inherit" }); +``` + +> [!IMPORTANT] +> DO NOT USE this modules in the compiler artifacts. diff --git a/lib_dev/paths.js b/lib_dev/paths.js new file mode 100644 index 0000000000..35da5c5593 --- /dev/null +++ b/lib_dev/paths.js @@ -0,0 +1,92 @@ +// @ts-check + +import * as path from "node:path"; + +/** + * The project root path + */ +export const projectDir = path.resolve(import.meta.dirname, ".."); + +/** + * path: `/compiler/` + */ +export const compilerRootDir = path.resolve(projectDir, "compiler"); + +/** + * path: `/runtime/` + */ +export const runtimeDir = path.resolve(projectDir, "runtime"); + +/** + * path: `/lib/js/` + */ +export const runtimeCjsOutputDir = path.resolve(projectDir, "lib", "js"); + +/** + * path: `/lib/es6/` + */ +export const runtimeEsmOutputDir = path.resolve(projectDir, "lib", "es6"); + +/** + * path: `/rewatch/` + */ +export const rewatchDir = path.resolve(projectDir, "rewatch"); + +/** + * path: `/ninja/` + */ +export const ninjaDir = path.resolve(projectDir, "ninja"); + +/** + * path: `/tests/` + */ +export const testDir = path.resolve(projectDir, "tests"); + +/** + * path: `/tests/tests/` + */ +export const compilerTestDir = path.resolve(testDir, "tests"); + +/** + * path: `/tests/build_tests/` + */ +export const buildTestDir = path.resolve(testDir, "build_tests"); + +/** + * path: `/tests/docstring_tests/` + */ +export const docstringTestDir = path.resolve(testDir, "docstring_tests"); + +/** + * path: `/compiler/common/bs_version.ml` + */ +export const compilerVersionFile = path.resolve( + compilerRootDir, + "common", + "bs_version.ml", +); + +/** + * path: `/_build/install/default/bin/` + */ +export const compilerBinDir = path.resolve( + projectDir, + "_build", + "install", + "default", + "bin", +); + +/** + * path: `/_build/install/default/bin/ounit_tests` + */ +export const ounitTestBin = path.join(compilerBinDir, "ounit_tests"); + +/** + * path: `/tests/gentype_tests/typescript-react-example/` + */ +export const gentypeExampleDir = path.resolve( + testDir, + "gentype_tests", + "typescript-react-example", +); diff --git a/lib_dev/process.js b/lib_dev/process.js new file mode 100644 index 0000000000..444d28019a --- /dev/null +++ b/lib_dev/process.js @@ -0,0 +1,210 @@ +import * as child_process from "node:child_process"; +import * as path from "node:path"; +import { bsc_exe, rescript_exe } from "#cli/bins"; + +/** + * @typedef {{ + * throwOnFail?: boolean, + * } & child_process.SpawnOptions} ExecOptions + * + * @typedef {{ + * status: number, + * stdout: string, + * stderr: string, + * }} ExecResult + */ + +const signals = { + SIGINT: 2, + SIGQUIT: 3, + SIGKILL: 9, + SIGTERM: 15, +}; + +export const { + shell, + node, + yarn, + mocha, + bsc, + rescript, + execBin, + execBuild, + execClean, +} = setup(); + +/** + * @param {string} [cwd] + */ +export function setup(cwd = process.cwd()) { + /** + * @param {string} command + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + async function exec(command, args = [], options = {}) { + const { throwOnFail = options.stdio === "inherit" } = options; + + const stdoutChunks = []; + const stderrChunks = []; + + const subprocess = child_process.spawn(command, args, { + cwd, + shell: process.platform === "win32", + stdio: ["ignore", "pipe", "pipe"], + ...options, + }); + + subprocess.stdout?.on("data", chunk => { + stdoutChunks.push(chunk); + }); + + subprocess.stderr?.on("data", chunk => { + stderrChunks.push(chunk); + }); + + return await new Promise((resolve, reject) => { + subprocess.once("error", err => { + reject(err); + }); + + subprocess.once("close", (exitCode, signal) => { + const stdout = Buffer.concat(stdoutChunks).toString("utf8"); + const stderr = Buffer.concat(stderrChunks).toString("utf8"); + + let code = exitCode ?? 1; + if (signals[signal]) { + // + 128 is standard POSIX practice, see also https://nodejs.org/api/process.html#exit-codes + code = signals[signal] + 128; + } + + if (throwOnFail && code !== 0) { + reject( + new Error( + `Command ${command} exited with non-zero status: ${code}`, + ), + ); + } else { + resolve({ status: code, stdout, stderr }); + } + }); + }); + } + + return { + /** + * bash shell script + * + * @param {string} script + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + shell(script, args = [], options = {}) { + return exec("bash", [script, ...args], options); + }, + + /** + * Execute JavaScript on Node.js + * + * @param {string} script + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + node(script, args = [], options = {}) { + return exec("node", [script, ...args], options); + }, + + /** + * Execute Yarn command + * + * @param {string} command + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + yarn(command, args = [], options = {}) { + return exec("yarn", [...command.split(" "), ...args], options); + }, + + /** + * Execute Mocha CLI + * + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + mocha(args = [], options = {}) { + // `yarn mocha` works, but format output differently + // No more efforts here since we're plannig to drop Mocha + return exec("npx", ["mocha", ...args], options); + }, + + /** + * `rescript` CLI + * + * @param {( + * | "build" + * | "clean" + * | "format" + * | "dump" + * | (string & {}) + * )} command + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + rescript(command, args = [], options = {}) { + const cliPath = path.join(import.meta.dirname, "../cli/rescript.js"); + return exec("node", [cliPath, command, ...args].filter(Boolean), options); + }, + + /** + * `bsc` CLI + * + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + bsc(args = [], options = {}) { + return exec(bsc_exe, args, options); + }, + + /** + * Execute ReScript `build` command directly + * + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + execBuild(args = [], options = {}) { + return exec(rescript_exe, ["build", ...args], options); + }, + + /** + * Execute ReScript `clean` command directly + * + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + execClean(args = [], options = {}) { + return exec(rescript_exe, ["clean", ...args], options); + }, + + /** + * Execute any binary or wrapper. + * It should support Windows as well + * + * @param {string} bin + * @param {string[]} [args] + * @param {ExecOptions} [options] + * @return {Promise} + */ + execBin(bin, args = [], options = {}) { + return exec(bin, args, options); + }, + }; +} diff --git a/lib_dev/utils.js b/lib_dev/utils.js new file mode 100644 index 0000000000..642811bdf9 --- /dev/null +++ b/lib_dev/utils.js @@ -0,0 +1,6 @@ +/** + * @param {string} s + */ +export function normalizeNewlines(s) { + return s.replace(/\r\n/g, "\n"); +} diff --git a/package.json b/package.json index 6ae357785a..1c152114eb 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "rescript", "version": "12.0.0-alpha.11", "description": "ReScript toolchain", + "type": "module", "keywords": [ "ReScript", "Compiler", @@ -37,21 +38,21 @@ "node": ">=20.11.0" }, "bin": { - "bsc": "cli/bsc", - "bstracing": "lib/bstracing", - "rescript": "cli/rescript", - "rescript-tools": "cli/rescript-tools", - "rewatch": "cli/rewatch" + "bsc": "cli/bsc.js", + "bstracing": "lib/bstracing.js", + "rescript": "cli/rescript.js", + "rescript-tools": "cli/rescript-tools.js", + "rewatch": "cli/rewatch.js" }, "scripts": { "test": "node scripts/test.js -all", "test-bsb": "node scripts/test.js -bsb", "test-ocaml": "node scripts/test.js -ounit", - "format": "biome format --changed --no-errors-on-unmatched --write .", - "format:all": "biome format --write .", - "checkFormat": "biome format --changed --no-errors-on-unmatched .", - "checkFormat:all": "biome format .", - "coverage": "nyc --timeout=3000 --reporter=html mocha tests/tests/src/*_test.js && open ./coverage/index.html" + "check": "biome check --changed --no-errors-on-unmatched .", + "check:all": "biome check .", + "format": "biome check --changed --no-errors-on-unmatched . --fix", + "coverage": "nyc --timeout=3000 --reporter=html mocha tests/tests/src/*_test.js && open ./coverage/index.html", + "typecheck": "tsc" }, "files": [ "CHANGELOG.md", @@ -72,12 +73,18 @@ "./package.json": "./package.json" }, "imports": { - "#cli/bin_path": "./cli/bin_path.js" + "#cli/*": "./cli/common/*.js", + "#dev/*": "./lib_dev/*.js", + "#lib/minisocket": "./lib/minisocket.js" }, "devDependencies": { - "@biomejs/biome": "1.8.3", + "@biomejs/biome": "1.9.4", + "@types/node": "^20.14.9", + "@types/semver": "^7.5.8", "mocha": "10.8.2", - "nyc": "15.0.0" + "nyc": "15.0.0", + "semver": "7.6.2", + "typescript": "5.8.2" }, "workspaces": [ "tests/dependencies/**", diff --git a/packages/artifacts.txt b/packages/artifacts.txt index 66f14ed9f9..7be00eae08 100644 --- a/packages/artifacts.txt +++ b/packages/artifacts.txt @@ -4,15 +4,15 @@ COPYING.LESSER CREDITS.md LICENSE README.md -cli/bin_path.js -cli/bsc -cli/rescript -cli/rescript-tools -cli/rescript_arg.js -cli/rescript_bsb.js -cli/rescript_dump.js -cli/rescript_format.js -cli/rewatch +cli/bsc.js +cli/common/args.js +cli/common/bins.js +cli/common/bsb.js +cli/rescript-tools.js +cli/rescript.js +cli/rescript/dump.js +cli/rescript/format.js +cli/rewatch.js darwin/bsb_helper.exe darwin/bsc.exe darwin/ninja.exe diff --git a/packages/playground-bundling/package.json b/packages/playground-bundling/package.json index d7dbd99c89..2f7b0ca1ce 100644 --- a/packages/playground-bundling/package.json +++ b/packages/playground-bundling/package.json @@ -2,6 +2,7 @@ "name": "proj", "version": "1.0.0", "description": "", + "type": "module", "main": "index.js", "scripts": { "build": "rescript clean && rescript build && node ./scripts/generate_cmijs.js", diff --git a/packages/playground-bundling/rollup.config.cjs b/packages/playground-bundling/rollup.config.cjs deleted file mode 100644 index f4bf6db3aa..0000000000 --- a/packages/playground-bundling/rollup.config.cjs +++ /dev/null @@ -1,22 +0,0 @@ -const resolve = require("@rollup/plugin-node-resolve"); - -const { globSync } = require("glob"); -const path = require("path"); - -const RESCRIPT_COMPILER_ROOT_DIR = path.join(__dirname, "..", ".."); -const LIB_DIR = path.join(RESCRIPT_COMPILER_ROOT_DIR, "lib"); -const PLAYGROUND_DIR = path.join(RESCRIPT_COMPILER_ROOT_DIR, "playground"); -// Final target output directory where all the cmijs will be stored -const PACKAGES_DIR = path.join(PLAYGROUND_DIR, "packages"); -const outputFolder = path.join(PACKAGES_DIR, "compiler-builtins", "stdlib"); - -module.exports = globSync(`${LIB_DIR}/es6/*.js`).map((entryPoint) => { - return { - input: entryPoint, - output: { - dir: outputFolder, - format: "esm", - }, - plugins: [resolve({ browser: true })], - }; -}); diff --git a/packages/playground-bundling/rollup.config.mjs b/packages/playground-bundling/rollup.config.mjs new file mode 100644 index 0000000000..21f6260b44 --- /dev/null +++ b/packages/playground-bundling/rollup.config.mjs @@ -0,0 +1,20 @@ +import * as path from "node:path"; +import nodeResolve from "@rollup/plugin-node-resolve"; +import { glob } from "glob"; + +const RESCRIPT_COMPILER_ROOT_DIR = path.join(import.meta.dirname, "..", ".."); +const LIB_DIR = path.join(RESCRIPT_COMPILER_ROOT_DIR, "lib"); +const PLAYGROUND_DIR = path.join(RESCRIPT_COMPILER_ROOT_DIR, "playground"); +// Final target output directory where all the cmijs will be stored +const PACKAGES_DIR = path.join(PLAYGROUND_DIR, "packages"); +const outputFolder = path.join(PACKAGES_DIR, "compiler-builtins", "stdlib"); + +const entryPoint = await glob(`${LIB_DIR}/es6/*.js`); +export default { + input: entryPoint, + output: { + dir: outputFolder, + format: "esm", + }, + plugins: [nodeResolve({ browser: true })], +}; diff --git a/packages/playground-bundling/scripts/generate_cmijs.js b/packages/playground-bundling/scripts/generate_cmijs.js index 00c2f6273d..7d0df1e877 100644 --- a/packages/playground-bundling/scripts/generate_cmijs.js +++ b/packages/playground-bundling/scripts/generate_cmijs.js @@ -1,6 +1,6 @@ #!/usr/bin/env node -"use strict"; +// @ts-check /* * Requires the version matching `rescript` binary to be `npm link`ed in this @@ -15,17 +15,22 @@ * playground bundle. */ -const child_process = require("child_process"); -const fs = require("fs"); -const path = require("path"); +import * as child_process from "node:child_process"; +import * as fs from "node:fs"; +import * as path from "node:path"; -const resConfig = require("../rescript.json"); +import resConfig from "../rescript.json" with { type: "json" }; -const RESCRIPT_COMPILER_ROOT_DIR = path.join(__dirname, "..", "..", ".."); +const RESCRIPT_COMPILER_ROOT_DIR = path.join( + import.meta.dirname, + "..", + "..", + "..", +); const PLAYGROUND_DIR = path.join(RESCRIPT_COMPILER_ROOT_DIR, "playground"); // The playground-bundling root dir -const PROJECT_ROOT_DIR = path.join(__dirname, ".."); +const PROJECT_ROOT_DIR = path.join(import.meta.dirname, ".."); // Final target output directory where all the cmijs will be stored const PACKAGES_DIR = path.join(PLAYGROUND_DIR, "packages"); @@ -35,23 +40,23 @@ if (!fs.existsSync(PACKAGES_DIR)) { fs.mkdirSync(PACKAGES_DIR, { recursive: true }); } -const config = { - cwd: PROJECT_ROOT_DIR, - encoding: "utf8", - stdio: [0, 1, 2], - shell: true, -}; - +/** + * @param {string} cmd + */ function e(cmd) { console.log(`>>>>>> running command: ${cmd}`); - child_process.execSync(cmd, config); - console.log(`<<<<<<`); + child_process.execSync(cmd, { + cwd: PROJECT_ROOT_DIR, + encoding: "utf8", + stdio: [0, 1, 2], + }); + console.log("<<<<<<"); } -e(`npm install`); +e("npm install"); e(`npm link ${RESCRIPT_COMPILER_ROOT_DIR}`); -e(`npx rescript clean`); -e(`npx rescript`); +e("npx rescript clean"); +e("npx rescript"); const packages = resConfig["bs-dependencies"]; @@ -63,41 +68,41 @@ function buildCompilerCmij() { "node_modules", "rescript", "lib", - "ocaml" + "ocaml", ); const outputFolder = path.join(PACKAGES_DIR, "compiler-builtins"); - const cmijFile = path.join(outputFolder, `cmij.js`); + const cmijFile = path.join(outputFolder, "cmij.cjs"); if (!fs.existsSync(outputFolder)) { fs.mkdirSync(outputFolder, { recursive: true }); } e( - `find ${rescriptLibOcamlFolder} -name "*.cmi" -or -name "*.cmj" | xargs -n1 basename | xargs js_of_ocaml build-fs -o ${cmijFile} -I ${rescriptLibOcamlFolder}` + `find ${rescriptLibOcamlFolder} -name "*.cmi" -or -name "*.cmj" | xargs -n1 basename | xargs js_of_ocaml build-fs -o ${cmijFile} -I ${rescriptLibOcamlFolder}`, ); } function buildThirdPartyCmijs() { - packages.forEach(function installLib(pkg) { + for (const pkg of packages) { const libOcamlFolder = path.join( PROJECT_ROOT_DIR, "node_modules", pkg, "lib", - "ocaml" + "ocaml", ); const libEs6Folder = path.join( PROJECT_ROOT_DIR, "node_modules", pkg, "lib", - "es6" + "es6", ); const outputFolder = path.join(PACKAGES_DIR, pkg); - const cmijFile = path.join(outputFolder, `cmij.js`); + const cmijFile = path.join(outputFolder, "cmij.cjs"); if (!fs.existsSync(outputFolder)) { fs.mkdirSync(outputFolder, { recursive: true }); @@ -105,9 +110,9 @@ function buildThirdPartyCmijs() { e(`find ${libEs6Folder} -name '*.js' -exec cp {} ${outputFolder} \\;`); e( - `find ${libOcamlFolder} -name "*.cmi" -or -name "*.cmj" | xargs -n1 basename | xargs js_of_ocaml build-fs -o ${cmijFile} -I ${libOcamlFolder}` + `find ${libOcamlFolder} -name "*.cmi" -or -name "*.cmj" | xargs -n1 basename | xargs js_of_ocaml build-fs -o ${cmijFile} -I ${libOcamlFolder}`, ); - }); + } } function bundleStdlibJs() { diff --git a/packages/playground-bundling/tsconfig.json b/packages/playground-bundling/tsconfig.json new file mode 100644 index 0000000000..49d00ee978 --- /dev/null +++ b/packages/playground-bundling/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "resolveJsonModule": true + }, + "include": ["scripts", "rescript.json"], + "exclude": ["lib/**"] +} diff --git a/playground/playground_test.js b/playground/playground_test.cjs similarity index 65% rename from playground/playground_test.js rename to playground/playground_test.cjs index be5cc1df71..3e7a40e022 100644 --- a/playground/playground_test.js +++ b/playground/playground_test.cjs @@ -1,13 +1,13 @@ // Playground bundle is UMD module // It uses `module.exports` in current context, or fallback to `globalThis` -const { rescript_compiler } = require("./compiler.js") +const { rescript_compiler } = require("./compiler.cjs"); -require("./packages/compiler-builtins/cmij.js") -require("./packages/@rescript/react/cmij.js") +require("./packages/compiler-builtins/cmij.cjs"); +require("./packages/@rescript/react/cmij.cjs"); -let compiler = rescript_compiler.make() +const compiler = rescript_compiler.make(); -let result = compiler.rescript.compile(` +const result = compiler.rescript.compile(` @@jsxConfig({ version: 4, mode: "automatic" }) module A = { @@ -27,7 +27,7 @@ let result = compiler.rescript.compile(` } } - let sum = [1,2,3] + let sum = [1,2,3] ->Array.map(x => x * 2) ->Array.reduce(0, (acc, item) => acc + item) @@ -41,29 +41,29 @@ let result = compiler.rescript.compile(` let a = `); -if(result.js_code != "") { - console.log('-- Playground test output --'); +if (result.js_code !== "") { + console.log("-- Playground test output --"); console.log(`ReScript version: ${compiler.rescript.version}`); - console.log('----'); - if(result.type === "unexpected_error") { + console.log("----"); + if (result.type === "unexpected_error") { console.log("UNEXPECTED ERROR"); console.log(result); process.exit(1); } - if(result.errors && result.errors.length > 0) { + if (result.errors && result.errors.length > 0) { console.log("COMPILATION ERROR"); - for(let error of result.errors) { + for (const error of result.errors) { console.log(error.shortMsg); } process.exit(1); } - if(result.warnings.length === 0) { + if (result.warnings.length === 0) { console.log("TEST FAILED"); console.log("The code should have at least one warning."); process.exit(1); } console.log(result.js_code); - console.log('-- Playground test complete --'); + console.log("-- Playground test complete --"); } diff --git a/runtime/RescriptTools.res b/runtime/RescriptTools.res index 6ad891d51b..ea41dd74eb 100644 --- a/runtime/RescriptTools.res +++ b/runtime/RescriptTools.res @@ -11,5 +11,5 @@ You can use this when you're already running a JS process and want to avoid the let stringifiedJson = ChildProcess.execFileSync(RescriptTools.binaryPath, ["-v"]) ``` */ -@module("../../cli/bin_path.js") +@module("#cli/bins") external binaryPath: string = "rescript_tools_exe" diff --git a/scripts/buildNinjaBinary.js b/scripts/buildNinjaBinary.js index 92e3411be2..0bfc6f8dfe 100755 --- a/scripts/buildNinjaBinary.js +++ b/scripts/buildNinjaBinary.js @@ -1,19 +1,20 @@ #!/usr/bin/env node -const child_process = require("child_process"); -const path = require("path"); +// @ts-check + +import { execSync } from "node:child_process"; +import { ninjaDir } from "#dev/paths"; const platform = process.platform; -const ninjaDir = path.join(__dirname, "..", "ninja"); const buildCommand = "python configure.py --bootstrap --verbose"; if (platform === "win32") { // On Windows, the build uses the MSVC compiler which needs to be on the path. - child_process.execSync(buildCommand, { cwd: ninjaDir }); + execSync(buildCommand, { cwd: ninjaDir }); } else { if (process.platform === "darwin") { - process.env["CXXFLAGS"] = "-flto"; + process.env.CXXFLAGS = "-flto"; } - child_process.execSync(buildCommand, { stdio: [0, 1, 2], cwd: ninjaDir }); - child_process.execSync(`strip ninja`, { stdio: [0, 1, 2], cwd: ninjaDir }); + execSync(buildCommand, { stdio: [0, 1, 2], cwd: ninjaDir }); + execSync("strip ninja", { stdio: [0, 1, 2], cwd: ninjaDir }); } diff --git a/scripts/buildRuntime.sh b/scripts/buildRuntime.sh index 8cf8ad5e92..5d794a7321 100755 --- a/scripts/buildRuntime.sh +++ b/scripts/buildRuntime.sh @@ -2,13 +2,13 @@ set -e shopt -s extglob -(cd runtime && ../cli/rescript clean) +(cd runtime && ../cli/rescript.js clean) rm -f lib/es6/*.js lib/js/*.js lib/ocaml/* mkdir -p lib/es6 lib/js lib/ocaml mkdir -p runtime/lib/es6 runtime/lib/js -(cd runtime && ../cli/rescript build) +(cd runtime && ../cli/rescript.js build) cp runtime/lib/es6/!(Pervasives_mini).js lib/es6 cp runtime/lib/js/!(Pervasives_mini).js lib/js diff --git a/scripts/copyExes.js b/scripts/copyExes.js index b9ebe91cc3..e7c443fd19 100755 --- a/scripts/copyExes.js +++ b/scripts/copyExes.js @@ -1,23 +1,25 @@ #!/usr/bin/env node -// Copy exes built by dune to platform bin dir -const path = require("path"); -const fs = require("fs"); -const child_process = require("child_process"); -const { duneBinDir } = require("./dune"); -const { absolutePath: platformBinDir } = require("#cli/bin_path"); +// @ts-check + +// Copy exes built by dune to platform bin dir -const ninjaDir = path.join(__dirname, "..", "ninja"); -const rewatchDir = path.join(__dirname, "..", "rewatch"); +import * as child_process from "node:child_process"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import { platformDir } from "#cli/bins"; +import { compilerBinDir, ninjaDir, rewatchDir } from "#dev/paths"; -if (!fs.existsSync(platformBinDir)) { - fs.mkdirSync(platformBinDir); -} +fs.mkdirSync(platformDir, { recursive: true }); +/** + * @param {string} dir + * @param {string} exe + */ function copyExe(dir, exe) { const ext = process.platform === "win32" ? ".exe" : ""; const src = path.join(dir, exe + ext); - const dest = path.join(platformBinDir, exe + ".exe"); + const dest = path.join(platformDir, `${exe}.exe`); // For some reason, the copy operation fails in Windows CI if the file already exists. if (process.platform === "win32" && fs.existsSync(dest)) { @@ -41,11 +43,11 @@ function copyExe(dir, exe) { } if (process.argv.includes("-all") || process.argv.includes("-compiler")) { - copyExe(duneBinDir, "rescript"); - copyExe(duneBinDir, "rescript-editor-analysis"); - copyExe(duneBinDir, "rescript-tools"); - copyExe(duneBinDir, "bsc"); - copyExe(duneBinDir, "bsb_helper"); + copyExe(compilerBinDir, "rescript"); + copyExe(compilerBinDir, "rescript-editor-analysis"); + copyExe(compilerBinDir, "rescript-tools"); + copyExe(compilerBinDir, "bsc"); + copyExe(compilerBinDir, "bsb_helper"); } if (process.argv.includes("-all") || process.argv.includes("-ninja")) { diff --git a/scripts/cppo.js b/scripts/cppo.js index 2394e01538..6bd9b43144 100644 --- a/scripts/cppo.js +++ b/scripts/cppo.js @@ -1,8 +1,8 @@ // @ts-check -const { execFileSync } = require("child_process"); +import { execFileSync } from "node:child_process"; -[ +const targets = [ ["belt_HashSetString.res", "hashset.res.cppo", "TYPE_STRING"], ["belt_HashSetString.resi", "hashset.resi.cppo", "TYPE_STRING"], ["belt_HashSetInt.res", "hashset.res.cppo", "TYPE_INT"], @@ -35,10 +35,12 @@ const { execFileSync } = require("child_process"); ["belt_internalMapInt.res", "internal_map.res.cppo", "TYPE_INT"], ["belt_internalSetString.res", "internal_set.res.cppo", "TYPE_STRING"], ["belt_internalSetInt.res", "internal_set.res.cppo", "TYPE_INT"], -].forEach(([output, input, type]) => { +]; + +for (const [output, input, type] of targets) { execFileSync( "cppo", ["-n", "-D", type, `runtime/cppo/${input}`, "-o", `runtime/${output}`], { stdio: "inherit" }, ); -}); +} diff --git a/scripts/dune.js b/scripts/dune.js deleted file mode 100644 index dd22149381..0000000000 --- a/scripts/dune.js +++ /dev/null @@ -1,12 +0,0 @@ -var path = require("path"); - -var duneBinDir = path.join( - __dirname, - "..", - "_build", - "install", - "default", - "bin", -); - -exports.duneBinDir = duneBinDir; diff --git a/scripts/format.sh b/scripts/format.sh index 11c1fa299a..b9b8f0fed7 100755 --- a/scripts/format.sh +++ b/scripts/format.sh @@ -5,6 +5,6 @@ shopt -s extglob dune build @fmt --auto-promote files=$(find runtime tests -type f \( -name "*.res" -o -name "*.resi" \) ! -name "syntaxErrors*" ! -name "generated_mocha_test.res" ! -path "tests/syntax_*" ! -path "tests/analysis_tests/tests*" ! -path "*/node_modules/*") -./cli/rescript format $files +./cli/rescript.js format $files yarn format diff --git a/scripts/format_check.sh b/scripts/format_check.sh index 9489a75008..656f86a732 100755 --- a/scripts/format_check.sh +++ b/scripts/format_check.sh @@ -18,7 +18,7 @@ case "$(uname -s)" in echo "Checking ReScript code formatting..." files=$(find runtime tests -type f \( -name "*.res" -o -name "*.resi" \) ! -name "syntaxErrors*" ! -name "generated_mocha_test.res" ! -path "tests/syntax_*" ! -path "tests/analysis_tests/tests*" ! -path "*/node_modules/*") - if ./cli/rescript format -check $files; then + if ./cli/rescript.js format -check $files; then printf "${successGreen}✅ ReScript code formatting ok.${reset}\n" else printf "${warningYellow}⚠️ ReScript code formatting issues found.${reset}\n" @@ -31,4 +31,4 @@ case "$(uname -s)" in esac echo "Biome format check" -yarn checkFormat +yarn check diff --git a/scripts/npmPack.js b/scripts/npmPack.js index 656c0c6514..967803c827 100755 --- a/scripts/npmPack.js +++ b/scripts/npmPack.js @@ -1,4 +1,5 @@ #!/usr/bin/env node + // @ts-check // TODO: Use `yarn pack --json` instead. @@ -28,21 +29,21 @@ * @typedef {[PackOutputEntry]} PackOutput */ -const { spawnSync, execSync } = require("child_process"); -const path = require("path"); -const fs = require("fs"); +import { execSync, spawnSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { projectDir } from "#dev/paths"; const mode = process.argv.includes("-updateArtifactList") ? "updateArtifactList" : "package"; -const rootPath = path.join(__dirname, ".."); -const fileListPath = path.join(rootPath, "packages", "artifacts.txt"); +const fileListPath = path.join(projectDir, "packages", "artifacts.txt"); const output = spawnSync( - "npm pack --json" + (mode === "updateArtifactList" ? " --dry-run" : ""), + `npm pack --json${mode === "updateArtifactList" ? " --dry-run" : ""}`, { - cwd: rootPath, + cwd: projectDir, encoding: "utf8", shell: true, }, @@ -77,8 +78,8 @@ function getFilesAddedByCI() { const files = ["ninja.COPYING"]; - for (let platform of platforms) { - for (let exe of exes) { + for (const platform of platforms) { + for (const exe of exes) { files.push(`${platform}/${exe}`); } } diff --git a/scripts/prebuilt.js b/scripts/prebuilt.js index 3d5b80cc48..6f3f2c43fd 100755 --- a/scripts/prebuilt.js +++ b/scripts/prebuilt.js @@ -1,37 +1,38 @@ #!/usr/bin/env node -//@ts-check -const path = require("path"); -const fs = require("fs"); -const assert = require("assert"); +// @ts-check -const package_config = require(path.join(__dirname, "..", "package.json")); -const bsVersion = fs.readFileSync( - path.join(__dirname, "..", "compiler", "common", "bs_version.ml"), - "utf-8", -); +import assert from "node:assert"; +import fs from "node:fs"; +import packageJson from "rescript/package.json" with { type: "json" }; +import semver from "semver"; +import { compilerVersionFile } from "#dev/paths"; /** - * @param {string} bsVersion - * @param {string} version + * @param {semver.SemVer} bsVersion + * @param {semver.SemVer} version */ function verifyVersion(bsVersion, version) { - try { - let [major, minor] = bsVersion - .split("\n") - .find(x => x.startsWith("let version = ")) - .split("=")[1] - .trim() - .slice(1, -1) - .split("."); - let [specifiedMajor, specifiedMinor] = version.split("."); - console.log( - `Version check: package.json: ${specifiedMajor}.${specifiedMinor} vs ABI: ${major}.${minor}`, - ); - return major === specifiedMajor && minor === specifiedMinor; - } catch (e) { - return false; - } + const { major, minor } = bsVersion; + const { major: specifiedMajor, minor: specifiedMinor } = version; + console.log( + `Version check: package.json: ${specifiedMajor}.${specifiedMinor} vs ABI: ${major}.${minor}`, + ); + return major === specifiedMajor && minor === specifiedMinor; } -assert(verifyVersion(bsVersion, package_config.version)); +const bsVersionPattern = /let version = "(?.*)"/m; +const bsVersionFileContent = fs.readFileSync(compilerVersionFile, "utf-8"); +const bsVersionMatch = bsVersionFileContent.match(bsVersionPattern)?.groups; +assert.ok(bsVersionMatch, "Failed to parse the compiler version file"); + +const bsVersion = semver.parse(bsVersionMatch.version); +assert.ok(bsVersion, "Failed to parse the compiler version file"); + +const packageVersion = semver.parse(packageJson.version); +assert.ok(packageVersion, "Failed to parse the version of the package.json"); + +assert.ok( + verifyVersion(bsVersion, packageVersion), + `Bump the compiler version in ${compilerVersionFile}`, +); diff --git a/scripts/setVersion.js b/scripts/setVersion.js index d82e25425f..24d39f7ccd 100644 --- a/scripts/setVersion.js +++ b/scripts/setVersion.js @@ -1,11 +1,11 @@ -//@ts-check -/** - * This file is used only in dev time, feel free to use es6 - */ -const fs = require("fs"); +#!/usr/bin/env node -const packageSpec = JSON.parse(fs.readFileSync("./package.json", "utf8")); -const { version, name } = packageSpec; +// @ts-check + +import fs from "node:fs"; +import packageSpec from "rescript/package.json" with { type: "json" }; + +const { name, version } = packageSpec; const stdlibPackageSpec = JSON.parse( fs.readFileSync("./packages/std/package.json", "utf8"), diff --git a/scripts/test.js b/scripts/test.js index 010103b42e..1a975f1ef8 100644 --- a/scripts/test.js +++ b/scripts/test.js @@ -1,13 +1,25 @@ -//@ts-check -const cp = require("child_process"); -const path = require("path"); -const fs = require("fs"); -const os = require("os"); -const { rescript_exe } = require("#cli/bin_path"); - -const duneBinDir = require("./dune").duneBinDir; - -const { exec } = require("../tests/build_tests/utils.js"); +// @ts-check + +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { + buildTestDir, + compilerTestDir, + docstringTestDir, + ounitTestBin, + projectDir, +} from "#dev/paths"; + +import { + execBin, + execBuild, + execClean, + mocha, + node, + rescript, + shell, +} from "#dev/process"; let ounitTest = false; let mochaTest = false; @@ -43,144 +55,136 @@ if (process.argv.includes("-all")) { runtimeDocstrings = true; } -async function runTests() { - if (formatTest) { - cp.execSync("bash scripts/format_check.sh", { - cwd: path.join(__dirname, ".."), - stdio: [0, 1, 2], +if (formatTest) { + await shell("./scripts/format_check.sh", [], { + cwd: projectDir, + stdio: "inherit", + }); +} + +if (ounitTest) { + if (process.platform === "win32") { + console.log("Skipping OUnit tests on Windows"); + } else { + await execBin(ounitTestBin, [], { + stdio: "inherit", }); } +} + +if (mochaTest) { + await execClean([], { + cwd: compilerTestDir, + stdio: "inherit", + }); + + await execBuild([], { + cwd: compilerTestDir, + stdio: "inherit", + }); + + await mocha(["-t", "10000", "tests/tests/**/*_test.mjs"], { + cwd: projectDir, + stdio: "inherit", + }); + + await node("tests/tests/src/core/Core_TestSuite.mjs", [], { + cwd: projectDir, + stdio: "inherit", + }); + + await node("tests/tests/src/core/Core_TempTests.mjs", [], { + cwd: projectDir, + stdio: "inherit", + }); +} + +if (bsbTest) { + console.log("Doing build_tests"); + const files = fs.readdirSync(buildTestDir); + + let hasError = false; - if (ounitTest) { - if (process.platform === "win32") { - console.log("Skipping OUnit tests on Windows"); + for (const file of files) { + const testDir = path.join(buildTestDir, file); + if (file === "node_modules" || !fs.lstatSync(testDir).isDirectory()) { + continue; + } + if (!fs.existsSync(path.join(testDir, "input.js"))) { + console.warn(`input.js does not exist in ${testDir}`); } else { - cp.execSync(path.join(duneBinDir, "ounit_tests"), { - stdio: [0, 1, 2], - }); + console.log(`testing ${file}`); + + // note existsSync test already ensure that it is a directory + const out = await node("input.js", [], { cwd: testDir }); + console.log(out.stdout); + + if (out.status === 0) { + console.log("✅ success in", file); + } else { + console.log(`❌ error in ${file} with stderr:\n`, out.stderr); + hasError = true; + } } } - if (mochaTest) { - cp.execSync(`${rescript_exe} clean`, { - cwd: path.join(__dirname, "..", "tests/tests"), - stdio: [0, 1, 2], - }); + if (hasError) { + process.exit(1); + } +} - cp.execSync(`${rescript_exe} build`, { - cwd: path.join(__dirname, "..", "tests/tests"), - stdio: [0, 1, 2], - }); +if (runtimeDocstrings) { + if (process.platform === "win32") { + console.log(`Skipping docstrings tests on ${process.platform}`); + } else if (process.platform === "darwin" && os.release().startsWith("22")) { + // Workaround for intermittent hangs in CI + console.log("Skipping docstrings tests on macOS 13"); + } else { + console.log("Running runtime docstrings tests"); + + const generated_mocha_test_res = path.join( + "tests", + "docstring_tests", + "generated_mocha_test.res", + ); + + // Remove `generated_mocha_test.res` if file exists + if (fs.existsSync(generated_mocha_test_res)) { + console.log(`Removing ${generated_mocha_test_res}`); + fs.unlinkSync(generated_mocha_test_res); + } - cp.execSync("npx mocha -t 10000 tests/tests/**/*_test.mjs", { - cwd: path.join(__dirname, ".."), - stdio: [0, 1, 2], + await execBuild([], { + cwd: docstringTestDir, + stdio: "inherit", }); - cp.execSync("node tests/tests/src/core/Core_TestSuite.mjs", { - cwd: path.join(__dirname, ".."), - stdio: [0, 1, 2], + // Generate rescript file with all tests `generated_mocha_test.res` + await node(path.join(docstringTestDir, "DocTest.res.js"), [], { + cwd: projectDir, + stdio: "inherit", }); - cp.execSync("node tests/tests/src/core/Core_TempTests.mjs", { - cwd: path.join(__dirname, ".."), - stdio: [0, 1, 2], + // Build again to check if generated_mocha_test.res has syntax or type erros + await execBuild([], { + cwd: docstringTestDir, + stdio: "inherit", }); - } - - if (bsbTest) { - console.log("Doing build_tests"); - const buildTestDir = path.join(__dirname, "..", "tests", "build_tests"); - const files = fs.readdirSync(buildTestDir); - - let hasError = false; - - for (const file of files) { - const testDir = path.join(buildTestDir, file); - if (file === "node_modules" || !fs.lstatSync(testDir).isDirectory()) { - continue; - } - if (!fs.existsSync(path.join(testDir, "input.js"))) { - console.warn(`input.js does not exist in ${testDir}`); - } else { - console.log(`testing ${file}`); - - // note existsSync test already ensure that it is a directory - const out = await exec(`node`, ["input.js"], { cwd: testDir }); - console.log(out.stdout); - - if (out.status === 0) { - console.log("✅ success in", file); - } else { - console.log(`❌ error in ${file} with stderr:\n`, out.stderr); - hasError = true; - } - } - } - if (hasError) { - process.exit(1); - } - } - - if (runtimeDocstrings) { - if (process.platform === "win32") { - console.log(`Skipping docstrings tests on ${process.platform}`); - } else if (process.platform === "darwin" && os.release().startsWith("22")) { - // Workaround for intermittent hangs in CI - console.log("Skipping docstrings tests on macOS 13") - } else { - console.log("Running runtime docstrings tests"); - - const generated_mocha_test_res = path.join( - "tests", - "docstring_tests", - "generated_mocha_test.res", - ); - - // Remove `generated_mocha_test.res` if file exists - if (fs.existsSync(generated_mocha_test_res)) { - console.log(`Removing ${generated_mocha_test_res}`); - fs.unlinkSync(generated_mocha_test_res); - } + // Format generated_mocha_test.res + console.log("Formatting generated_mocha_test.res"); + await rescript("format", [generated_mocha_test_res], { + cwd: projectDir, + stdio: "inherit", + }); - cp.execSync(`${rescript_exe} build`, { - cwd: path.join(__dirname, "..", "tests/docstring_tests"), - stdio: [0, 1, 2], - }); - - // Generate rescript file with all tests `generated_mocha_test.res` - cp.execSync( - `node ${path.join("tests", "docstring_tests", "DocTest.res.mjs")}`, - { - cwd: path.join(__dirname, ".."), - stdio: [0, 1, 2], - }, - ); - - // Build again to check if generated_mocha_test.res has syntax or type erros - cp.execSync(`${rescript_exe} build`, { - cwd: path.join(__dirname, "..", "tests/docstring_tests"), - stdio: [0, 1, 2], - }); - - // Format generated_mocha_test.res - console.log("Formatting generated_mocha_test.res"); - cp.execSync(`./cli/rescript format ${generated_mocha_test_res}`, { - cwd: path.join(__dirname, ".."), - stdio: [0, 1, 2], - }); - - console.log("Run mocha test"); - cp.execSync( - `npx mocha ${path.join("tests", "docstring_tests", "generated_mocha_test.res.mjs")}`, - { - cwd: path.join(__dirname, ".."), - stdio: [0, 1, 2], - }, - ); - } + console.log("Run mocha test"); + await mocha( + [path.join("tests", "docstring_tests", "generated_mocha_test.res.js")], + { + cwd: projectDir, + stdio: "inherit", + }, + ); } } - -runTests(); diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/.watchmanconfig b/tests/analysis_tests/tests-reanalyze/deadcode/.watchmanconfig deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/analysis_tests/tests-reanalyze/termination/.watchmanconfig b/tests/analysis_tests/tests-reanalyze/termination/.watchmanconfig deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/build_tests/build_warn_as_error/input.js b/tests/build_tests/build_warn_as_error/input.js index 01e4c30179..17a0bdd42b 100644 --- a/tests/build_tests/build_warn_as_error/input.js +++ b/tests/build_tests/build_warn_as_error/input.js @@ -1,31 +1,26 @@ -var p = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; -var o1 = p.spawnSync(rescript_exe, ["build"], { - encoding: "utf8", - cwd: __dirname, -}); +const { execBuild, execClean } = setup(import.meta.dirname); -var first_message = o1.stdout +const o1 = await execBuild(); + +const first_message = o1.stdout .split("\n") .map(s => s.trim()) - .find(s => s == "Warning number 110"); + .find(s => s === "Warning number 110"); if (!first_message) { assert.fail(o1.stdout); } // Second build using -warn-error +110 -var o2 = p.spawnSync(rescript_exe, ["build", "-warn-error", "+110"], { - encoding: "utf8", - cwd: __dirname, -}); +const o2 = await execBuild(["-warn-error", "+110"]); -var second_message = o2.stdout +const second_message = o2.stdout .split("\n") .map(s => s.trim()) - .find(s => s == "Warning number 110 (configured as error)"); + .find(s => s === "Warning number 110 (configured as error)"); if (!second_message) { assert.fail(o2.stdout); @@ -33,21 +28,15 @@ if (!second_message) { // Third build, without -warn-error +110 // The result should not be a warning as error -var o3 = p.spawnSync(rescript_exe, ["build"], { - encoding: "utf8", - cwd: __dirname, -}); +const o3 = await execBuild(); -var third_message = o3.stdout +const third_message = o3.stdout .split("\n") .map(s => s.trim()) - .find(s => s == "Dependency Finished"); + .find(s => s === "Dependency Finished"); if (!third_message) { assert.fail(o3.stdout); } -var cleanup = p.spawnSync(rescript_exe, ["clean"], { - encoding: "utf8", - cwd: __dirname, -}); +await execClean(); diff --git a/tests/build_tests/case/input.js b/tests/build_tests/case/input.js index b3cbcc4d85..f91b89964c 100644 --- a/tests/build_tests/case/input.js +++ b/tests/build_tests/case/input.js @@ -1,18 +1,19 @@ -var p = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); -var { normalizeNewlines } = require("../utils.js"); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; +import { normalizeNewlines } from "#dev/utils"; -var o = p.spawnSync(rescript_exe, { encoding: "utf8", cwd: __dirname }); +const { execBuild } = setup(import.meta.dirname); + +const { stderr } = await execBuild(); if ( ![ - `Error: Invalid bsconfig.json implementation and interface have different path names or different cases src/demo vs src/Demo\n`, + "Error: Invalid bsconfig.json implementation and interface have different path names or different cases src/demo vs src/Demo\n", // Windows: path separator - `Error: Invalid bsconfig.json implementation and interface have different path names or different cases src\\demo vs src\\Demo\n`, + "Error: Invalid bsconfig.json implementation and interface have different path names or different cases src\\demo vs src\\Demo\n", // Linux: files are parsed in different order - `Error: Invalid bsconfig.json implementation and interface have different path names or different cases src/Demo vs src/demo\n`, - ].includes(normalizeNewlines(o.stderr)) + "Error: Invalid bsconfig.json implementation and interface have different path names or different cases src/Demo vs src/demo\n", + ].includes(normalizeNewlines(stderr)) ) { - assert.fail(o.stderr); + assert.fail(stderr); } diff --git a/tests/build_tests/case2/input.js b/tests/build_tests/case2/input.js index 421017507e..2b5299779f 100644 --- a/tests/build_tests/case2/input.js +++ b/tests/build_tests/case2/input.js @@ -1,18 +1,21 @@ -var p = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); -var { normalizeNewlines } = require("../utils.js"); +// @ts-check -var o = p.spawnSync(rescript_exe, { encoding: "utf8", cwd: __dirname }); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; +import { normalizeNewlines } from "#dev/utils"; + +const { execBuild } = setup(import.meta.dirname); + +const { stderr } = await execBuild(); if ( ![ - `Error: Invalid bsconfig.json implementation and interface have different path names or different cases src/X vs src/x\n`, + "Error: Invalid bsconfig.json implementation and interface have different path names or different cases src/X vs src/x\n", // Windows: path separator - `Error: Invalid bsconfig.json implementation and interface have different path names or different cases src\\X vs src\\x\n`, + "Error: Invalid bsconfig.json implementation and interface have different path names or different cases src\\X vs src\\x\n", // Linux: files are parsed in different order - `Error: Invalid bsconfig.json implementation and interface have different path names or different cases src/x vs src/X\n`, - ].includes(normalizeNewlines(o.stderr)) + "Error: Invalid bsconfig.json implementation and interface have different path names or different cases src/x vs src/X\n", + ].includes(normalizeNewlines(stderr)) ) { - assert.fail(o.stderr); + assert.fail(stderr); } diff --git a/tests/build_tests/case3/input.js b/tests/build_tests/case3/input.js index c33330667b..45d78e684a 100644 --- a/tests/build_tests/case3/input.js +++ b/tests/build_tests/case3/input.js @@ -1,14 +1,13 @@ -//@ts-check - -var p = require("child_process"); -var fs = require("fs"); -var path = require("path"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); -p.spawnSync(`${rescript_exe} clean && ${rescript_exe} build`, { - encoding: "utf8", - cwd: __dirname, -}); - -var o = fs.readFileSync(path.join(__dirname, "src", "hello.bs.js"), "ascii"); +// @ts-check + +import assert from "node:assert"; +import fs from "node:fs/promises"; +import path from "node:path"; +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +await execBuild(); + +const o = await fs.readFile(path.join("src", "hello.res.js"), "ascii"); assert.ok(/HelloGen\.f/.test(o)); diff --git a/tests/build_tests/case3/rescript.json b/tests/build_tests/case3/rescript.json index 267c827078..a543e5788c 100644 --- a/tests/build_tests/case3/rescript.json +++ b/tests/build_tests/case3/rescript.json @@ -6,10 +6,10 @@ "subdirs": true }, "package-specs": { - "module": "commonjs", + "module": "esmodule", "in-source": true }, - "suffix": ".bs.js", + "suffix": ".res.js", "bs-dependencies": [], "warnings": { "error": "+101" } } diff --git a/tests/build_tests/case3/src/B01.bs.js b/tests/build_tests/case3/src/B01.res.js similarity index 100% rename from tests/build_tests/case3/src/B01.bs.js rename to tests/build_tests/case3/src/B01.res.js diff --git a/tests/build_tests/case3/src/B02.bs.js b/tests/build_tests/case3/src/B02.res.js similarity index 100% rename from tests/build_tests/case3/src/B02.bs.js rename to tests/build_tests/case3/src/B02.res.js diff --git a/tests/build_tests/case3/src/B03.bs.js b/tests/build_tests/case3/src/B03.res.js similarity index 100% rename from tests/build_tests/case3/src/B03.bs.js rename to tests/build_tests/case3/src/B03.res.js diff --git a/tests/build_tests/case3/src/B04.bs.js b/tests/build_tests/case3/src/B04.res.js similarity index 100% rename from tests/build_tests/case3/src/B04.bs.js rename to tests/build_tests/case3/src/B04.res.js diff --git a/tests/build_tests/case3/src/B05.bs.js b/tests/build_tests/case3/src/B05.res.js similarity index 100% rename from tests/build_tests/case3/src/B05.bs.js rename to tests/build_tests/case3/src/B05.res.js diff --git a/tests/build_tests/case3/src/a01.bs.js b/tests/build_tests/case3/src/a01.res.js similarity index 100% rename from tests/build_tests/case3/src/a01.bs.js rename to tests/build_tests/case3/src/a01.res.js diff --git a/tests/build_tests/case3/src/a02.bs.js b/tests/build_tests/case3/src/a02.res.js similarity index 100% rename from tests/build_tests/case3/src/a02.bs.js rename to tests/build_tests/case3/src/a02.res.js diff --git a/tests/build_tests/case3/src/a03.bs.js b/tests/build_tests/case3/src/a03.res.js similarity index 100% rename from tests/build_tests/case3/src/a03.bs.js rename to tests/build_tests/case3/src/a03.res.js diff --git a/tests/build_tests/case3/src/a04.bs.js b/tests/build_tests/case3/src/a04.res.js similarity index 100% rename from tests/build_tests/case3/src/a04.bs.js rename to tests/build_tests/case3/src/a04.res.js diff --git a/tests/build_tests/case3/src/a05.bs.js b/tests/build_tests/case3/src/a05.res.js similarity index 100% rename from tests/build_tests/case3/src/a05.bs.js rename to tests/build_tests/case3/src/a05.res.js diff --git a/tests/build_tests/case3/src/hello.bs.js b/tests/build_tests/case3/src/hello.res.js similarity index 66% rename from tests/build_tests/case3/src/hello.bs.js rename to tests/build_tests/case3/src/hello.res.js index 08c02c69b7..2e8c61cbdd 100644 --- a/tests/build_tests/case3/src/hello.bs.js +++ b/tests/build_tests/case3/src/hello.res.js @@ -1,11 +1,12 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; -var HelloGen = require("./hello.gen"); +import * as HelloGen from "./hello.gen"; function f(prim) { return HelloGen.f(prim); } -exports.f = f; +export { + f, +} /* ./hello.gen Not a pure module */ diff --git a/tests/build_tests/cli_compile_status/input.js b/tests/build_tests/cli_compile_status/input.js index e41e57b39a..c26e567862 100755 --- a/tests/build_tests/cli_compile_status/input.js +++ b/tests/build_tests/cli_compile_status/input.js @@ -1,44 +1,33 @@ // @ts-check -const assert = require("assert"); -const path = require("path"); -const child_process = require("child_process"); -const { normalizeNewlines } = require("../utils.js"); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; +import { normalizeNewlines } from "#dev/utils"; -const rescriptPath = path.join(__dirname, "..", "..", "..", "cli", "rescript") +const { rescript } = setup(import.meta.dirname); // Shows compile time for `rescript build` command -let out = child_process.spawnSync("node", [rescriptPath, "build"], { - encoding: "utf8", - cwd: __dirname, -}); +let out = await rescript("build"); assert.match( normalizeNewlines(out.stdout), - new RegExp(`>>>> Start compiling -Dependency Finished ->>>> Finish compiling \\d+ mseconds`), + />>>> Start compiling\nDependency Finished\n>>>> Finish compiling \d+ mseconds/, ); // Shows compile time for `rescript` command -out = child_process.spawnSync("node", [rescriptPath], { - encoding: "utf8", - cwd: __dirname, -}); +out = await rescript("build"); assert.match( normalizeNewlines(out.stdout), - new RegExp(`>>>> Start compiling -Dependency Finished ->>>> Finish compiling \\d+ mseconds`), + />>>> Start compiling\nDependency Finished\n>>>> Finish compiling \d+ mseconds/, ); // Doesn't show compile time for `rescript build -verbose` command // Because we can't be sure that -verbose is a valid argument // And bsb won't fail with a usage message. // It works this way not only for -verbose, but any other arg, including -h/--help/-help -out = child_process.spawnSync("node", [rescriptPath, "build", "-verbose"], { - encoding: "utf8", - cwd: __dirname, -}); +out = await rescript("build", ["-verbose"]); -assert.match(normalizeNewlines(out.stdout), /Package stack: test \nDependency Finished\n/); +assert.match( + normalizeNewlines(out.stdout), + /Package stack: test {2}\nDependency Finished\n/, +); assert.match(normalizeNewlines(out.stdout), /ninja.exe"? -C lib[\\/]bs ?\n/); diff --git a/tests/build_tests/cli_help/input.js b/tests/build_tests/cli_help/input.js index 326f1b4f99..facfbecf2b 100755 --- a/tests/build_tests/cli_help/input.js +++ b/tests/build_tests/cli_help/input.js @@ -1,10 +1,10 @@ // @ts-check -const assert = require("assert"); -const path = require("path"); -const { exec, normalizeNewlines } = require("../utils.js"); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; +import { normalizeNewlines } from "#dev/utils"; -const rescriptPath = path.join(__dirname, "..", "..", "..", "cli", "rescript") +const { rescript } = setup(import.meta.dirname); const cliHelp = "Usage: rescript \n" + @@ -68,84 +68,102 @@ const dumpHelp = * @param {string[]} params * @param {{ stdout: string; stderr: string; status: number; }} expected */ -async function runTest(params, expected) { - const out = await exec("node", [rescriptPath, ...params], { - cwd: __dirname, - }); +async function test(params, expected) { + const out = await rescript("", params); assert.equal(normalizeNewlines(out.stdout), expected.stdout); assert.equal(normalizeNewlines(out.stderr), expected.stderr); assert.equal(out.status, expected.status); } - -async function test() { - // Shows build help with --help arg - await runTest(["build", "--help"], { stdout: buildHelp, stderr: "", status: 0 }); - await runTest(["build", "-w", "--help"], { stdout: buildHelp, stderr: "", status: 0 }); - - await runTest(["-w", "--help"], { stdout: cliHelp, stderr: "", status: 0 }); - - // Shows cli help with --help arg even if there are invalid arguments after it - await runTest(["--help", "-w"], { stdout: cliHelp, stderr: "", status: 0 }); - - // Shows build help with -h arg - await runTest(["build", "-h"], { stdout: buildHelp, stderr: "", status: 0 }); - - // Exits with build help with unknown arg - await runTest(["build", "-foo"], { - stdout: "", - stderr: 'Error: Unknown option "-foo".\n' + buildHelp, - status: 2, - }); - - // Shows cli help with --help arg - await runTest(["--help"], { stdout: cliHelp, stderr: "", status: 0 }); - - // Shows cli help with -h arg - await runTest(["-h"], { stdout: cliHelp, stderr: "", status: 0 }); - - // Shows cli help with -h arg - await runTest(["help"], { stdout: cliHelp, stderr: "", status: 0 }); - - // Exits with cli help with unknown command - await runTest(["built"], { - stdout: "", - stderr: `Error: Unknown command "built".\n` + cliHelp, - status: 2, - }); - - // Exits with build help with unknown args - await runTest(["-foo"], { - stdout: "", - stderr: 'Error: Unknown option "-foo".\n' + buildHelp, - status: 2, - }); - - // Shows clean help with --help arg - await runTest(["clean", "--help"], { stdout: cleanHelp, stderr: "", status: 0 }); - - // Shows clean help with -h arg - await runTest(["clean", "-h"], { stdout: cleanHelp, stderr: "", status: 0 }); - - // Exits with clean help with unknown arg - await runTest(["clean", "-foo"], { - stdout: "", - stderr: 'Error: Unknown option "-foo".\n' + cleanHelp, - status: 2, - }); - - // Shows format help with --help arg - await runTest(["format", "--help"], { stdout: formatHelp, stderr: "", status: 0 }); - - // Shows format help with -h arg - await runTest(["format", "-h"], { stdout: formatHelp, stderr: "", status: 0 }); - - // Shows dump help with --help arg - await runTest(["dump", "--help"], { stdout: dumpHelp, stderr: "", status: 0 }); - - // Shows dump help with -h arg - await runTest(["dump", "-h"], { stdout: dumpHelp, stderr: "", status: 0 }); -} - -void test(); +// Shows build help with --help arg +await test(["build", "--help"], { + stdout: buildHelp, + stderr: "", + status: 0, +}); + +await test(["build", "-w", "--help"], { + stdout: buildHelp, + stderr: "", + status: 0, +}); + +await test(["-w", "--help"], { stdout: cliHelp, stderr: "", status: 0 }); + +// Shows cli help with --help arg even if there are invalid arguments after it +await test(["--help", "-w"], { stdout: cliHelp, stderr: "", status: 0 }); + +// Shows build help with -h arg +await test(["build", "-h"], { stdout: buildHelp, stderr: "", status: 0 }); + +// Exits with build help with unknown arg +await test(["build", "-foo"], { + stdout: "", + stderr: `Error: Unknown option "-foo".\n${buildHelp}`, + status: 2, +}); + +// Shows cli help with --help arg +await test(["--help"], { stdout: cliHelp, stderr: "", status: 0 }); + +// Shows cli help with -h arg +await test(["-h"], { stdout: cliHelp, stderr: "", status: 0 }); + +// Shows cli help with -h arg +await test(["help"], { stdout: cliHelp, stderr: "", status: 0 }); + +// Exits with cli help with unknown command +await test(["built"], { + stdout: "", + stderr: `Error: Unknown command "built".\n${cliHelp}`, + status: 2, +}); + +// Exits with build help with unknown args +await test(["-foo"], { + stdout: "", + stderr: `Error: Unknown option "-foo".\n${buildHelp}`, + status: 2, +}); + +// Shows clean help with --help arg +await test(["clean", "--help"], { + stdout: cleanHelp, + stderr: "", + status: 0, +}); + +// Shows clean help with -h arg +await test(["clean", "-h"], { stdout: cleanHelp, stderr: "", status: 0 }); + +// Exits with clean help with unknown arg +await test(["clean", "-foo"], { + stdout: "", + stderr: `Error: Unknown option "-foo".\n${cleanHelp}`, + status: 2, +}); + +// Shows format help with --help arg +await test(["format", "--help"], { + stdout: formatHelp, + stderr: "", + status: 0, +}); + +// Shows format help with -h arg +await test(["format", "-h"], { + stdout: formatHelp, + stderr: "", + status: 0, +}); + +// Shows dump help with --help arg +await test(["dump", "--help"], { + stdout: dumpHelp, + stderr: "", + status: 0, +}); + +// Shows dump help with -h arg +await test(["dump", "-h"], { stdout: dumpHelp, stderr: "", status: 0 }); diff --git a/tests/build_tests/custom_namespace/input.js b/tests/build_tests/custom_namespace/input.js index e4502cb0c4..718d172356 100644 --- a/tests/build_tests/custom_namespace/input.js +++ b/tests/build_tests/custom_namespace/input.js @@ -1,10 +1,10 @@ -var child_process = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; -child_process.execSync(`${rescript_exe} clean && ${rescript_exe} build`, { - cwd: __dirname, -}); +const { execClean, execBuild } = setup(import.meta.dirname); -var x = require("./src/demo.bs.js"); +await execClean(); +await execBuild(); + +const x = await import("./src/demo.res.js"); assert.equal(x.v, 42); diff --git a/tests/build_tests/custom_namespace/rescript.json b/tests/build_tests/custom_namespace/rescript.json index 9677227f12..2d0bb7284b 100644 --- a/tests/build_tests/custom_namespace/rescript.json +++ b/tests/build_tests/custom_namespace/rescript.json @@ -7,14 +7,13 @@ }, "namespace": "Foo_bar", "package-specs": { - "module": "commonjs", - "in-source": true + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" }, "bsc-flags": ["-bs-no-version-header"], - "bs-dependencies": [], "warnings": { "number": "-40+6+7", "error": true - }, - "suffix": ".bs.js" + } } diff --git a/tests/build_tests/custom_namespace/src/demo.bs.js b/tests/build_tests/custom_namespace/src/demo.res.js similarity index 55% rename from tests/build_tests/custom_namespace/src/demo.bs.js rename to tests/build_tests/custom_namespace/src/demo.res.js index 160a8f1d2b..4237b506f2 100644 --- a/tests/build_tests/custom_namespace/src/demo.bs.js +++ b/tests/build_tests/custom_namespace/src/demo.res.js @@ -1,7 +1,9 @@ -'use strict'; + let v = 42; -exports.v = v; +export { + v, +} /* No side effect */ diff --git a/tests/build_tests/cycle/input.js b/tests/build_tests/cycle/input.js index d94a234e49..a35f908978 100644 --- a/tests/build_tests/cycle/input.js +++ b/tests/build_tests/cycle/input.js @@ -1,14 +1,16 @@ -//@ts-check -const cp = require("child_process"); -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -var output = cp.spawnSync(rescript_exe, { encoding: "utf8", shell: true }); +import * as assert from "node:assert"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { setup } from "#dev/process"; -assert(/dependency cycle/.test(output.stdout)); +const { execBuild } = setup(import.meta.dirname); -var compilerLogFile = path.join(__dirname, "lib", "bs", ".compiler.log"); -var compilerLog = fs.readFileSync(compilerLogFile, "utf8"); -assert(/dependency cycle/.test(compilerLog)); +const output = await execBuild(); + +assert.match(output.stdout, /dependency cycle/); + +const compilerLogFile = path.join("lib", "bs", ".compiler.log"); +const compilerLog = await fs.readFile(compilerLogFile, "utf8"); +assert.match(compilerLog, /dependency cycle/); diff --git a/tests/build_tests/cycle/rescript.json b/tests/build_tests/cycle/rescript.json index f43ea2c7c0..397c6c585b 100644 --- a/tests/build_tests/cycle/rescript.json +++ b/tests/build_tests/cycle/rescript.json @@ -6,10 +6,10 @@ "subdirs": true }, "package-specs": { - "module": "commonjs", - "in-source": true + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" }, - "suffix": ".bs.js", "bs-dependencies": [], "warnings": { "error": "+101" } } diff --git a/tests/build_tests/cycle1/input.js b/tests/build_tests/cycle1/input.js index 1894a6c1a8..83e04e104e 100644 --- a/tests/build_tests/cycle1/input.js +++ b/tests/build_tests/cycle1/input.js @@ -1,16 +1,17 @@ -//@ts-check -const cp = require("child_process"); -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); -const { rescript_exe } = require("#cli/bin_path"); +// @ts-check -cp.execSync(`${rescript_exe} clean`, { cwd: __dirname }); +import * as assert from "node:assert"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { setup } from "#dev/process"; -var output = cp.spawnSync(rescript_exe, { encoding: "utf8", shell: true }); +const { execBuild, execClean } = setup(import.meta.dirname); -assert(/is dangling/.test(output.stdout)); +await execClean(); +const output = await execBuild(); -var compilerLogFile = path.join(__dirname, "lib", "bs", ".compiler.log"); -var compilerLog = fs.readFileSync(compilerLogFile, "utf8"); -assert(/is dangling/.test(compilerLog)); +assert.match(output.stdout, /is dangling/); + +const compilerLogFile = path.join("lib", "bs", ".compiler.log"); +const compilerLog = await fs.readFile(compilerLogFile, "utf8"); +assert.match(compilerLog, /is dangling/); diff --git a/tests/build_tests/cycle1/rescript.json b/tests/build_tests/cycle1/rescript.json index fdbf975812..21bff92f92 100644 --- a/tests/build_tests/cycle1/rescript.json +++ b/tests/build_tests/cycle1/rescript.json @@ -8,7 +8,7 @@ }, "package-specs": { "module": "esmodule", - "in-source": true - }, - "suffix": ".bs.js" + "in-source": true, + "suffix": ".res.js" + } } diff --git a/tests/build_tests/deprecated-package-specs/input.js b/tests/build_tests/deprecated-package-specs/input.js index 7a7769861d..a4a4ed69d1 100644 --- a/tests/build_tests/deprecated-package-specs/input.js +++ b/tests/build_tests/deprecated-package-specs/input.js @@ -1,8 +1,11 @@ -const child_process = require("child_process"); -const assert = require("assert"); -const { rescript_exe } = require("#cli/bin_path"); +// @ts-check -const out = child_process.spawnSync(rescript_exe, { encoding: "utf8" }); +import assert from "node:assert"; +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +const out = await execBuild(); assert.match( out.stderr, /deprecated: Option "es6-global" is deprecated\. Use "esmodule" instead\./, diff --git a/tests/build_tests/devonly/input.js b/tests/build_tests/devonly/input.js index 2aec9809b2..50a4ceabd1 100644 --- a/tests/build_tests/devonly/input.js +++ b/tests/build_tests/devonly/input.js @@ -1,5 +1,7 @@ -//@ts-check -var cp = require("child_process"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -cp.execSync(rescript_exe, { cwd: __dirname, encoding: "utf8" }); +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +await execBuild(); diff --git a/tests/build_tests/devonly/rescript.json b/tests/build_tests/devonly/rescript.json index e68f677194..5af3898abc 100644 --- a/tests/build_tests/devonly/rescript.json +++ b/tests/build_tests/devonly/rescript.json @@ -13,10 +13,9 @@ } ], "package-specs": { - "module": "commonjs", - "in-source": true + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" }, - "suffix": ".bs.js", - "bs-dependencies": [], "warnings": { "error": "+101" } } diff --git a/tests/build_tests/devonly/src/demo.bs.js b/tests/build_tests/devonly/src/demo.res.js similarity index 64% rename from tests/build_tests/devonly/src/demo.bs.js rename to tests/build_tests/devonly/src/demo.res.js index 1b69c81d7f..b4786279d6 100644 --- a/tests/build_tests/devonly/src/demo.bs.js +++ b/tests/build_tests/devonly/src/demo.res.js @@ -1,7 +1,6 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; -let Depdemo = require("./depdemo.bs.js"); +import * as Depdemo from "./depdemo.res.js"; console.log(Depdemo.a); diff --git a/tests/build_tests/devonly/src/depdemo.bs.js b/tests/build_tests/devonly/src/depdemo.res.js similarity index 74% rename from tests/build_tests/devonly/src/depdemo.bs.js rename to tests/build_tests/devonly/src/depdemo.res.js index 7a46d38e23..a81ebd8f92 100644 --- a/tests/build_tests/devonly/src/depdemo.bs.js +++ b/tests/build_tests/devonly/src/depdemo.res.js @@ -1,8 +1,9 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; let a = 3; -exports.a = a; +export { + a, +} /* No side effect */ diff --git a/tests/build_tests/devonly/src2/hello.bs.js b/tests/build_tests/devonly/src2/hello.res.js similarity index 74% rename from tests/build_tests/devonly/src2/hello.bs.js rename to tests/build_tests/devonly/src2/hello.res.js index e49a9a2be3..cf0b79fe71 100644 --- a/tests/build_tests/devonly/src2/hello.bs.js +++ b/tests/build_tests/devonly/src2/hello.res.js @@ -1,8 +1,9 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; let v = 3; -exports.v = v; +export { + v, +} /* No side effect */ diff --git a/tests/build_tests/devonly/src2/hellodep.bs.js b/tests/build_tests/devonly/src2/hellodep.res.js similarity index 65% rename from tests/build_tests/devonly/src2/hellodep.bs.js rename to tests/build_tests/devonly/src2/hellodep.res.js index 0f6e84ce17..6c488f5087 100644 --- a/tests/build_tests/devonly/src2/hellodep.bs.js +++ b/tests/build_tests/devonly/src2/hellodep.res.js @@ -1,7 +1,6 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; -let Hello = require("./hello.bs.js"); +import * as Hello from "./hello.res.js"; console.log(Hello.v); diff --git a/tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/package.json b/tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/package.json index 92b37ba7fb..6b9eef9a35 100644 --- a/tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/package.json +++ b/tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/package.json @@ -1,18 +1,4 @@ { "name": "z", - "version": "0.1.0", - "scripts": { - "build": "bsb -make-world", - "start": "bsb -make-world -w", - "clean": "bsb -clean-world" - }, - "keywords": [ - "BuckleScript" - ], - "author": "", - "license": "MIT", - "devDependencies": { - "bs-platform": "^7.0.1", - "gentype": "^3.7.1" - } + "version": "0.1.0" } diff --git a/tests/build_tests/duplicated_symlinked_packages/node_modules/z/bsconfig.json b/tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/rescript.json similarity index 63% rename from tests/build_tests/duplicated_symlinked_packages/node_modules/z/bsconfig.json rename to tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/rescript.json index c99d72b2b4..9ea351dd4d 100644 --- a/tests/build_tests/duplicated_symlinked_packages/node_modules/z/bsconfig.json +++ b/tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/rescript.json @@ -6,16 +6,12 @@ "subdirs" : true }, "package-specs": { - "module": "commonjs", + "module": "esmodule", "in-source": true }, - "suffix": ".bs.js", - "bs-dependencies": [ - - ], + "suffix": ".res.js", "warnings": { "error" : "+101" }, - "namespace": true, - "refmt": 3 + "namespace": true } diff --git a/tests/build_tests/duplicated_symlinked_packages/a/package.json b/tests/build_tests/duplicated_symlinked_packages/a/package.json index f0cb45e231..7d9dd31f9e 100644 --- a/tests/build_tests/duplicated_symlinked_packages/a/package.json +++ b/tests/build_tests/duplicated_symlinked_packages/a/package.json @@ -1,15 +1,4 @@ { "name": "a", - "version": "0.1.0", - "scripts": { - "build": "rescript build", - "start": "rescript build -w", - "clean": "rescript clean" - }, - "keywords": [ - "ReScript" - ], - "author": "", - "license": "MIT", - "devDependencies": {} + "version": "0.1.0" } diff --git a/tests/build_tests/duplicated_symlinked_packages/a/bsconfig.json b/tests/build_tests/duplicated_symlinked_packages/a/rescript.json similarity index 74% rename from tests/build_tests/duplicated_symlinked_packages/a/bsconfig.json rename to tests/build_tests/duplicated_symlinked_packages/a/rescript.json index e59898305e..43650453d1 100644 --- a/tests/build_tests/duplicated_symlinked_packages/a/bsconfig.json +++ b/tests/build_tests/duplicated_symlinked_packages/a/rescript.json @@ -6,10 +6,10 @@ "subdirs": true }, "package-specs": { - "module": "commonjs", - "in-source": true + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" }, - "suffix": ".bs.js", "bs-dependencies": ["c", "z"], "warnings": { "error": "+101" }, "namespace": true diff --git a/tests/build_tests/duplicated_symlinked_packages/b/package.json b/tests/build_tests/duplicated_symlinked_packages/b/package.json index 6cba4e4ddc..17346b27df 100644 --- a/tests/build_tests/duplicated_symlinked_packages/b/package.json +++ b/tests/build_tests/duplicated_symlinked_packages/b/package.json @@ -1,15 +1,4 @@ { "name": "b", - "version": "0.1.0", - "scripts": { - "build": "rescript build", - "start": "rescript build -w", - "clean": "rescript clean" - }, - "keywords": [ - "ReScript" - ], - "author": "", - "license": "MIT", - "devDependencies": {} + "version": "0.1.0" } diff --git a/tests/build_tests/duplicated_symlinked_packages/b/bsconfig.json b/tests/build_tests/duplicated_symlinked_packages/b/rescript.json similarity index 74% rename from tests/build_tests/duplicated_symlinked_packages/b/bsconfig.json rename to tests/build_tests/duplicated_symlinked_packages/b/rescript.json index 29d031fd4b..46f7424882 100644 --- a/tests/build_tests/duplicated_symlinked_packages/b/bsconfig.json +++ b/tests/build_tests/duplicated_symlinked_packages/b/rescript.json @@ -6,10 +6,10 @@ "subdirs": true }, "package-specs": { - "module": "commonjs", - "in-source": true + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" }, - "suffix": ".bs.js", "bs-dependencies": ["c"], "warnings": { "error": "+101" }, "namespace": true diff --git a/tests/build_tests/duplicated_symlinked_packages/c/package.json b/tests/build_tests/duplicated_symlinked_packages/c/package.json index 907967c8be..f8623644bc 100644 --- a/tests/build_tests/duplicated_symlinked_packages/c/package.json +++ b/tests/build_tests/duplicated_symlinked_packages/c/package.json @@ -1,18 +1,4 @@ { - "name": "z", - "version": "0.1.0", - "scripts": { - "build": "rescript build", - "start": "rescript build -w", - "clean": "rescript clean" - }, - "keywords": [ - "ReScript" - ], - "author": "", - "license": "MIT", - "devDependencies": { - "bs-platform": "^7.0.1", - "gentype": "^3.7.1" - } + "name": "c", + "version": "0.1.0" } diff --git a/tests/build_tests/duplicated_symlinked_packages/c/bsconfig.json b/tests/build_tests/duplicated_symlinked_packages/c/rescript.json similarity index 73% rename from tests/build_tests/duplicated_symlinked_packages/c/bsconfig.json rename to tests/build_tests/duplicated_symlinked_packages/c/rescript.json index 24cc6980db..2941524ae2 100644 --- a/tests/build_tests/duplicated_symlinked_packages/c/bsconfig.json +++ b/tests/build_tests/duplicated_symlinked_packages/c/rescript.json @@ -6,11 +6,9 @@ "subdirs": true }, "package-specs": { - "module": "commonjs", + "module": "esmodule", "in-source": true }, - "suffix": ".bs.js", - "bs-dependencies": [], "warnings": { "error": "+101" }, "namespace": true } diff --git a/tests/build_tests/duplicated_symlinked_packages/input.js b/tests/build_tests/duplicated_symlinked_packages/input.js index a80c90d0d5..f15c2adcb9 100644 --- a/tests/build_tests/duplicated_symlinked_packages/input.js +++ b/tests/build_tests/duplicated_symlinked_packages/input.js @@ -1,16 +1,20 @@ -const fs = require("fs"); -const path = require("path"); -const child_process = require("child_process"); -const { rescript_exe } = require("#cli/bin_path"); +// @ts-check -const expectedFilePath = path.join(__dirname, "out.expected"); +import * as fs from "node:fs/promises"; +import { setup } from "#dev/process"; + +const { execBuild, execClean } = setup(import.meta.dirname); + +const expectedFilePath = "./out.expected"; const updateTests = process.argv[2] === "update"; +/** + * @param {string} output + * @return {string} + */ function postProcessErrorOutput(output) { - output = output.trimRight(); - output = output.replace(new RegExp(__dirname, "gi"), "."); - return output; + return output.trimEnd().replace(new RegExp(import.meta.dirname, "gi"), "."); } if (process.platform === "win32") { @@ -18,23 +22,22 @@ if (process.platform === "win32") { process.exit(0); } -child_process.execSync(`${rescript_exe} clean`, { cwd: __dirname }); - -child_process.exec(rescript_exe, { cwd: __dirname }, (err, stdout, stderr) => { - const actualErrorOutput = postProcessErrorOutput(stderr.toString()); - if (updateTests) { - fs.writeFileSync(expectedFilePath, actualErrorOutput); - } else { - const expectedErrorOutput = postProcessErrorOutput( - fs.readFileSync(expectedFilePath, { encoding: "utf-8" }), - ); - if (expectedErrorOutput !== actualErrorOutput) { - console.error(`The old and new error output aren't the same`); - console.error("\n=== Old:"); - console.error(expectedErrorOutput); - console.error("\n=== New:"); - console.error(actualErrorOutput); - process.exit(1); - } +await execClean(); +const { stderr } = await execBuild(); + +const actualErrorOutput = postProcessErrorOutput(stderr.toString()); +if (updateTests) { + await fs.writeFile(expectedFilePath, actualErrorOutput); +} else { + const expectedErrorOutput = postProcessErrorOutput( + await fs.readFile(expectedFilePath, { encoding: "utf-8" }), + ); + if (expectedErrorOutput !== actualErrorOutput) { + console.error(`The old and new error output aren't the same`); + console.error("\n=== Old:"); + console.error(expectedErrorOutput); + console.error("\n=== New:"); + console.error(actualErrorOutput); + process.exit(1); } -}); +} diff --git a/tests/build_tests/duplicated_symlinked_packages/node_modules/z/package.json b/tests/build_tests/duplicated_symlinked_packages/node_modules/z/package.json index 92b37ba7fb..6b9eef9a35 100644 --- a/tests/build_tests/duplicated_symlinked_packages/node_modules/z/package.json +++ b/tests/build_tests/duplicated_symlinked_packages/node_modules/z/package.json @@ -1,18 +1,4 @@ { "name": "z", - "version": "0.1.0", - "scripts": { - "build": "bsb -make-world", - "start": "bsb -make-world -w", - "clean": "bsb -clean-world" - }, - "keywords": [ - "BuckleScript" - ], - "author": "", - "license": "MIT", - "devDependencies": { - "bs-platform": "^7.0.1", - "gentype": "^3.7.1" - } + "version": "0.1.0" } diff --git a/tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/bsconfig.json b/tests/build_tests/duplicated_symlinked_packages/node_modules/z/rescript.json similarity index 74% rename from tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/bsconfig.json rename to tests/build_tests/duplicated_symlinked_packages/node_modules/z/rescript.json index c99d72b2b4..025a177cc4 100644 --- a/tests/build_tests/duplicated_symlinked_packages/a/node_modules/z/bsconfig.json +++ b/tests/build_tests/duplicated_symlinked_packages/node_modules/z/rescript.json @@ -6,13 +6,9 @@ "subdirs" : true }, "package-specs": { - "module": "commonjs", + "module": "esmodule", "in-source": true }, - "suffix": ".bs.js", - "bs-dependencies": [ - - ], "warnings": { "error" : "+101" }, diff --git a/tests/build_tests/exports/input.js b/tests/build_tests/exports/input.js index 76ead396b3..50a4ceabd1 100644 --- a/tests/build_tests/exports/input.js +++ b/tests/build_tests/exports/input.js @@ -1,7 +1,7 @@ -var child_process = require("child_process"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -child_process.execSync(rescript_exe, { - cwd: __dirname, - encoding: "utf8", -}); +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +await execBuild(); diff --git a/tests/build_tests/exports/rescript.json b/tests/build_tests/exports/rescript.json index 341475886f..1abffa2047 100644 --- a/tests/build_tests/exports/rescript.json +++ b/tests/build_tests/exports/rescript.json @@ -1,6 +1,5 @@ { "name": "exports", "version": "0.1.0", - "sources": ["src"], - "bs-dependencies": [] + "sources": ["src"] } diff --git a/tests/build_tests/gpr_978/input.js b/tests/build_tests/gpr_978/input.js index 70c0949700..384a36e77a 100644 --- a/tests/build_tests/gpr_978/input.js +++ b/tests/build_tests/gpr_978/input.js @@ -1,13 +1,15 @@ -//@ts-check -const cp = require("child_process"); -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); -const { rescript_exe } = require("#cli/bin_path"); - -const output = cp.spawnSync(rescript_exe, { encoding: "utf8", shell: true }); -assert(/M is exported twice/.test(output.stdout)); - -const compilerLogFile = path.join(__dirname, "lib", "bs", ".compiler.log"); -const compilerLog = fs.readFileSync(compilerLogFile, "utf8"); -assert(/M is exported twice/.test(compilerLog)); +// @ts-check + +import * as assert from "node:assert"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +const output = await execBuild(); +assert.match(output.stdout, /M is exported twice/); + +const compilerLogFile = path.join("lib", "bs", ".compiler.log"); +const compilerLog = await fs.readFile(compilerLogFile, "utf8"); +assert.match(compilerLog, /M is exported twice/); diff --git a/tests/build_tests/gpr_978/rescript.json b/tests/build_tests/gpr_978/rescript.json index 406397e559..d5acde0ade 100644 --- a/tests/build_tests/gpr_978/rescript.json +++ b/tests/build_tests/gpr_978/rescript.json @@ -1,8 +1,5 @@ { "name": "gpr_978", "version": "0.0.0", - "sources": [ - "src" - ], - "bs-dependencies": [] -} \ No newline at end of file + "sources": ["src"] +} diff --git a/tests/build_tests/hyphen2/input.js b/tests/build_tests/hyphen2/input.js index 84c35bb893..50a4ceabd1 100644 --- a/tests/build_tests/hyphen2/input.js +++ b/tests/build_tests/hyphen2/input.js @@ -1,4 +1,7 @@ -var p = require("child_process"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -p.execSync(rescript_exe, { cwd: __dirname }); +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +await execBuild(); diff --git a/tests/build_tests/in_source/input.js b/tests/build_tests/in_source/input.js index 533a61a521..f29b5a2e37 100644 --- a/tests/build_tests/in_source/input.js +++ b/tests/build_tests/in_source/input.js @@ -1,24 +1,9 @@ -var child_process = require("child_process"); +// @ts-check -var assert = require("assert"); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; -var { rescript_exe } = require("#cli/bin_path"); +const { execBuild } = setup(import.meta.dirname); -assert.throws( - () => { - var output = child_process.execSync(`${rescript_exe} build -regen`, { - cwd: __dirname, - encoding: "utf8", - }); - }, - function (err) { - if (err.message.match(/detected two module formats/)) { - return true; - } - return false; - }, -); - -// assert.throws(()=>{ -// throw new Error('Wrong value') -// }, /x/) +const output = await execBuild(["-regen"]); +assert.match(output.stderr, /detected two module formats/); diff --git a/tests/build_tests/install/input.js b/tests/build_tests/install/input.js index 407e1f9558..4c7df0215d 100644 --- a/tests/build_tests/install/input.js +++ b/tests/build_tests/install/input.js @@ -1,29 +1,20 @@ -var p = require("child_process"); -var fs = require("fs"); -var path = require("path"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -p.spawnSync(rescript_exe, [`clean`], { - encoding: "utf8", - cwd: __dirname, -}); -p.spawnSync(rescript_exe, [`build`, `-install`], { - encoding: "utf8", - cwd: __dirname, -}); +import * as assert from "node:assert"; +import { existsSync } from "node:fs"; +import * as path from "node:path"; +import { setup } from "#dev/process"; -var fooExists = fs.existsSync(path.join(__dirname, "lib", "ocaml", "Foo.cmi")); -assert.ok(fooExists == false); +const { execBuild, execClean } = setup(import.meta.dirname); -p.spawnSync(rescript_exe, { - encoding: "utf8", - cwd: __dirname, -}); -p.spawnSync(rescript_exe, [`build`, `-install`], { - encoding: "utf8", - cwd: __dirname, -}); +await execClean(); +await execBuild(["-install"]); -fooExists = fs.existsSync(path.join(__dirname, "lib", "ocaml", "Foo.cmi")); +let fooExists = existsSync(path.join("lib", "ocaml", "Foo.cmi")); +assert.ok(!fooExists); + +await execBuild(); +await execBuild(["-install"]); + +fooExists = existsSync(path.join("lib", "ocaml", "Foo.cmi")); assert.ok(fooExists); diff --git a/tests/build_tests/install/rescript.json b/tests/build_tests/install/rescript.json index c5e0d91b0e..b073ff2022 100644 --- a/tests/build_tests/install/rescript.json +++ b/tests/build_tests/install/rescript.json @@ -6,10 +6,10 @@ "subdirs": true }, "package-specs": { - "module": "commonjs", - "in-source": true + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" }, - "suffix": ".bs.js", "bs-dependencies": [], "warnings": { "error": "+101" } } diff --git a/tests/build_tests/install/src/Foo.bs.js b/tests/build_tests/install/src/Foo.res.js similarity index 76% rename from tests/build_tests/install/src/Foo.bs.js rename to tests/build_tests/install/src/Foo.res.js index cf2ea83c43..6078c7d3cf 100644 --- a/tests/build_tests/install/src/Foo.bs.js +++ b/tests/build_tests/install/src/Foo.res.js @@ -1,10 +1,11 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; function main() { console.log("hello"); } -exports.main = main; +export { + main, +} /* No side effect */ diff --git a/tests/build_tests/jsx_settings_inheritance/input.js b/tests/build_tests/jsx_settings_inheritance/input.js index 96e9ab8353..50a4ceabd1 100644 --- a/tests/build_tests/jsx_settings_inheritance/input.js +++ b/tests/build_tests/jsx_settings_inheritance/input.js @@ -1,5 +1,7 @@ -//@ts-check -var cp = require("child_process"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -cp.execSync(rescript_exe, { cwd: __dirname }); +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +await execBuild(); diff --git a/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/rescript.json b/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/rescript.json index e948391f26..c2ed78b174 100644 --- a/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/rescript.json +++ b/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/rescript.json @@ -5,9 +5,9 @@ "mode": "classic" }, "sources": [{ "dir": "src", "subdirs": true }], - "package-specs": [{ "module": "commonjs", "in-source": true }], - "suffix": ".bs.js", + "package-specs": { "module": "esmodule", "in-source": true }, + "suffix": ".res.js", "bs-dev-dependencies": [], "bsc-flags": [], "uncurried": false -} \ No newline at end of file +} diff --git a/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/React.mjs b/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/React.res.js similarity index 54% rename from tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/React.mjs rename to tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/React.res.js index abd3ce43c9..b9440275de 100644 --- a/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/React.mjs +++ b/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/React.res.js @@ -1,7 +1,6 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; -let React = require("react"); +import * as React from "react"; let Ref = {}; @@ -23,12 +22,14 @@ function lazy_(load) { let Uncurried = {}; -exports.Ref = Ref; -exports.Children = Children; -exports.Context = Context; -exports.Fragment = Fragment; -exports.StrictMode = StrictMode; -exports.Suspense = Suspense; -exports.lazy_ = lazy_; -exports.Uncurried = Uncurried; +export { + Ref, + Children, + Context, + Fragment, + StrictMode, + Suspense, + lazy_, + Uncurried, +} /* react Not a pure module */ diff --git a/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/ReactDOM.mjs b/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/ReactDOM.res.js similarity index 65% rename from tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/ReactDOM.mjs rename to tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/ReactDOM.res.js index 531f41295f..0827b13dea 100644 --- a/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/ReactDOM.mjs +++ b/tests/build_tests/jsx_settings_inheritance/node_modules/@rescript/react/src/ReactDOM.res.js @@ -1,5 +1,4 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; let Root = {}; @@ -12,7 +11,9 @@ let Ref = {}; let Props = {}; -exports.Client = Client; -exports.Ref = Ref; -exports.Props = Props; +export { + Client, + Ref, + Props, +} /* No side effect */ diff --git a/tests/build_tests/jsx_settings_inheritance/node_modules/a/package.json b/tests/build_tests/jsx_settings_inheritance/node_modules/a/package.json index db9848a748..f9244b8b0f 100644 --- a/tests/build_tests/jsx_settings_inheritance/node_modules/a/package.json +++ b/tests/build_tests/jsx_settings_inheritance/node_modules/a/package.json @@ -1,4 +1,4 @@ { - "name": "a", - "version": "0.0.0" -} \ No newline at end of file + "name": "a", + "version": "0.0.0" +} diff --git a/tests/build_tests/jsx_settings_inheritance/node_modules/a/rescript.json b/tests/build_tests/jsx_settings_inheritance/node_modules/a/rescript.json index a9aad4cff9..266065ca7b 100644 --- a/tests/build_tests/jsx_settings_inheritance/node_modules/a/rescript.json +++ b/tests/build_tests/jsx_settings_inheritance/node_modules/a/rescript.json @@ -8,15 +8,13 @@ "dir": "src", "subdirs": true }, - "package-specs": [ - { - "module": "commonjs", - "in-source": true - } - ], - "suffix": ".mjs", + "package-specs": { + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" + }, "namespace": true, "bs-dependencies": [ "@rescript/react" ] -} \ No newline at end of file +} diff --git a/tests/build_tests/jsx_settings_inheritance/node_modules/a/src/A.mjs b/tests/build_tests/jsx_settings_inheritance/node_modules/a/src/A.res.js similarity index 70% rename from tests/build_tests/jsx_settings_inheritance/node_modules/a/src/A.mjs rename to tests/build_tests/jsx_settings_inheritance/node_modules/a/src/A.res.js index cdd60ab268..6b95c9bba3 100644 --- a/tests/build_tests/jsx_settings_inheritance/node_modules/a/src/A.mjs +++ b/tests/build_tests/jsx_settings_inheritance/node_modules/a/src/A.res.js @@ -1,7 +1,6 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; -let JsxRuntime = require("react/jsx-runtime"); +import * as JsxRuntime from "react/jsx-runtime"; function A(props) { return JsxRuntime.jsx("div", { @@ -11,5 +10,7 @@ function A(props) { let make = A; -exports.make = make; +export { + make, +} /* react/jsx-runtime Not a pure module */ diff --git a/tests/build_tests/jsx_settings_inheritance/node_modules/b/rescript.json b/tests/build_tests/jsx_settings_inheritance/node_modules/b/rescript.json index da3c68d2cd..b3b346ec46 100644 --- a/tests/build_tests/jsx_settings_inheritance/node_modules/b/rescript.json +++ b/tests/build_tests/jsx_settings_inheritance/node_modules/b/rescript.json @@ -4,15 +4,13 @@ "dir": "src", "subdirs": true }, - "package-specs": [ - { - "module": "commonjs", - "in-source": true - } - ], - "suffix": ".mjs", + "package-specs": { + "module": "esmodule", + "in-source": true, + "suffix": ".mjs" + }, "namespace": true, "bs-dependencies": [ "@rescript/react" ] -} \ No newline at end of file +} diff --git a/tests/build_tests/jsx_settings_inheritance/node_modules/b/src/B.mjs b/tests/build_tests/jsx_settings_inheritance/node_modules/b/src/B.res.js similarity index 70% rename from tests/build_tests/jsx_settings_inheritance/node_modules/b/src/B.mjs rename to tests/build_tests/jsx_settings_inheritance/node_modules/b/src/B.res.js index 85e5b19562..757e5af351 100644 --- a/tests/build_tests/jsx_settings_inheritance/node_modules/b/src/B.mjs +++ b/tests/build_tests/jsx_settings_inheritance/node_modules/b/src/B.res.js @@ -1,7 +1,6 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; -let JsxRuntime = require("react/jsx-runtime"); +import * as JsxRuntime from "react/jsx-runtime"; function B(props) { return JsxRuntime.jsx("div", { @@ -11,5 +10,7 @@ function B(props) { let make = B; -exports.make = make; +export { + make, +} /* react/jsx-runtime Not a pure module */ diff --git a/tests/build_tests/jsx_settings_inheritance/rescript.json b/tests/build_tests/jsx_settings_inheritance/rescript.json index bedc0f0d67..3036b57b61 100644 --- a/tests/build_tests/jsx_settings_inheritance/rescript.json +++ b/tests/build_tests/jsx_settings_inheritance/rescript.json @@ -8,17 +8,11 @@ "dir": "src", "subdirs": true }, - "package-specs": [ - { - "module": "commonjs", - "in-source": true - } - ], - "suffix": ".mjs", + "package-specs": { + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" + }, "namespace": true, - "bs-dependencies": [ - "@rescript/react", - "a", - "b" - ] -} \ No newline at end of file + "bs-dependencies": ["@rescript/react", "a", "b"] +} diff --git a/tests/build_tests/jsx_settings_inheritance/src/C.mjs b/tests/build_tests/jsx_settings_inheritance/src/C.res.js similarity index 63% rename from tests/build_tests/jsx_settings_inheritance/src/C.mjs rename to tests/build_tests/jsx_settings_inheritance/src/C.res.js index 8904c9bed0..f341b1a58a 100644 --- a/tests/build_tests/jsx_settings_inheritance/src/C.mjs +++ b/tests/build_tests/jsx_settings_inheritance/src/C.res.js @@ -1,9 +1,8 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; -let A$A = require("a/src/A.mjs"); -let B$B = require("b/src/B.mjs"); -let JsxRuntime = require("react/jsx-runtime"); +import * as A$A from "a/src/A.res.js"; +import * as B$B from "b/src/B.res.js"; +import * as JsxRuntime from "react/jsx-runtime"; function C(props) { return JsxRuntime.jsxs(JsxRuntime.Fragment, { @@ -16,5 +15,7 @@ function C(props) { let make = C; -exports.make = make; +export { + make, +} /* A-A Not a pure module */ diff --git a/tests/build_tests/nested/input.js b/tests/build_tests/nested/input.js index a56e24f14e..68b05999ce 100644 --- a/tests/build_tests/nested/input.js +++ b/tests/build_tests/nested/input.js @@ -1,17 +1,22 @@ -var p = require("child_process"); -var assert = require("assert"); -var fs = require("fs"); -var path = require("path"); -var { rescript_exe } = require("#cli/bin_path"); -p.execSync(rescript_exe, { cwd: __dirname }); +// @ts-check -var content = fs.readFileSync(path.join(__dirname, "src", "demo.js"), "utf8"); +import * as assert from "node:assert"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { setup } from "#dev/process"; -assert.ok(content.match(/A00_a1_main/g).length === 3); -assert.ok(content.match(/B00_b1_main/g).length === 3); -assert.ok(content.match(/A0_main/g).length === 2); -assert.ok(content.match(/a0_main/g).length === 1); -assert.ok(content.match(/B0_main/g).length === 2); -assert.ok(content.match(/b0_main/g).length === 1); +const { execBuild } = setup(import.meta.dirname); -assert.ok(require("./src/demo.js").v === 4, "nested"); +await execBuild(); + +const content = await fs.readFile(path.join("src", "demo.js"), "utf8"); + +assert.equal(content.match(/A00_a1_main/g)?.length, 3); +assert.equal(content.match(/B00_b1_main/g)?.length, 3); +assert.equal(content.match(/A0_main/g)?.length, 2); +assert.equal(content.match(/a0_main/g)?.length, 1); +assert.equal(content.match(/B0_main/g)?.length, 2); +assert.equal(content.match(/b0_main/g)?.length, 1); + +const mod = await import("./src/demo.js"); +assert.equal(mod.v, 4, "nested"); diff --git a/tests/build_tests/nested/rescript.json b/tests/build_tests/nested/rescript.json index 745772f871..d796e4f378 100644 --- a/tests/build_tests/nested/rescript.json +++ b/tests/build_tests/nested/rescript.json @@ -6,7 +6,7 @@ "subdirs": true }, "package-specs": { - "module": "commonjs", + "module": "esmodule", "in-source": true }, "warnings": { "error": true } diff --git a/tests/build_tests/nnest/input.js b/tests/build_tests/nnest/input.js index e3ad473862..98da456f4d 100644 --- a/tests/build_tests/nnest/input.js +++ b/tests/build_tests/nnest/input.js @@ -1,28 +1,22 @@ // @ts-check -var p = require("child_process"); -var assert = require("assert"); -var fs = require("fs"); -var path = require("path"); -var { rescript_exe } = require("#cli/bin_path"); -p.execSync(rescript_exe, { cwd: __dirname }); +import * as assert from "node:assert"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { setup } from "#dev/process"; -var content = fs.readFileSync(path.join(__dirname, "src", "demo.js"), "utf8"); +const { execBuild } = setup(import.meta.dirname); -assert.ok(content.match(/A0_a1_main/g).length === 3); -assert.ok(content.match(/B0_b1_main/g).length === 3); -assert.ok(content.match(/A0_main/g).length === 2); -assert.ok(content.match(/a0_main/g).length === 1); -assert.ok(content.match(/B0_main/g).length === 2); -assert.ok(content.match(/b0_main/g).length === 1); +await execBuild(); -assert.ok(require("./src/demo.js").v === 4, "nested"); +const content = await fs.readFile(path.join("src", "demo.js"), "utf8"); -// var testWarnError = /warnings\s*=\s*[^\r\n]*-warn-error/; +assert.equal(content.match(/A0_a1_main/g)?.length, 3); +assert.equal(content.match(/B0_b1_main/g)?.length, 3); +assert.equal(content.match(/A0_main/g)?.length, 2); +assert.equal(content.match(/a0_main/g)?.length, 1); +assert.equal(content.match(/B0_main/g)?.length, 2); +assert.equal(content.match(/b0_main/g)?.length, 1); -// function hasWarnError(file) { -// var content = fs.readFileSync(file, "utf8"); -// return testWarnError.test(content); -// } - -// assert.ok(hasWarnError(path.join(__dirname,'lib','bs','build.ninja'))) +const mod = await import("./src/demo.js"); +assert.equal(mod.v, 4, "nested"); diff --git a/tests/build_tests/nnest/rescript.json b/tests/build_tests/nnest/rescript.json index e1e67b2128..dcbfeefd72 100644 --- a/tests/build_tests/nnest/rescript.json +++ b/tests/build_tests/nnest/rescript.json @@ -6,7 +6,7 @@ "subdirs": true }, "package-specs": { - "module": "commonjs", + "module": "esmodule", "in-source": true }, "namespace": true, diff --git a/tests/build_tests/ns/input.js b/tests/build_tests/ns/input.js index 55e41645da..50a4ceabd1 100755 --- a/tests/build_tests/ns/input.js +++ b/tests/build_tests/ns/input.js @@ -1,4 +1,7 @@ -var child_process = require("child_process"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -child_process.execSync(rescript_exe, { cwd: __dirname }); +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +await execBuild(); diff --git a/tests/build_tests/post-build/input.js b/tests/build_tests/post-build/input.js index 8a9b223f42..83fd43098f 100644 --- a/tests/build_tests/post-build/input.js +++ b/tests/build_tests/post-build/input.js @@ -1,13 +1,16 @@ -var child_process = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check + +import * as assert from "node:assert"; +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); if (process.platform === "win32") { console.log("Skipping test on Windows"); process.exit(0); } -var out = child_process.spawnSync(rescript_exe, { encoding: "utf8" }); +const out = await execBuild(); if (out.status !== 0) { assert.fail(out.stdout + out.stderr); diff --git a/tests/build_tests/react_ppx/input.js b/tests/build_tests/react_ppx/input.js index 96e9ab8353..50a4ceabd1 100644 --- a/tests/build_tests/react_ppx/input.js +++ b/tests/build_tests/react_ppx/input.js @@ -1,5 +1,7 @@ -//@ts-check -var cp = require("child_process"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -cp.execSync(rescript_exe, { cwd: __dirname }); +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +await execBuild(); diff --git a/tests/build_tests/react_ppx/rescript.json b/tests/build_tests/react_ppx/rescript.json index 62d4a8e2fb..0ed0b3be50 100644 --- a/tests/build_tests/react_ppx/rescript.json +++ b/tests/build_tests/react_ppx/rescript.json @@ -7,12 +7,10 @@ "dir": "src", "subdirs": true }, - "package-specs": [ - { - "module": "commonjs", - "in-source": true - } - ], - "suffix": ".bs.js", + "package-specs": { + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" + }, "namespace": true } diff --git a/tests/build_tests/react_ppx/src/React.bs.js b/tests/build_tests/react_ppx/src/React.res.js similarity index 52% rename from tests/build_tests/react_ppx/src/React.bs.js rename to tests/build_tests/react_ppx/src/React.res.js index 05c8865770..fb408bebf1 100644 --- a/tests/build_tests/react_ppx/src/React.bs.js +++ b/tests/build_tests/react_ppx/src/React.res.js @@ -1,5 +1,4 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; let Ref = {}; @@ -12,9 +11,11 @@ let Fragment = {}; let Suspense = {}; -exports.Ref = Ref; -exports.Children = Children; -exports.Context = Context; -exports.Fragment = Fragment; -exports.Suspense = Suspense; +export { + Ref, + Children, + Context, + Fragment, + Suspense, +} /* No side effect */ diff --git a/tests/build_tests/react_ppx/src/gpr_3695_test.bs.js b/tests/build_tests/react_ppx/src/gpr_3695_test.res.js similarity index 59% rename from tests/build_tests/react_ppx/src/gpr_3695_test.bs.js rename to tests/build_tests/react_ppx/src/gpr_3695_test.res.js index 42dcc0f6db..ebaf897020 100644 --- a/tests/build_tests/react_ppx/src/gpr_3695_test.bs.js +++ b/tests/build_tests/react_ppx/src/gpr_3695_test.res.js @@ -1,7 +1,6 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; -let Foo = require("Foo"); +import * as Foo from "Foo"; let React = {}; @@ -11,7 +10,9 @@ function test(className) { return Foo; } -exports.React = React; -exports.Test = Test; -exports.test = test; +export { + React, + Test, + test, +} /* Foo Not a pure module */ diff --git a/tests/build_tests/react_ppx/src/gpr_3987_test.bs.js b/tests/build_tests/react_ppx/src/gpr_3987_test.res.js similarity index 83% rename from tests/build_tests/react_ppx/src/gpr_3987_test.bs.js rename to tests/build_tests/react_ppx/src/gpr_3987_test.res.js index a8451b2174..378f9156ca 100644 --- a/tests/build_tests/react_ppx/src/gpr_3987_test.bs.js +++ b/tests/build_tests/react_ppx/src/gpr_3987_test.res.js @@ -1,7 +1,6 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; -let JsxRuntime = require("react/jsx-runtime"); +import * as JsxRuntime from "react/jsx-runtime"; function makeContainer(text) { let container = document.createElement("div"); @@ -56,8 +55,10 @@ JsxRuntime.jsx(Gpr_3987_test$Gpr3987ReproError, { onChange: (param, param$1) => {} }); -exports.makeContainer = makeContainer; -exports.Gpr3987ReproOk = Gpr3987ReproOk; -exports.Gpr3987ReproOk2 = Gpr3987ReproOk2; -exports.Gpr3987ReproError = Gpr3987ReproError; +export { + makeContainer, + Gpr3987ReproOk, + Gpr3987ReproOk2, + Gpr3987ReproError, +} /* Not a pure module */ diff --git a/tests/build_tests/react_ppx/src/recursive_component_test.bs.js b/tests/build_tests/react_ppx/src/recursive_component_test.res.js similarity index 87% rename from tests/build_tests/react_ppx/src/recursive_component_test.bs.js rename to tests/build_tests/react_ppx/src/recursive_component_test.res.js index c24783b0fa..4e3fd9951f 100644 --- a/tests/build_tests/react_ppx/src/recursive_component_test.bs.js +++ b/tests/build_tests/react_ppx/src/recursive_component_test.res.js @@ -1,5 +1,4 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; function mm(x) { @@ -19,5 +18,7 @@ let Rec = { mm: mm }; -exports.Rec = Rec; +export { + Rec, +} /* No side effect */ diff --git a/tests/build_tests/rerror/input.js b/tests/build_tests/rerror/input.js index 6f452f1331..70a81c8dba 100644 --- a/tests/build_tests/rerror/input.js +++ b/tests/build_tests/rerror/input.js @@ -1,35 +1,28 @@ // @ts-check -var child_process = require("child_process"); -var assert = require("assert"); -var os = require("os"); -var { rescript_exe } = require("#cli/bin_path"); -child_process.spawnSync(`${rescript_exe} clean`, { - cwd: __dirname, - encoding: "utf8", -}); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; -var o = child_process.spawnSync(rescript_exe, { - cwd: __dirname, - encoding: "utf8", - shell: true, -}); +const { execBuild, execClean } = setup(import.meta.dirname); + +await execClean(); +const output = await execBuild([]); // verify the output is in reason syntax -var u = o.stdout.match(/=>/g); +const u = output.stdout.match(/=>/g); -var lines = o.stdout +const lines = output.stdout .split(/\r?\n/) .map(x => x.trim()) .filter(Boolean); -var test = false; -for (var i = 0; i < lines.length; ++i) { +let test = false; +for (let i = 0; i < lines.length; i++) { if (lines[i] === "We've found a bug for you!") { console.log(`line ${i} found`); - assert.ok(/src[\\/]demo.res:1:21-23/.test(lines[i + 1])); + assert.match(lines[i + 1], /src[\\/]demo.res:1:21-23/); test = true; } } assert.ok(test); -assert.ok(u.length === 2); +assert.equal(u?.length, 2); diff --git a/tests/build_tests/scoped_ppx/input.js b/tests/build_tests/scoped_ppx/input.js index 9d75560d0d..d3e3f06ee7 100644 --- a/tests/build_tests/scoped_ppx/input.js +++ b/tests/build_tests/scoped_ppx/input.js @@ -1,21 +1,19 @@ -var cp = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check + +import * as assert from "node:assert"; +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); if (process.platform === "win32") { console.log("Skipping test on Windows"); process.exit(0); } -cp.execSync(rescript_exe, { cwd: __dirname, encoding: "utf8" }); - -var output = cp.execSync(`${rescript_exe} build -- -t commands src/hello.ast`, { - cwd: __dirname, - encoding: "utf8", -}); +await execBuild(); +const output = await execBuild(["--", "-t", "commands", "src/hello.ast"]); -assert( - /-ppx '.*\/test\.js -hello' -ppx '.*\/test\.js -heyy' -ppx .*test\.js/.test( - output, - ), +assert.match( + output.stdout, + /-ppx '.*\/test\.js -hello' -ppx '.*\/test\.js -heyy' -ppx .*test\.js/, ); diff --git a/tests/build_tests/scoped_ppx/node_modules/@hongbo/ppx1/package.json b/tests/build_tests/scoped_ppx/node_modules/@hongbo/ppx1/package.json new file mode 100644 index 0000000000..5bbefffbab --- /dev/null +++ b/tests/build_tests/scoped_ppx/node_modules/@hongbo/ppx1/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/tests/build_tests/scoped_ppx/node_modules/@hongbo/ppx1/test.js b/tests/build_tests/scoped_ppx/node_modules/@hongbo/ppx1/test.js index 34ea82903f..e0ec31c3e2 100755 --- a/tests/build_tests/scoped_ppx/node_modules/@hongbo/ppx1/test.js +++ b/tests/build_tests/scoped_ppx/node_modules/@hongbo/ppx1/test.js @@ -1,12 +1,11 @@ #!/usr/bin/env node -//@ts-check -var fs = require('fs') - -// let [_node, _js, file_in, file_out] = process.argv -var file_in = process.argv[process.argv.length - 2] -var file_out = process.argv[process.argv.length - 1] -// console.log(process.argv) -// debugger; -fs.createReadStream(file_in) - .pipe(fs.createWriteStream(file_out)) +// @ts-check + +const fs = require('node:fs') + +const file_in = process.argv[process.argv.length - 2] +const file_out = process.argv[process.argv.length - 1] + +fs.createReadStream(file_in) + .pipe(fs.createWriteStream(file_out)) diff --git a/tests/build_tests/super_errors/input.js b/tests/build_tests/super_errors/input.js index ffe4642523..f31370b097 100644 --- a/tests/build_tests/super_errors/input.js +++ b/tests/build_tests/super_errors/input.js @@ -1,65 +1,69 @@ -const fs = require("fs"); -const path = require("path"); -const child_process = require("child_process"); +// @ts-check -const { bsc_exe: bsc } = require("#cli/bin_path"); -const { normalizeNewlines } = require("../utils.js"); +import { readdirSync } from "node:fs"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { setup } from "#dev/process"; +import { normalizeNewlines } from "#dev/utils"; -const expectedDir = path.join(__dirname, "expected"); +const { bsc } = setup(import.meta.dirname); -const fixtures = fs - .readdirSync(path.join(__dirname, "fixtures")) - .filter(fileName => path.extname(fileName) === ".res"); +const expectedDir = path.join(import.meta.dirname, "expected"); -// const runtime = path.join(__dirname, '..', '..', 'runtime') -const prefix = `${bsc} -w +A -bs-jsx 4`; +const fixtures = readdirSync("fixtures").filter( + fileName => path.extname(fileName) === ".res", +); -const updateTests = process.argv[2] === "update"; +const prefix = ["-w", "+A", "-bs-jsx", "4"]; +const updateTests = process.argv[2] === "update"; +/** + * @param {string} output + * @return {string} + */ function postProcessErrorOutput(output) { - output = output.trimRight(); - output = output.replace( + let result = output; + result = result.trimEnd(); + result = result.replace( /(?:[A-Z]:)?[\\/][^ ]+?tests[\\/]build_tests[\\/]super_errors[\\/]([^:]+)/g, (_match, path, _offset, _string) => "/.../" + path.replace("\\", "/"), ); - return normalizeNewlines(output); + return normalizeNewlines(result); } let doneTasksCount = 0; let atLeastOneTaskFailed = false; -fixtures.forEach(fileName => { - const fullFilePath = path.join(__dirname, "fixtures", fileName); - const command = `${prefix} -color always ${fullFilePath}`; - child_process.exec(command, (err, stdout, stderr) => { - doneTasksCount++; - // careful of: - // - warning test that actually succeeded in compiling (warning's still in stderr, so the code path is shared here) - // - accidentally succeeding tests (not likely in this context), - // actual, correctly erroring test case - const actualErrorOutput = postProcessErrorOutput(stderr.toString()); - const expectedFilePath = path.join(expectedDir, fileName + ".expected"); - if (updateTests) { - fs.writeFileSync(expectedFilePath, actualErrorOutput); - } else { - const expectedErrorOutput = postProcessErrorOutput( - fs.readFileSync(expectedFilePath, { encoding: "utf-8" }), +for (const fileName of fixtures) { + const fullFilePath = path.join(import.meta.dirname, "fixtures", fileName); + const { stderr } = await bsc([...prefix, "-color", "always", fullFilePath]); + doneTasksCount++; + // careful of: + // - warning test that actually succeeded in compiling (warning's still in stderr, so the code path is shared here) + // - accidentally succeeding tests (not likely in this context), + // actual, correctly erroring test case + const actualErrorOutput = postProcessErrorOutput(stderr.toString()); + const expectedFilePath = path.join(expectedDir, `${fileName}.expected`); + if (updateTests) { + await fs.writeFile(expectedFilePath, actualErrorOutput); + } else { + const expectedErrorOutput = postProcessErrorOutput( + await fs.readFile(expectedFilePath, "utf-8"), + ); + if (expectedErrorOutput !== actualErrorOutput) { + console.error( + `The old and new error output for the test ${fullFilePath} aren't the same`, ); - if (expectedErrorOutput !== actualErrorOutput) { - console.error( - `The old and new error output for the test ${fullFilePath} aren't the same`, - ); - console.error("\n=== Old:"); - console.error(expectedErrorOutput); - console.error("\n=== New:"); - console.error(actualErrorOutput); - atLeastOneTaskFailed = true; - } + console.error("\n=== Old:"); + console.error(expectedErrorOutput); + console.error("\n=== New:"); + console.error(actualErrorOutput); + atLeastOneTaskFailed = true; + } - if (doneTasksCount === fixtures.length && atLeastOneTaskFailed) { - process.exit(1); - } + if (doneTasksCount === fixtures.length && atLeastOneTaskFailed) { + process.exit(1); } - }); -}); + } +} diff --git a/tests/build_tests/transitive_pinned_dependency1/a/rescript.json b/tests/build_tests/transitive_pinned_dependency1/a/rescript.json index 065cbb35b8..9ab943fa18 100644 --- a/tests/build_tests/transitive_pinned_dependency1/a/rescript.json +++ b/tests/build_tests/transitive_pinned_dependency1/a/rescript.json @@ -11,13 +11,13 @@ } ], "package-specs": { - "module": "commonjs", - "in-source": false + "module": "esmodule", + "in-source": false, + "suffix": ".res.js" }, "warnings": { "error": true }, - "suffix": ".mjs", "bs-dependencies": ["b"], "pinned-dependencies": ["b"] } diff --git a/tests/build_tests/transitive_pinned_dependency1/input.js b/tests/build_tests/transitive_pinned_dependency1/input.js index 565410ca01..7ac7da56f3 100644 --- a/tests/build_tests/transitive_pinned_dependency1/input.js +++ b/tests/build_tests/transitive_pinned_dependency1/input.js @@ -1,14 +1,15 @@ -//@ts-check -var child_process = require("child_process"); -var assert = require("assert"); -var fs = require("fs"); -var { rescript_exe } = require("#cli/bin_path"); - -console.log( - child_process.execSync(rescript_exe, { encoding: "utf8", cwd: "./a" }), -); +// @ts-check + +import * as assert from "node:assert"; +import { existsSync } from "node:fs"; +import { setup } from "#dev/process"; + +const { execBuild } = setup("./a"); + +const output = await execBuild(); +console.log(output); -assert( - fs.existsSync("./node_modules/c/lib/js/tests/test.mjs"), +assert.ok( + existsSync("./node_modules/c/lib/es6/tests/test.res.js"), "dev files of module 'c' were not built by 'a' even though 'c' is a transitive pinned dependency of 'a' through 'b'", ); diff --git a/tests/build_tests/transitive_pinned_dependency1/node_modules/b/bsconfig.json b/tests/build_tests/transitive_pinned_dependency1/node_modules/b/bsconfig.json index 1bbb63d9e1..47680b2c98 100644 --- a/tests/build_tests/transitive_pinned_dependency1/node_modules/b/bsconfig.json +++ b/tests/build_tests/transitive_pinned_dependency1/node_modules/b/bsconfig.json @@ -1,27 +1,27 @@ { - "name": "b", - "namespace": true, - "sources": [ - { - "dir": "src" - }, - { - "dir": "tests", - "type": "dev" - } - ], - "package-specs": { - "module": "commonjs", - "in-source": false + "name": "b", + "namespace": true, + "sources": [ + { + "dir": "src" }, - "warnings": { - "error": true - }, - "suffix": ".mjs", - "bs-dependencies": [ - "c" - ], - "pinned-dependencies": [ - "c" - ] -} \ No newline at end of file + { + "dir": "tests", + "type": "dev" + } + ], + "package-specs": { + "module": "esmodule", + "in-source": false, + "suffix": ".res.js" + }, + "warnings": { + "error": true + }, + "bs-dependencies": [ + "c" + ], + "pinned-dependencies": [ + "c" + ] +} diff --git a/tests/build_tests/transitive_pinned_dependency1/node_modules/c/bsconfig.json b/tests/build_tests/transitive_pinned_dependency1/node_modules/c/bsconfig.json index c481bde6ef..aeb18883bb 100644 --- a/tests/build_tests/transitive_pinned_dependency1/node_modules/c/bsconfig.json +++ b/tests/build_tests/transitive_pinned_dependency1/node_modules/c/bsconfig.json @@ -1,21 +1,21 @@ { - "name": "c", - "namespace": true, - "sources": [ - { - "dir": "src" - }, - { - "dir": "tests", - "type": "dev" - } - ], - "package-specs": { - "module": "commonjs", - "in-source": false + "name": "c", + "namespace": true, + "sources": [ + { + "dir": "src" }, - "warnings": { - "error": true - }, - "suffix": ".mjs" -} \ No newline at end of file + { + "dir": "tests", + "type": "dev" + } + ], + "package-specs": { + "module": "esmodule", + "in-source": false, + "suffix": ".res.js" + }, + "warnings": { + "error": true + } +} diff --git a/tests/build_tests/transitive_pinned_dependency2/a/rescript.json b/tests/build_tests/transitive_pinned_dependency2/a/rescript.json index 40bd9a1a7d..42e66a06c4 100644 --- a/tests/build_tests/transitive_pinned_dependency2/a/rescript.json +++ b/tests/build_tests/transitive_pinned_dependency2/a/rescript.json @@ -11,12 +11,12 @@ } ], "package-specs": { - "module": "commonjs", - "in-source": false + "module": "esmodule", + "in-source": false, + "suffix": ".res.js" }, "warnings": { "error": true }, - "suffix": ".mjs", "bs-dependencies": ["b"] } diff --git a/tests/build_tests/transitive_pinned_dependency2/input.js b/tests/build_tests/transitive_pinned_dependency2/input.js index aa9c501afc..31f05eab92 100644 --- a/tests/build_tests/transitive_pinned_dependency2/input.js +++ b/tests/build_tests/transitive_pinned_dependency2/input.js @@ -1,14 +1,15 @@ -//@ts-check -var child_process = require("child_process"); -var assert = require("assert"); -var fs = require("fs"); -var { rescript_exe } = require("#cli/bin_path"); - -console.log( - child_process.execSync(rescript_exe, { encoding: "utf8", cwd: "./a" }), -); +// @ts-check + +import * as assert from "node:assert"; +import { existsSync } from "node:fs"; +import { setup } from "#dev/process"; + +const { execBuild } = setup("./a"); + +const output = await execBuild(); +console.log(output); -assert( - !fs.existsSync("./node_modules/c/lib/js/tests/test.mjs"), +assert.ok( + !existsSync("./node_modules/c/lib/es6/tests/test.res.js"), "dev files of module 'c' were built by 'a' even though 'c' is not a pinned dependency of 'a'", ); diff --git a/tests/build_tests/transitive_pinned_dependency2/node_modules/b/bsconfig.json b/tests/build_tests/transitive_pinned_dependency2/node_modules/b/bsconfig.json index 1bbb63d9e1..2fdd222a49 100644 --- a/tests/build_tests/transitive_pinned_dependency2/node_modules/b/bsconfig.json +++ b/tests/build_tests/transitive_pinned_dependency2/node_modules/b/bsconfig.json @@ -1,27 +1,27 @@ { - "name": "b", - "namespace": true, - "sources": [ - { - "dir": "src" - }, - { - "dir": "tests", - "type": "dev" - } - ], - "package-specs": { - "module": "commonjs", - "in-source": false + "name": "b", + "namespace": true, + "sources": [ + { + "dir": "src" }, - "warnings": { - "error": true - }, - "suffix": ".mjs", - "bs-dependencies": [ - "c" - ], - "pinned-dependencies": [ - "c" - ] -} \ No newline at end of file + { + "dir": "tests", + "type": "dev" + } + ], + "package-specs": { + "module": "commonjs", + "in-source": false + }, + "warnings": { + "error": true + }, + "suffix": ".mjs", + "bs-dependencies": [ + "c" + ], + "pinned-dependencies": [ + "c" + ] +} diff --git a/tests/build_tests/transitive_pinned_dependency2/node_modules/c/bsconfig.json b/tests/build_tests/transitive_pinned_dependency2/node_modules/c/bsconfig.json index c481bde6ef..aeb18883bb 100644 --- a/tests/build_tests/transitive_pinned_dependency2/node_modules/c/bsconfig.json +++ b/tests/build_tests/transitive_pinned_dependency2/node_modules/c/bsconfig.json @@ -1,21 +1,21 @@ { - "name": "c", - "namespace": true, - "sources": [ - { - "dir": "src" - }, - { - "dir": "tests", - "type": "dev" - } - ], - "package-specs": { - "module": "commonjs", - "in-source": false + "name": "c", + "namespace": true, + "sources": [ + { + "dir": "src" }, - "warnings": { - "error": true - }, - "suffix": ".mjs" -} \ No newline at end of file + { + "dir": "tests", + "type": "dev" + } + ], + "package-specs": { + "module": "esmodule", + "in-source": false, + "suffix": ".res.js" + }, + "warnings": { + "error": true + } +} diff --git a/tests/build_tests/unboxed_bool_with_const/input.js b/tests/build_tests/unboxed_bool_with_const/input.js index 59b01f8273..dd2470e600 100644 --- a/tests/build_tests/unboxed_bool_with_const/input.js +++ b/tests/build_tests/unboxed_bool_with_const/input.js @@ -1,14 +1,12 @@ -//@ts-check +// @ts-check -var cp = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); -var { normalizeNewlines } = require("../utils.js"); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; +import { normalizeNewlines } from "#dev/utils"; -var out = cp.spawnSync(rescript_exe, { - cwd: __dirname, - encoding: "utf8", -}); +const { execBuild } = setup(import.meta.dirname); + +const out = await execBuild(); assert.equal( normalizeNewlines(out.stdout.slice(out.stdout.indexOf("Main.res:3:3-14"))), diff --git a/tests/build_tests/unboxed_bool_with_const/bsconfig.json b/tests/build_tests/unboxed_bool_with_const/rescript.json similarity index 67% rename from tests/build_tests/unboxed_bool_with_const/bsconfig.json rename to tests/build_tests/unboxed_bool_with_const/rescript.json index 1cbcace50a..186e6f201b 100644 --- a/tests/build_tests/unboxed_bool_with_const/bsconfig.json +++ b/tests/build_tests/unboxed_bool_with_const/rescript.json @@ -8,8 +8,8 @@ } ], "package-specs": { - "module": "commonjs", - "in-source": true - }, - "suffix": ".bs.js" + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" + } } diff --git a/tests/build_tests/uncurried-always/input.js b/tests/build_tests/uncurried-always/input.js index a7370b0c2f..6d8beddd22 100644 --- a/tests/build_tests/uncurried-always/input.js +++ b/tests/build_tests/uncurried-always/input.js @@ -1,6 +1,8 @@ -//@ts-check -const cp = require("child_process"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -cp.execSync(`${rescript_exe} clean`, { cwd: __dirname }); -cp.execSync(`${rescript_exe}`, { cwd: __dirname }); +import { setup } from "#dev/process"; + +const { execBuild, execClean } = setup(import.meta.dirname); + +await execClean(); +await execBuild(); diff --git a/tests/build_tests/unicode/input.js b/tests/build_tests/unicode/input.js index 2e7443629b..4723a8f55c 100644 --- a/tests/build_tests/unicode/input.js +++ b/tests/build_tests/unicode/input.js @@ -1,20 +1,21 @@ -//@ts-check -var child_process = require("child_process"); -var fs = require("fs"); -var path = require("path"); +// @ts-check -var { rescript_exe } = require("#cli/bin_path"); +import * as assert from "node:assert"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); if (process.platform === "win32") { console.log("Skipping test on Windows"); process.exit(0); } -console.log(child_process.execSync(rescript_exe, { encoding: "utf8" })); - -var content = - "" + fs.readFileSync(path.join(__dirname, "lib", "bs", ".sourcedirs.json")); - -var assert = require("assert"); +await execBuild(); +const content = await fs.readFile( + path.join("lib", "bs", ".sourcedirs.json"), + "utf-8", +); -assert(JSON.parse(content).dirs.some(x => x.includes("📕annotation"))); +assert.ok(JSON.parse(content).dirs.some(x => x.includes("📕annotation"))); diff --git a/tests/build_tests/utils.js b/tests/build_tests/utils.js deleted file mode 100644 index d0715e907f..0000000000 --- a/tests/build_tests/utils.js +++ /dev/null @@ -1,60 +0,0 @@ -const child_process = require("child_process"); - -const signals = { - SIGINT: 2, - SIGQUIT: 3, - SIGKILL: 9, - SIGTERM: 15, -}; - -/** - * @param {string} command - * @param {Array} args - * @param {child_process.SpawnOptions} [options] - */ -async function exec(command, args, options) { - const stdoutChunks = []; - const stderrChunks = []; - - const subprocess = child_process.spawn(command, args, { - stdio: ["ignore", "pipe", "pipe"], - ...options, - }); - - subprocess.stdout.on("data", chunk => { - stdoutChunks.push(chunk); - }); - - subprocess.stderr.on("data", chunk => { - stderrChunks.push(chunk); - }); - - return await new Promise((resolve, reject) => { - subprocess.once("error", err => { - reject(err); - }); - - subprocess.once("close", (exitCode, signal) => { - const stdout = Buffer.concat(stdoutChunks).toString("utf8"); - const stderr = Buffer.concat(stderrChunks).toString("utf8"); - - let code = exitCode ?? 1; - if (signals[signal]) { - // + 128 is standard POSIX practice, see also https://nodejs.org/api/process.html#exit-codes - code = signals[signal] + 128; - } - - resolve({ status: code, stdout, stderr }); - }); - }); -} - -/** - * @param {string} s - */ -function normalizeNewlines(s) { - return s.replace(/\r\n/g, '\n'); -} - -exports.exec = exec; -exports.normalizeNewlines = normalizeNewlines; diff --git a/tests/build_tests/warn_legacy_config/input.js b/tests/build_tests/warn_legacy_config/input.js index 6a273a047f..e079332080 100644 --- a/tests/build_tests/warn_legacy_config/input.js +++ b/tests/build_tests/warn_legacy_config/input.js @@ -1,10 +1,12 @@ -const { spawnSync } = require("child_process"); -const assert = require("assert"); -const { rescript_exe } = require("#cli/bin_path"); +// @ts-check -const output = spawnSync(rescript_exe, { encoding: "utf8" }); -assert( - /^Warning: bsconfig.json is deprecated. Migrate it to rescript.json/.test( - output.stdout, - ), +import * as assert from "node:assert"; +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +const output = await execBuild(); +assert.match( + output.stdout, + /^Warning: bsconfig.json is deprecated. Migrate it to rescript.json/, ); diff --git a/tests/build_tests/weird_deps/input.js b/tests/build_tests/weird_deps/input.js index d76198e96e..b5d4af7317 100644 --- a/tests/build_tests/weird_deps/input.js +++ b/tests/build_tests/weird_deps/input.js @@ -1,15 +1,12 @@ -//@ts-check +// @ts-check -var cp = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); -var { normalizeNewlines } = require("../utils.js"); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; +import { normalizeNewlines } from "#dev/utils"; -var out = cp.spawnSync(rescript_exe, { - cwd: __dirname, - encoding: "utf8", -}); +const { execBuild } = setup(import.meta.dirname); +const out = await execBuild(); if (out.stdout !== "") { assert.fail(out.stdout); } else { diff --git a/tests/build_tests/weird_deps/rescript.json b/tests/build_tests/weird_deps/rescript.json index 4dc59a53e5..30c2891d34 100644 --- a/tests/build_tests/weird_deps/rescript.json +++ b/tests/build_tests/weird_deps/rescript.json @@ -12,10 +12,10 @@ } ], "package-specs": { - "module": "commonjs", - "in-source": true + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" }, - "suffix": ".bs.js", "bs-dependencies": ["weird"], "warnings": { "error": "+101" } } diff --git a/tests/build_tests/weird_devdeps/input.js b/tests/build_tests/weird_devdeps/input.js index 77d621f892..fa9afcce6c 100644 --- a/tests/build_tests/weird_devdeps/input.js +++ b/tests/build_tests/weird_devdeps/input.js @@ -1,15 +1,12 @@ -//@ts-check +// @ts-check -var cp = require("child_process"); -var assert = require("assert"); -var os = require("os"); -var rescript_exe = require("#cli/bin_path").rescript_exe; +import * as assert from "node:assert"; +import * as os from "node:os"; +import { setup } from "#dev/process"; -var out = cp.spawnSync(rescript_exe, { - cwd: __dirname, - encoding: "utf8", -}); +const { execBuild } = setup(import.meta.dirname); +const out = await execBuild(); if (out.stdout !== "") { assert.fail(out.stdout); } else { diff --git a/tests/build_tests/weird_devdeps/rescript.json b/tests/build_tests/weird_devdeps/rescript.json index 91696bc454..85174f02e8 100644 --- a/tests/build_tests/weird_devdeps/rescript.json +++ b/tests/build_tests/weird_devdeps/rescript.json @@ -12,10 +12,10 @@ } ], "package-specs": { - "module": "commonjs", - "in-source": true + "module": "esmodule", + "in-source": true, + "suffix": ".res.js" }, - "suffix": ".bs.js", "bs-dependencies": [], "bs-dev-dependencies": ["weird"], "warnings": { "error": "+101" } diff --git a/tests/build_tests/weird_names/input.js b/tests/build_tests/weird_names/input.js index c8e27d5371..56347603ae 100644 --- a/tests/build_tests/weird_names/input.js +++ b/tests/build_tests/weird_names/input.js @@ -1,15 +1,18 @@ -var cp = require("child_process"); -var assert = require("assert"); -var path = require("path"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -var out = cp.spawnSync(rescript_exe, { encoding: "utf8" }); +import * as assert from "node:assert"; +import * as path from "node:path"; +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +const out = await execBuild(); if (out.stderr !== "") { assert.fail(out.stderr); } -let files = [ +const files = [ "_app.res", "[...params_max_3].res", "[...params].res", @@ -19,8 +22,8 @@ let files = [ "utils.test.res", ]; -for (let f of files) { - let { name } = path.parse(f); - let m = `./lib/js/src/${name}.js`; - assert.deepEqual(require(m).a, 1); +for (const f of files) { + const { name } = path.parse(f); + const mod = await import(`./lib/es6/src/${name}.js`); + assert.deepEqual(mod.a, 1); } diff --git a/tests/build_tests/weird_names/rescript.json b/tests/build_tests/weird_names/rescript.json index 305524ed2c..357d524c49 100644 --- a/tests/build_tests/weird_names/rescript.json +++ b/tests/build_tests/weird_names/rescript.json @@ -4,5 +4,8 @@ "sources": { "dir": "src", "subdirs": true + }, + "package-specs": { + "module": "esmodule" } } diff --git a/tests/build_tests/weird_names_not_found_bug/input.js b/tests/build_tests/weird_names_not_found_bug/input.js index 3bb70620c5..078fb29aed 100644 --- a/tests/build_tests/weird_names_not_found_bug/input.js +++ b/tests/build_tests/weird_names_not_found_bug/input.js @@ -1,8 +1,10 @@ -var cp = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); +import * as assert from "node:assert"; +import { setup } from "#dev/process"; + +const { execBuild } = await setup(import.meta.dirname); + +const out = await execBuild(); -var out = cp.spawnSync(rescript_exe, { encoding: "utf8" }); if (out.stderr !== "") { assert.fail(out.stderr); } diff --git a/tests/build_tests/weird_names_not_found_bug/rescript.json b/tests/build_tests/weird_names_not_found_bug/rescript.json index 305524ed2c..357d524c49 100644 --- a/tests/build_tests/weird_names_not_found_bug/rescript.json +++ b/tests/build_tests/weird_names_not_found_bug/rescript.json @@ -4,5 +4,8 @@ "sources": { "dir": "src", "subdirs": true + }, + "package-specs": { + "module": "esmodule" } } diff --git a/tests/build_tests/x-y/input.js b/tests/build_tests/x-y/input.js index 1b2ea568cb..50a4ceabd1 100644 --- a/tests/build_tests/x-y/input.js +++ b/tests/build_tests/x-y/input.js @@ -1,4 +1,7 @@ -var p = require("child_process"); -var { rescript_exe } = require("#cli/bin_path"); +// @ts-check -p.execSync(rescript_exe); +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); + +await execBuild(); diff --git a/tests/build_tests/xpkg/input.js b/tests/build_tests/xpkg/input.js index d499746478..664cb16cd1 100644 --- a/tests/build_tests/xpkg/input.js +++ b/tests/build_tests/xpkg/input.js @@ -1,12 +1,9 @@ -var p = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); -try { - var output = p.spawnSync(`${rescript_exe} build -regen`, { - shell: true, - encoding: "utf8", - }); +// @ts-check - assert.ok(output.stderr.match(/reserved package name/)); -} finally { -} +import * as assert from "node:assert"; +import { setup } from "#dev/process"; + +const { execBuild } = await setup(import.meta.dirname); + +const output = await execBuild(["-regen"]); +assert.match(output.stderr, /reserved package name/); diff --git a/tests/build_tests/zerocycle/input.js b/tests/build_tests/zerocycle/input.js index aa23bdbc08..c81430b7c7 100644 --- a/tests/build_tests/zerocycle/input.js +++ b/tests/build_tests/zerocycle/input.js @@ -1,5 +1,8 @@ -var p = require("child_process"); -var assert = require("assert"); -var { rescript_exe } = require("#cli/bin_path"); -var out = p.spawnSync(rescript_exe, { encoding: "utf8", cwd: __dirname }); -assert(out.status == 0); +// @ts-check + +import * as assert from "node:assert"; +import { setup } from "#dev/process"; + +const { execBuild } = setup(import.meta.dirname); +const output = await execBuild(); +assert.ok(output.status === 0); diff --git a/tests/build_tests/zerocycle/rescript.json b/tests/build_tests/zerocycle/rescript.json index 4210d87b96..1c3fa9736f 100644 --- a/tests/build_tests/zerocycle/rescript.json +++ b/tests/build_tests/zerocycle/rescript.json @@ -3,9 +3,9 @@ "version": "0.1.0", "sources": ["src"], "package-specs": { - "module": "commonjs", + "module": "esmodule", "in-source": true }, - "suffix": ".bs.js", + "suffix": ".res.js", "bs-dependencies": [] } diff --git a/tests/build_tests/zerocycle/src/bar.res.js b/tests/build_tests/zerocycle/src/bar.res.js new file mode 100644 index 0000000000..c1a2d01a74 --- /dev/null +++ b/tests/build_tests/zerocycle/src/bar.res.js @@ -0,0 +1,18 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +let Bar = {}; + +let Nested = { + Bar: Bar +}; + +let Bar$1 = { + t: 42 +}; + +export { + Nested, + Bar$1 as Bar, +} +/* No side effect */ diff --git a/tests/build_tests/zerocycle/src/demo.res.js b/tests/build_tests/zerocycle/src/demo.res.js new file mode 100644 index 0000000000..0e473e85e6 --- /dev/null +++ b/tests/build_tests/zerocycle/src/demo.res.js @@ -0,0 +1,9 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +let Foo = {}; + +export { + Foo, +} +/* No side effect */ diff --git a/tests/build_tests/zerocycle/src/demo2.res.js b/tests/build_tests/zerocycle/src/demo2.res.js new file mode 100644 index 0000000000..59cc76cd64 --- /dev/null +++ b/tests/build_tests/zerocycle/src/demo2.res.js @@ -0,0 +1,9 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +let Foo2 = {}; + +export { + Foo2, +} +/* No side effect */ diff --git a/tests/docstring_tests/Mocha.res.mjs b/tests/build_tests/zerocycle/src/foo.res.js similarity index 100% rename from tests/docstring_tests/Mocha.res.mjs rename to tests/build_tests/zerocycle/src/foo.res.js diff --git a/tests/build_tests/zerocycle/src/foo2.res.js b/tests/build_tests/zerocycle/src/foo2.res.js new file mode 100644 index 0000000000..d856702bfe --- /dev/null +++ b/tests/build_tests/zerocycle/src/foo2.res.js @@ -0,0 +1,2 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE +/* This output is empty. Its source's type definitions, externals and/or unused code got optimized away. */ diff --git a/tests/docstring_tests/.gitignore b/tests/docstring_tests/.gitignore index 448ac7b39c..57ede28ad4 100644 --- a/tests/docstring_tests/.gitignore +++ b/tests/docstring_tests/.gitignore @@ -1,2 +1 @@ -generated_mocha_test.res -generated_mocha_test.res.mjs +generated_mocha_test.res* diff --git a/tests/docstring_tests/ArrayUtils.res.mjs b/tests/docstring_tests/ArrayUtils.res.js similarity index 100% rename from tests/docstring_tests/ArrayUtils.res.mjs rename to tests/docstring_tests/ArrayUtils.res.js diff --git a/tests/docstring_tests/DocTest.res b/tests/docstring_tests/DocTest.res index bcb0bcba5f..f974435984 100644 --- a/tests/docstring_tests/DocTest.res +++ b/tests/docstring_tests/DocTest.res @@ -47,7 +47,7 @@ let getOutput = buffer => ->Array.join("") let extractDocFromFile = async file => { - let toolsBin = Path.join([Process.cwd(), "cli", "rescript-tools"]) + let toolsBin = Path.join([Process.cwd(), "cli", "rescript-tools.js"]) let {stdout} = await SpawnAsync.run(~command=toolsBin, ~args=["doc", file]) diff --git a/tests/docstring_tests/DocTest.res.mjs b/tests/docstring_tests/DocTest.res.js similarity index 92% rename from tests/docstring_tests/DocTest.res.mjs rename to tests/docstring_tests/DocTest.res.js index 8ce01923db..2c75b3a9ad 100644 --- a/tests/docstring_tests/DocTest.res.mjs +++ b/tests/docstring_tests/DocTest.res.js @@ -1,14 +1,14 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -import * as Fs from "fs"; -import * as Os from "os"; -import * as Url from "url"; -import * as Path from "path"; import * as Stdlib from "rescript/lib/es6/Stdlib.js"; +import * as Nodefs from "node:fs"; +import * as Nodeos from "node:os"; +import * as Nodeurl from "node:url"; import * as Belt_List from "rescript/lib/es6/Belt_List.js"; -import * as ArrayUtils from "./ArrayUtils.res.mjs"; +import * as Nodepath from "node:path"; +import * as ArrayUtils from "./ArrayUtils.res.js"; import * as Belt_Array from "rescript/lib/es6/Belt_Array.js"; -import * as SpawnAsync from "./SpawnAsync.res.mjs"; +import * as SpawnAsync from "./SpawnAsync.res.js"; import * as Stdlib_Exn from "rescript/lib/es6/Stdlib_Exn.js"; import * as Stdlib_Int from "rescript/lib/es6/Stdlib_Int.js"; import * as Stdlib_Dict from "rescript/lib/es6/Stdlib_Dict.js"; @@ -51,7 +51,7 @@ function getOutput(buffer) { } async function extractDocFromFile(file) { - let toolsBin = Path.join(process.cwd(), "cli", "rescript-tools"); + let toolsBin = Nodepath.join(process.cwd(), "cli", "rescript-tools.js"); let match = await SpawnAsync.run(toolsBin, [ "doc", file @@ -204,10 +204,10 @@ function getCodeBlocks(example) { return Belt_Array.reverse(Stdlib_List.toArray(loop(Stdlib_List.fromArray(Stdlib_Array.reduce(example.docstrings, [], (acc, docstring) => acc.concat(docstring.split("\n")))), /* [] */0))).join("\n\n"); } -let batchSize = Os.cpus().length; +let batchSize = Nodeos.cpus().length; async function extractExamples() { - let files = Fs.readdirSync("runtime"); + let files = Nodefs.readdirSync("runtime"); let docFiles = files.filter(f => { if (f.startsWith("Js") || f.startsWith("RescriptTools") || f.startsWith("Stdlib_")) { return false; @@ -222,7 +222,7 @@ async function extractExamples() { console.log("Extracting examples from " + docFiles.length.toString() + " runtime files..."); let examples = []; await ArrayUtils.forEachAsyncInBatches(docFiles, batchSize, async f => { - let doc = await extractDocFromFile(Path.join("runtime", f)); + let doc = await extractDocFromFile(Nodepath.join("runtime", f)); examples.push(...getExamples(doc)); }); examples.sort((a, b) => Primitive_string.compare(a.id, b.id)); @@ -267,8 +267,8 @@ async function main() { let content = "describe(\"" + key + "\", () => {\n" + codeExamples.join("\n") + "\n })"; output.push(content); }); - let dirname = Path.dirname(Url.fileURLToPath(import.meta.url)); - let filepath = Path.join(dirname, "generated_mocha_test.res"); + let dirname = Nodepath.dirname(Nodeurl.fileURLToPath(import.meta.url)); + let filepath = Nodepath.join(dirname, "generated_mocha_test.res"); let fileContent = "open Mocha\n@@warning(\"-32-34-60-37-109-3-44\")\n\n" + output.join("\n"); return await Promises.writeFile(filepath, fileContent); } diff --git a/tests/docstring_tests/Mocha.res.js b/tests/docstring_tests/Mocha.res.js new file mode 100644 index 0000000000..d856702bfe --- /dev/null +++ b/tests/docstring_tests/Mocha.res.js @@ -0,0 +1,2 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE +/* This output is empty. Its source's type definitions, externals and/or unused code got optimized away. */ diff --git a/tests/docstring_tests/Node.res b/tests/docstring_tests/Node.res index 2182b31703..95eb4241bc 100644 --- a/tests/docstring_tests/Node.res +++ b/tests/docstring_tests/Node.res @@ -1,6 +1,6 @@ module Path = { - @module("path") @variadic external join: array => string = "join" - @module("path") external dirname: string => string = "dirname" + @module("node:path") @variadic external join: array => string = "join" + @module("node:path") external dirname: string => string = "dirname" } module Process = { @@ -9,7 +9,7 @@ module Process = { } module Fs = { - @module("fs") external readdirSync: string => array = "readdirSync" + @module("node:fs") external readdirSync: string => array = "readdirSync" @module("node:fs/promises") external writeFile: (string, string) => promise = "writeFile" } @@ -22,7 +22,7 @@ module ChildProcess = { type readable type spawnReturns = {stderr: readable, stdout: readable} type options = {cwd?: string, env?: Dict.t, timeout?: int} - @module("child_process") + @module("node:child_process") external spawn: (string, array, ~options: options=?) => spawnReturns = "spawn" @send external on: (readable, string, Buffer.t => unit) => unit = "on" @@ -32,12 +32,12 @@ module ChildProcess = { } module OS = { - @module("os") + @module("node:os") external cpus: unit => array<{.}> = "cpus" } module URL = { - @module("url") external fileURLToPath: string => string = "fileURLToPath" + @module("node:url") external fileURLToPath: string => string = "fileURLToPath" } @val @scope(("import", "meta")) external url: string = "url" diff --git a/tests/docstring_tests/Node.res.mjs b/tests/docstring_tests/Node.res.js similarity index 100% rename from tests/docstring_tests/Node.res.mjs rename to tests/docstring_tests/Node.res.js diff --git a/tests/docstring_tests/SpawnAsync.res.mjs b/tests/docstring_tests/SpawnAsync.res.js similarity index 74% rename from tests/docstring_tests/SpawnAsync.res.mjs rename to tests/docstring_tests/SpawnAsync.res.js index 22c6d33dae..0f56176257 100644 --- a/tests/docstring_tests/SpawnAsync.res.mjs +++ b/tests/docstring_tests/SpawnAsync.res.js @@ -1,10 +1,10 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -import * as Child_process from "child_process"; import * as Primitive_option from "rescript/lib/es6/Primitive_option.js"; +import * as Nodechild_process from "node:child_process"; async function run(command, args, options) { - let spawn = Child_process.spawn(command, args, options !== undefined ? Primitive_option.valFromOption(options) : undefined); + let spawn = Nodechild_process.spawn(command, args, options !== undefined ? Primitive_option.valFromOption(options) : undefined); let stdout = []; let stderr = []; spawn.stdout.on("data", data => { @@ -30,4 +30,4 @@ async function run(command, args, options) { export { run, } -/* child_process Not a pure module */ +/* node:child_process Not a pure module */ diff --git a/tests/docstring_tests/rescript.json b/tests/docstring_tests/rescript.json index e987791ab6..d8b223e112 100644 --- a/tests/docstring_tests/rescript.json +++ b/tests/docstring_tests/rescript.json @@ -7,5 +7,5 @@ "module": "esmodule", "in-source": true }, - "suffix": ".res.mjs" + "suffix": ".res.js" } diff --git a/tests/gentype_tests/typescript-react-example/Makefile b/tests/gentype_tests/typescript-react-example/Makefile index 7a821b93a4..5062da0431 100644 --- a/tests/gentype_tests/typescript-react-example/Makefile +++ b/tests/gentype_tests/typescript-react-example/Makefile @@ -1,9 +1,9 @@ SHELL = /bin/bash test: - npm run lint + npm run check npm run build - npm run tsc + npm run typecheck @git diff --quiet src/ \ || { echo; echo "Please review the Gentype outputs too!"; echo; false; } \ || exit 1 diff --git a/tests/gentype_tests/typescript-react-example/biome.json b/tests/gentype_tests/typescript-react-example/biome.json index d9c8975046..f89a93677e 100644 --- a/tests/gentype_tests/typescript-react-example/biome.json +++ b/tests/gentype_tests/typescript-react-example/biome.json @@ -1,11 +1,13 @@ { - "$schema": "https://biomejs.dev/schemas/1.8.3/schema.json", + "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", "extends": ["../../../biome.json"], "linter": { - "enabled": true, - "rules": { - "recommended": true - }, + "ignore": ["**/*.res.js", "**/*.gen.ts*"] + }, + "organizeImports": { + "ignore": ["**/*.res.js", "**/*.gen.ts*"] + }, + "formatter": { "ignore": ["**/*.res.js", "**/*.gen.ts*"] } } diff --git a/tests/gentype_tests/typescript-react-example/package.json b/tests/gentype_tests/typescript-react-example/package.json index 861e6c2c13..721b4bf4ba 100644 --- a/tests/gentype_tests/typescript-react-example/package.json +++ b/tests/gentype_tests/typescript-react-example/package.json @@ -5,8 +5,8 @@ "start": "rescript build -w", "build": "rescript", "clean": "rescript clean", - "tsc": "tsc -p tsconfig.json", - "lint": "biome check src" + "typecheck": "tsc", + "check": "biome check --changed --no-errors-on-unmatched ." }, "dependencies": { "@rescript/react": "^0.13.1", @@ -15,10 +15,9 @@ "rescript": "workspace:^" }, "devDependencies": { - "@biomejs/biome": "1.8.3", - "@types/node": "^18.15.12", - "@types/react": "^18.3.19", - "@types/react-dom": "^18.3.5", - "typescript": "^5.2.2" + "@biomejs/biome": "1.9.4", + "@types/react": "^18.3.3", + "@types/react-dom": "^18.3.0", + "typescript": "5.8.2" } } diff --git a/tests/gentype_tests/typescript-react-example/src/App.css b/tests/gentype_tests/typescript-react-example/src/App.css index c5c6e8a68a..31be39dcc4 100644 --- a/tests/gentype_tests/typescript-react-example/src/App.css +++ b/tests/gentype_tests/typescript-react-example/src/App.css @@ -23,6 +23,10 @@ } @keyframes App-logo-spin { - from { transform: rotate(0deg); } - to { transform: rotate(360deg); } + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } } diff --git a/tests/gentype_tests/typescript-react-example/src/MyMath.ts b/tests/gentype_tests/typescript-react-example/src/MyMath.ts index 8727646f29..9c4db39420 100644 --- a/tests/gentype_tests/typescript-react-example/src/MyMath.ts +++ b/tests/gentype_tests/typescript-react-example/src/MyMath.ts @@ -21,7 +21,7 @@ export class AbsoluteValue { export type stringFunction = (_: string) => string; -export const useColor = (x: "tomato" | "gray"): number => 0; +export const useColor = (_x: "tomato" | "gray"): number => 0; export const higherOrder = (foo: (_1: number, _2: number) => number) => foo(3, 4); diff --git a/tests/gentype_tests/typescript-react-example/src/index.tsx b/tests/gentype_tests/typescript-react-example/src/index.tsx index 1bdb73f6c2..1fdcd83b2c 100644 --- a/tests/gentype_tests/typescript-react-example/src/index.tsx +++ b/tests/gentype_tests/typescript-react-example/src/index.tsx @@ -1,16 +1,16 @@ import type * as React from "react"; import * as ReactDOM from "react-dom"; -import App from "./App"; -import * as ImportJsValue from "./ImportJsValue.gen"; -import * as Uncurried from "./Uncurried.gen"; +import App from "./App.tsx"; +import * as ImportJsValue from "./ImportJsValue.gen.tsx"; +import * as Uncurried from "./Uncurried.gen.tsx"; import "./index.css"; -import * as MyMath from "./MyMath"; -import * as Types from "./nested/Types.gen"; -import { Universe_Nested2_Nested3_nested3Value } from "./NestedModules.gen"; -import * as Records from "./Records.gen"; -import * as Variants from "./Variants.gen"; -import Hooks from "./Hooks.gen"; -import * as DocStrings from "./Docstrings.gen"; +import * as DocStrings from "./Docstrings.gen.tsx"; +import Hooks from "./Hooks.gen.tsx"; +import * as MyMath from "./MyMath.tsx"; +import { Universe_Nested2_Nested3_nested3Value } from "./NestedModules.gen.tsx"; +import * as Records from "./Records.gen.tsx"; +import * as TestPromise from "./TestPromise.gen.tsx"; +import * as Variants from "./Variants.gen.tsx"; import { printManyPayloads, printVariantWithPayload, @@ -18,8 +18,8 @@ import { testManyPayloads, testVariantWithPayloads, testWithPayload, -} from "./VariantsWithPayload.gen"; -import * as TestPromise from "./TestPromise.gen"; +} from "./VariantsWithPayload.gen.tsx"; +import * as Types from "./nested/Types.gen.tsx"; const consoleLog = console.log; @@ -126,7 +126,7 @@ type Props = { readonly method?: "push" | "replace"; }; -export const make: React.FC = (x: Props) => { +export const make: React.FC = (_x: Props) => { return
; }; diff --git a/tests/gentype_tests/typescript-react-example/tsconfig.json b/tests/gentype_tests/typescript-react-example/tsconfig.json index ab864d616d..589016b98d 100644 --- a/tests/gentype_tests/typescript-react-example/tsconfig.json +++ b/tests/gentype_tests/typescript-react-example/tsconfig.json @@ -1,13 +1,13 @@ { "compilerOptions": { - "target": "esnext", - "module": "esnext", - "moduleResolution": "node", - "lib": ["dom", "dom.iterable", "esnext"], + "module": "ESNext", + "moduleResolution": "Node", + "lib": ["DOM", "DOM.Iterable", "ESNext"], + "jsx": "react-jsx", "strict": true, "skipLibCheck": true, "allowJs": true, - "jsx": "react-jsx", + "allowImportingTsExtensions": true, "noEmit": true }, "include": ["src"] diff --git a/tests/gentype_tests/typescript-react-example/tsconfig.prod.json b/tests/gentype_tests/typescript-react-example/tsconfig.prod.json deleted file mode 100644 index fc8520e737..0000000000 --- a/tests/gentype_tests/typescript-react-example/tsconfig.prod.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "./tsconfig.json" -} diff --git a/tests/gentype_tests/typescript-react-example/tsconfig.test.json b/tests/gentype_tests/typescript-react-example/tsconfig.test.json deleted file mode 100644 index 2c7b284162..0000000000 --- a/tests/gentype_tests/typescript-react-example/tsconfig.test.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "module": "commonjs" - } -} diff --git a/tests/tests/rescript.json b/tests/tests/rescript.json index c7dfdd6f05..4a21d34945 100644 --- a/tests/tests/rescript.json +++ b/tests/tests/rescript.json @@ -15,4 +15,4 @@ "-w -3-6-26-27-29-30-32..40-44-45-52-60-9-106+104", "-warn-error A" ] -} \ No newline at end of file +} diff --git a/tests/tests/src/tagged_template_lib.js b/tests/tests/src/tagged_template_lib.js index 5b4a6ed8af..beaacb5b0a 100644 --- a/tests/tests/src/tagged_template_lib.js +++ b/tests/tests/src/tagged_template_lib.js @@ -1,4 +1,4 @@ -exports.sql = (strings, ...values) => { +export const sql = (strings, ...values) => { let result = ""; for (let i = 0; i < values.length; i++) { result += strings[i] + "'" + values[i] + "'"; @@ -7,6 +7,6 @@ exports.sql = (strings, ...values) => { return result; }; -exports.length = (strings, ...values) => +export const length = (strings, ...values) => strings.reduce((acc, curr) => acc + curr.length, 0) + values.reduce((acc, curr) => acc + curr, 0); diff --git a/tests/tools_tests/rescript.json b/tests/tools_tests/rescript.json index c7968f1bf4..d901f81336 100644 --- a/tests/tools_tests/rescript.json +++ b/tests/tools_tests/rescript.json @@ -5,7 +5,7 @@ "subdirs": true }, "package-specs": { - "module": "commonjs", + "module": "esmodule", "in-source": true }, "suffix": ".res.js", diff --git a/tests/tools_tests/src/expected/TestPpx.res.jsout b/tests/tools_tests/src/expected/TestPpx.res.jsout index 87ea7737ee..e69de29bb2 100644 --- a/tests/tools_tests/src/expected/TestPpx.res.jsout +++ b/tests/tools_tests/src/expected/TestPpx.res.jsout @@ -1,117 +0,0 @@ -// Generated by ReScript, PLEASE EDIT WITH CARE -'use strict'; - -let React = require("react"); - -console.log("ppx test"); - -console.log("ppx test"); - -let M = { - v: 10 -}; - -let OptionalFields = { - r: { - y: 1.0 - } -}; - -function one(x) { - return x; -} - -function two(x, y) { - return x + y | 0; -} - -let n = 6; - -let Arity = { - one: one, - two: two, - n: n -}; - -React.useState(() => 0); - -async function fpromise(promise, _x) { - return await promise; -} - -let Uncurried = {}; - -async function async_succ(x) { - return x + 1 | 0; -} - -async function async_foo(x, y) { - let a = async_succ(x); - let b = async_succ(y); - return await a + await b | 0; -} - -function add(x, y) { - return x + y | 0; -} - -function partial_add(extra) { - return 3 + extra | 0; -} - -function plus(x, y) { - return x + y | 0; -} - -let z = 3; - -let Pipe = { - plus: plus, - z: z -}; - -let concat = "ab"; - -async function test() { - return 12; -} - -async function f() { - return await test() + 1 | 0; -} - -let a = "A"; - -let b = "B"; - -let vv = 10; - -let neq = false; - -let neq2 = false; - -let eq = true; - -let eq2 = true; - -exports.a = a; -exports.b = b; -exports.M = M; -exports.vv = vv; -exports.OptionalFields = OptionalFields; -exports.Arity = Arity; -exports.fpromise = fpromise; -exports.Uncurried = Uncurried; -exports.async_succ = async_succ; -exports.async_foo = async_foo; -exports.add = add; -exports.partial_add = partial_add; -exports.Pipe = Pipe; -exports.concat = concat; -exports.neq = neq; -exports.neq2 = neq2; -exports.eq = eq; -exports.eq2 = eq2; -exports.test = test; -exports.f = f; -/* Not a pure module */ diff --git a/tools/rescript.json b/tools/rescript.json index 26ece932ef..1fa23c615a 100644 --- a/tools/rescript.json +++ b/tools/rescript.json @@ -6,9 +6,9 @@ "dir": "npm" } ], - "suffix": ".bs.js", + "suffix": ".res.js", "package-specs": { - "module": "commonjs", + "module": "esmodule", "in-source": false } } diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000000..3778657f66 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "allowJs": true, + "resolveJsonModule": true, + "strict": true, + "strictNullChecks": true, + "noImplicitAny": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": [ + "cli/*", + "lib/*", + "lib_dev/*", + "scripts/*", + "tests/**/input.js", + ".github/workflows/*.js", + "package.json" + ], + "exclude": ["*.res.js", "*.res.mjs"] +} diff --git a/yarn.lock b/yarn.lock index cdfccb6b60..521187df7b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -183,18 +183,18 @@ __metadata: languageName: node linkType: hard -"@biomejs/biome@npm:1.8.3": - version: 1.8.3 - resolution: "@biomejs/biome@npm:1.8.3" - dependencies: - "@biomejs/cli-darwin-arm64": "npm:1.8.3" - "@biomejs/cli-darwin-x64": "npm:1.8.3" - "@biomejs/cli-linux-arm64": "npm:1.8.3" - "@biomejs/cli-linux-arm64-musl": "npm:1.8.3" - "@biomejs/cli-linux-x64": "npm:1.8.3" - "@biomejs/cli-linux-x64-musl": "npm:1.8.3" - "@biomejs/cli-win32-arm64": "npm:1.8.3" - "@biomejs/cli-win32-x64": "npm:1.8.3" +"@biomejs/biome@npm:1.9.4": + version: 1.9.4 + resolution: "@biomejs/biome@npm:1.9.4" + dependencies: + "@biomejs/cli-darwin-arm64": "npm:1.9.4" + "@biomejs/cli-darwin-x64": "npm:1.9.4" + "@biomejs/cli-linux-arm64": "npm:1.9.4" + "@biomejs/cli-linux-arm64-musl": "npm:1.9.4" + "@biomejs/cli-linux-x64": "npm:1.9.4" + "@biomejs/cli-linux-x64-musl": "npm:1.9.4" + "@biomejs/cli-win32-arm64": "npm:1.9.4" + "@biomejs/cli-win32-x64": "npm:1.9.4" dependenciesMeta: "@biomejs/cli-darwin-arm64": optional: true @@ -214,62 +214,62 @@ __metadata: optional: true bin: biome: bin/biome - checksum: 10c0/95fe99ce82cd8242f1be51cbf3ac26043b253f5a369d3dc24df09bdb32ec04dba679b1d4fa8b9d602b1bf2c30ecd80af14aa8f5c92d6e0cd6214a99a1099a65b + checksum: 10c0/b5655c5aed9a6fffe24f7d04f15ba4444389d0e891c9ed9106fab7388ac9b4be63185852cc2a937b22940dac3e550b71032a4afd306925cfea436c33e5646b3e languageName: node linkType: hard -"@biomejs/cli-darwin-arm64@npm:1.8.3": - version: 1.8.3 - resolution: "@biomejs/cli-darwin-arm64@npm:1.8.3" +"@biomejs/cli-darwin-arm64@npm:1.9.4": + version: 1.9.4 + resolution: "@biomejs/cli-darwin-arm64@npm:1.9.4" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard -"@biomejs/cli-darwin-x64@npm:1.8.3": - version: 1.8.3 - resolution: "@biomejs/cli-darwin-x64@npm:1.8.3" +"@biomejs/cli-darwin-x64@npm:1.9.4": + version: 1.9.4 + resolution: "@biomejs/cli-darwin-x64@npm:1.9.4" conditions: os=darwin & cpu=x64 languageName: node linkType: hard -"@biomejs/cli-linux-arm64-musl@npm:1.8.3": - version: 1.8.3 - resolution: "@biomejs/cli-linux-arm64-musl@npm:1.8.3" +"@biomejs/cli-linux-arm64-musl@npm:1.9.4": + version: 1.9.4 + resolution: "@biomejs/cli-linux-arm64-musl@npm:1.9.4" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard -"@biomejs/cli-linux-arm64@npm:1.8.3": - version: 1.8.3 - resolution: "@biomejs/cli-linux-arm64@npm:1.8.3" +"@biomejs/cli-linux-arm64@npm:1.9.4": + version: 1.9.4 + resolution: "@biomejs/cli-linux-arm64@npm:1.9.4" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard -"@biomejs/cli-linux-x64-musl@npm:1.8.3": - version: 1.8.3 - resolution: "@biomejs/cli-linux-x64-musl@npm:1.8.3" +"@biomejs/cli-linux-x64-musl@npm:1.9.4": + version: 1.9.4 + resolution: "@biomejs/cli-linux-x64-musl@npm:1.9.4" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard -"@biomejs/cli-linux-x64@npm:1.8.3": - version: 1.8.3 - resolution: "@biomejs/cli-linux-x64@npm:1.8.3" +"@biomejs/cli-linux-x64@npm:1.9.4": + version: 1.9.4 + resolution: "@biomejs/cli-linux-x64@npm:1.9.4" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard -"@biomejs/cli-win32-arm64@npm:1.8.3": - version: 1.8.3 - resolution: "@biomejs/cli-win32-arm64@npm:1.8.3" +"@biomejs/cli-win32-arm64@npm:1.9.4": + version: 1.9.4 + resolution: "@biomejs/cli-win32-arm64@npm:1.9.4" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard -"@biomejs/cli-win32-x64@npm:1.8.3": - version: 1.8.3 - resolution: "@biomejs/cli-win32-x64@npm:1.8.3" +"@biomejs/cli-win32-x64@npm:1.9.4": + version: 1.9.4 + resolution: "@biomejs/cli-win32-x64@npm:1.9.4" conditions: os=win32 & cpu=x64 languageName: node linkType: hard @@ -443,15 +443,14 @@ __metadata: version: 0.0.0-use.local resolution: "@tests/gentype-react-example@workspace:tests/gentype_tests/typescript-react-example" dependencies: - "@biomejs/biome": "npm:1.8.3" + "@biomejs/biome": "npm:1.9.4" "@rescript/react": "npm:^0.13.1" - "@types/node": "npm:^18.15.12" - "@types/react": "npm:^18.3.19" - "@types/react-dom": "npm:^18.3.5" + "@types/react": "npm:^18.3.3" + "@types/react-dom": "npm:^18.3.0" react: "npm:^18.3.1" react-dom: "npm:^18.3.1" rescript: "workspace:^" - typescript: "npm:^5.2.2" + typescript: "npm:5.8.2" languageName: unknown linkType: soft @@ -489,12 +488,12 @@ __metadata: languageName: unknown linkType: soft -"@types/node@npm:^18.15.12": - version: 18.19.81 - resolution: "@types/node@npm:18.19.81" +"@types/node@npm:^20.14.9": + version: 20.17.27 + resolution: "@types/node@npm:20.17.27" dependencies: - undici-types: "npm:~5.26.4" - checksum: 10c0/fb1ae8a741b1b902c9fb6640075704e64c0e47aff2920eab502186c2d0b6ee65204c3ec8dd8a45260702c5a8d1b5dba33e6552aa6128d3787c70b0475c7f808d + undici-types: "npm:~6.19.2" + checksum: 10c0/09f30c65e5f2a082eddf26a7ffa859bf2b77e1123829309823e7691227fd5a691b30cd3ac413d65829aa25c1eebd2f717bed80f2f8a7f83aaa6c2c3a047b3504 languageName: node linkType: hard @@ -505,7 +504,7 @@ __metadata: languageName: node linkType: hard -"@types/react-dom@npm:^18.3.5": +"@types/react-dom@npm:^18.3.0": version: 18.3.5 resolution: "@types/react-dom@npm:18.3.5" peerDependencies: @@ -514,13 +513,20 @@ __metadata: languageName: node linkType: hard -"@types/react@npm:^18.3.19": - version: 18.3.19 - resolution: "@types/react@npm:18.3.19" +"@types/react@npm:^18.3.3": + version: 18.3.20 + resolution: "@types/react@npm:18.3.20" dependencies: "@types/prop-types": "npm:*" csstype: "npm:^3.0.2" - checksum: 10c0/236bfe0c4748ada1a640f13573eca3e0fc7c9d847b442947adb352b0718d6d285357fd84c33336c8ffb8cbfabc0d58a43a647c7fd79857fecd61fb58ab6f7918 + checksum: 10c0/65fa867c91357e4c4c646945c8b99044360f8973cb7f928ec4de115fe3207827985d45be236e6fd6c092b09f631c2126ce835c137be30718419e143d73300d8f + languageName: node + linkType: hard + +"@types/semver@npm:^7.5.8": + version: 7.5.8 + resolution: "@types/semver@npm:7.5.8" + checksum: 10c0/8663ff927234d1c5fcc04b33062cb2b9fcfbe0f5f351ed26c4d1e1581657deebd506b41ff7fdf89e787e3d33ce05854bc01686379b89e9c49b564c4cfa988efa languageName: node linkType: hard @@ -2121,15 +2127,19 @@ __metadata: version: 0.0.0-use.local resolution: "rescript@workspace:." dependencies: - "@biomejs/biome": "npm:1.8.3" + "@biomejs/biome": "npm:1.9.4" + "@types/node": "npm:^20.14.9" + "@types/semver": "npm:^7.5.8" mocha: "npm:10.8.2" nyc: "npm:15.0.0" + semver: "npm:7.6.2" + typescript: "npm:5.8.2" bin: - bsc: cli/bsc - bstracing: lib/bstracing - rescript: cli/rescript - rescript-tools: cli/rescript-tools - rewatch: cli/rewatch + bsc: cli/bsc.js + bstracing: lib/bstracing.js + rescript: cli/rescript.js + rescript-tools: cli/rescript-tools.js + rewatch: cli/rewatch.js languageName: unknown linkType: soft @@ -2192,6 +2202,15 @@ __metadata: languageName: node linkType: hard +"semver@npm:7.6.2": + version: 7.6.2 + resolution: "semver@npm:7.6.2" + bin: + semver: bin/semver.js + checksum: 10c0/97d3441e97ace8be4b1976433d1c32658f6afaff09f143e52c593bae7eef33de19e3e369c88bd985ce1042c6f441c80c6803078d1de2a9988080b66684cbb30c + languageName: node + linkType: hard + "semver@npm:^6.0.0, semver@npm:^6.3.0, semver@npm:^6.3.1": version: 6.3.1 resolution: "semver@npm:6.3.1" @@ -2450,7 +2469,7 @@ __metadata: languageName: node linkType: hard -"typescript@npm:^5.2.2": +"typescript@npm:5.8.2": version: 5.8.2 resolution: "typescript@npm:5.8.2" bin: @@ -2460,7 +2479,7 @@ __metadata: languageName: node linkType: hard -"typescript@patch:typescript@npm%3A^5.2.2#optional!builtin": +"typescript@patch:typescript@npm%3A5.8.2#optional!builtin": version: 5.8.2 resolution: "typescript@patch:typescript@npm%3A5.8.2#optional!builtin::version=5.8.2&hash=5786d5" bin: @@ -2470,10 +2489,10 @@ __metadata: languageName: node linkType: hard -"undici-types@npm:~5.26.4": - version: 5.26.5 - resolution: "undici-types@npm:5.26.5" - checksum: 10c0/bb673d7876c2d411b6eb6c560e0c571eef4a01c1c19925175d16e3a30c4c428181fb8d7ae802a261f283e4166a0ac435e2f505743aa9e45d893f9a3df017b501 +"undici-types@npm:~6.19.2": + version: 6.19.8 + resolution: "undici-types@npm:6.19.8" + checksum: 10c0/078afa5990fba110f6824823ace86073b4638f1d5112ee26e790155f481f2a868cc3e0615505b6f4282bdf74a3d8caad715fd809e870c2bb0704e3ea6082f344 languageName: node linkType: hard