Files
orca/config/packaged-runtime-node-modules.cjs
T
Brennan Benson fd9125ea8c feat(native-chat): Codex structured native chat restructure (#16729)
* feat(native-chat): port structured Codex sessions from restructure-recovery

Rebuilds the desktop structured native-chat implementation from
brennanb2025/native-chat-restructure-recovery (tip 4e31c08db3) on top of
current main as a single commit, scoped to the local Codex path.

Ported:
- Structured agent-session core: durable record store + single-writer lease,
  canonical journal, agent-session wire host/attach/eviction/subscribers,
  `agentSession.*` RPC surface (registered via ALL_RPC_METHODS; host-side
  mobile allowlist included for wire compat), pty write gate, transcript
  additions, and the Codex app-server adapter/launch resolution.
- Renderer: NativeChatStructuredSession view/composer stack, structured
  launch path with the single-flight guard, local structured session tabs
  sync, activation gate + structured inventory (read-only
  `agentSession.handoffStatus` probe), agent-session tabs in the tab strip,
  AI-vault structured session activation, and the settings pane with the
  parent Experimental Chat UI toggle plus the nested "Use updated structured
  native chat" toggle. New sessions require both flags, agent codex, no
  prompt, and a local non-WSL, non-Windows-host execution host
  (structured-native-chat-availability).
- Fixes 72c013cea6 (verified Codex launch recovery), 8ddbaf5e3d (defer
  native terminal view switching affordances), and 4e31c08db3 (release the
  launch gate after a visibility retry) with their regression tests,
  including the third-launch-after-retry guard case.
- Cross-version agent-session wire test + CI lane, packaging entries
  (proper-lockfile, agent-tooling asar excludes), and the wire-compat doc
  section.

Deliberately not ported: mobile/ changes, the Claude structured runtime
(only the claude-transcript-branch-proof and claude-structured-owner-identity
leaf modules remain, backing the kept TUI-recovery arms), the terminal↔chat
adoption/handoff flow (`agentSession.adoptTerminal`/`requestHandoff`, the
handoff request engine, TUI adoption machinery, orca-runtime adoption
methods), renderer switching affordances and their dead leftovers, the
hook/subagent-status refactor cluster, and unrelated branch changes. The
crash-during-acquisition recovery path (restart handoff adjudication,
restore/reverse re-acquire, lease schema handoff keys) is kept because every
plain direct launch depends on it; a trimmed handoff coordinator exposes
only status/restore/close.

Branch edits that targeted files main has since split (ipc/pty.ts,
worktrees.ts, rpc/methods/terminal.ts, useIpcEvents, pty-connection,
store/slices/terminals.ts, runtime-types, web preload) were re-applied to
the split modules, preserving main's newer logic (Windows CIM fallback,
browser tab close rework, cold-restore resume flow, dispatcher threading).

Known seam: the mobile clipboard image-provenance CONSUMER gate ships
(agentSession.send refuses unproven mobile image refs with
agent_session_image_untrusted) but the producer hunk in
rpc/methods/clipboard.ts stays with the unported mobile cluster, so mobile
image sends into structured chat fail closed until that side ports.

* fix(native-chat): trust only authenticated local image uploads

* fix(build): preserve Windows process-tree patch application

* test(windows): include process creation time in addon fixture

* fix(build): run windows-process-tree node-gyp from the physical package dir

gyp expands the node-addon-api dependency by probing node, whose cwd
resolves to the package's physical directory in the store, so the emitted
target is a store-relative ../../../../node-addon-api@... hop. gyp then
resolves that hop against the rebuild cwd; from the node_modules
symlink/junction it escapes the store and configure fails with
"node_addon_api.gyp not found" (run 32999886072).

Rebuild from realpath(package dir) so both bases agree, matching how the
package manager itself runs native install scripts. The regression test
replays gyp's expansion+resolution against the planned cwd and fails
without the fix.

* fix(native-chat): keep chat tabs visible through terminal closes and empty-worktree launches

Two proven blockers in the native Codex tab contract:

