From 5cd0831796da77c2164c010ded5117b7793800c1 Mon Sep 17 00:00:00 2001 From: Florian Hammerschmidt Date: Thu, 3 Dec 2026 17:18:32 +0100 Subject: [PATCH 1/4] Support the ReScript 13 flat build layout --- CHANGELOG.md | 1 + server/src/bsc-args/rewatch.ts | 10 +- server/src/constants.ts | 9 - server/src/find-runtime.ts | 4 +- server/src/incrementalCompilation.ts | 155 +++++++-------- server/src/server.ts | 163 +++++++++------- server/src/utils.ts | 55 +++--- server/test/README.md | 65 +++++++ server/test/build-layout.cjs | 274 +++++++++++++++++++++++++++ shared/src/buildLayout.ts | 81 ++++++++ shared/src/findBinary.ts | 36 +--- 11 files changed, 628 insertions(+), 225 deletions(-) create mode 100644 server/test/README.md create mode 100644 server/test/build-layout.cjs create mode 100644 shared/src/buildLayout.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ea4025dd..09b455e5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ ## [Unreleased] #### :bug: Bug fix +- Support the flat `lib/rescript` build layout in ReScript 13. https://github.com/rescript-lang/rescript-vscode/issues/1194 - Fix language server crash (`ERR_INVALID_URL`) when resolving platform binaries for ReScript v12+ projects. https://github.com/rescript-lang/rescript-vscode/issues/1181 diff --git a/server/src/bsc-args/rewatch.ts b/server/src/bsc-args/rewatch.ts index e38b8d2bb..91af4b776 100644 --- a/server/src/bsc-args/rewatch.ts +++ b/server/src/bsc-args/rewatch.ts @@ -86,7 +86,7 @@ export async function getRewatchBscArgs( entry.file.sourceFilePath, ]; - const env: NodeJS.ProcessEnv = {}; + const env: NodeJS.ProcessEnv = entry.flatLayout ? { ...process.env } : {}; if (bscBinaryLocation != null) { env["RESCRIPT_BSC_EXE"] = bscBinaryLocation; } @@ -122,7 +122,13 @@ export async function getRewatchBscArgs( } const compilerArgs = JSON.parse( - cp.execFileSync(rewatchPath, rewatchArguments, { env }).toString().trim(), + cp + .execFileSync(rewatchPath, rewatchArguments, { + env, + ...(entry.flatLayout ? { cwd: entry.project.rootPath } : {}), + }) + .toString() + .trim(), ) as RewatchCompilerArgs; entry.buildRewatch = { diff --git a/server/src/constants.ts b/server/src/constants.ts index 28e213bff..e0352e8f6 100644 --- a/server/src/constants.ts +++ b/server/src/constants.ts @@ -32,18 +32,9 @@ export let bsconfigPartialPath = "bsconfig.json"; export let rescriptJsonPartialPath = "rescript.json"; export let compilerDirPartialPath = path.join("lib", "bs"); export let compilerOcamlDirPartialPath = path.join("lib", "ocaml"); -export let compilerLogPartialPath = path.join("lib", "bs", ".compiler.log"); -export let compilerInfoPartialPath = path.join( - "lib", - "bs", - "compiler-info.json", -); export let buildNinjaPartialPath = path.join("lib", "bs", "build.ninja"); -export let rewatchLockPartialPath = path.join("lib", "rewatch.lock"); -export let rescriptLockPartialPath = path.join("lib", "rescript.lock"); export let resExt = ".res"; export let resiExt = ".resi"; -export let cmiExt = ".cmi"; export let startBuildAction = "Start Build"; // bsconfig defaults according configuration schema (https://rescript-lang.org/docs/manual/latest/build-configuration-schema) diff --git a/server/src/find-runtime.ts b/server/src/find-runtime.ts index 0f35032bc..d62dcd09d 100644 --- a/server/src/find-runtime.ts +++ b/server/src/find-runtime.ts @@ -1,6 +1,6 @@ import { readdir, stat as statAsync, readFile } from "fs/promises"; import { join, resolve } from "path"; -import { compilerInfoPartialPath } from "./constants"; +import { buildLayout } from "../../shared/src/buildLayout"; import { NormalizedPath, normalizePath } from "./utils"; // Efficient parallel folder traversal to find node_modules directories @@ -97,7 +97,7 @@ async function findRuntimePath( project: NormalizedPath, ): Promise { // Try a compiler-info.json file first - const compilerInfo = resolve(project, compilerInfoPartialPath); + const compilerInfo = resolve(project, buildLayout(project).compilerInfo); try { const contents = await readFile(compilerInfo, "utf8"); const compileInfo: { runtime_path?: string } = JSON.parse(contents); diff --git a/server/src/incrementalCompilation.ts b/server/src/incrementalCompilation.ts index da65b9d4d..026c7e57a 100644 --- a/server/src/incrementalCompilation.ts +++ b/server/src/incrementalCompilation.ts @@ -1,3 +1,4 @@ +import { buildLayout, compiledArtifact } from "../../shared/src/buildLayout"; import * as path from "path"; import fs from "fs"; import * as utils from "./utils"; @@ -18,12 +19,6 @@ import { getLogger } from "./logger"; const execFilePromise = promisify(cp.execFile); -const INCREMENTAL_FOLDER_NAME = "___incremental"; -const INCREMENTAL_FILE_FOLDER_LOCATION = path.join( - c.compilerDirPartialPath, - INCREMENTAL_FOLDER_NAME, -); - export type IncrementallyCompiledFileInfo = { file: { /** File type. */ @@ -42,6 +37,7 @@ export type IncrementallyCompiledFileInfo = { originalTypeFileLocation: NormalizedPath; }; buildSystem: "bsb" | "rewatch"; + flatLayout: boolean; /** Cache for build.ninja assets. */ buildNinja: { /** When build.ninja was last modified. Used as a cache key. */ @@ -113,75 +109,65 @@ export function incrementalCompilationFileChanged(changedPath: NormalizedPath) { getLogger().log("[watcher] Was compiling, killing"); cancelActiveCompilation(entry); } - cleanUpIncrementalFiles( - entry.file.sourceFilePath, - entry.project.rootPath, - ); + cleanUpIncrementalFiles(entry); } } } -export function removeIncrementalFileFolder( +// Discard scratch output from a previous editor session before opening a project. +export async function removeIncrementalFileFolder( projectRootPath: NormalizedPath, - onAfterRemove?: () => void, + rescriptVersion?: string, ) { - fs.rm( - path.resolve(projectRootPath, INCREMENTAL_FILE_FOLDER_LOCATION), - { force: true, recursive: true }, - (_) => { - onAfterRemove?.(); - }, - ); -} - -export function recreateIncrementalFileFolder(projectRootPath: NormalizedPath) { - getLogger().log("Recreating incremental file folder"); - removeIncrementalFileFolder(projectRootPath, () => { - fs.mkdir( - path.resolve(projectRootPath, INCREMENTAL_FILE_FOLDER_LOCATION), - { recursive: true }, - (_) => {}, + try { + await fs.promises.rm( + path.resolve( + projectRootPath, + buildLayout(projectRootPath, rescriptVersion).incremental, + ), + { force: true, recursive: true }, ); - }); + } catch (error) { + getLogger().log( + `Could not clear ReScript incremental scratch files: ${error}`, + ); + } } -export function cleanUpIncrementalFiles( - filePath: NormalizedPath, - projectRootPath: NormalizedPath, -) { - const ext = filePath.endsWith(".resi") ? ".resi" : ".res"; - const namespace = utils.getNamespaceNameFromConfigFile(projectRootPath); - const fileNameNoExt = path.basename(filePath, ext); - const moduleNameNamespaced = - namespace.kind === "success" && namespace.result !== "" - ? `${fileNameNoExt}-${namespace.result}` - : fileNameNoExt; - - getLogger().log("Cleaning up incremental file assets for: " + fileNameNoExt); - - fs.unlink( - path.resolve( - projectRootPath, - INCREMENTAL_FILE_FOLDER_LOCATION, - path.basename(filePath), - ), - (_) => {}, +function cleanUpIncrementalFiles(entry: IncrementallyCompiledFileInfo) { + const { moduleNameNamespaced, incrementalFilePath } = entry.file; + getLogger().log( + "Cleaning up incremental file assets for: " + moduleNameNamespaced, ); + fs.unlink(incrementalFilePath, () => {}); - [ - moduleNameNamespaced + ".ast", - moduleNameNamespaced + ".cmt", - moduleNameNamespaced + ".cmti", - moduleNameNamespaced + ".cmi", - moduleNameNamespaced + ".cmj", - ].forEach((file) => { + [".ast", ".cmt", ".cmti", ".cmi", ".cmj"].forEach((extension) => { fs.unlink( - path.resolve(projectRootPath, INCREMENTAL_FILE_FOLDER_LOCATION, file), - (_) => {}, + path.join( + entry.project.incrementalFolderPath, + moduleNameNamespaced + extension, + ), + () => {}, ); }); } +export function invalidateCompilerArgs( + projectRootPath: NormalizedPath, + send: send, +) { + for (const entry of incrementallyCompiledFileInfo.values()) { + if ( + entry.project.rootPath === projectRootPath || + entry.project.workspaceRootPath === projectRootPath + ) { + entry.buildNinja = null; + entry.buildRewatch = null; + entry.project.callArgs = figureOutBscArgs(send, entry); + } + } +} + export async function getBscArgs( send: (msg: p.Message) => void, entry: IncrementallyCompiledFileInfo, @@ -290,6 +276,7 @@ function triggerIncrementalCompilationOfFile( ); } + const layout = buildLayout(projectRootPath, project.rescriptVersion); const bscBinaryLocation = project.bscBinaryLocation; if (bscBinaryLocation == null) { getLogger().log("Could not find bsc binary location for " + filePath); @@ -297,30 +284,22 @@ function triggerIncrementalCompilationOfFile( } const ext = filePath.endsWith(".resi") ? ".resi" : ".res"; const moduleName = path.basename(filePath, ext); - const moduleNameNamespaced = - project.namespaceName != null - ? `${moduleName}-${project.namespaceName}` - : moduleName; + const moduleNameNamespaced = project.namespaceName + ? `${moduleName}-${project.namespaceName}` + : moduleName; // projectRootPath is already NormalizedPath, appending a constant string still makes it a NormalizedPath const incrementalFolderPath: NormalizedPath = path.join( projectRootPath, - INCREMENTAL_FILE_FOLDER_LOCATION, + layout.incremental, ) as NormalizedPath; - const relSourcePath = path.relative(projectRootPath, filePath); - const relSourceDir = path.dirname(relSourcePath); - const typeExt = ext === ".res" ? ".cmt" : ".cmti"; - const originalTypeFileName = - project.namespaceName != null - ? `${moduleName}-${project.namespaceName}${typeExt}` - : `${moduleName}${typeExt}`; - // projectRootPath is already NormalizedPath, appending constant strings still yields a NormalizedPath - const originalTypeFileLocation = path.resolve( + const originalTypeFileLocation = compiledArtifact( projectRootPath, - c.compilerDirPartialPath, - relSourceDir, - originalTypeFileName, + filePath, + project.namespaceName, + ext === ".res" ? ".cmt" : ".cmti", + layout, ) as NormalizedPath; incrementalFileCacheEntry = { @@ -344,7 +323,9 @@ function triggerIncrementalCompilationOfFile( bscBinaryLocation, incrementalFolderPath, }, - buildSystem: foundRewatchLockfileInProjectRoot ? "rewatch" : "bsb", + flatLayout: layout.flat, + buildSystem: + layout.flat || foundRewatchLockfileInProjectRoot ? "rewatch" : "bsb", buildRewatch: null, buildNinja: null, compilation: null, @@ -415,10 +396,7 @@ async function figureOutBscArgs( let callArgs: Array = []; if (config.extensionConfiguration.incrementalTypechecking?.acrossFiles) { - callArgs.push( - "-I", - path.resolve(entry.project.rootPath, INCREMENTAL_FILE_FOLDER_LOCATION), - ); + callArgs.push("-I", entry.project.incrementalFolderPath); } buildArgs.forEach(([key, value]: Array) => { @@ -448,7 +426,7 @@ rule mij } } else { // TODO: once ReScript v12 is out we can remove this check for `.` - if (value === ".") { + if (value === "." && !entry.flatLayout) { callArgs.push( "-I", path.resolve(entry.project.rootPath, c.compilerOcamlDirPartialPath), @@ -522,7 +500,7 @@ function remapCodeActionsToSourceFile( */ function filterIncrementalDiagnostics( diagnostics: p.Diagnostic[], - sourceFileName: string, + scratchFile: string, ): { filtered: p.Diagnostic[]; hasIgnoredMessages: boolean } { let hasIgnoredMessages = false; @@ -535,7 +513,7 @@ function filterIncrementalDiagnostics( .filter((d) => { if ( !d.message.startsWith("Uninterpreted extension 'rescript.") && - (!d.message.includes(`/${INCREMENTAL_FOLDER_NAME}/${sourceFileName}`) || + (!d.message.replace(/\\/g, "/").includes(scratchFile) || // The `Multiple definition of the name ` type error's // message includes the filepath with LOC of the duplicate definition d.message.startsWith("Multiple definition of the") || @@ -614,7 +592,7 @@ function processAndPublishDiagnostics( const rawDiagnostics = Object.values(result)[0] ?? []; const { filtered: res, hasIgnoredMessages } = filterIncrementalDiagnostics( rawDiagnostics, - entry.file.sourceFileName, + `/${path.basename(entry.project.incrementalFolderPath)}/${entry.file.sourceFileName}`, ); // Log error if compilation produced unexpected output @@ -669,7 +647,7 @@ async function compileContents( entry.project.callArgs = Promise.resolve(callArgsRetried); } else { getLogger().log( - "Could not figure out call args. Maybe build.ninja does not exist yet?", + "Could not get compiler arguments. The project may need a build first.", ); return; } @@ -687,7 +665,7 @@ async function compileContents( let cwd = entry.buildSystem === "bsb" ? entry.project.rootPath - : path.resolve(entry.project.rootPath, c.compilerDirPartialPath); + : path.dirname(entry.project.incrementalFolderPath); getLogger().log( `About to invoke bsc from \"${cwd}\", used ${entry.buildSystem}`, @@ -801,7 +779,8 @@ export function handleClosedFile(filePath: NormalizedPath) { getLogger().log("Closed: " + filePath); const entry = incrementallyCompiledFileInfo.get(filePath); if (entry == null) return; - cleanUpIncrementalFiles(filePath, entry.project.rootPath); + cancelActiveCompilation(entry); + cleanUpIncrementalFiles(entry); incrementallyCompiledFileInfo.delete(filePath); originalTypeFileToFilePath.delete(entry.file.originalTypeFileLocation); } diff --git a/server/src/server.ts b/server/src/server.ts index 23ccd9602..59d516256 100644 --- a/server/src/server.ts +++ b/server/src/server.ts @@ -1,3 +1,9 @@ +import { + buildLayout, + compiledArtifact, + flatBuildLayout, + legacyBuildLayout, +} from "../../shared/src/buildLayout"; import process from "process"; import * as p from "vscode-languageserver-protocol"; import * as v from "vscode-languageserver"; @@ -166,7 +172,10 @@ export let getCurrentCompilerDiagnosticsForFile = ( let sendUpdatedDiagnostics = async () => { for (const [projectRootPath, projectFile] of projectsFiles) { let { filesWithDiagnostics } = projectFile; - let compilerLogPath = path.join(projectRootPath, c.compilerLogPartialPath); + let compilerLogPath = path.join( + projectRootPath, + buildLayout(projectRootPath, projectFile.rescriptVersion).compilerLog, + ); let content = ""; try { content = fs.readFileSync(compilerLogPath, { encoding: "utf-8" }); @@ -183,7 +192,7 @@ let sendUpdatedDiagnostics = async () => { if (linesWithParseErrors.length > 0) { let params: p.ShowMessageParams = { type: p.MessageType.Warning, - message: `There are more compiler warning/errors that we could not parse. You can help us fix this by opening an [issue on the repository](https://github.com/rescript-lang/rescript-vscode/issues/new?title=Compiler%20log%20parse%20error), pasting the contents of the file [lib/bs/.compiler.log](file://${compilerLogPath}).`, + message: `There are more compiler warning/errors that we could not parse. You can help us fix this by opening an [issue on the repository](https://github.com/rescript-lang/rescript-vscode/issues/new?title=Compiler%20log%20parse%20error), pasting the contents of the file [.compiler.log](${utils.pathToURI(utils.normalizePath(compilerLogPath)!)}).`, }; let message: p.NotificationMessage = { jsonrpc: c.jsonrpcVersion, @@ -336,7 +345,7 @@ let deleteProjectDiagnostics = (projectRootPath: utils.NormalizedPath) => { projectsFiles.delete(projectRootPath); projectCompilationStates.delete(projectRootPath); if (config.extensionConfiguration.incrementalTypechecking?.enable) { - ic.removeIncrementalFileFolder(projectRootPath); + ic.removeIncrementalFileFolder(projectRootPath, root.rescriptVersion); } } }; @@ -381,18 +390,21 @@ async function onWorkspaceDidChangeWatchedFiles( ) { await Promise.all( params.changes.map(async (change) => { - if (change.uri.includes("build.ninja")) { - if ( - config.extensionConfiguration.cache?.projectConfig?.enable === true - ) { - let projectRoot = utils.findProjectRootOfFile( - utils.uriToNormalizedPath(change.uri as utils.FileURI), - ); - if (projectRoot != null) { + const changedPath = utils.uriToNormalizedPath( + change.uri as utils.FileURI, + ); + const changedName = path.basename(changedPath); + if (changedName === "build.ninja" || changedName === ".sourcedirs.json") { + const projectRoot = utils.findProjectRootOfFile(changedPath); + if (projectRoot != null) { + ic.invalidateCompilerArgs(projectRoot, send); + if ( + config.extensionConfiguration.cache?.projectConfig?.enable === true + ) { await syncProjectConfigCache(projectRoot); } } - } else if (change.uri.includes("compiler.log")) { + } else if (changedName === ".compiler.log") { try { await sendUpdatedDiagnostics(); sendCompilationFinishedMessage(); @@ -406,9 +418,7 @@ async function onWorkspaceDidChangeWatchedFiles( getLogger().error("Error while sending updated diagnostics"); } } else { - ic.incrementalCompilationFileChanged( - utils.uriToNormalizedPath(change.uri as utils.FileURI), - ); + ic.incrementalCompilationFileChanged(changedPath); } }), ); @@ -428,9 +438,6 @@ let openedFile = async (fileUri: utils.FileURI, fileContent: string) => { // projectRootPath is already normalized (NormalizedPath) from findProjectRootOfFile let projectRootState = projectsFiles.get(projectRootPath); if (projectRootState == null) { - if (config.extensionConfiguration.incrementalTypechecking?.enable) { - ic.recreateIncrementalFileFolder(projectRootPath); - } const namespaceName = utils.getNamespaceNameFromConfigFile(projectRootPath); @@ -458,12 +465,20 @@ let openedFile = async (fileUri: utils.FileURI, fileContent: string) => { await syncProjectConfigCache(projectRootPath); } } - let root = projectsFiles.get(projectRootPath)!; - root.openFiles.add(filePath); + const isFirstOpen = projectRootState.openFiles.size === 0; + projectRootState.openFiles.add(filePath); + if ( + isFirstOpen && + config.extensionConfiguration.incrementalTypechecking?.enable + ) { + await ic.removeIncrementalFileFolder( + projectRootPath, + projectRootState.rescriptVersion, + ); + } + const root = projectRootState; // check if a lock file exists. If not, start a build watcher ourselves // because otherwise the diagnostics info we'll display might be stale - // ReScript < 12: .bsb.lock in project root - // ReScript >= 12: lib/rescript.lock // For monorepos, the lock file is at the monorepo root, not the subpackage let rescriptBinaryPath = await findRescriptBinary(projectRootPath); let buildRootPath = projectRootPath; @@ -474,10 +489,10 @@ let openedFile = async (fileUri: utils.FileURI, fileContent: string) => { buildRootPath = monorepoRootPath; } } - let bsbLockPath = path.join(buildRootPath, c.bsbLock); - let rescriptLockPath = path.join(buildRootPath, c.rescriptLockPartialPath); - let hasLockFile = - fs.existsSync(bsbLockPath) || fs.existsSync(rescriptLockPath); + const hasLockFile = buildLayout( + buildRootPath, + root.rescriptVersion, + ).watchLocks.some((lock) => fs.existsSync(path.join(buildRootPath, lock))); if ( projectRootState.hasPromptedToStartBuild === false && config.extensionConfiguration.askToStartBuild === true && @@ -1182,8 +1197,6 @@ async function createInterface(msg: p.RequestMessage): Promise { return response; } - let resPartialPath = filePath.split(projDir)[1]; - // The .cmi filename may have a namespace suffix appended. let namespaceResult = utils.getNamespaceNameFromConfigFile(projDir); @@ -1202,15 +1215,17 @@ async function createInterface(msg: p.RequestMessage): Promise { return response; } - let namespace = namespaceResult.result; - let suffixToAppend = namespace.length > 0 ? "-" + namespace : ""; - - let cmiPartialPath = path.join( - path.dirname(resPartialPath), - path.basename(resPartialPath, c.resExt) + suffixToAppend + c.cmiExt, + const layout = buildLayout( + projDir, + projectsFiles.get(projDir)?.rescriptVersion, + ); + const cmiPath = compiledArtifact( + projDir, + filePath, + namespaceResult.result, + ".cmi", + layout, ); - - let cmiPath = path.join(projDir, c.compilerDirPartialPath, cmiPartialPath); let cmiAvailable = fs.existsSync(cmiPath); if (!cmiAvailable) { @@ -1233,14 +1248,25 @@ async function createInterface(msg: p.RequestMessage): Promise { ["createInterface", filePath, cmiPath], msg, ); - let result = typeof response.result === "string" ? response.result : ""; + const interfaceSource = response.result; + if (typeof interfaceSource !== "string") { + const failure: p.ResponseMessage = { + jsonrpc: c.jsonrpcVersion, + id: msg.id, + error: { + code: p.ErrorCodes.InternalError, + message: "Unable to generate interface source.", + }, + }; + return failure; + } try { let resiPath = lookup.replaceFileExtensionWithNormalizedPath( filePath, c.resiExt, ); - fs.writeFileSync(resiPath, result, { encoding: "utf-8" }); + fs.writeFileSync(resiPath, interfaceSource, { encoding: "utf-8" }); let response: p.ResponseMessage = { jsonrpc: c.jsonrpcVersion, id: msg.id, @@ -1311,10 +1337,21 @@ async function startBuildWatcher( getLogger().info( `Starting build watcher for ${projectRootPath} in ${buildCwd} (ReScript ${root.rescriptVersion ?? "unknown"})`, ); + const layout = buildLayout(projectRootPath, root.rescriptVersion); + // Running the flat-layout compiler directly gives the editor the PID that + // owns watch.lock, so shutdown can clean its own lock without deleting + // another watcher's lock. The wrapper remains the fallback. + const nativePath = layout.flat + ? await utils.findRescriptExeBinary(projectRootPath) + : null; + const runtimePath = nativePath + ? await utils.getRuntimePathFromProjectRoot(projectRootPath) + : null; let bsbProcess = utils.runBuildWatcherUsingValidBuildPath( - rescriptBinaryPath, + runtimePath && nativePath ? nativePath : rescriptBinaryPath, buildCwd, root.rescriptVersion, + runtimePath ?? undefined, ); root.bsbWatcherByEditor = bsbProcess; root.buildRootPath = buildCwd; @@ -1518,36 +1555,23 @@ async function onMessage(msg: p.Message) { We use this to register the file watchers for the project. The client can watch files for us and send us events via the `workspace/didChangeWatchedFiles` */ - const watchers = Array.from(workspaceFolders).flatMap( - (projectRootPath) => [ - { - // Only watch the root compiler log for each workspace folder. - // In monorepos, `**/lib/bs/.compiler.log` matches every package and dependency, - // causing a burst of events per save. - globPattern: { - baseUri: utils.pathToURI(projectRootPath), - pattern: c.compilerLogPartialPath, - }, - kind: p.WatchKind.Change | p.WatchKind.Create | p.WatchKind.Delete, - }, - { - // Watch ninja output - globPattern: { - baseUri: utils.pathToURI(projectRootPath), - pattern: path.join("**", c.buildNinjaPartialPath), - }, - kind: p.WatchKind.Change | p.WatchKind.Create | p.WatchKind.Delete, - }, - { - // Watch build artifacts - globPattern: { - baseUri: utils.pathToURI(projectRootPath), - pattern: path.join(c.compilerDirPartialPath, "**/*.{cmi,cmt}"), - }, + const watchers = Array.from(workspaceFolders).flatMap((root) => { + const baseUri = utils.pathToURI(root); + return [legacyBuildLayout, flatBuildLayout].flatMap((layout) => + [ + // Only watch the workspace root log; dependencies can emit many + // otherwise redundant log events when the root build runs. + layout.compilerLog, + `**/${layout.projectGraph}`, + layout.flat + ? `**/${layout.artifacts}/*.{cmi,cmt,cmti}` + : `${layout.artifacts}/**/*.{cmi,cmt,cmti}`, + ].map((pattern) => ({ + globPattern: { baseUri, pattern }, kind: p.WatchKind.Change | p.WatchKind.Create | p.WatchKind.Delete, - }, - ], - ); + })), + ); + }); const registrationParams: p.RegistrationParams = { registrations: [ { @@ -1653,8 +1677,7 @@ async function onMessage(msg: p.Message) { // These are static configuration options the client can set to enable certain let extensionClientCapabilitiesFromClient = initParams .initializationOptions?.extensionClientCapabilities as - | extensionClientCapabilities - | undefined; + extensionClientCapabilities | undefined; if (extensionClientCapabilitiesFromClient != null) { extensionClientCapabilities = extensionClientCapabilitiesFromClient; diff --git a/server/src/utils.ts b/server/src/utils.ts index e4c34e256..421693c0f 100644 --- a/server/src/utils.ts +++ b/server/src/utils.ts @@ -26,7 +26,7 @@ import { reportError } from "./errorReporter"; import config from "./config"; import { filesDiagnostics, projectsFiles, projectFiles } from "./projectFiles"; import { workspaceFolders } from "./server"; -import { rewatchLockPartialPath, rescriptLockPartialPath } from "./constants"; +import { buildLayout } from "../../shared/src/buildLayout"; import { findRescriptRuntimesInProject } from "./find-runtime"; /** @@ -306,7 +306,7 @@ export async function findReScriptVersionForProjectRoot( } try { - let version = childProcess.execSync(`${bscExe} -v`); + let version = childProcess.execFileSync(bscExe, ["-v"]); return version .toString() .replace(/rescript/gi, "") @@ -391,6 +391,15 @@ export let runAnalysisAfterSanityCheck = async ( let stdout = ""; try { stdout = childProcess.execFileSync(binaryPath, args, options).toString(); + // The flat-layout compiler prints interface source directly, rather than + // returning a JSON-encoded string like the legacy analysis binary. + if ( + args[0] === "createInterface" && + projectRootPath != null && + buildLayout(projectRootPath, rescriptVersion).flat + ) { + return stdout; + } return JSON.parse(stdout); } catch (e) { console.error(e); @@ -451,19 +460,11 @@ export function computeWorkspaceRootPathFromLockfile( return null; } - const projectRewatchLockfiles = [ - ...Array.from(workspaceFolders).map((w) => - path.resolve(w, rewatchLockPartialPath), + const roots = new Set([projectRootPath, ...workspaceFolders]); + const foundRewatchLockfileInProjectRoot = Array.from(roots).some((root) => + buildLayout(root, projectsFiles.get(root)?.rescriptVersion).watchLocks.some( + (lock) => lock !== c.bsbLock && fs.existsSync(path.join(root, lock)), ), - ...Array.from(workspaceFolders).map((w) => - path.resolve(w, rescriptLockPartialPath), - ), - path.resolve(projectRootPath, rewatchLockPartialPath), - path.resolve(projectRootPath, rescriptLockPartialPath), - ]; - - const foundRewatchLockfileInProjectRoot = projectRewatchLockfiles.some( - (lockFile) => fs.existsSync(lockFile), ); // if we find a rewatch.lock in the project root, it's a compilation of a local package @@ -621,9 +622,13 @@ export let runBuildWatcherUsingValidBuildPath = ( buildPath: p.DocumentUri, projectRootPath: p.DocumentUri, rescriptVersion?: string | null, + runtimePath?: string, ) => { - let cwdEnv = { + const cwdEnv = { cwd: projectRootPath, + ...(runtimePath == null + ? {} + : { env: { ...process.env, RESCRIPT_RUNTIME: runtimePath } }), }; // ReScript >= 12.0.0 uses "rescript watch" instead of "rescript build -w" let useWatchCommand = @@ -637,7 +642,7 @@ export let runBuildWatcherUsingValidBuildPath = ( ); let proc: childProcess.ChildProcess; - if (process.platform === "win32") { + if (process.platform === "win32" && !buildPath.endsWith(".exe")) { /* - a node.js script in node_modules/.bin on windows is wrapped in a batch script wrapper (there's also a regular binary of the same name on @@ -658,7 +663,7 @@ export let runBuildWatcherUsingValidBuildPath = ( // have a handler that exits when stdin closes: `process.stdin.on("close", exitProcess)` proc = childProcess.spawn(buildPath, args, { ...cwdEnv, - detached: true, + detached: process.platform !== "win32", stdio: ["pipe", "pipe", "pipe"], }); } @@ -714,15 +719,17 @@ export let killBuildWatcher = ( } // Clean up lock files since the rescript compiler doesn't remove them on SIGTERM - // ReScript >= 12 uses lib/rescript.lock, older versions use .bsb.lock if (buildRootPath != null) { - const lockFiles = [ - path.join(buildRootPath, "lib", "rescript.lock"), - path.join(buildRootPath, ".bsb.lock"), - ]; - for (const lockFilePath of lockFiles) { + const layout = buildLayout(buildRootPath); + for (const lock of layout.watchLocks) { + const lockFilePath = path.join(buildRootPath, lock); try { - if (fs.existsSync(lockFilePath)) { + // Do not remove a PID-bearing watch lock belonging to another process. + if ( + lock.endsWith("/watch.lock") + ? fs.readFileSync(lockFilePath, "utf8").trim() === String(proc.pid) + : lock !== "lib/rewatch.lock" && fs.existsSync(lockFilePath) + ) { fs.unlinkSync(lockFilePath); getLogger().log(`Removed lock file: ${lockFilePath}`); } diff --git a/server/test/README.md b/server/test/README.md new file mode 100644 index 000000000..e0d3eac7c --- /dev/null +++ b/server/test/README.md @@ -0,0 +1,65 @@ +# Build-layout smoke test + +This runs the bundled Node language server over the extension's IPC protocol. +It tests the watch command, nested namespaced .cmi lookup and interface +generation, go-to-definition and unsaved autocomplete for a local module and +the stdlib, and diagnostics +both before and after saving. It checks the LSP watcher registration and sends +the file-change notification that a client would normally deliver. + +Build the extension with `npm run bundle`, then make two disposable fixtures +outside the checkout. Use Node 22 or later. Each fixture needs the following +files (do not create `Main.resi`): + +`package.json`: + +```json +{ "name": "test-layout", "private": true } +``` + +`rescript.json`: + +```json +{ + "name": "test-layout", + "namespace": true, + "sources": [{ "dir": "src", "subdirs": true }], + "package-specs": { "module": "esmodule", "in-source": true }, + "suffix": ".res.mjs" +} +``` + +`src/nested/Helper.res`: + +```rescript +let value = 42 +``` + +`src/nested/Main.res`: + +```rescript +let value = Helper.value + 1 +let length = String.length("abc") +``` + +Install `rescript@12.3.1` in the first fixture. In the second fixture, install a +compiler that creates `lib/rescript`; alpha.7 does not. When using a compiler +preview, install the matching compiler, platform and runtime packages from the +same preview. For example, on Linux x64 the [flat-layout compiler PR's +preview](https://github.com/rescript-lang/rescript/pull/9245#issuecomment-6678610457) +provides the following packages: + +```sh +npm install https://pkg.pr.new/rescript@9245 \ + https://pkg.pr.new/@rescript/runtime@9245 \ + https://pkg.pr.new/@rescript/linux-x64@9245 +``` + +Run `npx rescript build` in both fixtures, then from the extension checkout: + +```sh +node server/test/build-layout.cjs /path/to/v12-fixture /path/to/v13-fixture +``` + +The test temporarily edits the fixture source and starts a watcher, so use +scratch projects and don't run other build commands in them concurrently. diff --git a/server/test/build-layout.cjs b/server/test/build-layout.cjs new file mode 100644 index 000000000..7652534b5 --- /dev/null +++ b/server/test/build-layout.cjs @@ -0,0 +1,274 @@ +// Run with two built fixtures (v12, then a compiler using lib/rescript). +// See server/test/README.md for fixture setup. +const assert = require("node:assert/strict"); +const { fork } = require("node:child_process"); +const fs = require("node:fs"); +const path = require("node:path"); +const { fileURLToPath, pathToFileURL } = require("node:url"); + +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const uri = (file) => pathToFileURL(file).href; + +async function smokeTest(root, flat) { + const relative = flat ? "lib/rescript" : "lib/bs"; + const log = path.join(root, relative, ".compiler.log"); + const lock = path.join( + root, + flat ? "lib/rescript/watch.lock" : "lib/watch.lock", + ); + const file = path.join(root, "src/nested/Main.res"); + const interfaceFile = file + "i"; + const document = { uri: uri(file) }; + const cleanSource = fs.readFileSync(file, "utf8"); + const badSource = cleanSource + '\nlet invalid: int = "wrong"\n'; + const configuration = { + askToStartBuild: false, + logLevel: "log", + incrementalTypechecking: { enable: true }, + cache: { projectConfig: { enable: false } }, + }; + const server = fork(path.join(__dirname, "../out/cli.js"), ["--node-ipc"], { + cwd: root, + silent: true, + }); + const messages = []; + let output = ""; + server.stdout.on("data", (chunk) => (output += chunk)); + server.stderr.on("data", (chunk) => (output += chunk)); + const send = (payload) => server.send({ jsonrpc: "2.0", ...payload }); + server.on("message", (m) => { + messages.push(m); + if (m.method && m.id !== undefined) { + send({ + id: m.id, + result: m.method === "workspace/configuration" ? [configuration] : null, + }); + } + }); + async function until(predicate, description) { + for (let i = 0; i < 250; i++) { + const match = predicate(); + if (match) return match; + if (server.exitCode !== null) break; + await wait(40); + } + throw new Error( + description + + "\n" + + output + + "\n" + + JSON.stringify(messages.slice(-20), null, 2), + ); + } + let counter = 0; + async function request(method, params) { + const id = ++counter; + send({ id, method, params }); + const m = await until( + () => messages.find((x) => x.id === id && !x.method), + "No response for " + method, + ); + assert.ok(!m.error, JSON.stringify(m.error)); + return m.result; + } + const notify = (method, params) => send({ method, params }); + const diagnostics = (from, hasError) => + messages + .slice(from) + .find( + (m) => + m.method === "textDocument/publishDiagnostics" && + m.params.uri === document.uri && + (hasError + ? m.params.diagnostics.some((d) => d.severity === 1) + : m.params.diagnostics.length === 0), + ); + + try { + assert.ok(fs.existsSync(log), "Fixture must be built before running"); + assert.ok(!fs.existsSync(interfaceFile), "Use a fixture with no Main.resi"); + await request("initialize", { + processId: process.pid, + rootUri: uri(root), + workspaceFolders: [{ uri: uri(root), name: path.basename(root) }], + capabilities: {}, + initializationOptions: { extensionConfiguration: configuration }, + }); + notify("initialized", {}); + const registration = await until( + () => messages.find((m) => m.method === "client/registerCapability"), + "Server never registered file watchers", + ); + const patterns = + registration.params.registrations[0].registerOptions.watchers.map( + (watcher) => watcher.globPattern.pattern, + ); + assert.ok(patterns.includes(relative + "/.compiler.log")); + if (flat) assert.ok(patterns.includes("**/lib/rescript/.sourcedirs.json")); + + assert.equal( + (await request("rescript/startBuild", document)).success, + true, + ); + await until( + () => fs.existsSync(lock), + "Build watcher did not create its lock", + ); + + notify("textDocument/didOpen", { + textDocument: { + ...document, + languageId: "rescript", + version: 1, + text: cleanSource, + }, + }); + const result = await request("textDocument/createInterface", document); + assert.equal(result?.uri, uri(interfaceFile)); + assert.match(fs.readFileSync(interfaceFile, "utf8"), /let value: int/); + fs.unlinkSync(interfaceFile); + await until( + () => + messages.find((m) => + m.params?.message?.includes("Recompiled Main.res"), + ), + "No incremental compile on open", + ); + + const definition = async (line, symbol) => { + const character = cleanSource.split("\n")[line].lastIndexOf(symbol) + 1; + const result = await request("textDocument/definition", { + textDocument: document, + position: { line, character }, + }); + return Array.isArray(result) ? result[0]?.uri : result?.uri; + }; + assert.equal( + await definition(0, "Helper.value"), + uri(path.join(root, "src/nested/Helper.res")), + ); + const stdlib = await definition(1, "length"); + assert.ok(stdlib, "Expected a stdlib definition"); + const stdlibPath = fileURLToPath(stdlib); + assert.ok(fs.existsSync(stdlibPath), stdlibPath); + assert.equal( + path.dirname(stdlibPath), + path.join( + root, + "node_modules/@rescript/runtime", + flat ? "" : "lib/ocaml", + ), + ); + + for (const [j, [prefix, expected]] of [ + ["Helper.va", "value"], + ["String.len", "length"], + ].entries()) { + const row = `let smoke = ${prefix}`; + const body = cleanSource.trimEnd() + "\n" + row; + const line = body.split("\n").length - 1; + notify("textDocument/didChange", { + textDocument: { ...document, version: 2 + j }, + contentChanges: [{ text: body }], + }); + const result = await request("textDocument/completion", { + textDocument: document, + position: { line, character: row.length }, + }); + const items = Array.isArray(result) ? result : (result?.items ?? []); + const match = items.find((item) => item.label === expected); + assert.ok(match, JSON.stringify(result)); + assert.equal( + fs.readFileSync(file, "utf8"), + cleanSource, + "Original file was changed", + ); + console.log( + `Matched ${prefix} → ${match.label}: ${match.detail} (${relative})`, + ); + } + + let start = messages.length; + notify("textDocument/didChange", { + textDocument: { ...document, version: 4 }, + contentChanges: [{ text: badSource }], + }); + await until( + () => diagnostics(start, true), + "No diagnostic for an unsaved type error", + ); + assert.ok( + fs.existsSync( + path.join( + root, + relative, + flat ? "incremental" : "___incremental", + "Main.res", + ), + ), + ); + + start = messages.length; + notify("textDocument/didChange", { + textDocument: { ...document, version: 5 }, + contentChanges: [{ text: cleanSource }], + }); + await until( + () => diagnostics(start, false), + "Unsaved diagnostic did not clear", + ); + + start = messages.length; + fs.writeFileSync(file, badSource); + await until( + () => /wrong/.test(fs.readFileSync(log, "utf8")), + "Watch build did not report the saved type error", + ); + notify("workspace/didChangeWatchedFiles", { + changes: [{ uri: uri(log), type: 2 }], + }); + await until( + () => diagnostics(start, true), + "No diagnostic from the new compiler log", + ); + + await request("shutdown", null); + notify("exit"); + await until(() => server.exitCode === 0, "Server did not exit cleanly"); + if (flat) { + await until( + () => !fs.existsSync(lock), + "Build watcher lock was not cleared on shutdown", + ); + } + console.log( + `Passed ${relative}: watcher, interface, local and stdlib definitions, unsaved and saved diagnostics`, + ); + } finally { + if (server.exitCode === null) { + send({ id: ++counter, method: "shutdown", params: null }); + await wait(100); + notify("exit"); + await wait(100); + if (server.exitCode === null) server.kill(); + } + fs.writeFileSync(file, cleanSource); + fs.rmSync(interfaceFile, { force: true }); + } +} + +async function main() { + const roots = process.argv.slice(2); + assert.equal( + roots.length, + 2, + "Usage: node server/test/build-layout.cjs V12_FIXTURE V13_FIXTURE", + ); + for (const [i, root] of roots.entries()) + await smokeTest(path.resolve(root), i === 1); +} + +main().catch((e) => { + console.error(e); + process.exitCode = 1; +}); diff --git a/shared/src/buildLayout.ts b/shared/src/buildLayout.ts new file mode 100644 index 000000000..aa67f00d2 --- /dev/null +++ b/shared/src/buildLayout.ts @@ -0,0 +1,81 @@ +import * as fs from "fs"; +import * as path from "path"; +import * as semver from "semver"; + +const makeLayout = (flat: boolean) => { + // Use slash-separated paths so the same strings can be used in LSP glob patterns. + const artifacts = flat ? "lib/rescript" : "lib/bs"; + return { + flat, + artifacts, + compilerInfo: `${artifacts}/compiler-info.json`, + compilerLog: `${artifacts}/.compiler.log`, + projectGraph: `${artifacts}/${flat ? ".sourcedirs.json" : "build.ninja"}`, + incremental: `${artifacts}/${flat ? "incremental" : "___incremental"}`, + watchLocks: flat + ? [`${artifacts}/watch.lock`] + : [ + ".bsb.lock", + "lib/rescript.lock", + "lib/rewatch.lock", + "lib/watch.lock", + ], + }; +}; + +export const legacyBuildLayout = makeLayout(false); +export const flatBuildLayout = makeLayout(true); + +export function findRescriptPackageDirectory(directory: string): string | null { + for (;;) { + const candidate = path.join(directory, "node_modules", "rescript"); + if (fs.existsSync(candidate)) return candidate; + const parent = path.dirname(directory); + if (parent === directory) return null; + directory = parent; + } +} + +function installedCompilerVersion(root: string): string | undefined { + const pkgDir = findRescriptPackageDirectory(root); + if (pkgDir !== null) { + try { + return JSON.parse( + fs.readFileSync(path.join(pkgDir, "package.json"), "utf8"), + ).version; + } catch {} + } +} + +export function buildLayout(root: string, version?: string) { + // Alpha.7 shipped before the layout change; alpha.8 and later use the + // flat layout even before the project has been built. + const parsed = semver.parse(version ?? installedCompilerVersion(root) ?? ""); + if (parsed) { + return semver.gte(parsed, "13.0.0-alpha.8") + ? flatBuildLayout + : legacyBuildLayout; + } + + // Custom compiler installs may not have a discoverable npm package. + return fs.existsSync(path.join(root, flatBuildLayout.artifacts)) + ? flatBuildLayout + : legacyBuildLayout; +} + +export function compiledArtifact( + root: string, + source: string, + namespace: string | null, + extension: ".cmi" | ".cmt" | ".cmti", + layout: ReturnType, +) { + const relative = path.relative(root, source); + const name = path.basename(relative, path.extname(relative)); + return path.join( + root, + layout.artifacts, + layout.flat ? "" : path.dirname(relative), + `${name}${namespace ? `-${namespace}` : ""}${extension}`, + ); +} diff --git a/shared/src/findBinary.ts b/shared/src/findBinary.ts index 902679ba8..abc04ae1a 100644 --- a/shared/src/findBinary.ts +++ b/shared/src/findBinary.ts @@ -3,6 +3,7 @@ import * as fsAsync from "fs/promises"; import * as path from "path"; import * as semver from "semver"; import * as url from "url"; +import { buildLayout, findRescriptPackageDirectory } from "./buildLayout"; export type BinaryName = | "bsc.exe" @@ -18,7 +19,6 @@ type FindBinaryOptions = { platformPath?: string | null; }; -const compilerInfoPartialPath = path.join("lib", "bs", "compiler-info.json"); // For arm64, try the arm64-specific directory first (e.g., darwinarm64), // then fall back to the generic platform directory (e.g., darwin) for older ReScript versions const platformDirArm64 = @@ -29,30 +29,6 @@ const normalizePath = (filePath: string | null): string | null => { return filePath != null ? path.normalize(filePath) : null; }; -const findFilePathFromProjectRoot = ( - directory: string | null, - filePartialPath: string, -): string | null => { - if (directory == null) { - return null; - } - - const filePath = path.join(directory, filePartialPath); - if (fs.existsSync(filePath)) { - return normalizePath(filePath); - } - - const parentDirStr = path.dirname(directory); - if (parentDirStr === directory) { - return null; - } - - return findFilePathFromProjectRoot( - normalizePath(parentDirStr), - filePartialPath, - ); -}; - export const findBinary = async ({ projectRootPath, binary, @@ -67,7 +43,7 @@ export const findBinary = async ({ try { const compilerInfo = path.resolve( projectRootPath, - compilerInfoPartialPath, + buildLayout(projectRootPath).compilerInfo, ); const contents = await fsAsync.readFile(compilerInfo, "utf8"); const compileInfo = JSON.parse(contents); @@ -85,10 +61,10 @@ export const findBinary = async ({ } catch {} } - const rescriptDir = findFilePathFromProjectRoot( - projectRootPath, - path.join("node_modules", "rescript"), - ); + const rescriptDir = + projectRootPath == null + ? null + : findRescriptPackageDirectory(projectRootPath); if (rescriptDir == null) { return null; } From 01044e4baea249acfa7d7cdea0b66f07ce141457 Mon Sep 17 00:00:00 2001 From: Florian Hammerschmidt Date: Thu, 3 Dec 2026 17:33:26 +0100 Subject: [PATCH 2/4] Match the CI Prettier version --- CHANGELOG.md | 1 + server/src/server.ts | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 09b455e5e..21137349d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ ## [Unreleased] #### :bug: Bug fix + - Support the flat `lib/rescript` build layout in ReScript 13. https://github.com/rescript-lang/rescript-vscode/issues/1194 - Fix language server crash (`ERR_INVALID_URL`) when resolving platform binaries for ReScript v12+ projects. https://github.com/rescript-lang/rescript-vscode/issues/1181 diff --git a/server/src/server.ts b/server/src/server.ts index 59d516256..d27d2c619 100644 --- a/server/src/server.ts +++ b/server/src/server.ts @@ -1677,7 +1677,8 @@ async function onMessage(msg: p.Message) { // These are static configuration options the client can set to enable certain let extensionClientCapabilitiesFromClient = initParams .initializationOptions?.extensionClientCapabilities as - extensionClientCapabilities | undefined; + | extensionClientCapabilities + | undefined; if (extensionClientCapabilitiesFromClient != null) { extensionClientCapabilities = extensionClientCapabilitiesFromClient; From d96ceb7628fb37366ff328602b1eed16c96573b9 Mon Sep 17 00:00:00 2001 From: Florian Hammerschmidt Date: Thu, 3 Dec 2026 17:50:38 +0100 Subject: [PATCH 3/4] Stage writable executables for CI stripping --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index cbafb4321..f51029111 100644 --- a/Makefile +++ b/Makefile @@ -3,8 +3,8 @@ SHELL = /bin/bash build: dune build cp -f _build/install/default/bin/rescript-editor-analysis analysis/rescript-editor-analysis.exe - cp -f _build/install/default/bin/rescript-editor-analysis rescript-editor-analysis.exe - cp -f _build/install/default/bin/rescript-tools rescript-tools.exe + install -m 755 _build/install/default/bin/rescript-editor-analysis rescript-editor-analysis.exe + install -m 755 _build/install/default/bin/rescript-tools rescript-tools.exe test: make -C analysis test From 7ce1d0ab7cfae2a2a1a2e8f2f2d9dcfd6bc93af3 Mon Sep 17 00:00:00 2001 From: Florian Hammerschmidt Date: Thu, 3 Dec 2026 18:58:07 +0100 Subject: [PATCH 4/4] Clean up editor-owned build watch locks on ReScript 12 --- server/src/server.ts | 19 ++++++++++++------- server/test/build-layout.cjs | 10 ++++------ 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/server/src/server.ts b/server/src/server.ts index d27d2c619..a6a8d5f77 100644 --- a/server/src/server.ts +++ b/server/src/server.ts @@ -1338,15 +1338,20 @@ async function startBuildWatcher( `Starting build watcher for ${projectRootPath} in ${buildCwd} (ReScript ${root.rescriptVersion ?? "unknown"})`, ); const layout = buildLayout(projectRootPath, root.rescriptVersion); - // Running the flat-layout compiler directly gives the editor the PID that - // owns watch.lock, so shutdown can clean its own lock without deleting - // another watcher's lock. The wrapper remains the fallback. - const nativePath = layout.flat + // The native watcher owns watch.lock in both layouts. Run it directly + // when available so shutdown knows which lock belongs to this editor. + const usesNativeWatch = + layout.flat || + (root.rescriptVersion != null && + semver.valid(root.rescriptVersion) != null && + semver.gte(root.rescriptVersion, "12.0.0")); + const nativePath = usesNativeWatch ? await utils.findRescriptExeBinary(projectRootPath) : null; - const runtimePath = nativePath - ? await utils.getRuntimePathFromProjectRoot(projectRootPath) - : null; + const runtimePath = + nativePath != null && fs.existsSync(nativePath) + ? await utils.getRuntimePathFromProjectRoot(projectRootPath) + : null; let bsbProcess = utils.runBuildWatcherUsingValidBuildPath( runtimePath && nativePath ? nativePath : rescriptBinaryPath, buildCwd, diff --git a/server/test/build-layout.cjs b/server/test/build-layout.cjs index 7652534b5..351c6e008 100644 --- a/server/test/build-layout.cjs +++ b/server/test/build-layout.cjs @@ -235,12 +235,10 @@ async function smokeTest(root, flat) { await request("shutdown", null); notify("exit"); await until(() => server.exitCode === 0, "Server did not exit cleanly"); - if (flat) { - await until( - () => !fs.existsSync(lock), - "Build watcher lock was not cleared on shutdown", - ); - } + assert.ok( + !fs.existsSync(lock), + `Build watcher lock was not cleared on shutdown: ${lock}`, + ); console.log( `Passed ${relative}: watcher, interface, local and stdlib definitions, unsaved and saved diagnostics`, );