mirror of
https://github.com/stablyai/orca.git
synced 2026-09-21 16:02:20 +00:00
* docs(windows): record the measured MSYS job-breakaway mechanism The per-PTY job already denies JOB_OBJECT_LIMIT_BREAKAWAY_OK for Cygwin/MSYS shells (#19068), but nothing records why, and a conpty.node built before that commit fails windows-msys-job.win32.test.ts in a way that reads as a source defect. Measured on a real Windows 11 host: both the plain and the exec- replacement Git Bash shapes leak, the escape is the MSYS runtime's own spawn/exec (fork keeps membership), and a single-variable A/B on usesCygwinRuntime flips the result 0/2 -> 4/4. Also names the gap the failure hid behind: node-pty-job-ownership.cjs asserts symbol presence, which cannot distinguish patch revisions. * fix(windows): reject a node-pty addon that predates the MSYS breakaway denial The native-runtime gate asserted only that terminateJob, listJobProcessIds and assignCurrentProcessToJob were exported. All three predate the Cygwin/MSYS breakaway denial, so an addon built before it passes every gate, isPtyJobOwnershipAvailable() returns true, and windows-pty-job.win32.test.ts passes 6/6 -- while every Git Bash child is created outside its pane's job and survives terminatePtyJob. Read the resolved .node and require the wide msys-2.0.dll literal that usesCygwinRuntime holds, the way stagedRelayAddonIsUnpatched() already tells a patched windows-process-tree addon from a published one. An addon the caller cannot name is refused rather than skipped: a gate that cannot see its subject is not a gate. Verified against real binaries on a Windows 11 host: the shared checkout's pre-#19068 build errors, a build from current patched source passes, a missing path errors. Also closes the cross-host packaging skip. The export half has to load the addon so it cannot run when the packaging host is not the target, which is how a Windows release built elsewhere could ship this. The marker is a file read and needs neither; an unrecognised layout warns rather than fails a release that was packaging fine. * fix(windows): check the MSYS breakaway denial on the rebuild path too The Electron probe carried the marker check, but it lives inside probeElectronNativeModules, which returns early whenever the Electron package binary is unusable. Covered by another path is not this path checks -- and the defect this whole change closes was a gate that looked like it checked. Reading the binary needs neither a loadable Electron nor an executable target arch, so assert it after the rebuild, beside the windows-process-tree assertion that exists for the same reason: this is the addon copied into the packaged app. Absent warns (a cross-platform rebuild need not leave a win32 addon on this disk); present and unmarked is fatal. The fixtures now write a real addon file, because the gate reads the binary it was told about rather than trusting the exports. Verified against the two real binaries measured on the Windows host: the pre-#19068 build fails this path, the build from current patched source passes. * fix(windows): check the marker on every ConPTY path the packaged app can load The packaged marker check read one hard-coded path, `build/Release/conpty.node`, and warned when it was absent. `loadNativeModule` tries `build/Release`, then `build/Debug`, then `prebuilds/win32-<arch>`, swallowing each failure, and `prunePackagedNodePty` drops the published prebuild only when a same-arch `build/Release` exists to replace it. So the two packages the check was added for were the two it could not see: - cross-host: no host but Windows can build conpty.node, so there is no `build/Release` and the prebuild is what ships. The check warned and returned. - cross-arch: `build/Release` is the packaging host's own arch, patched and marked, so the check printed OK -- while the target app cannot load it and falls through to the unmarked prebuild underneath. Measured, not assumed: both published Windows prebuilds in the node-pty tarball contain neither `msys-2.0.dll` nor `cygwin1.dll` in any encoding. They are the binary that leaks every MSYS pane child out of its job. It now sweeps every candidate present for the *target* arch and refuses a package with no candidate at all, which is a package with no ConPTY backend rather than a layout to shrug at. It runs for every Windows slice instead of only the branch the export check skips, so deleting the export check cannot silently take it too. A stale source build keeps the rebuild advice; the prebuild gets the advice that actually works, which is to package the slice on a Windows host of that arch. Also: the marker constant was re-typed in four places and was tied to the C++ literal that produces it by nothing at all, so editing the patch would have left a gate that fails every correctly rebuilt addon and tells the developer to do the one thing that cannot help. The fixtures now take the constant from the gate, and a test asserts the patch still adds `L"msys-2.0.dll"` to conpty.cc. And the rebuild path treated a missing addon as a warning even on the host that will run the install, where node-pty would fall through to that same prebuild. The verdict is now a value, so it is tested without a platform gate. * fix(windows): resolve the packaged ConPTY the way its loader does Sweeping every candidate and demanding the marker on all of them was wrong in the one case it was meant to make safe. `beforeBuild` runs `rebuild-native-deps.mjs --platform=win32 --arch=<target>`, so a cross-arch slice normally does get a patched `build/Release` for the target; `prunePackagedNodePty` keeps the prebuild anyway because its guard is `electronArch === process.arch` rather than the arch of the binary. That package is correct and its leftover prebuild is never reached, and the sweep failed it -- telling whoever ran it to package on a Windows arm64 host, which is both the wrong remedy and one no runner here can offer. Presence cannot separate that package from the one whose cross-arch rebuild quietly emitted the host's architecture, because the only difference is the arch of `build/Release`. So the gate now resolves the addon the way `loadNativeModule` does -- first candidate whose PE `IMAGE_FILE_HEADER.Machine` matches the target, walking root-then-lib for each layout in node-pty's own order -- and checks the marker on the one that will actually run. A package with no candidate, or none of the target's architecture, is refused: it has no ConPTY backend either way, and the second is exactly what a silently host-arch cross-build looks like. The PE machine reader already existed, privately, in the relay addon builder that needed the same "a cross-build cannot silently emit host arch" guarantee. It is now shared rather than copied. Two seams were unreachable from anything but Windows, so nothing tested them: - the afterPack hook's win32 block was an inline if/else that only a source-text assertion could inspect, and that assertion could not tell the difference between the check running and the check being wrapped in `try {} catch {}`. It is now `verifyPackagedWindowsNodePty`, and "the marker check runs even where the export check cannot" is four spied assertions instead of a string match. - the rebuild path's verdict read `process` directly, so the branch that fires only on the host being rebuilt for was dead on every other host. It now takes the host as arguments, and the fs checks, the warning and the failure are all exercised from macOS. Fixtures write a real PE header rather than `MZ fake addon`, since the gate now reads one. The machine table is pinned to the documented IMAGE_FILE_MACHINE values, because every fixture builds its header from that table and a table wrong in both entries would otherwise agree with itself. * fix(windows): say why the packaged ConPTY fell back, not just that it did The previous commit resolved the addon by architecture but still had one message for every way the resolution could land on the published prebuild. Those ways want opposite remedies, and the one it printed was the remedy the commit before it had just called wrong: - no source build in the package at all — the slice has to be built somewhere that can build node-pty for the target arch. - a source build that is there but is the packaging host's architecture, because the cross-arch rebuild did not honour `--arch` — re-running that rebuild is the fix, and "package on a Windows arm64 host" is neither necessary nor possible. The second is the common one, since node-pty publishes a prebuild for both Windows arches and prune keeps the target's on every cross-arch package. So the old text fired mostly on the case it described least. It now reports which source builds were skipped and the machine field each carried, and names the rebuild command. "Nothing the target can load" had the same problem in reverse: a zero-length or truncated `conpty.node` got a cross-architecture diagnosis. Every candidate is now named with what was actually read, including "not a PE image". The rebuild path asserts the architecture too. A rebuild that ignored `--arch` was otherwise only visible at packaging, two steps from the command that fixes it. Arches with no known machine value are left unjudged rather than guessed at. Two things the extraction broke or nearly broke, both found by mutation: - the shared PE reader answers `null` where the relay builder's private copy returned a number, which would have turned its "node-gyp ignored --arch" error into a `TypeError`. Both callers now go through `describePeMachine`. - the rebuild fixtures stage a script's co-located modules by walking its imports, and the walker only understood `from '...'` — so the gate's new `require('./windows-pe-machine.cjs')` was left behind and every subprocess test failed with a resolution error, which is the exact failure its own comment warns about. It now follows `require` and bare side-effect `import` as well, and has tests; the fixture stages the gate by walking it rather than by naming one file. Fixtures write real PE headers through one shared builder instead of three hand-rolled ones. * fix(windows): run the node-pty addon gates on the Windows job that can `rebuild-native-deps-node-pty.test.mjs` carries four `skipIf(platform !== 'win32')` tests. The full suite runs on ubuntu, and the Windows PR job runs an explicit file list that never named this file -- so those tests were skipped on Linux and never reached anywhere else. Three of them predate this branch. The Windows job is added the four node-pty addon suites plus the module-walker one; the comment above that list already says why it is the right place, which is that the addon assertions only hold once natives have been rebuilt. Running the path-joining suites there also covers the separator this gate's candidate list is built from. The rest is round-three review: - the rebuild-time arch assertion told a reader "node-gyp did not honour --arch" about a file that was not a PE image at all, which is a truncated or quarantined artifact and a different command to run. The two now read differently, and neither claims the other's cause. Same fix the packaged gate had one commit ago, in the place that had not had it yet. - the missing-addon error said node-pty "would load" a prebuild without checking it is there. It says "fall through to" now, which is true either way. - `isLoadableByArch` had no caller left once the packaged gate started needing the raw machine field for its message. Removed rather than kept warm. - each candidate's header is read once instead of up to three times. - the module walker's comment claimed every shape that reaches a co-located module; it does not follow `projectRequire`/`requireLocal`, and it must not -- those specifiers resolve against the project root, so following one stages the wrong path and the copy fails. Proven by trying: widening the pattern to require-shaped names broke nine tests on `projectRequire('./config/scripts/...')`. The comment now says what it follows and why it stops there. - a new test resolved a file URL with `.pathname`, which keeps the drive-letter slash on Windows -- the very job this commit adds it to. * docs(windows): put the superseded export-only gate in the past tense It describes what used to pass a broken addon, so present tense reads as a description of the gate the same document then explains replacing it. * fix(windows): repair what running the node-pty suites on Windows exposed Putting these files on the Windows job turned four assertions red on the first run. Three of them were in tests that carried `skipIf(platform !== 'win32')` and had therefore never executed anywhere, on any branch. - `writeFakeElectronRebuild` emitted the `windows-process-tree` addon a real rebuild leaves but never node-pty's, so every Windows test of the rebuild path ran against a tree no real rebuild can produce: node-pty "rebuilt" with nothing in `build/Release`. The new same-host check reads that state correctly and said so. The fake rebuild now writes `build/Release/conpty.node` when it was asked to rebuild node-pty for win32, with the marker and the target machine. - `mkTempProject` never staged `windows-process-tree-creation-time.cjs`. The rebuild script reaches it through `projectRequire`, which resolves against the project root, so the module walker cannot follow it and must not try. Staged by name, with a comment saying which of the two it is. Without it the windows-process-tree probe failed to load its own checker and the module joined `modulesToRebuild`, which is the second and third red assertion. - the two `nodePtyAddonPath` cases compared against a literal POSIX string. `resolve` returns a drive letter and backslashes on Windows, so they could only ever pass off it. Built from segments now, which still pins the `..` traversal that is the point of the test. Verified on macOS: ensure-native-runtime-job-ownership, verify-packaged-node-pty-job-ownership, windows-pe-machine, script-module-dependencies, rebuild-native-deps-node-pty, rebuild-native-deps, rebuild-native-deps-windows-process-tree, ensure-native-runtime -- 109 passed, 6 skipped. The 6 are the Windows-gated rebuild tests, which is the job this change is aimed at; Windows CI is the arbiter. * fix(windows): give the packaged fallback a third verdict, for a file that is no image The packaged gate had two remedies for landing on the published prebuild and picked between them on `!prebuilt`, which puts a truncated, empty or quarantined `build/Release/conpty.node` in the cross-arch bucket: "the source build beside it is the wrong architecture ... re-run with --arch". It is not the wrong architecture, it is not an architecture, and `--arch` is not the command. The rebuild-path gate was split for exactly this a commit ago; this is the same split in the place that had not had it. Also from review of the settled state: - the stale-source-build branch ended in a call that happened to throw, so a reader could not see it was terminal and the file was read twice to get there. The verdict is now an Error the caller throws, built once from the read it already did, and shared with `assertCygwinBreakawayDenied` rather than copied. - four injection seams had no consumer in production or in tests (`deniesBreakaway`, `peMachine`, and `exists`/`peMachine` on the rebuild verdict). An unused seam is a way for the tested path and the real one to drift apart; the tests drive both with real files. Removed. - the loader table existed in a docblock and in the reference doc, already disagreeing about row four. The docblock cites the doc now. - `peImage` stamped machine `0x0000` for an arch it had no value for, because `writeUInt16LE(undefined)` coerces to zero. A fixture that quietly invents the field the gates read is the same species of silent lie the gates exist to catch; it throws, and a test holds it to that. - a test named for refusing an unreadable candidate asserted only that something threw. Renamed to what it proves. * fix(windows): make the rebuild fixtures represent a tree that can exist Second round of what running these suites on Windows exposed. The module the walker could not stage is now staged, so the probe reached its own checker and the real reasons surfaced: - `writeFakeWindowsProcessTree` exported `{}`. The creation-time gate reads `supportedProcessDataFlags` off the addon and calls its absence "the tarball prebuilt, not a build of the patched source" — correctly. The fixture predates that gate and, being Windows-only, never met it. The healthy fake now reports the flag, taken from the gate's own constant. Two tests were failing on this, the second only because the module then joined `modulesToRebuild`. - `rebuilds a loadable ConPTY native that lacks Orca job ownership` asked for a node-pty rebuild in a tree where node-pty had none of the payload its package ships. It gets `writeFakeNodePtyConptyPayload` like its two siblings. I also tried making the fake rebuild emit `build/Release/conpty.node` the way a real one does, and backed it out: `restoreNodePtyWindowsConptyRuntime` keys off that file and then reads `third_party/conpty`, so emitting it in a tree without the package payload turns one honest gap into an ENOENT two steps away. The payload fixture is where "node-pty has its addon" belongs. macOS: ensure-native-runtime-job-ownership, verify-packaged-node-pty-job-ownership, windows-pe-machine, script-module-dependencies, rebuild-native-deps-node-pty, rebuild-native-deps, rebuild-native-deps-windows-process-tree, ensure-native-runtime — 112 passed, 6 skipped. The 6 are the Windows-gated rebuild tests; Windows CI is the arbiter and is why they are on that job now. * fix(windows): register the node-pty addon suites in the scope list too Putting the five suites in the Windows lane's vitest argv gets them run once the job starts; `WINDOWS_PACKAGE_TESTS` in `pr-code-change-scope.mjs` is what decides whether the job starts at all. Only the argv was updated, so a PR touching just `rebuild-native-deps-node-pty.test.mjs` would not have started the Windows job, and its four Windows-only cases — including the same-host-absent one added here — would have run on no machine for that PR. Exactly the shape of gap this branch is about. Both lists now name all five, and `windows-pe-machine`, `windows-pe-image-fixture` and `script-module-dependencies` join `NATIVE_RUNTIME_PREFIXES` so a change to the modules themselves starts it too. `win32-test-lane-registration.test.mjs` exists to catch precisely this and did not, because its matcher only recognises suite-level gates (`describe.runIf` / `describe.skipIf`) and a `.win32.` filename. These tests gate per `it`. Widening it is not this branch's change to make: about thirty files across the repo carry per-`it` Windows gates and are unregistered, so the ratchet would move far beyond node-pty. Flagged rather than done. Message repairs from the same review: - the non-PE arm of the rebuild-time arch error read "... is not a PE image, so nothing can load it, so node-pty would fall back ...". The shared consequence clause already opens with ", so". - the no-source-build packaging error ended "Package this Windows slice on such a host", which is wrong advice for the case where the host IS such a host and the rebuild simply left nothing — reachable when the artifact is removed before prune runs. It now names both readings and points at the beforeBuild output. - the relay-addon builder blamed `--arch` for a build output that is not a PE at all, the same guess the node-pty gate was taught to stop making. - the patch-drift assertion was a bare `toBe(true)`, so a real drift read as "expected false to be true". It now names the two things that can have drifted and what happens until they agree.
482 lines
15 KiB
JavaScript
482 lines
15 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
import { spawnSync } from 'node:child_process'
|
|
import { createRequire } from 'node:module'
|
|
import { existsSync, readFileSync, realpathSync } from 'node:fs'
|
|
import { release } from 'node:os'
|
|
import { basename, dirname, resolve } from 'node:path'
|
|
import {
|
|
ensureWindowsProcessTreeCommandLinePatch,
|
|
inspectWindowsProcessTreeAddon,
|
|
stageWindowsProcessTreeNodeAddonApiHeaders,
|
|
windowsProcessTreeAddonPath
|
|
} from './windows-process-tree-gyp-rebuild.mjs'
|
|
|
|
const require = createRequire(import.meta.url)
|
|
const { assertNodePtyJobOwnership, nodePtyAddonPath } = require('./node-pty-job-ownership.cjs')
|
|
const { assertWindowsProcessTreeCreationTime } = require('./windows-process-tree-creation-time.cjs')
|
|
const scriptPath = import.meta.filename
|
|
const projectDir = resolve(import.meta.dirname, '../..')
|
|
const runtime = readRuntimeArg()
|
|
|
|
const NATIVE_MODULES = [
|
|
'node-pty',
|
|
...(process.platform === 'win32'
|
|
? ['@orca/windows-registry', '@vscode/windows-process-tree']
|
|
: [])
|
|
]
|
|
const NODE_PTY_CONPTY_RUNTIME_FILES = ['conpty.dll', 'OpenConsole.exe']
|
|
const CHILD_CHECK_FLAG = '--check-only'
|
|
|
|
if (process.argv.includes(CHILD_CHECK_FLAG)) {
|
|
const failures = collectNativeModuleFailures()
|
|
if (failures.length > 0) {
|
|
for (const failure of failures) {
|
|
console.error(`${failure.moduleName}: ${failure.message}`)
|
|
}
|
|
process.exit(1)
|
|
}
|
|
process.exit(0)
|
|
}
|
|
|
|
if (runtime === 'node') {
|
|
ensureNodeRuntime()
|
|
} else if (runtime === 'electron') {
|
|
ensureElectronRuntime()
|
|
} else {
|
|
console.error('Usage: node config/scripts/ensure-native-runtime.mjs --runtime=node|electron')
|
|
process.exit(2)
|
|
}
|
|
|
|
function readRuntimeArg() {
|
|
const inline = process.argv.find((arg) => arg.startsWith('--runtime='))
|
|
if (inline) {
|
|
return inline.slice('--runtime='.length)
|
|
}
|
|
|
|
const runtimeIndex = process.argv.indexOf('--runtime')
|
|
if (runtimeIndex !== -1) {
|
|
return process.argv[runtimeIndex + 1]
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
function ensureNodeRuntime() {
|
|
const initial = runNodeCheck()
|
|
const patchedNodePtyRebuildReason = getPatchedNodePtyRebuildReason()
|
|
if (initial.ok && !patchedNodePtyRebuildReason) {
|
|
return
|
|
}
|
|
|
|
if (patchedNodePtyRebuildReason) {
|
|
console.warn(`[native-runtime] ${patchedNodePtyRebuildReason}`)
|
|
if (!initial.ok) {
|
|
printCheckError(initial)
|
|
}
|
|
const failedModules = initial.failures.map((failure) => failure.moduleName)
|
|
const rebuildModules = [
|
|
'node-pty',
|
|
...failedModules.filter((moduleName) => moduleName !== 'node-pty')
|
|
]
|
|
rebuildNodeRuntimeModules(rebuildModules)
|
|
verifyNodeRuntimeAfterRebuild()
|
|
return
|
|
}
|
|
|
|
const failedModules = initial.failures.map((failure) => failure.moduleName)
|
|
console.warn(
|
|
`[native-runtime] ${formatRuntimeLabel('node')} cannot load native modules; rebuilding ${failedModules.join(', ')} for Node.`
|
|
)
|
|
printCheckError(initial)
|
|
rebuildNodeRuntimeModules(failedModules)
|
|
verifyNodeRuntimeAfterRebuild()
|
|
}
|
|
|
|
function verifyNodeRuntimeAfterRebuild() {
|
|
const final = runNodeCheck()
|
|
if (!final.ok) {
|
|
console.error(
|
|
`[native-runtime] Native modules still do not load for ${formatRuntimeLabel('node')}.`
|
|
)
|
|
printCheckError(final)
|
|
process.exit(1)
|
|
}
|
|
}
|
|
|
|
function ensureElectronRuntime() {
|
|
const initial = runElectronCheck()
|
|
const patchedNodePtyRebuildReason = getPatchedNodePtyRebuildReason()
|
|
if (initial.ok && !patchedNodePtyRebuildReason) {
|
|
return
|
|
}
|
|
|
|
if (patchedNodePtyRebuildReason) {
|
|
console.warn(`[native-runtime] ${patchedNodePtyRebuildReason}`)
|
|
if (!initial.ok) {
|
|
printCheckError(initial)
|
|
}
|
|
} else {
|
|
console.warn(
|
|
`[native-runtime] ${formatRuntimeLabel('electron')} cannot load native modules; rebuilding native deps for Electron.`
|
|
)
|
|
printCheckError(initial)
|
|
}
|
|
runNodeScript(['config/scripts/rebuild-native-deps.mjs'])
|
|
|
|
const final = runElectronCheck()
|
|
if (!final.ok) {
|
|
console.error(
|
|
`[native-runtime] Native modules still do not load for ${formatRuntimeLabel('electron')}.`
|
|
)
|
|
printCheckError(final)
|
|
process.exit(1)
|
|
}
|
|
}
|
|
|
|
function runNodeCheck() {
|
|
// Why: a failed native addon load can poison the current process, so the
|
|
// post-rebuild verification must happen in a fresh Node process.
|
|
const result = spawnSync(process.execPath, [scriptPath, CHILD_CHECK_FLAG], {
|
|
cwd: projectDir,
|
|
encoding: 'utf8',
|
|
stdio: ['ignore', 'pipe', 'pipe']
|
|
})
|
|
|
|
return parseChildCheckResult(result)
|
|
}
|
|
|
|
function runElectronCheck() {
|
|
const electronExecutable = resolveInstalledElectronExecutable()
|
|
if (!electronExecutable.ok) {
|
|
return { ok: false, error: electronExecutable.error }
|
|
}
|
|
|
|
const result = spawnSync(electronExecutable.path, [scriptPath, CHILD_CHECK_FLAG], {
|
|
cwd: projectDir,
|
|
env: {
|
|
...process.env,
|
|
ELECTRON_RUN_AS_NODE: '1'
|
|
},
|
|
encoding: 'utf8',
|
|
stdio: ['ignore', 'pipe', 'pipe']
|
|
})
|
|
|
|
return parseChildCheckResult(result)
|
|
}
|
|
|
|
function resolveInstalledElectronExecutable() {
|
|
const electronPackageDir = resolve(projectDir, 'node_modules/electron')
|
|
try {
|
|
const electronVersion = JSON.parse(
|
|
readFileSync(resolve(electronPackageDir, 'package.json'), 'utf8')
|
|
).version
|
|
const platformPath = getElectronPlatformPath()
|
|
const installedVersion = readFileSync(resolve(electronPackageDir, 'dist', 'version'), 'utf8')
|
|
.trim()
|
|
.replace(/^v/, '')
|
|
if (installedVersion !== electronVersion) {
|
|
return {
|
|
ok: false,
|
|
error: new Error(
|
|
`Electron package binary version ${installedVersion} does not match ${electronVersion}.`
|
|
)
|
|
}
|
|
}
|
|
const installedPlatformPath = readFileSync(resolve(electronPackageDir, 'path.txt'), 'utf8')
|
|
if (installedPlatformPath !== platformPath) {
|
|
return {
|
|
ok: false,
|
|
error: new Error(
|
|
`Electron package path.txt points at ${installedPlatformPath}, expected ${platformPath}.`
|
|
)
|
|
}
|
|
}
|
|
const electronPath = process.env.ELECTRON_OVERRIDE_DIST_PATH
|
|
? resolve(process.env.ELECTRON_OVERRIDE_DIST_PATH, platformPath)
|
|
: resolve(electronPackageDir, 'dist', platformPath)
|
|
if (!existsSync(electronPath)) {
|
|
return { ok: false, error: new Error(`Electron executable is missing at ${electronPath}.`) }
|
|
}
|
|
return { ok: true, path: electronPath }
|
|
} catch (error) {
|
|
return { ok: false, error }
|
|
}
|
|
}
|
|
|
|
function getElectronPlatformPath() {
|
|
const targetPlatform =
|
|
process.env.ELECTRON_INSTALL_PLATFORM || process.env.npm_config_platform || process.platform
|
|
switch (targetPlatform) {
|
|
case 'mas':
|
|
case 'darwin':
|
|
return 'Electron.app/Contents/MacOS/Electron'
|
|
case 'freebsd':
|
|
case 'openbsd':
|
|
case 'linux':
|
|
return 'electron'
|
|
case 'win32':
|
|
return 'electron.exe'
|
|
default:
|
|
throw new Error(`Electron builds are not available on platform: ${targetPlatform}`)
|
|
}
|
|
}
|
|
|
|
function parseChildCheckResult(result) {
|
|
const failures = parseCheckFailures(result.stderr)
|
|
|
|
return {
|
|
ok: result.status === 0,
|
|
status: result.status,
|
|
stdout: result.stdout,
|
|
stderr: result.stderr,
|
|
error: result.error,
|
|
failures
|
|
}
|
|
}
|
|
|
|
function parseCheckFailures(stderr) {
|
|
const failures = []
|
|
for (const line of (stderr ?? '').split(/\r?\n/)) {
|
|
const match = /^([^:]+):\s*(.*)$/.exec(line)
|
|
if (match && NATIVE_MODULES.includes(match[1])) {
|
|
failures.push({ moduleName: match[1], message: match[2] })
|
|
}
|
|
}
|
|
return failures
|
|
}
|
|
|
|
function collectNativeModuleFailures() {
|
|
const failures = []
|
|
for (const moduleName of NATIVE_MODULES) {
|
|
try {
|
|
loadNativeModule(moduleName)
|
|
} catch (cause) {
|
|
failures.push({ moduleName, message: formatError(cause), cause })
|
|
}
|
|
}
|
|
return failures
|
|
}
|
|
|
|
function loadNativeModule(moduleName) {
|
|
if (moduleName === '@vscode/windows-process-tree') {
|
|
// A bare require loads the .node addon on win32, so it catches an ABI
|
|
// mismatch on its own. What it cannot catch is *which* addon loaded: the
|
|
// published tarball ships a prebuilt built from unpatched source that is
|
|
// node-addon-api, so it requires cleanly, reads every process's command
|
|
// line out of its address space, and ignores the CreationTime flag. Check
|
|
// the binary on both counts, not the load.
|
|
assertWindowsProcessTreeCreationTime({ module: require(moduleName) })
|
|
if (inspectWindowsProcessTreeAddon(windowsProcessTreeAddonPath()) === 'unpatched') {
|
|
throw new Error(
|
|
'the loaded addon still calls ReadProcessMemory, so it was not built from the patched ' +
|
|
'source. Rebuild it (pnpm run rebuild:electron) rather than using the published prebuild.'
|
|
)
|
|
}
|
|
return
|
|
}
|
|
if (moduleName === '@orca/windows-registry') {
|
|
const registry = require(moduleName)
|
|
// Why: the package defers loading its .node addon until the first registry call.
|
|
registry.getRegistryKey(registry.HK.CU, 'Environment')
|
|
return
|
|
}
|
|
if (moduleName === 'node-pty') {
|
|
loadNodePtyNativeModule()
|
|
return
|
|
}
|
|
|
|
require(moduleName)
|
|
}
|
|
|
|
function loadNodePtyNativeModule() {
|
|
require('node-pty')
|
|
|
|
const { loadNativeModule } = require('node-pty/lib/utils')
|
|
const nativeName = getNodePtyNativeModuleName()
|
|
// Why: node-pty's Windows JS wrapper defers conpty.node/pty.node until a
|
|
// terminal is created, so require('node-pty') alone can miss ABI mismatches.
|
|
const native = loadNativeModule(nativeName)
|
|
assertNodePtyWindowsConptyRuntime(native?.dir)
|
|
assertNodePtyJobOwnership({
|
|
nativeName,
|
|
native,
|
|
addonPath: nodePtyAddonPath(require.resolve('node-pty/lib/utils'), native, nativeName)
|
|
})
|
|
if (requiresPatchedNodePtySourceBuild() && !isNodePtyReleaseBuildDir(native?.dir)) {
|
|
throw new Error(
|
|
`node-pty resolved to ${native.dir}; expected build/Release so Orca's node-pty patch is active`
|
|
)
|
|
}
|
|
}
|
|
|
|
function assertNodePtyWindowsConptyRuntime(nativeDir) {
|
|
if (process.platform !== 'win32' || !isNodePtyReleaseBuildDir(nativeDir)) {
|
|
return
|
|
}
|
|
const runtimeDir = resolve(projectDir, 'node_modules', 'node-pty', 'build', 'Release', 'conpty')
|
|
const missingFile = NODE_PTY_CONPTY_RUNTIME_FILES.find(
|
|
(filename) => !existsSync(resolve(runtimeDir, filename))
|
|
)
|
|
if (missingFile) {
|
|
throw new Error(`node-pty ConPTY runtime file is missing: ${resolve(runtimeDir, missingFile)}`)
|
|
}
|
|
}
|
|
|
|
function getNodePtyNativeModuleName() {
|
|
if (process.platform !== 'win32') {
|
|
return 'pty'
|
|
}
|
|
|
|
return getWindowsBuildNumber() >= 18309 ? 'conpty' : 'pty'
|
|
}
|
|
|
|
function getPatchedNodePtyRebuildReason() {
|
|
if (!requiresPatchedNodePtySourceBuild()) {
|
|
return null
|
|
}
|
|
|
|
// Why: a loadable upstream node-pty prebuild is not enough; Orca's Unix and
|
|
// Windows patches only land in the source-built build/Release artifacts.
|
|
const nodePtyDir = resolve(projectDir, 'node_modules', 'node-pty')
|
|
const artifactPaths = patchedNodePtyArtifactPaths(nodePtyDir)
|
|
const missingArtifact = artifactPaths.find((artifactPath) => !existsSync(artifactPath))
|
|
|
|
if (!missingArtifact) {
|
|
return null
|
|
}
|
|
|
|
return 'Patched node-pty build artifacts are missing; rebuilding native deps.'
|
|
}
|
|
|
|
function patchedNodePtyArtifactPaths(nodePtyDir) {
|
|
if (process.platform === 'win32') {
|
|
const releaseDir = resolve(nodePtyDir, 'build', 'Release')
|
|
return [
|
|
resolve(releaseDir, 'conpty.node'),
|
|
...NODE_PTY_CONPTY_RUNTIME_FILES.map((filename) => resolve(releaseDir, 'conpty', filename))
|
|
]
|
|
}
|
|
|
|
const artifactPaths = [resolve(nodePtyDir, 'build', 'Release', 'pty.node')]
|
|
// Why: node-pty only builds spawn-helper on macOS; Linux builds only pty.node.
|
|
if (process.platform === 'darwin') {
|
|
artifactPaths.push(resolve(nodePtyDir, 'build', 'Release', 'spawn-helper'))
|
|
}
|
|
return artifactPaths
|
|
}
|
|
|
|
function requiresPatchedNodePtySourceBuild() {
|
|
const nodePtyPatchPath = resolve(projectDir, 'config', 'patches', 'node-pty@1.1.0.patch')
|
|
if (!existsSync(nodePtyPatchPath)) {
|
|
return false
|
|
}
|
|
|
|
return existsSync(resolve(projectDir, 'node_modules', 'node-pty'))
|
|
}
|
|
|
|
function isNodePtyReleaseBuildDir(nativeDir) {
|
|
return typeof nativeDir === 'string' && nativeDir.replace(/\\/g, '/').includes('build/Release/')
|
|
}
|
|
|
|
function getWindowsBuildNumber() {
|
|
const match = /(\d+)\.(\d+)\.(\d+)/g.exec(release())
|
|
return match && match.length === 4 ? Number.parseInt(match[3], 10) : 0
|
|
}
|
|
|
|
function rebuildNodeRuntimeModules(moduleNames) {
|
|
for (const moduleName of moduleNames) {
|
|
let moduleDir = dirname(require.resolve(`${moduleName}/package.json`))
|
|
if (moduleName === '@vscode/windows-process-tree') {
|
|
// Why before node-gyp: this module is rebuilt precisely because the
|
|
// binary was the unpatched one, and pnpm materializes it unpatched often
|
|
// enough that compiling the source as-is would just rebuild the same
|
|
// reader and fail the verify pass. The patched binding.gyp then includes
|
|
// deps/node-addon-api, which the tarball does not ship, and node-gyp must
|
|
// run from the physical dir -- both reasons live in
|
|
// windows-process-tree-gyp-rebuild.mjs.
|
|
ensureWindowsProcessTreeCommandLinePatch(moduleDir)
|
|
stageWindowsProcessTreeNodeAddonApiHeaders(moduleDir)
|
|
moduleDir = realpathSync(moduleDir)
|
|
}
|
|
console.warn(`[native-runtime] Rebuilding ${moduleName} with node-gyp.`)
|
|
runPnpm(['exec', 'node-gyp', 'rebuild'], { cwd: moduleDir })
|
|
if (moduleName === 'node-pty' && process.platform === 'win32') {
|
|
runNodeScript([resolve(moduleDir, 'scripts', 'post-install.js')])
|
|
}
|
|
}
|
|
}
|
|
|
|
function runPnpm(args, { cwd = projectDir } = {}) {
|
|
// cmd.exe resolves both Corepack's pnpm.cmd and pnpm 12's native pnpm.exe.
|
|
const command = 'pnpm'
|
|
const env =
|
|
process.platform === 'linux' && args.includes('node-gyp')
|
|
? { ...process.env, CXXFLAGS: `${process.env.CXXFLAGS ?? ''} -std=gnu++2a`.trim() }
|
|
: process.env
|
|
const result = spawnSync(command, args, {
|
|
cwd,
|
|
stdio: 'inherit',
|
|
shell: process.platform === 'win32',
|
|
env
|
|
})
|
|
|
|
if (result.error || result.status !== 0) {
|
|
console.error(`[native-runtime] ${command} ${args.join(' ')} failed in ${cwd}.`)
|
|
if (result.error) {
|
|
console.error(formatError(result.error))
|
|
}
|
|
process.exit(result.status ?? 1)
|
|
}
|
|
}
|
|
|
|
function runNodeScript(args) {
|
|
const result = spawnSync(process.execPath, args, {
|
|
cwd: projectDir,
|
|
stdio: 'inherit'
|
|
})
|
|
|
|
if (result.error || result.status !== 0) {
|
|
console.error(`[native-runtime] ${basename(process.execPath)} ${args.join(' ')} failed.`)
|
|
if (result.error) {
|
|
console.error(formatError(result.error))
|
|
}
|
|
process.exit(result.status ?? 1)
|
|
}
|
|
}
|
|
|
|
function printCheckError(result) {
|
|
for (const failure of result.failures ?? []) {
|
|
console.warn(`[native-runtime] ${failure.moduleName}: ${failure.message}`)
|
|
}
|
|
if (result.error) {
|
|
console.warn(`[native-runtime] ${formatError(result.error)}`)
|
|
}
|
|
if (result.stderr?.trim()) {
|
|
console.warn(result.stderr.trim())
|
|
}
|
|
if (result.stdout?.trim()) {
|
|
console.warn(result.stdout.trim())
|
|
}
|
|
if (
|
|
result.status != null &&
|
|
!result.error &&
|
|
!result.stderr?.trim() &&
|
|
!result.stdout?.trim() &&
|
|
result.status !== 0
|
|
) {
|
|
console.warn(`[native-runtime] Native check exited with status ${result.status}.`)
|
|
}
|
|
}
|
|
|
|
function formatError(error) {
|
|
return error instanceof Error ? error.message : String(error)
|
|
}
|
|
|
|
function formatRuntimeLabel(value) {
|
|
if (value === 'electron') {
|
|
return `Electron ${process.env.npm_package_devDependencies_electron ?? ''}`.trim()
|
|
}
|
|
return `Node ${process.versions.node}`
|
|
}
|