closeTerminalTab pre-empted the canonical unified close. With one terminal
left it deactivated the worktree on a terminal/editor/browser-only check,
blanking a workspace that still held a renderable agent-session tab; with
two or more it pre-picked a successor from terminal entities only,
re-stamping the group active before closeUnifiedTab's MRU/neighbor repair
could land on the chat tab. Successor choice now defers to the unified
contract whenever the terminal has a unified row, and deactivation is
gated on the unified renderable count (matching leaveWorktreeIfEmpty),
with the legacy pre-pick kept only for terminals without a unified row.

A structured session created on an empty worktree was published into the
host's headless group while preserveLocalLayout froze the local layout,
leaving the tab in store but permanently off screen. A preserveLocalLayout
owner now always takes client-owned placement — repairing a rendered
leaf whose group record is missing, or materializing a rendered group on a
truly empty worktree — and applies the client-derived layout repair while
still rejecting host-authored layout.

Regression tests drive the real store through closeTerminalTab (git
worktree and folder workspace) and the real snapshot applier for the
empty-worktree adoption states; all fail without the fixes.

* fix(native-chat): close stale turns and retry rejected sends

* fix(native-chat): retire hosted rows on structured tab activation

* fix(native-chat): preserve rpc defaults across main merge

* chore: format remote wire compatibility guide

* test(native-chat): cover retry after unconfirmed send

* fix(native-chat): reload outbox on session switch

* docs(settings): disclose structured chat platform limits

* fix(native-chat): await Codex launch-home preparation

* fix(codex): align child-process allowlist with async trust bridge

* test(identity): update inventory for tab surface refactor

* fix(windows): preserve process-tree CRLF patch sources

* fix(native-chat): anchor an unmatched chat echo where it was sent (#16117)

* fix(native-chat): anchor an unmatched chat echo where it was sent

The reported symptom was old user messages replaying below every new turn, so the
conversation read as scrambled. The cause was not that the echo failed to match a
transcript row. Claude consumes a mid-turn send through a `queued_command`
attachment and writes no `type:"user"` record for it, so some echoes can never
match, and no amount of matching will change that. The cause was WHERE an
unmatched echo rendered: buildMobileNativeChatTransientData appended every pending
item after the entire transcript, so it re-read below each turn that landed
afterwards.

Render each echo directly after the transcript row it was sent against, using the
baseline the send already captures. An unmatched echo is then at worst a duplicate
in the right position rather than a scrambled one, and it stays visible. Echoes
sharing an anchor keep send order; a send with no baseline, or one whose anchor
folding dropped, still falls back to the tail.

Deliberately NOT fixed by deleting the echo. Inferring from send ordering that an
echo can never match, then removing it, loses the user's own text for a message
the agent did receive, and it cannot fire in the common case anyway - measured
drain groups are 1,017 of size 1 against 55 larger. It also escalates an existing
gap: the count pass has no baseline-tail guard, unlike the glue pass, while
`messages` is a 40-row window that head-trims, resets on reconnect and grows at
the front on loadEarlier, so a false landing there would license deleting a
DIFFERENT outstanding message.

That count-pass gap is real and left for a separate change; anchoring makes its
worst case a duplicate in place rather than a scrambled conversation.

* fix(native-chat): preserve folded echo anchors

* fix(native-chat): preserve forward-folded echo anchors

* fix(native-chat): keep leading folded echoes in place

* fix(workspace-cleanup): show git status for every row (#16690)

* fix(native-chat): refuse structured chat on every Windows execution path

canUseStructuredNativeChat only refused win32 when a project runtime
resolved, so folder-workspace keys (and other keys with no project
runtime) failed open into structured chat on Windows. Fail closed on
win32 unconditionally after the host check, matching the settings copy:
local macOS/Linux only; Windows/WSL/SSH stay on terminal chat.

* fix(native-chat): restore runtime refusals behind the win32 gate

506d375de3 replaced the project-runtime checks with a bare platform test,
so a WSL or repair-required runtime resolution would no longer refuse
structured chat off-win32. Keep the unconditional win32 refusal and
re-run the runtime resolution after it, so the gate does not depend on
the resolver's own platform guard. Tests inject WSL and repair-required
resolutions on darwin/linux and fail against the regressed gate.

* fix structured session journal durability

* fix structured tab active pointer after restart

* fix(native-chat): await optional lease renewal callbacks

* refactor(skills): extract install error messages

* fix(agent-session): harden recovery ownership

* fix(native-chat): retain panes across tab activation

* fix(native-chat): address round-one review findings

* test(native-chat): align integration coverage after main merge

* fix(native-chat): harden round-two reliability

* fix(native-chat): harden round-three reliability

* fix(native-chat): close round-four recovery gaps

* fix(native-chat): separate bounded journal key forms

* fix(native-chat): reset outbox error in render on session switch

The switch effect adjusted error state after the sessionId prop changed,
tripping react-doctor's no-adjust-state-on-prop-change on the changed-code
gate and flashing the old session's banner for a frame. Reset it with the
render-time previous-value guard instead.

* fix(native-chat): invalidate stale outbox settlements

* test(native-chat): restore settled-error session-switch regression

a6e2379bd1 replaced this test with the in-flight settlement race test,
leaving the render-time error reset unpinned: deleting the reset block
still passed the whole native-chat suite. Keep both scenarios pinned;
they are distinct (settled error clears on switch vs stale settlement
invalidated in the commit-to-passive window).

* test(wire): make release checkouts race safe

* test(wire): pin cross-process checkout single-flight and importer specifier contract

* test(wire): harden release checkout lifecycle

* fix(build): drop CR-byte residue from windows-process-tree patch

The two trailing CR bytes on the patch's deletion lines are a proven
no-op: pnpm hashes patches CRLF-normalized (both forms hash to the
lockfile's 946ffb2b) and materializes this package without applying the
patch in either form, so the load-bearing build edits come solely from
applyWindowsProcessTreeBuildFixes() (#16947), which handles both source
EOL forms. Restore byte-identity with main and repin the contract test
to the post-#16947 reality: LF-only patch bytes plus lockfile hash sync.

* fix(native-chat): skip empty startup recovery
2026-08-28 16:45:58 -07:00

514 lines
18 KiB
JavaScript

const {
copyFileSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
realpathSync,
rmSync
} = require('node:fs')
const { dirname, join, resolve } = require('node:path')
const { builtinModules, createRequire } = require('node:module')
const projectDir = resolve(__dirname, '..')
const requireFromProject = createRequire(join(projectDir, 'package.json'))
const PACKAGED_RUNTIME_PACKAGE_ROOTS = [
'@electron-toolkit/utils',
'@linear/sdk',
'@parcel/watcher',
'electron-updater',
'i18next',
'jsonc-parser',
'node-pty',
'posthog-node',
'proper-lockfile',
// serve-sim (for CLI JS entry + closure + state/middleware + to make packaged require('serve-sim') + its internal relatives work; mirrors other runtime JS like ws/yaml/zod. Natives/dylibs still via extraResources + the node_modules/serve-sim copy in resources from builder. Client if added too.
'serve-sim',
'qrcode',
'ssh2',
'tweetnacl',
'ws',
'yaml',
'zod'
]
const WINDOWS_PACKAGED_RUNTIME_PACKAGE_ROOTS = [
'@vscode/windows-process-tree',
'windows-native-registry'
]
const NODE_PTY_PREBUILD_PREFIX_BY_PLATFORM = {
darwin: 'darwin-',
linux: 'linux-',
win32: 'win32-'
}
const NODE_PTY_CONPTY_RUNTIME_FILES = ['conpty.dll', 'OpenConsole.exe']
const PARCEL_WATCHER_PLATFORM_PREFIX_BY_PLATFORM = {
darwin: 'watcher-darwin',
linux: 'watcher-linux',
win32: 'watcher-win32'
}
const ELECTRON_ARCHITECTURE_BY_ENUM = {
0: 'ia32',
1: 'x64',
2: 'arm',
3: 'arm64',
4: 'universal'
}
const PACKAGED_NATIVE_ARCHITECTURES = new Set(['ia32', 'x64', 'arm', 'arm64'])
const TYPE_DECLARATION_ARTIFACT_RE = /\.d\.(?:c|m)?ts(?:\.map)?$/
const VERSIONED_ONNXRUNTIME_DYLIB_RE = /^libonnxruntime\.\d[\d.]*\.dylib$/
const NODE_BUILTINS = new Set([
...builtinModules,
...builtinModules.map((moduleName) => `node:${moduleName}`)
])
function packageNameFromSpecifier(specifier) {
if (specifier.startsWith('@')) {
const [scope, name] = specifier.split('/')
return scope && name ? `${scope}/${name}` : specifier
}
return specifier.split('/')[0]
}
function isPackagedExternalSpecifier(specifier) {
return (
!specifier.startsWith('.') &&
!specifier.startsWith('/') &&
specifier !== 'electron' &&
!NODE_BUILTINS.has(specifier)
)
}
function resolvePackageJsonPath(packageName, fromDir = projectDir) {
const nested = join(fromDir, 'node_modules', packageName, 'package.json')
if (existsSync(nested)) {
return nested
}
// Why: published serve-sim has no "." export (only ./middleware and ./state), so
// require.resolve('serve-sim') fails even though the package is present for bridge exec.
if (packageName === 'serve-sim') {
const direct = join(projectDir, 'node_modules', 'serve-sim', 'package.json')
if (existsSync(direct)) {
return direct
}
}
try {
return requireFromProject.resolve(`${packageName}/package.json`, { paths: [fromDir] })
} catch {
let entryPath
try {
entryPath = requireFromProject.resolve(packageName, { paths: [fromDir] })
} catch {
throw new Error(`Could not resolve package ${packageName} from ${fromDir}`)
}
let dir = dirname(entryPath)
while (dir !== dirname(dir)) {
const packageJsonPath = join(dir, 'package.json')
if (existsSync(packageJsonPath)) {
return packageJsonPath
}
dir = dirname(dir)
}
throw new Error(`Could not find package.json for ${packageName}`)
}
}
function readPackage(packageName, fromDir = projectDir) {
const packageJsonPath = resolvePackageJsonPath(packageName, fromDir)
const packageDir = realpathSync(dirname(packageJsonPath))
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'))
return {
name: packageJson.name ?? packageName,
packageDir,
dependencies: Object.keys(packageJson.dependencies ?? {})
}
}
function isKnownOmittedServeSimDependency(packageName, fromDir) {
if (packageName !== 'inspect-webkit') {
return false
}
const serveSimPackageJsonPath = join(projectDir, 'node_modules', 'serve-sim', 'package.json')
if (!existsSync(serveSimPackageJsonPath)) {
return false
}
try {
return realpathSync(fromDir) === realpathSync(dirname(serveSimPackageJsonPath))
} catch {
return false
}
}
function collectPackagedRuntimePackages(electronPlatformName = process.platform) {
const packages = new Map()
const visit = (packageName, fromDir = projectDir) => {
if (packageName === 'electron' || packages.has(packageName)) {
return
}
let packageInfo
try {
packageInfo = readPackage(packageName, fromDir)
} catch (error) {
// Why: serve-sim declares inspect-webkit, but current installs omit it.
// Keep that escape hatch narrow so broken packages still fail packaging.
if (isKnownOmittedServeSimDependency(packageName, fromDir)) {
return
}
throw error
}
if (packages.has(packageInfo.name)) {
return
}
packages.set(packageInfo.name, packageInfo.packageDir)
for (const dependencyName of packageInfo.dependencies) {
visit(dependencyName, packageInfo.packageDir)
}
}
// Why: cross-builds must select native dependencies from the artifact target, not the build host.
const packageRoots = [
...PACKAGED_RUNTIME_PACKAGE_ROOTS,
...(electronPlatformName === 'win32' ? WINDOWS_PACKAGED_RUNTIME_PACKAGE_ROOTS : [])
]
for (const packageName of packageRoots) {
visit(packageName)
}
// Why: @parcel/watcher loads its native .node addon from a platform-specific
// optionalDependency (e.g. @parcel/watcher-linux-x64-glibc) that the
// dependencies graph above never reaches. Include the ones installed for the
// build's supported architectures; afterPack pruning trims non-target
// platform/architecture variants. Without this the packaged main bundle's import of
// '@parcel/watcher' resolves at runtime but throws loading its binary.
const parcelWatcherDir = packages.get('@parcel/watcher')
if (parcelWatcherDir) {
const parcelWatcherPackage = JSON.parse(
readFileSync(join(parcelWatcherDir, 'package.json'), 'utf8')
)
for (const optionalName of Object.keys(parcelWatcherPackage.optionalDependencies ?? {})) {
try {
visit(optionalName)
} catch {
// Optional platform subpackage is not installed for this build; skip it.
}
}
}
return [...packages.entries()].sort(([left], [right]) => left.localeCompare(right))
}
function createPackagedRuntimeNodeModuleResources(electronPlatformName = process.platform) {
return collectPackagedRuntimePackages(electronPlatformName).map(([packageName, packageDir]) => ({
from: packageDir,
to: join('node_modules', ...packageName.split('/'))
}))
}
function normalizeAsarEntryPath(entry) {
return entry.replace(/\\/g, '/').replace(/^\/+/, '')
}
function findAsarEntry(entries, expectedPath) {
return entries.find((entry) => normalizeAsarEntryPath(entry) === expectedPath)
}
function verifyPackagedMainRuntimeDeps(resourcesDir, asar = require('@electron/asar')) {
const asarPath = join(resourcesDir, 'app.asar')
if (!existsSync(asarPath)) {
return
}
const mainFiles = ['out/main/index.js', 'out/main/agent-hooks/managed-agent-hook-controls.js']
const entries = asar.listPackage(asarPath)
const missing = new Set()
for (const file of mainFiles) {
const entry = findAsarEntry(entries, file)
if (!entry) {
throw new Error(`Packaged main file ${file} was not found in ${asarPath}`)
}
// Why: @electron/asar lists entries with host separators; Windows returns
// backslashes, and extractFile expects that same host-style path.
const internalPath = entry.replace(/^[\\/]+/, '')
const source = asar.extractFile(asarPath, internalPath).toString('utf8')
for (const match of source.matchAll(/require\(["']([^"']+)["']\)/g)) {
const specifier = match[1]
if (!isPackagedExternalSpecifier(specifier)) {
continue
}
const packageName = packageNameFromSpecifier(specifier)
if (!existsSync(join(resourcesDir, 'node_modules', ...packageName.split('/')))) {
missing.add(packageName)
}
}
}
if (missing.size > 0) {
throw new Error(
`Packaged main bundle has bare runtime imports without copied node_modules: ${[
...missing
].join(', ')}`
)
}
}
function normalizeNodePtyWindowsArch(electronArch) {
const architecture = normalizeElectronArchitecture(electronArch)
if (architecture !== 'x64' && architecture !== 'arm64') {
throw new Error(`Unsupported packaged node-pty Windows architecture: ${architecture}`)
}
return architecture
}
function normalizeElectronArchitecture(electronArch) {
const architecture =
typeof electronArch === 'number'
? ELECTRON_ARCHITECTURE_BY_ENUM[electronArch]
: electronArch === 'armv7l'
? 'arm'
: electronArch
if (!PACKAGED_NATIVE_ARCHITECTURES.has(architecture)) {
throw new Error(`Unsupported packaged runtime architecture: ${String(electronArch)}`)
}
return architecture
}
function pruneNodePtyNativeDirectories(directory, platformPrefix, electronArch, allowsSuffix) {
if (!existsSync(directory)) {
return
}
const architecture = normalizeElectronArchitecture(electronArch)
const targetPrefix = `${platformPrefix}${architecture}`
const platformPrefixes = Object.values(NODE_PTY_PREBUILD_PREFIX_BY_PLATFORM)
for (const entry of readdirSync(directory, { withFileTypes: true })) {
if (!entry.isDirectory() || !platformPrefixes.some((prefix) => entry.name.startsWith(prefix))) {
continue
}
const matchesTarget =
entry.name.startsWith(platformPrefix) &&
(entry.name === targetPrefix || (allowsSuffix && entry.name.startsWith(`${targetPrefix}-`)))
if (!matchesTarget) {
rmSync(join(directory, entry.name), { recursive: true, force: true })
}
}
}
function findNodePtyConptySourceDir(nodePtyDir, windowsArch) {
const conptyRoot = join(nodePtyDir, 'third_party', 'conpty')
if (!existsSync(conptyRoot)) {
throw new Error(`Packaged node-pty is missing ${conptyRoot}`)
}
for (const entry of readdirSync(conptyRoot, { withFileTypes: true })) {
if (!entry.isDirectory()) {
continue
}
const sourceDir = join(conptyRoot, entry.name, `win10-${windowsArch}`)
if (existsSync(sourceDir)) {
return sourceDir
}
}
throw new Error(`Packaged node-pty has no ConPTY payload for win10-${windowsArch}`)
}
function ensurePackagedNodePtyConptyRuntime(nodePtyDir, electronArch) {
const releaseDir = join(nodePtyDir, 'build', 'Release')
if (!existsSync(join(releaseDir, 'conpty.node'))) {
return
}
const runtimeDir = join(releaseDir, 'conpty')
const missingRuntimeFiles = NODE_PTY_CONPTY_RUNTIME_FILES.filter(
(filename) => !existsSync(join(runtimeDir, filename))
)
if (missingRuntimeFiles.length === 0) {
return
}
const windowsArch = normalizeNodePtyWindowsArch(electronArch)
const sourceDir = findNodePtyConptySourceDir(nodePtyDir, windowsArch)
mkdirSync(runtimeDir, { recursive: true })
for (const filename of missingRuntimeFiles) {
const sourceFile = join(sourceDir, filename)
if (!existsSync(sourceFile)) {
throw new Error(`Packaged node-pty is missing ${sourceFile}`)
}
// Why: node-pty's Windows addon loads conpty.dll relative to conpty.node,
// but its install script can run before electron-builder gathers resources.
copyFileSync(sourceFile, join(runtimeDir, filename))
}
}
function prunePackagedNodePty(resourcesDir, electronPlatformName, electronArch) {
const nodePtyDir = join(resourcesDir, 'node_modules', 'node-pty')
if (!existsSync(nodePtyDir)) {
return
}
// Why delete only conpty.node: node-pty's loader tries build/Release, then
// build/Debug, then prebuilds/<platform>-<arch>, swallowing every failure in
// between. Only the source build carries Orca's job-object exports, so an ABI
// mismatch or an AV quarantine of build/Release/conpty.node would silently
// fall through to the UNPATCHED prebuild -- teardown back to guessing by PID
// ancestry, with no error anywhere.
//
// Why NOT the whole prebuilds/ tree: Orca's own patch deletes the
// `conpty_console_list` and winpty `pty` gyp targets, so a Windows source
// build emits conpty.node and nothing else. conpty_console_list.node,
// pty.node, winpty.dll and winpty-agent.exe exist ONLY here. Removing them
// silently kills console-membership probing (the forked agent throws at
// require, and its caller resolves null with silent: true), and removes the
// winpty backend that node-pty still selects below Windows build 18309.
//
// Why the arch check: a cross-arch package copies the host's build/Release,
// so its mere presence does not mean it matches electronArch -- deleting the
// target-arch prebuild would then remove the only loadable binary.
if (
electronPlatformName === 'win32' &&
electronArch === process.arch &&
existsSync(join(nodePtyDir, 'build', 'Release', 'conpty.node'))
) {
const prebuildDir = join(nodePtyDir, 'prebuilds', `win32-${electronArch}`)
for (const staleFallback of ['conpty.node', 'conpty.pdb']) {
rmSync(join(prebuildDir, staleFallback), { force: true })
}
}
const allowedPrebuildPrefix = NODE_PTY_PREBUILD_PREFIX_BY_PLATFORM[electronPlatformName]
if (allowedPrebuildPrefix) {
pruneNodePtyNativeDirectories(
join(nodePtyDir, 'prebuilds'),
allowedPrebuildPrefix,
electronArch,
false
)
// Why: sequential cross-arch rebuilds accumulate ABI-tagged outputs here.
pruneNodePtyNativeDirectories(
join(nodePtyDir, 'bin'),
allowedPrebuildPrefix,
electronArch,
true
)
}
if (electronPlatformName === 'win32') {
ensurePackagedNodePtyConptyRuntime(nodePtyDir, electronArch)
} else {
// Why: conpty is Windows-only and node-pty resolves runtime binaries from
// build/Release or prebuilds/<platform>-<arch>, not third_party/conpty.
rmSync(join(nodePtyDir, 'third_party', 'conpty'), { recursive: true, force: true })
rmSync(join(nodePtyDir, 'deps', 'winpty'), { recursive: true, force: true })
}
}
function prunePackagedParcelWatcher(resourcesDir, electronPlatformName, electronArch) {
const parcelDir = join(resourcesDir, 'node_modules', '@parcel')
if (!existsSync(parcelDir)) {
return
}
// Why: we package every installed @parcel/watcher-<platform> optional
// subpackage (supportedArchitectures fetches all), but each build only needs
// its own platform/architecture binaries. Keep the core package and matching
// native variants; drop the rest.
const keepPrefix = PARCEL_WATCHER_PLATFORM_PREFIX_BY_PLATFORM[electronPlatformName]
const architecture = normalizeElectronArchitecture(electronArch)
const targetPrefix = keepPrefix ? `${keepPrefix}-${architecture}` : null
for (const entry of readdirSync(parcelDir, { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name === 'watcher') {
continue
}
// Why: only ever prune the watcher's own platform subpackages. Guards against
// nuking an unrelated @parcel/* runtime dep if one is added to the roots later.
if (!entry.name.startsWith('watcher-')) {
continue
}
if (
keepPrefix &&
entry.name.startsWith(keepPrefix) &&
(entry.name === targetPrefix || entry.name.startsWith(`${targetPrefix}-`))
) {
continue
}
rmSync(join(parcelDir, entry.name), { recursive: true, force: true })
}
}
function prunePackagedRuntimeTypeDeclarations(resourcesDir) {
const nodeModulesDir = join(resourcesDir, 'node_modules')
if (!existsSync(nodeModulesDir)) {
return
}
pruneMatchingFiles(nodeModulesDir, (filename) => TYPE_DECLARATION_ARTIFACT_RE.test(filename))
}
function prunePackagedSherpaOnnx(resourcesDir, electronPlatformName) {
if (electronPlatformName !== 'darwin') {
return
}
const nodeModulesDir = join(resourcesDir, 'node_modules')
if (!existsSync(nodeModulesDir)) {
return
}
for (const entry of readdirSync(nodeModulesDir, { withFileTypes: true })) {
if (!entry.isDirectory() || !entry.name.startsWith('sherpa-onnx-darwin-')) {
continue
}
const packageDir = join(nodeModulesDir, entry.name)
const packageEntries = readdirSync(packageDir)
const hasVersionedOnnxRuntime = packageEntries.some((filename) =>
VERSIONED_ONNXRUNTIME_DYLIB_RE.test(filename)
)
if (hasVersionedOnnxRuntime) {
// Why: darwin sherpa-onnx binaries link to the versioned ONNX Runtime
// install name; the unversioned dylib is a duplicate fallback copy.
rmSync(join(packageDir, 'libonnxruntime.dylib'), { force: true })
}
}
}
function prunePackagedZodSources(resourcesDir) {
// Why: Zod's src tree is TypeScript source only selected by the @zod/source
// condition; packaged runtime import/require paths resolve to built JS.
rmSync(join(resourcesDir, 'node_modules', 'zod', 'src'), { recursive: true, force: true })
}
function prunePackagedRuntimeNodeModules(resourcesDir, electronPlatformName, electronArch) {
const architecture = normalizeElectronArchitecture(electronArch)
prunePackagedNodePty(resourcesDir, electronPlatformName, architecture)
prunePackagedParcelWatcher(resourcesDir, electronPlatformName, architecture)
prunePackagedRuntimeTypeDeclarations(resourcesDir)
prunePackagedSherpaOnnx(resourcesDir, electronPlatformName)
prunePackagedZodSources(resourcesDir)
}
function pruneMatchingFiles(directory, shouldPrune) {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const entryPath = join(directory, entry.name)
if (entry.isDirectory()) {
pruneMatchingFiles(entryPath, shouldPrune)
} else if (entry.isFile() && shouldPrune(entry.name)) {
rmSync(entryPath, { force: true })
}
}
}
module.exports = {
PACKAGED_RUNTIME_PACKAGE_ROOTS,
createPackagedRuntimeNodeModuleResources,
findAsarEntry,
isPackagedExternalSpecifier,
packageNameFromSpecifier,
prunePackagedNodePty,
prunePackagedParcelWatcher,
prunePackagedRuntimeNodeModules,
prunePackagedSherpaOnnx,
prunePackagedRuntimeTypeDeclarations,
prunePackagedZodSources,
verifyPackagedMainRuntimeDeps
}