@orkestrel/sea 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#options","#format","#detect","#injectPe","#injectElf","#injectMacho","#patchChecksum","#readU32","#readU16","#ensureValidPEAlignment","#stripTrailingNulls","#parseResourceDirectory","#rvaToFileOffset","#buildResourceTree","#serializeResourceTree","#align","#writeU16","#writeU32","#fixupDirectoryRvas","#appendFile","#readResourceString","#sortResourceKeys","#fixupDataEntries","#readU64","#readElfProgramHeaders","#readElfNoteName","#writeElfProgramHeaderEntry","#writeU64","#verifyElfNoteMapping","#shiftMachoLinkeditOffsets","#verifyMachoSection","#options","#emitter","#status","#destroyed","#check","#validate","#compress","#blob","#assemble","#assets","#emitter","#root","#loadSea","#assets","#keys","#add"],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/helpers.ts","../../../src/server/injectors/Injector.ts","../../../src/server/seals/SEA.ts","../../../src/server/assets/Asset.ts","../../../src/server/assets/AssetManager.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { SEACompressionMode, SEAEntryFormat, SEAPlatform } from './types.js'\n\n/** SEA sentinel fuse value embedded in the Node.js binary */\nexport const SEA_SENTINEL_FUSE = 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2'\n\n/** Resource name for the SEA blob in the executable */\nexport const SEA_BLOB_RESOURCE = 'NODE_SEA_BLOB'\n\n/** Default Brotli compression quality level (maximum) */\nexport const DEFAULT_SEA_COMPRESSION_QUALITY = 11\n\n/** Windows PE subsystem value: GUI application (no terminal window) */\nexport const WINDOWS_SUBSYSTEM_GUI = 2\n\n/** Windows PE subsystem value: console application */\nexport const WINDOWS_SUBSYSTEM_CONSOLE = 3\n\n/** File extension indicating Brotli compression */\nexport const BROTLI_EXTENSION = '.br'\n\n/** File extensions that should NOT be Brotli-compressed */\nexport const SKIP_EXTENSIONS = new Set([\n\t'.br',\n\t'.gz',\n\t'.zst',\n\t'.png',\n\t'.jpg',\n\t'.jpeg',\n\t'.gif',\n\t'.webp',\n\t'.avif',\n\t'.ico',\n\t'.woff',\n\t'.woff2',\n\t'.ttf',\n\t'.otf',\n\t'.eot',\n\t'.mp3',\n\t'.mp4',\n\t'.webm',\n\t'.ogg',\n\t'.zip',\n\t'.tar',\n])\n\n/** Default SEA entry point module format when none is specified */\nexport const DEFAULT_ENTRY_FORMAT: SEAEntryFormat = 'cjs'\n\n/** Asset key for the raw (uncompressed) client HTML entry */\nexport const CLIENT_ASSET_KEY_RAW = 'client.html'\n\n/** Asset key for the Brotli-compressed client HTML entry */\nexport const CLIENT_ASSET_KEY_BR = 'client.html.br'\n\n// === Binary Format Magic\n\n/** DOS MZ header magic (first 2 bytes of a PE file) */\nexport const PE_MAGIC = 0x5a4d\n\n/** PE signature: \"PE\\0\\0\" as a 32-bit value */\nexport const PE_SIGNATURE = 0x00004550\n\n/** PE32 optional header magic */\nexport const PE32_MAGIC = 0x10b\n\n/** PE32+ (64-bit) optional header magic */\nexport const PE32_PLUS_MAGIC = 0x20b\n\n/** ELF magic: 0x7F 'E' 'L' 'F' as a 32-bit big-endian value */\nexport const ELF_MAGIC = 0x7f454c46\n\n/** ELF 64-bit class identifier */\nexport const ELF_CLASS_64 = 2\n\n/** ELF little-endian data encoding */\nexport const ELF_DATA_LSB = 1\n\n/** ELF program header type: note segment */\nexport const ELF_PT_NOTE = 4\n\n/** Mach-O 64-bit magic (little-endian) */\nexport const MACHO_MAGIC_64 = 0xfeedfacf\n\n/** Mach-O LC_SEGMENT_64 load command */\nexport const MACHO_LC_SEGMENT_64 = 0x19\n\n// === PE Resource Directory\n\n/** PE resource type: RT_RCDATA (raw data) */\nexport const PE_RT_RCDATA = 10\n\n/** Size of IMAGE_RESOURCE_DIRECTORY in bytes */\nexport const PE_RESOURCE_DIR_SIZE = 16\n\n/** Size of IMAGE_RESOURCE_DIRECTORY_ENTRY in bytes */\nexport const PE_RESOURCE_ENTRY_SIZE = 8\n\n/** Size of IMAGE_RESOURCE_DATA_ENTRY in bytes */\nexport const PE_RESOURCE_DATA_ENTRY_SIZE = 16\n\n/** PE section header size in bytes */\nexport const PE_SECTION_HEADER_SIZE = 40\n\n/** High bit mask for resource directory entry offset (indicates subdirectory) */\nexport const PE_RESOURCE_SUBDIR_FLAG = 0x80000000\n\n/** High bit mask for resource name entry (indicates named vs integer ID) */\nexport const PE_RESOURCE_NAME_FLAG = 0x80000000\n\n// === PE Section Characteristics\n\n/** Section contains initialized data */\nexport const PE_SCN_INITIALIZED_DATA = 0x00000040\n\n/** Section is readable */\nexport const PE_SCN_MEM_READ = 0x40000000\n\n// === Platform\n\n/** Platform-specific SEA build configurations */\nexport const SEA_PLATFORMS: Readonly<Record<string, SEAPlatform>> = Object.freeze({\n\twin32: Object.freeze({\n\t\texecutable: 'node.exe',\n\t\tverify: Object.freeze(['signtool', 'verify', '/pa']),\n\t}),\n\tdarwin: Object.freeze({\n\t\texecutable: 'node',\n\t\tremove: Object.freeze(['codesign', '--remove-signature']),\n\t\tsign: Object.freeze(['codesign', '--sign', '-']),\n\t\tverify: Object.freeze(['codesign', '--verify', '--strict']),\n\t}),\n\tlinux: Object.freeze({\n\t\texecutable: 'node',\n\t}),\n})\n\n// === Compression\n\n/** Maps a {@link SEACompressionMode} to its numeric Brotli mode value */\nexport const SEA_COMPRESSION_MODE_VALUES: Readonly<Record<SEACompressionMode, number>> =\n\tObject.freeze({\n\t\tgeneric: 0,\n\t\ttext: 1,\n\t\tfont: 2,\n\t})\n","import type { SEAErrorCode } from './types.js'\n\n// Error surface for the seal build. `SEAError` is the coded base every\n// domain failure throws through, so a caller can branch on `code` rather\n// than parsing a message string. `ShellError` specializes it for the shell\n// boundary — `runShell` maps a failed `execFileSync` invocation to a\n// `ShellError` carrying the captured stdout/stderr, so a caller can inspect\n// the process output rather than parsing the thrown message.\n\n/**\n * The coded base error for every failure raised by the seal build.\n *\n * @remarks\n * Carries a machine-readable {@link SEAErrorCode} and optional `context`\n * for structured diagnostics. Narrow a caught value with {@link isSEAError}.\n *\n * @example\n * ```ts\n * try {\n * seal.execute()\n * } catch (error) {\n * if (isSEAError(error)) {\n * console.error(error.code, error.context)\n * }\n * }\n * ```\n */\nexport class SEAError extends Error {\n\treadonly code: SEAErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(code: SEAErrorCode, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tthis.name = 'SEAError'\n\t\tthis.code = code\n\t\tif (context !== undefined) {\n\t\t\tthis.context = context\n\t\t}\n\t}\n}\n\n/**\n * Whether a value is a {@link SEAError}.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a `SEAError`\n *\n * @example\n * ```ts\n * if (isSEAError(caught)) {\n * console.error(caught.code)\n * }\n * ```\n */\nexport function isSEAError(value: unknown): value is SEAError {\n\treturn value instanceof SEAError\n}\n\n/**\n * An error thrown when a shell command run via `runShell` exits non-zero.\n *\n * @remarks\n * Carries the captured `stdout` and `stderr` buffers from the failed process.\n * Always carries {@link SEAErrorCode} `'SHELL'`. Narrow a caught value with\n * {@link isShellError}.\n *\n * @example\n * ```ts\n * try {\n * runShell(['codesign', '--sign', '-', path])\n * } catch (error) {\n * if (isShellError(error)) {\n * console.error(error.stderr.toString())\n * }\n * }\n * ```\n */\nexport class ShellError extends SEAError {\n\treadonly stdout: Buffer\n\treadonly stderr: Buffer\n\n\tconstructor(message: string, stdout: Buffer, stderr: Buffer) {\n\t\tsuper('SHELL', message)\n\t\tthis.name = 'ShellError'\n\t\tthis.stdout = stdout\n\t\tthis.stderr = stderr\n\t}\n}\n\n/**\n * Whether a value is a {@link ShellError}.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a `ShellError`\n *\n * @example\n * ```ts\n * if (isShellError(caught)) {\n * console.error(caught.stdout.toString())\n * }\n * ```\n */\nexport function isShellError(value: unknown): value is ShellError {\n\treturn value instanceof ShellError\n}\n","import type {\n\tExecutableFormat,\n\tSEABlobOptions,\n\tSEACompressionManifest,\n\tSEACompressionOptions,\n\tSEACompressionResult,\n\tSEACompressionSize,\n\tSEAEntryOptions,\n\tSEAErrorCode,\n\tSEAPlatform,\n\tSEAProgressHandler,\n\tSEAShellOptions,\n\tSEAWindowsSignOptions,\n} from './types.js'\nimport {\n\texistsSync,\n\topenSync,\n\treadSync,\n\treaddirSync,\n\treadFileSync,\n\trealpathSync,\n\twriteSync,\n\tcloseSync,\n\twriteFileSync,\n\tfsyncSync,\n\trenameSync,\n\tftruncateSync,\n\tfstatSync,\n\tlstatSync,\n} from 'node:fs'\nimport { brotliCompressSync, constants as zlibConstants } from 'node:zlib'\nimport { resolve, relative, join, extname, isAbsolute, sep, dirname } from 'node:path'\nimport { execFileSync, spawn } from 'node:child_process'\nimport {\n\tBROTLI_EXTENSION,\n\tDEFAULT_SEA_COMPRESSION_QUALITY,\n\tSEA_COMPRESSION_MODE_VALUES,\n\tSEA_PLATFORMS,\n\tSKIP_EXTENSIONS,\n} from './constants.js'\nimport { SEAError, ShellError } from './errors.js'\n\n// === Type Guards\n\n/**\n * Check if a value is a valid {@link ExecutableFormat}.\n *\n * @param value - Value to check\n * @returns True when value is `'pe'`, `'elf'`, or `'macho'`\n */\nexport function isExecutableFormat(value: unknown): value is ExecutableFormat {\n\treturn value === 'pe' || value === 'elf' || value === 'macho'\n}\n\n// === Platform Helpers\n\n/**\n * Get the platform configuration for the current OS.\n *\n * @param platform - Platform identifier. Default: `process.platform`.\n * @returns Platform configuration, or undefined if unsupported\n */\nexport function platformConfig(platform?: string): SEAPlatform | undefined {\n\treturn SEA_PLATFORMS[platform ?? process.platform]\n}\n\n/**\n * Check if the current or specified platform is supported for SEA builds.\n *\n * @param platform - Platform identifier to check\n * @returns True when the platform has a known configuration\n */\nexport function isPlatformSupported(platform?: string): boolean {\n\treturn (platform ?? process.platform) in SEA_PLATFORMS\n}\n\n// === Filesystem Helpers\n\n/**\n * Assert that a path exists, throwing a coded {@link SEAError} if not.\n *\n * @param path - Absolute or relative path to check\n * @param message - Error message when path is missing\n * @param code - Error code to throw with. Default: `'STATE'`.\n */\nexport function ensureExists(path: string, message: string, code?: SEAErrorCode): void {\n\tif (!existsSync(path)) {\n\t\tthrow new SEAError(code ?? 'STATE', message, { path })\n\t}\n}\n\n/**\n * Check if a file should be Brotli-compressed based on its extension.\n *\n * @param path - Path to the file\n * @returns True when the file type benefits from compression\n */\nexport function isCompressible(path: string): boolean {\n\tconst ext = extname(path).toLowerCase()\n\treturn !SKIP_EXTENSIONS.has(ext)\n}\n\n/**\n * Recursively walk a directory and return all file paths.\n *\n * @param directory - Directory to walk\n * @param base - Base directory for relative path calculation\n * @returns Array of relative file paths\n */\nexport function walkDirectory(directory: string, base?: string): readonly string[] {\n\tconst root = base ?? directory\n\tconst result: string[] = []\n\tconst entries = readdirSync(directory, { withFileTypes: true })\n\t// Sort by byte order (not localeCompare, which is locale-dependent) so\n\t// asset order is deterministic across platforms and Node builds.\n\tentries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n\n\tfor (const entry of entries) {\n\t\t// Symlinks can escape the compression root (point outside `directory`),\n\t\t// which would make the walk non-deterministic across platforms/filesystems.\n\t\tif (entry.isSymbolicLink()) continue\n\t\tconst fullPath = join(directory, entry.name)\n\t\tif (entry.isDirectory()) {\n\t\t\tresult.push(...walkDirectory(fullPath, root))\n\t\t} else if (entry.isFile()) {\n\t\t\tresult.push(relative(root, fullPath))\n\t\t}\n\t}\n\n\treturn result\n}\n\n// === Shell Helpers\n\n/**\n * Redact password arguments from a shell command.\n *\n * @param command - Command arguments to redact\n * @returns A copy with values following password flags replaced by a marker\n */\nexport function redactCommand(command: readonly string[]): readonly string[] {\n\tconst secretFlags = new Set(['/p', '-p', '--password'])\n\treturn command.map((token, index) => {\n\t\tconst previous = command[index - 1]\n\t\tif (previous !== undefined && secretFlags.has(previous.toLowerCase())) {\n\t\t\treturn '***'\n\t\t}\n\t\treturn token\n\t})\n}\n\n/**\n * Run a command synchronously and return stdout.\n *\n * @param command - Command to execute (first element is the binary)\n * @param options - Shell options (cwd, env, timeout, signal)\n * @returns stdout as a Buffer\n * @throws SEAError with code `'STATE'` when `command` is empty\n * @throws SEAError with code `'ABORT'` when `options.signal` is already aborted\n * @throws SEAError with code `'TIMEOUT'` when the command exceeds `options.timeout`\n * @throws ShellError when the command exits with non-zero status\n */\nexport function runShell(command: string[], options?: SEAShellOptions): Buffer {\n\tconst [cmd, ...args] = command\n\tif (cmd === undefined) {\n\t\tthrow new SEAError('STATE', 'Command array must not be empty')\n\t}\n\tif (options?.signal?.aborted === true) {\n\t\tthrow new SEAError('ABORT', 'Shell command aborted', { command: redactCommand(command) })\n\t}\n\t// Node v22+ blocks direct execFileSync of .cmd/.bat files without a shell (EINVAL)\n\tconst useShell = cmd.endsWith('.cmd') || cmd.endsWith('.bat')\n\ttry {\n\t\treturn execFileSync(cmd, args, {\n\t\t\tcwd: options?.cwd,\n\t\t\tenv: options?.env !== undefined ? { ...process.env, ...options.env } : undefined,\n\t\t\tstdio: ['pipe', 'pipe', 'pipe'],\n\t\t\tshell: useShell,\n\t\t\ttimeout: options?.timeout,\n\t\t})\n\t} catch (thrown: unknown) {\n\t\tif (!(thrown instanceof Error)) {\n\t\t\tthrow thrown\n\t\t}\n\t\tconst redacted = redactCommand(command)\n\t\tconst code = 'code' in thrown && typeof thrown.code === 'string' ? thrown.code : undefined\n\t\tif (code === 'ETIMEDOUT') {\n\t\t\tthrow new SEAError('TIMEOUT', 'Shell command timed out', {\n\t\t\t\tcommand: redacted,\n\t\t\t\ttimeout: options?.timeout,\n\t\t\t})\n\t\t}\n\t\tconst stdout =\n\t\t\t'stdout' in thrown && Buffer.isBuffer(thrown.stdout) ? thrown.stdout : Buffer.alloc(0)\n\t\tconst stderr =\n\t\t\t'stderr' in thrown && Buffer.isBuffer(thrown.stderr) ? thrown.stderr : Buffer.alloc(0)\n\t\tthrow new ShellError('Command failed: ' + redacted.join(' '), stdout, stderr)\n\t}\n}\n\n// === Compression Helpers\n\n/**\n * Compute a size comparison between original and compressed byte counts.\n *\n * @param original - Original byte count\n * @param compressed - Compressed byte count\n * @returns SEACompressionSize with ratio\n */\nexport function computeSize(original: number, compressed: number): SEACompressionSize {\n\tconst ratio = original > 0 ? compressed / original : 0\n\treturn { original, compressed, ratio }\n}\n\n/**\n * Brotli-compress a single file, writing the output alongside it.\n *\n * @param input - Absolute path to the source file\n * @param output - Absolute path for the compressed output\n * @param options - Compression options (quality, mode)\n * @returns Compression result with size comparison\n */\nexport function compressFile(\n\tinput: string,\n\toutput: string,\n\toptions?: SEACompressionOptions,\n): SEACompressionResult {\n\tconst quality = options?.quality ?? DEFAULT_SEA_COMPRESSION_QUALITY\n\tconst mode = SEA_COMPRESSION_MODE_VALUES[options?.mode ?? 'generic']\n\n\tconst raw = readFileSync(input)\n\tconst compressed = brotliCompressSync(raw, {\n\t\tparams: {\n\t\t\t[zlibConstants.BROTLI_PARAM_QUALITY]: quality,\n\t\t\t[zlibConstants.BROTLI_PARAM_MODE]: mode,\n\t\t},\n\t})\n\n\t// walkDirectory already skips symlinks on the read side; mirror that here\n\t// on the write side so a planted symlink at `output` (e.g. `X.br -> /victim`)\n\t// cannot redirect this write to an arbitrary file.\n\tlet outputStat: ReturnType<typeof lstatSync> | undefined\n\ttry {\n\t\toutputStat = lstatSync(output)\n\t} catch {\n\t\toutputStat = undefined\n\t}\n\tif (outputStat !== undefined && outputStat.isSymbolicLink()) {\n\t\tthrow new SEAError('OUTPUT', 'Refusing to write compressed output through a symlink', {\n\t\t\toutput,\n\t\t})\n\t}\n\n\twriteFileSync(output, compressed)\n\n\treturn {\n\t\tinput,\n\t\toutput,\n\t\tsize: computeSize(raw.length, compressed.length),\n\t}\n}\n\n/**\n * Compress all compressible files in a directory tree.\n *\n * @param directory - Absolute path to the directory\n * @param options - Compression options\n * @param progress - Optional callback invoked after each file is compressed\n * @returns Compression manifest with all results\n */\nexport function compressDirectory(\n\tdirectory: string,\n\toptions?: SEACompressionOptions,\n\tprogress?: SEAProgressHandler,\n): SEACompressionManifest {\n\tconst files = walkDirectory(directory)\n\tconst results: SEACompressionResult[] = []\n\tlet totalOriginal = 0\n\tlet totalCompressed = 0\n\n\tfor (const relativePath of files) {\n\t\tconst fullPath = resolve(directory, relativePath)\n\t\tif (!isCompressible(fullPath)) continue\n\n\t\tconst outputPath = fullPath + BROTLI_EXTENSION\n\t\tconst result = compressFile(fullPath, outputPath, options)\n\t\tresults.push(result)\n\t\ttotalOriginal += result.size.original\n\t\ttotalCompressed += result.size.compressed\n\t\tprogress?.(result)\n\t}\n\n\treturn {\n\t\tassets: results,\n\t\ttotal: computeSize(totalOriginal, totalCompressed),\n\t}\n}\n\n// === PE Helpers\n\n/**\n * Check whether a number is a nonzero power of two.\n *\n * @param value - Number to check\n * @returns True when the value is a positive power of two\n */\nexport function isPowerOfTwo(value: number): boolean {\n\treturn value > 0 && (value & (value - 1)) === 0\n}\n\n/**\n * Parse the PE header offset from a Windows executable.\n *\n * @param fd - Open file descriptor\n * @returns The offset to the PE signature\n */\nexport function parsePEOffset(fd: number): number {\n\tconst buf = Buffer.alloc(4)\n\treadSync(fd, buf, 0, 4, 0x3c)\n\treturn buf.readUInt32LE(0)\n}\n\n/**\n * Read a 16-bit unsigned integer from a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to read from\n * @returns The 16-bit value\n */\nexport function readU16(fd: number, offset: number): number {\n\tconst buf = Buffer.alloc(2)\n\treadSync(fd, buf, 0, 2, offset)\n\treturn buf.readUInt16LE(0)\n}\n\n/**\n * Write a 16-bit unsigned integer to a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to write at\n * @param value - The 16-bit value to write\n */\nexport function writeU16(fd: number, offset: number, value: number): void {\n\tconst buf = Buffer.alloc(2)\n\tbuf.writeUInt16LE(value, 0)\n\twriteSync(fd, buf, 0, 2, offset)\n}\n\n/**\n * Check if a file is a Windows PE executable.\n *\n * @param path - Path to the file\n * @returns True when the file has a valid PE signature\n */\nexport function isPEExecutable(path: string): boolean {\n\tlet fd: number | undefined\n\ttry {\n\t\tfd = openSync(path, 'r')\n\t\tconst peOffset = parsePEOffset(fd)\n\t\tconst sig = Buffer.alloc(4)\n\t\treadSync(fd, sig, 0, 4, peOffset)\n\t\treturn sig.toString('ascii') === 'PE\\0\\0'\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tif (fd !== undefined) closeSync(fd)\n\t}\n}\n\n/**\n * Patch the PE subsystem field in a Windows executable.\n *\n * @param path - Path to the executable\n * @param subsystem - Numeric subsystem value (2 = GUI, 3 = Console)\n */\nexport function patchPESubsystem(path: string, subsystem: number): void {\n\tconst fd = openSync(path, 'r+')\n\ttry {\n\t\tconst peOffset = parsePEOffset(fd)\n\t\t// Subsystem field is at PE offset + 0x5C (in the Optional Header)\n\t\twriteU16(fd, peOffset + 0x5c, subsystem)\n\t} finally {\n\t\tcloseSync(fd)\n\t}\n}\n\n/**\n * Remove the Authenticode signature from a PE executable by zeroing\n * the security directory entry in the optional header.\n *\n * @remarks\n * If the certificate overlay described by the security directory sits at the\n * very end of the file (the common case for `signtool`-signed binaries), the\n * file is truncated to the certificate's start FIRST so the overlay bytes are\n * discarded rather than left as dead weight for a downstream injector to\n * bury mid-file. The directory read is bounds-checked so a malformed or\n * truncated security directory cannot throw unexpectedly — it is simply\n * skipped and only the directory entry is zeroed.\n *\n * @param path - Path to the executable\n */\nexport function stripPESignature(path: string): void {\n\tconst fd = openSync(path, 'r+')\n\ttry {\n\t\tconst peOffset = parsePEOffset(fd)\n\t\t// COFF header: 24 bytes from PE signature\n\t\t// Optional header magic at peOffset + 24\n\t\tconst magic = readU16(fd, peOffset + 24)\n\t\t// PE32+ has security dir at different offset than PE32\n\t\tconst securityDirOffset = magic === 0x20b ? peOffset + 168 : peOffset + 152\n\n\t\tconst dirBuf = Buffer.alloc(8)\n\t\tconst dirRead = readSync(fd, dirBuf, 0, 8, securityDirOffset)\n\t\tif (dirRead === 8) {\n\t\t\tconst certOffset = dirBuf.readUInt32LE(0)\n\t\t\tconst certSize = dirBuf.readUInt32LE(4)\n\t\t\tif (certOffset > 0 && certSize > 0) {\n\t\t\t\tconst fileSize = fstatSync(fd).size\n\t\t\t\tif (certOffset <= fileSize && certOffset + certSize === fileSize) {\n\t\t\t\t\tftruncateSync(fd, certOffset)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Zero out the 8-byte security directory entry (VirtualAddress + Size)\n\t\tconst zeroes = Buffer.alloc(8)\n\t\twriteSync(fd, zeroes, 0, 8, securityDirOffset)\n\t} finally {\n\t\tcloseSync(fd)\n\t}\n}\n\n// === Signing Helpers\n\n/**\n * Build the `signtool sign` argv for signing a Windows executable.\n *\n * @remarks\n * Requires EXACTLY ONE certificate source — `sign.file` (a `.pfx`/`.p12`\n * file, paired with `sign.password` when present) XOR `sign.thumbprint` (a\n * certificate already installed in the Windows store). When `sign.timestamp`\n * is set it is parsed with the `URL` constructor and must be an `http:` or\n * `https:` URL. The returned argv is passed directly to `runShell` — never\n * through a shell — so nothing in `sign` can be interpreted as a flag or\n * injected into a command line. `sign.password` is NEVER included in a\n * thrown error's message or `context`.\n *\n * @param sign - Windows signing options\n * @param target - Absolute path to the executable to sign\n * @returns The `signtool` argv, ready for `runShell`\n * @throws SEAError with code `'SIGN'` when neither `file` nor `thumbprint` is set\n * @throws SEAError with code `'SIGN'` when both `file` and `thumbprint` are set\n * @throws SEAError with code `'SIGN'` when `timestamp` is not a parseable http(s) URL\n * @throws SEAError with code `'SIGN'` when `digest` is not `'sha1'`, `'sha256'`, `'sha384'`, or `'sha512'`\n *\n * @example\n * ```ts\n * createSignCommand({ thumbprint: 'AABBCCDDEEFF00112233445566778899AABBCCDD' }, 'dist/sea/app.exe')\n * // ['signtool', 'sign', '/fd', 'sha256', '/sha1', 'AABBCCDDEEFF00112233445566778899AABBCCDD', 'dist/sea/app.exe']\n * ```\n */\nexport function createSignCommand(sign: SEAWindowsSignOptions, target: string): string[] {\n\tconst hasFile = sign.file !== undefined\n\tconst hasThumbprint = sign.thumbprint !== undefined\n\n\tif (!hasFile && !hasThumbprint) {\n\t\tthrow new SEAError(\n\t\t\t'SIGN',\n\t\t\t'Windows signing requires exactly one of sign.file or sign.thumbprint',\n\t\t)\n\t}\n\tif (hasFile && hasThumbprint) {\n\t\tthrow new SEAError(\n\t\t\t'SIGN',\n\t\t\t'Windows signing accepts only one of sign.file or sign.thumbprint, not both',\n\t\t)\n\t}\n\n\tif (sign.timestamp !== undefined) {\n\t\tlet parsed: URL\n\t\ttry {\n\t\t\tparsed = new URL(sign.timestamp)\n\t\t} catch {\n\t\t\tthrow new SEAError('SIGN', 'Windows signing timestamp must be an http(s) URL', {\n\t\t\t\ttimestamp: sign.timestamp,\n\t\t\t})\n\t\t}\n\t\tif (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n\t\t\tthrow new SEAError('SIGN', 'Windows signing timestamp must be an http(s) URL', {\n\t\t\t\ttimestamp: sign.timestamp,\n\t\t\t})\n\t\t}\n\t}\n\n\tconst digest = sign.digest ?? 'sha256'\n\tconst supportedDigests = new Set(['sha1', 'sha256', 'sha384', 'sha512'])\n\tif (!supportedDigests.has(digest)) {\n\t\tthrow new SEAError('SIGN', 'Unsupported signing digest', { digest: sign.digest })\n\t}\n\n\treturn [\n\t\t'signtool',\n\t\t'sign',\n\t\t'/fd',\n\t\tdigest,\n\t\t...(sign.file !== undefined\n\t\t\t? ['/f', sign.file, ...(sign.password !== undefined ? ['/p', sign.password] : [])]\n\t\t\t: []),\n\t\t...(sign.thumbprint !== undefined ? ['/sha1', sign.thumbprint] : []),\n\t\t...(sign.timestamp !== undefined ? ['/tr', sign.timestamp, '/td', digest] : []),\n\t\ttarget,\n\t]\n}\n\n// === Formatting Helpers\n\n/**\n * Format a byte count as a human-readable string.\n *\n * @param bytes - Byte count\n * @returns Formatted string (e.g. `\"1.23 MB\"`, `\"456 KB\"`)\n */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) return `${String(bytes)} B`\n\tif (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`\n\treturn `${(bytes / (1024 * 1024)).toFixed(2)} MB`\n}\n\n/**\n * Assert that an asset key is safe to use as a relative filesystem/archive key.\n *\n * @remarks\n * Rejects an empty key, an absolute path, a key containing a backslash, a\n * Windows drive-relative specifier (e.g. `'C:foo'`), or any `/`-separated\n * segment equal to `'..'` — all of which could escape the intended asset root.\n *\n * @param key - Asset key to validate\n * @throws SEAError with code `'ASSET'` when the key is unsafe\n *\n * @example\n * ```ts\n * ensureSafeKey('client.html.br') // ok\n * ensureSafeKey('../secrets') // throws SEAError('ASSET', ...)\n * ensureSafeKey('C:foo') // throws SEAError('ASSET', ...)\n * ```\n */\nexport function ensureSafeKey(key: string): void {\n\tif (key.length === 0) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not be empty', { key })\n\t}\n\tif (isAbsolute(key)) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not be an absolute path', { key })\n\t}\n\tif (key.includes('\\\\')) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not contain a backslash', { key })\n\t}\n\tif (/^[A-Za-z]:/.test(key)) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not be a drive-relative specifier', { key })\n\t}\n\tif (key.split('/').includes('..')) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not contain a \"..\" segment', { key })\n\t}\n}\n\n/**\n * Assert that `path` (resolved against `base`) real-path-resolves to a\n * location inside `base`, defeating a symlink escape.\n *\n * @remarks\n * Resolves `path` against `base`, then dereferences both the resolved path\n * and `base` with `realpathSync` and requires the real resolved path to\n * equal the real base or begin with the real base plus a path separator.\n * Dereferencing BOTH sides means a symlinked base itself (e.g. macOS `/tmp`\n * -> `/private/tmp`) still matches, while a symlink inside the tree that\n * points outside the real base is correctly rejected. A `realpathSync`\n * failure (e.g. `ENOENT`) is wrapped as a coded `SEAError` rather than\n * leaking the raw Node error.\n *\n * @param base - Absolute path to the containing root\n * @param path - Path to validate, resolved against `base` if relative\n * @returns The real (symlink-resolved) contained path\n * @throws SEAError with code `'ASSET'` when the real path escapes `base`\n * @throws SEAError with code `'ASSET'` when the path cannot be resolved\n *\n * @example\n * ```ts\n * ensureContained('/dist/app', 'browser') // '/dist/app/browser' (real path)\n * ensureContained('/dist/app', '../../etc') // throws SEAError('ASSET', ...)\n * ```\n */\nexport function ensureContained(base: string, path: string): string {\n\tconst resolved = resolve(base, path)\n\n\tlet real: string\n\tlet realBase: string\n\ttry {\n\t\treal = realpathSync(resolved)\n\t\trealBase = realpathSync(base)\n\t} catch (thrown: unknown) {\n\t\tconst cause = thrown instanceof Error ? thrown.message : String(thrown)\n\t\tthrow new SEAError('ASSET', 'Path not found or unresolvable', { path, cause })\n\t}\n\n\tif (real !== realBase && !real.startsWith(realBase + sep)) {\n\t\tthrow new SEAError('ASSET', 'Path escapes the build root', { base, path })\n\t}\n\n\treturn real\n}\n\n/**\n * Assert that `name` is a single safe path segment suitable as an output\n * executable base name.\n *\n * @remarks\n * Rejects an empty name, `'.'`, `'..'`, a name containing a `/` or `\\`\n * separator, an absolute path, or a Windows drive-relative specifier (e.g.\n * `'C:foo'`) — all of which could redirect the output executable outside\n * the intended output directory.\n *\n * @param name - Output executable base name to validate\n * @throws SEAError with code `'ASSET'` when the name is unsafe\n *\n * @example\n * ```ts\n * ensureSafeName('myapp') // ok\n * ensureSafeName('../evil') // throws SEAError('ASSET', ...)\n * ```\n */\nexport function ensureSafeName(name: string): void {\n\tif (name.length === 0 || name === '.' || name === '..') {\n\t\tthrow new SEAError('ASSET', 'Executable name must be a single path segment', { name })\n\t}\n\tif (name.includes('/') || name.includes('\\\\')) {\n\t\tthrow new SEAError('ASSET', 'Executable name must not contain a path separator', { name })\n\t}\n\tif (isAbsolute(name)) {\n\t\tthrow new SEAError('ASSET', 'Executable name must not be an absolute path', { name })\n\t}\n\tif (/^[A-Za-z]:/.test(name)) {\n\t\tthrow new SEAError('ASSET', 'Executable name must not be a drive-relative specifier', {\n\t\t\tname,\n\t\t})\n\t}\n}\n\n/**\n * Fsync a directory to durably persist a prior file rename/create within it.\n *\n * @remarks\n * A `rename`/`create` is only durable once its CONTAINING directory entry is\n * flushed — fsyncing the file itself is not enough. `path` is the directory\n * to fsync (callers pass `dirname(target)`, not the file itself). On Windows\n * there is no directory file handle to fsync, so this is a no-op there (the\n * platform lacks the primitive, not a failure). Some filesystems/platforms\n * return a benign errno for a directory fsync attempt (`EINVAL`, `ENOTSUP`,\n * `EISDIR`, `EPERM`, `EACCES`) — those are treated as \"fsync unsupported\n * here\" and swallowed; anything else (e.g. `ENOENT`, meaning the directory\n * itself is missing) is a genuine failure and is thrown as a coded `SEAError`.\n *\n * @param path - Directory path to fsync\n * @throws SEAError with code `'OUTPUT'` when the directory sync fails for an\n * unrecognized reason\n *\n * @example\n * ```ts\n * syncDirectory('/dist/app/bin')\n * ```\n */\nexport function syncDirectory(path: string): void {\n\t// Windows has no directory file handle to fsync — nothing to do there.\n\tif (process.platform === 'win32') return\n\n\ttry {\n\t\tconst fd = openSync(path, 'r')\n\t\ttry {\n\t\t\tfsyncSync(fd)\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\t} catch (thrown: unknown) {\n\t\tconst code =\n\t\t\tthrown instanceof Error && 'code' in thrown && typeof thrown.code === 'string'\n\t\t\t\t? thrown.code\n\t\t\t\t: undefined\n\t\t// These codes mean \"this filesystem/platform doesn't support directory\n\t\t// fsync\" — benign and safe to ignore. Anything else (e.g. ENOENT, the\n\t\t// directory truly doesn't exist) is a genuine failure.\n\t\tif (\n\t\t\tcode === 'EINVAL' ||\n\t\t\tcode === 'ENOTSUP' ||\n\t\t\tcode === 'EISDIR' ||\n\t\t\tcode === 'EPERM' ||\n\t\t\tcode === 'EACCES'\n\t\t) {\n\t\t\treturn\n\t\t}\n\t\tconst cause = thrown instanceof Error ? thrown.message : String(thrown)\n\t\tthrow new SEAError('OUTPUT', 'Failed to sync output directory', { path, cause })\n\t}\n}\n\n/**\n * Finalize a built executable by durably flushing it to disk and atomically\n * moving it into place.\n *\n * @remarks\n * Opens `source` for read/write, `fsync`s it to force the OS to flush buffered\n * writes, closes it, then `rename`s it to `target`. Never deletes `target` on\n * failure — the caller retains whatever was previously there. After the file\n * is already in place, the containing directory is fsynced ({@link syncDirectory})\n * as a further durability step so the rename itself survives a crash.\n *\n * @param source - Absolute path to the built (temporary) executable\n * @param target - Absolute path to move the finalized executable to\n * @throws SEAError with code `'OUTPUT'` when any step fails\n *\n * @example\n * ```ts\n * finalizeExecutable('/tmp/build/app.tmp', '/dist/app')\n * ```\n */\nexport function finalizeExecutable(source: string, target: string): void {\n\ttry {\n\t\tconst fd = openSync(source, 'r+')\n\t\ttry {\n\t\t\tfsyncSync(fd)\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\t\trenameSync(source, target)\n\t} catch (thrown: unknown) {\n\t\tconst cause = thrown instanceof Error ? thrown.message : String(thrown)\n\t\tthrow new SEAError('OUTPUT', 'Failed to finalize executable', { source, target, cause })\n\t}\n\tsyncDirectory(dirname(target))\n}\n\n/**\n * Build the Node.js `--experimental-sea-config` JSON object for a SEA blob.\n *\n * @remarks\n * A pure leaf extracted from the SEA build orchestrator. The `mainFormat`\n * field (`'commonjs' | 'module'`) exists only in Node >= 25.7 — for a `'cjs'`\n * entry (the default) `mainFormat` is OMITTED entirely so the config still\n * builds on older Node hosts where `'commonjs'` is already the implicit\n * default; for an `'esm'` entry `mainFormat: 'module'` is set explicitly\n * (this requires a Node >= 25.7 build host). Node also documents that\n * `useSnapshot` is incompatible with an ESM entry — combining the two throws.\n *\n * @param entry - SEA entry point options\n * @param blob - Absolute output path for the generated blob\n * @param assets - Optional key→path mapping for embedded assets\n * @param options - Optional blob behavior overrides (cache, snapshot)\n * @returns the SEA config object, ready to be written to disk as JSON\n * @throws SEAError with code `'BLOB'` when `useSnapshot` is combined with an ESM entry\n *\n * @example\n * ```ts\n * const config = createBlobConfig({ path: 'dist/bin/serve.cjs' }, 'dist/bin/sea-prep.blob', undefined)\n * ```\n */\nexport function createBlobConfig(\n\tentry: SEAEntryOptions,\n\tblob: string,\n\tassets: Readonly<Record<string, string>> | undefined,\n\toptions?: SEABlobOptions,\n): Readonly<Record<string, unknown>> {\n\tconst format = entry.format ?? 'cjs'\n\tconst snapshot = options?.snapshot ?? false\n\n\tif (format === 'esm' && snapshot) {\n\t\tthrow new SEAError(\n\t\t\t'BLOB',\n\t\t\t'useSnapshot cannot be combined with an ESM entry (mainFormat module)',\n\t\t)\n\t}\n\n\treturn {\n\t\tmain: entry.path,\n\t\toutput: blob,\n\t\tdisableExperimentalSEAWarning: true,\n\t\tuseSnapshot: snapshot,\n\t\tuseCodeCache: options?.cache ?? true,\n\t\t...(assets ? { assets } : {}),\n\t\t...(format === 'esm' ? { mainFormat: 'module' } : {}),\n\t}\n}\n\n// === ELF Helpers\n\n/**\n * Align an ELF note component size to its four-byte boundary.\n *\n * @param value - Component size to align\n * @returns The value rounded up to the next multiple of four\n */\nexport function alignELFNoteSize(value: number): number {\n\tconst remainder = value % 4\n\treturn remainder === 0 ? value : value + (4 - remainder)\n}\n\n/**\n * Build an ELF `PT_NOTE` entry's header bytes (namesz/descsz/type + padded\n * name) for the SEA blob note, without the blob body itself.\n *\n * @remarks\n * A pure leaf extracted from the ELF injector: the blob body is streamed\n * from disk separately (never buffered here) so this only produces the\n * fixed-size note header and reports the total on-disk size the complete\n * note entry (header + 4-byte-padded blob) will occupy, so the caller can\n * size the covering `PT_LOAD`/`PT_NOTE` segments before writing anything.\n * The Node.js SEA runtime matches a note by the first 8 bytes of its name\n * (`strncmp(name, \"NODE_SEA\", 8)`), so `resource` is written in full but\n * only needs to begin with those 8 bytes to be found at runtime.\n *\n * @param resource - Note name (SEA resource identifier, e.g. `NODE_SEA_BLOB`)\n * @param blobSize - Size in bytes of the SEA blob that will follow the header\n * @returns The note header bytes and the total on-disk size of header + blob\n *\n * @example\n * ```ts\n * const { header, entryTotal } = buildELFNoteHeader('NODE_SEA_BLOB', 4096)\n * ```\n */\nexport function buildELFNoteHeader(\n\tresource: string,\n\tblobSize: number,\n): { readonly header: Buffer; readonly entryTotal: number } {\n\tconst nameBytes = Buffer.from(`${resource}\\0`, 'utf-8')\n\tconst alignedNameSize = alignELFNoteSize(nameBytes.length)\n\n\tconst header = Buffer.alloc(12 + alignedNameSize)\n\theader.writeUInt32LE(nameBytes.length, 0) // namesz\n\theader.writeUInt32LE(blobSize, 4) // descsz\n\theader.writeUInt32LE(0, 8) // type\n\tnameBytes.copy(header, 12)\n\n\tconst alignedDescSize = alignELFNoteSize(blobSize)\n\treturn { header, entryTotal: header.length + alignedDescSize }\n}\n\n/**\n * Copy a byte range from one open file descriptor to another, streaming in\n * fixed-size chunks instead of buffering the whole range in memory.\n *\n * @remarks\n * Reads `length` bytes from `source` starting at file offset `start`, in\n * `chunk`-sized reads, and writes each chunk to `target` with a `null`\n * write position so writes land sequentially at `target`'s current file\n * position (rather than at `start`, which is meaningless for `target`). A\n * short read from `source` (fewer bytes returned than requested, including\n * `0` before `length` is exhausted) is treated as a genuine failure and\n * throws rather than silently writing a truncated range.\n *\n * @param source - Open, readable file descriptor to copy from\n * @param target - Open, writable file descriptor to copy to\n * @param start - Byte offset in `source` to begin reading from\n * @param length - Number of bytes to copy; `0` is a no-op\n * @param chunk - Read/write chunk size in bytes, for tuning memory use and\n * exercising the streaming loop in tests. Default: 4 MB.\n * @throws SEAError with code `'OUTPUT'` when `source` is exhausted before\n * `length` bytes have been copied\n *\n * @example\n * ```ts\n * const srcFd = openSync('big.bin', 'r')\n * const dstFd = openSync('out.bin', 'w')\n * copyRange(srcFd, dstFd, 1024, 4096)\n * ```\n */\nexport function copyRange(\n\tsource: number,\n\ttarget: number,\n\tstart: number,\n\tlength: number,\n\tchunk = 4 * 1024 * 1024,\n): void {\n\tif (length <= 0) return\n\n\tconst bufferSize = Math.min(chunk, length)\n\tconst buffer = Buffer.alloc(bufferSize)\n\tlet position = start\n\tlet remaining = length\n\n\twhile (remaining > 0) {\n\t\tconst toRead = Math.min(chunk, remaining)\n\t\tconst bytesRead = readSync(source, buffer, 0, toRead, position)\n\t\tif (bytesRead === 0) {\n\t\t\tthrow new SEAError('OUTPUT', 'Unexpected end of file while copying byte range', {\n\t\t\t\tstart,\n\t\t\t\tlength,\n\t\t\t\tposition,\n\t\t\t\tremaining,\n\t\t\t})\n\t\t}\n\t\twriteSync(target, buffer, 0, bytesRead, null)\n\t\tposition += bytesRead\n\t\tremaining -= bytesRead\n\t}\n}\n\n// === SEA Helpers\n\n/**\n * Patch the sentinel fuse in a binary from `:0` to `:1`.\n *\n * Searches the file in 64 MB chunks with overlap to handle any file size.\n * The fuse signals to the Node.js runtime that a SEA blob is present.\n * This is normally handled by the Injector but is also available standalone\n * when using native PE resource injection.\n *\n * @param executable - Absolute path to the executable\n * @param fuse - Sentinel fuse string (without the `:0` suffix)\n */\nexport function patchSentinelFuse(executable: string, fuse: string): void {\n\tconst fd = openSync(executable, 'r+')\n\ttry {\n\t\tconst needle = Buffer.from(fuse, 'utf-8')\n\t\tconst chunkSize = 64 * 1024 * 1024 // 64 MB\n\t\tconst readSize = chunkSize + needle.length\n\t\tconst buffer = Buffer.alloc(readSize)\n\n\t\tlet offset = 0\n\t\twhile (true) {\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, readSize, offset)\n\t\t\tif (bytesRead === 0) break\n\n\t\t\tconst chunk = buffer.subarray(0, bytesRead)\n\t\t\tconst idx = chunk.indexOf(needle)\n\n\t\t\tif (idx !== -1) {\n\t\t\t\tconst fuseEnd = offset + idx + needle.length\n\t\t\t\tconst valueBuf = Buffer.alloc(2)\n\t\t\t\tconst valueRead = readSync(fd, valueBuf, 0, 2, fuseEnd)\n\n\t\t\t\tif (valueRead < 2) {\n\t\t\t\t\tthrow new SEAError('FUSE', 'Could not read sentinel fuse value', { executable, fuse })\n\t\t\t\t}\n\n\t\t\t\tconst value = valueBuf.toString('utf-8')\n\n\t\t\t\tif (value === ':0') {\n\t\t\t\t\twriteSync(fd, Buffer.from('1', 'utf-8'), 0, 1, fuseEnd + 1)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif (value === ':1') {\n\t\t\t\t\treturn // Already patched\n\t\t\t\t}\n\n\t\t\t\tthrow new SEAError('FUSE', `Unexpected sentinel fuse value: ${value}`, {\n\t\t\t\t\texecutable,\n\t\t\t\t\tfuse,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\toffset += chunkSize\n\t\t}\n\n\t\tthrow new SEAError('FUSE', `Sentinel fuse not found in executable: ${fuse}`, {\n\t\t\texecutable,\n\t\t\tfuse,\n\t\t})\n\t} finally {\n\t\tcloseSync(fd)\n\t}\n}\n\n// === Runtime Helpers\n\n/**\n * Launch the system default browser at an http(s) URL.\n *\n * @remarks\n * A best-effort launch for bundled local-UI apps: dispatches by\n * `process.platform` (`win32` -> `rundll32 url.dll,FileProtocolHandler`,\n * `darwin` -> `open`, else -> `xdg-open`), each invoked with an argv array\n * (never a shell) so the URL cannot be interpreted as a flag or injected\n * into a command line. The child process is spawned `detached` with\n * `stdio: 'ignore'` and immediately `unref()`d so it never keeps the host\n * app alive. Only `http:` and `https:` URLs are accepted — any other\n * scheme (including a string that merely looks like a CLI flag, e.g.\n * `'-e ...'`) fails to parse as an http(s) URL and is rejected before\n * anything is spawned.\n *\n * @param url - Absolute http or https URL to open\n * @throws SEAError with code `'BROWSER'` when `url` is not a parseable absolute URL\n * @throws SEAError with code `'BROWSER'` when `url` is not an `http:`/`https:` URL\n *\n * @example\n * ```ts\n * openBrowser('http://localhost:3000')\n * ```\n */\nexport function openBrowser(url: string): void {\n\tlet parsed: URL\n\ttry {\n\t\tparsed = new URL(url)\n\t} catch {\n\t\tthrow new SEAError('BROWSER', 'openBrowser requires a valid absolute URL', { url })\n\t}\n\n\tif (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n\t\tthrow new SEAError('BROWSER', 'openBrowser only supports http and https URLs', {\n\t\t\turl,\n\t\t\tprotocol: parsed.protocol,\n\t\t})\n\t}\n\n\tconst child =\n\t\tprocess.platform === 'win32'\n\t\t\t? spawn('rundll32', ['url.dll,FileProtocolHandler', parsed.href], {\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: 'ignore',\n\t\t\t\t})\n\t\t\t: process.platform === 'darwin'\n\t\t\t\t? spawn('open', [parsed.href], { detached: true, stdio: 'ignore' })\n\t\t\t\t: spawn('xdg-open', [parsed.href], { detached: true, stdio: 'ignore' })\n\n\t// Best-effort launch: if the target browser opener binary is absent, the\n\t// child emits an async 'error' (ENOENT) event. There is nothing to recover\n\t// here (unlike the build pipeline, there is no coded failure to surface to\n\t// a caller who has already returned) — an unhandled 'error' event would\n\t// otherwise crash the host app, so this is a deliberate, documented no-op.\n\tchild.on('error', () => {})\n\tchild.unref()\n}\n","/**\n * Injector\n *\n * Cross-platform binary resource injector for PE, ELF, and Mach-O executables.\n * Pure TypeScript file I/O — no WASM, no external tools, no size ceiling.\n *\n * PE — adds an RT_RCDATA resource via resource directory rebuild.\n * ELF — appends a PT_NOTE segment with the blob as note data.\n * Mach-O — appends an LC_SEGMENT_64 load command with a section.\n */\n\nimport type { ExecutableFormat, InjectorInterface, InjectorOptions } from '../types.js'\nimport {\n\topenSync,\n\treadSync,\n\twriteSync,\n\tcloseSync,\n\tstatSync,\n\tfstatSync,\n\tchmodSync,\n\trmSync,\n\tappendFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport {\n\tPE_MAGIC,\n\tPE_SIGNATURE,\n\tPE32_MAGIC,\n\tPE32_PLUS_MAGIC,\n\tPE_RT_RCDATA,\n\tPE_RESOURCE_DIR_SIZE,\n\tPE_RESOURCE_ENTRY_SIZE,\n\tPE_RESOURCE_DATA_ENTRY_SIZE,\n\tPE_SECTION_HEADER_SIZE,\n\tPE_RESOURCE_SUBDIR_FLAG,\n\tPE_RESOURCE_NAME_FLAG,\n\tPE_SCN_INITIALIZED_DATA,\n\tPE_SCN_MEM_READ,\n\tELF_MAGIC,\n\tELF_CLASS_64,\n\tELF_DATA_LSB,\n\tELF_PT_NOTE,\n\tMACHO_MAGIC_64,\n\tMACHO_LC_SEGMENT_64,\n} from '../constants.js'\nimport {\n\tpatchSentinelFuse,\n\tbuildELFNoteHeader,\n\tfinalizeExecutable,\n\tcopyRange,\n\tisPowerOfTwo,\n} from '../helpers.js'\nimport { SEAError } from '../errors.js'\n\n// === Injector\n\nexport class Injector implements InjectorInterface {\n\t#options: InjectorOptions\n\t#format: ExecutableFormat\n\n\tconstructor(options: InjectorOptions) {\n\t\tthis.#options = options\n\t\tthis.#format = this.#detect()\n\t}\n\n\tget format(): ExecutableFormat {\n\t\treturn this.#format\n\t}\n\n\tinject(): void {\n\t\tlet peOptionalOffset: number | undefined\n\t\tswitch (this.#format) {\n\t\t\tcase 'pe':\n\t\t\t\tpeOptionalOffset = this.#injectPe()\n\t\t\t\tbreak\n\t\t\tcase 'elf':\n\t\t\t\tthis.#injectElf()\n\t\t\t\tbreak\n\t\t\tcase 'macho':\n\t\t\t\tthis.#injectMacho()\n\t\t\t\tbreak\n\t\t}\n\n\t\tif (this.#options.fuse !== undefined) {\n\t\t\tpatchSentinelFuse(this.#options.executable, this.#options.fuse)\n\t\t}\n\n\t\t// The checksum must be the TRUE last PE write — computed after the\n\t\t// sentinel-fuse byte flip above — or an unsigned build ships a stale\n\t\t// checksum that doesn't cover the fuse mutation.\n\t\tif (peOptionalOffset !== undefined) {\n\t\t\tthis.#patchChecksum(peOptionalOffset)\n\t\t}\n\t}\n\n\t// === Format Detection\n\n\t#detect(): ExecutableFormat {\n\t\tconst fd = openSync(this.#options.executable, 'r')\n\t\ttry {\n\t\t\tconst header = Buffer.alloc(4)\n\t\t\treadSync(fd, header, 0, 4, 0)\n\t\t\tconst magic16 = header.readUInt16LE(0)\n\t\t\tconst magic32 = header.readUInt32BE(0)\n\t\t\tconst magic32le = header.readUInt32LE(0)\n\n\t\t\tif (magic16 === PE_MAGIC) return 'pe'\n\t\t\tif (magic32 === ELF_MAGIC) return 'elf'\n\t\t\tif (magic32le === MACHO_MAGIC_64) return 'macho'\n\n\t\t\t// Fat/universal Mach-O (either byte order) — dedicated message so\n\t\t\t// callers know exactly why: this injector only handles thin binaries.\n\t\t\tif (magic32 === 0xcafebabe || magic32 === 0xbebafeca) {\n\t\t\t\tthrow new SEAError(\n\t\t\t\t\t'FORMAT',\n\t\t\t\t\t'Mach-O universal/fat binaries are not supported; provide a thin arm64 or x86_64 binary',\n\t\t\t\t\t{ executable: this.#options.executable, magic: magic32 },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// 32-bit or big-endian thin Mach-O (magic 0xfeedface / 0xcefaedfe) —\n\t\t\t// only 64-bit little-endian Mach-O (0xfeedfacf) is supported.\n\t\t\tif (\n\t\t\t\tmagic32le === 0xfeedface ||\n\t\t\t\tmagic32le === 0xcefaedfe ||\n\t\t\t\tmagic32 === 0xfeedface ||\n\t\t\t\tmagic32 === 0xcefaedfe\n\t\t\t) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Only 64-bit little-endian Mach-O is supported', {\n\t\t\t\t\texecutable: this.#options.executable,\n\t\t\t\t\tmagic: magic32,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tthrow new SEAError(\n\t\t\t\t'FORMAT',\n\t\t\t\t`Unknown executable format (magic: 0x${magic32.toString(16).padStart(8, '0')})`,\n\t\t\t\t{ executable: this.#options.executable, magic: magic32 },\n\t\t\t)\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// PE Injection\n\t// =========================================================================\n\t//\n\t// Strategy: parse the existing PE structure, gather all current resource\n\t// entries (preserving icons, manifests, version info), build a new .rsrc\n\t// section that includes the existing resources plus the injected blob,\n\t// append it to the file, add a new section header entry, and update the\n\t// PE headers (resource data directory, SizeOfImage, NumberOfSections).\n\t//\n\t// The blob data is streamed from disk — never held in memory.\n\n\t#injectPe(): number {\n\t\tconst fd = openSync(this.#options.executable, 'r+')\n\t\ttry {\n\t\t\t// --- Parse PE headers ---\n\t\t\tconst peOffset = this.#readU32(fd, 0x3c)\n\t\t\tconst sig = this.#readU32(fd, peOffset)\n\t\t\tif (sig !== PE_SIGNATURE) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Invalid PE signature', {\n\t\t\t\t\texecutable: this.#options.executable,\n\t\t\t\t\tsignature: sig,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst coffOffset = peOffset + 4\n\t\t\tconst numberOfSections = this.#readU16(fd, coffOffset + 2)\n\t\t\tconst optionalHeaderSize = this.#readU16(fd, coffOffset + 16)\n\t\t\tconst optionalOffset = coffOffset + 20\n\n\t\t\tconst optMagic = this.#readU16(fd, optionalOffset)\n\t\t\tconst is64 = optMagic === PE32_PLUS_MAGIC\n\t\t\tif (optMagic !== PE32_MAGIC && optMagic !== PE32_PLUS_MAGIC) {\n\t\t\t\tthrow new SEAError(\n\t\t\t\t\t'FORMAT',\n\t\t\t\t\t`Unsupported PE optional header magic: 0x${optMagic.toString(16)}`,\n\t\t\t\t\t{ executable: this.#options.executable, optionalHeaderMagic: optMagic },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst sectionAlignment = this.#readU32(fd, optionalOffset + 32)\n\t\t\tconst fileAlignment = this.#readU32(fd, optionalOffset + 36)\n\t\t\tthis.#ensureValidPEAlignment(sectionAlignment, fileAlignment)\n\n\t\t\t// SizeOfImage offset: same in PE32 and PE32+\n\t\t\tconst sizeOfImageOffset = optionalOffset + 56\n\n\t\t\t// Data directory starts after the fixed optional header fields\n\t\t\t// PE32: 96 bytes fixed + data dirs; PE32+: 112 bytes fixed + data dirs\n\t\t\tconst dataDirOffset = optionalOffset + (is64 ? 112 : 96)\n\n\t\t\t// Resource table is data directory entry index 2\n\t\t\tconst resourceDirRvaOffset = dataDirOffset + 2 * 8\n\t\t\tconst resourceDirSizeOffset = resourceDirRvaOffset + 4\n\t\t\tconst existingResourceRva = this.#readU32(fd, resourceDirRvaOffset)\n\n\t\t\t// --- Parse section table ---\n\t\t\tconst sectionTableOffset = optionalOffset + optionalHeaderSize\n\n\t\t\t// Collect all sections and find the resource section\n\t\t\tconst sections: Array<{\n\t\t\t\tname: string\n\t\t\t\tvirtualSize: number\n\t\t\t\tvirtualAddress: number\n\t\t\t\trawSize: number\n\t\t\t\trawOffset: number\n\t\t\t\tcharacteristics: number\n\t\t\t\theaderOffset: number\n\t\t\t}> = []\n\n\t\t\tlet rsrcSectionIndex = -1\n\n\t\t\tfor (let i = 0; i < numberOfSections; i++) {\n\t\t\t\tconst off = sectionTableOffset + i * PE_SECTION_HEADER_SIZE\n\t\t\t\tconst nameBuf = Buffer.alloc(8)\n\t\t\t\treadSync(fd, nameBuf, 0, 8, off)\n\t\t\t\tconst name = this.#stripTrailingNulls(nameBuf.toString('ascii'))\n\t\t\t\tconst virtualSize = this.#readU32(fd, off + 8)\n\t\t\t\tconst virtualAddress = this.#readU32(fd, off + 12)\n\t\t\t\tconst rawSize = this.#readU32(fd, off + 16)\n\t\t\t\tconst rawOffset = this.#readU32(fd, off + 20)\n\t\t\t\tconst characteristics = this.#readU32(fd, off + 36)\n\n\t\t\t\tsections.push({\n\t\t\t\t\tname,\n\t\t\t\t\tvirtualSize,\n\t\t\t\t\tvirtualAddress,\n\t\t\t\t\trawSize,\n\t\t\t\t\trawOffset,\n\t\t\t\t\tcharacteristics,\n\t\t\t\t\theaderOffset: off,\n\t\t\t\t})\n\n\t\t\t\tif (\n\t\t\t\t\texistingResourceRva >= virtualAddress &&\n\t\t\t\t\texistingResourceRva < virtualAddress + Math.max(virtualSize, rawSize)\n\t\t\t\t) {\n\t\t\t\t\trsrcSectionIndex = i\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// --- Check space for a new section header entry ---\n\t\t\tconst sectionTableEnd = sectionTableOffset + numberOfSections * PE_SECTION_HEADER_SIZE\n\t\t\tconst firstSectionFileOffset = sections.reduce(\n\t\t\t\t(min, s) => (s.rawOffset > 0 && s.rawOffset < min ? s.rawOffset : min),\n\t\t\t\tInfinity,\n\t\t\t)\n\t\t\tconst availableHeaderSpace = firstSectionFileOffset - sectionTableEnd\n\t\t\tif (availableHeaderSpace < PE_SECTION_HEADER_SIZE) {\n\t\t\t\tthrow new SEAError(\n\t\t\t\t\t'INJECT',\n\t\t\t\t\t'No room in PE header for a new section entry ' +\n\t\t\t\t\t\t`(${String(availableHeaderSpace)} bytes available, need ${String(PE_SECTION_HEADER_SIZE)})`,\n\t\t\t\t\t{\n\t\t\t\t\t\texecutable: this.#options.executable,\n\t\t\t\t\t\tavailableHeaderSpace,\n\t\t\t\t\t\trequiredHeaderSpace: PE_SECTION_HEADER_SIZE,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// --- Gather existing resource leaves ---\n\t\t\tconst existingLeaves: Array<{\n\t\t\t\ttypeId: number\n\t\t\t\ttypeName: string | undefined\n\t\t\t\tnameId: number\n\t\t\t\tnameName: string | undefined\n\t\t\t\tlanguage: number\n\t\t\t\tcodePage: number\n\t\t\t\tdataRva: number\n\t\t\t\tdataSize: number\n\t\t\t}> = []\n\n\t\t\tif (rsrcSectionIndex !== -1 && existingResourceRva !== 0) {\n\t\t\t\tconst rsrc = sections[rsrcSectionIndex]\n\t\t\t\tif (rsrc !== undefined) {\n\t\t\t\t\tthis.#parseResourceDirectory(\n\t\t\t\t\t\tfd,\n\t\t\t\t\t\trsrc.rawOffset,\n\t\t\t\t\t\texistingResourceRva,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\texistingLeaves,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// --- Remove old blob entry if overwriting ---\n\t\t\tconst overwrite = this.#options.overwrite !== false\n\t\t\tconst upperName = this.#options.resource.toUpperCase()\n\t\t\tconst filteredLeaves = existingLeaves.filter((leaf) => {\n\t\t\t\tif (!overwrite) return true\n\t\t\t\tif (leaf.typeId !== PE_RT_RCDATA) return true\n\t\t\t\treturn leaf.nameName?.toUpperCase() !== upperName\n\t\t\t})\n\n\t\t\t// --- Read existing resource data ---\n\t\t\t// For each existing leaf, read its data from the original file\n\t\t\tconst leafDataMap = new Map<number, Buffer>()\n\t\t\tfor (let i = 0; i < filteredLeaves.length; i++) {\n\t\t\t\tconst leaf = filteredLeaves[i]\n\t\t\t\tif (leaf === undefined) continue\n\t\t\t\t// Convert data RVA to file offset\n\t\t\t\tconst fileOffset = this.#rvaToFileOffset(leaf.dataRva, sections)\n\t\t\t\tif (fileOffset >= 0) {\n\t\t\t\t\tconst buf = Buffer.alloc(leaf.dataSize)\n\t\t\t\t\treadSync(fd, buf, 0, leaf.dataSize, fileOffset)\n\t\t\t\t\tleafDataMap.set(i, buf)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// --- Build new resource section ---\n\t\t\tconst blobSize = statSync(this.#options.blob).size\n\n\t\t\t// Build resource tree: group by type → name → language\n\t\t\tconst tree = this.#buildResourceTree(filteredLeaves, upperName, blobSize)\n\n\t\t\t// Serialize the resource directory + data entries (without blob data)\n\t\t\tconst { directoryBuffer, dataRegionSize } = this.#serializeResourceTree(\n\t\t\t\ttree,\n\t\t\t\tleafDataMap,\n\t\t\t\tblobSize,\n\t\t\t)\n\n\t\t\t// Total section raw size = directory + data region (existing data + blob)\n\t\t\tconst totalRawSize = directoryBuffer.length + dataRegionSize\n\t\t\tconst alignedRawSize = this.#align(totalRawSize, fileAlignment)\n\n\t\t\t// --- Determine new section placement ---\n\t\t\t// Virtual address: highest VA end of all sections, aligned\n\t\t\tlet highestVaEnd = 0\n\t\t\tfor (const s of sections) {\n\t\t\t\tconst end = s.virtualAddress + Math.max(s.virtualSize, s.rawSize)\n\t\t\t\tif (end > highestVaEnd) highestVaEnd = end\n\t\t\t}\n\t\t\tconst newVa = this.#align(highestVaEnd, sectionAlignment)\n\t\t\tconst newVirtualSize = totalRawSize\n\n\t\t\t// File offset: end of file, aligned\n\t\t\tconst fileSize = statSync(this.#options.executable).size\n\t\t\tconst newRawOffset = this.#align(fileSize, fileAlignment)\n\n\t\t\t// --- Write new section header ---\n\t\t\tconst newHeaderOffset = sectionTableEnd\n\t\t\tconst headerBuf = Buffer.alloc(PE_SECTION_HEADER_SIZE)\n\n\t\t\t// Section name: .rsrc2 (avoids confusion with existing .rsrc)\n\t\t\theaderBuf.write('.rsrc2', 0, 6, 'ascii')\n\t\t\theaderBuf.writeUInt32LE(newVirtualSize, 8) // VirtualSize\n\t\t\theaderBuf.writeUInt32LE(newVa, 12) // VirtualAddress\n\t\t\theaderBuf.writeUInt32LE(alignedRawSize, 16) // SizeOfRawData\n\t\t\theaderBuf.writeUInt32LE(newRawOffset, 20) // PointerToRawData\n\t\t\theaderBuf.writeUInt32LE(0, 24) // PointerToRelocations\n\t\t\theaderBuf.writeUInt32LE(0, 28) // PointerToLinenumbers\n\t\t\theaderBuf.writeUInt16LE(0, 32) // NumberOfRelocations\n\t\t\theaderBuf.writeUInt16LE(0, 34) // NumberOfLinenumbers\n\t\t\theaderBuf.writeUInt32LE(PE_SCN_INITIALIZED_DATA | PE_SCN_MEM_READ, 36) // Characteristics\n\n\t\t\twriteSync(fd, headerBuf, 0, PE_SECTION_HEADER_SIZE, newHeaderOffset)\n\n\t\t\t// --- Update PE headers ---\n\t\t\t// NumberOfSections\n\t\t\tthis.#writeU16(fd, coffOffset + 2, numberOfSections + 1)\n\n\t\t\t// Resource data directory → point to new section\n\t\t\tthis.#writeU32(fd, resourceDirRvaOffset, newVa)\n\t\t\tthis.#writeU32(fd, resourceDirSizeOffset, directoryBuffer.length)\n\n\t\t\t// SizeOfImage — must cover the new section\n\t\t\tconst newSizeOfImage = this.#align(\n\t\t\t\tnewVa + Math.max(newVirtualSize, alignedRawSize),\n\t\t\t\tsectionAlignment,\n\t\t\t)\n\t\t\tthis.#writeU32(fd, sizeOfImageOffset, newSizeOfImage)\n\n\t\t\tcloseSync(fd)\n\n\t\t\t// --- Write new section data to file ---\n\t\t\t// Pad file to aligned offset\n\t\t\tconst currentFileSize = statSync(this.#options.executable).size\n\t\t\tif (newRawOffset > currentFileSize) {\n\t\t\t\tconst padding = Buffer.alloc(newRawOffset - currentFileSize)\n\t\t\t\tappendFileSync(this.#options.executable, padding)\n\t\t\t}\n\n\t\t\t// Fixup RVAs in the directory buffer: add newVa as base\n\t\t\tthis.#fixupDirectoryRvas(directoryBuffer, newVa)\n\n\t\t\t// Write the directory buffer\n\t\t\tappendFileSync(this.#options.executable, directoryBuffer)\n\n\t\t\t// Write existing resource data\n\t\t\tfor (let i = 0; i < filteredLeaves.length; i++) {\n\t\t\t\tconst data = leafDataMap.get(i)\n\t\t\t\tif (data !== undefined) {\n\t\t\t\t\tappendFileSync(this.#options.executable, data)\n\t\t\t\t\t// Pad to DWORD alignment\n\t\t\t\t\tconst padLen = this.#align(data.length, 4) - data.length\n\t\t\t\t\tif (padLen > 0) {\n\t\t\t\t\t\tappendFileSync(this.#options.executable, Buffer.alloc(padLen))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Stream the blob from disk\n\t\t\tthis.#appendFile(this.#options.executable, this.#options.blob)\n\n\t\t\t// Pad the section to aligned raw size\n\t\t\tconst writtenSize = statSync(this.#options.executable).size - newRawOffset\n\t\t\tif (writtenSize < alignedRawSize) {\n\t\t\t\tappendFileSync(this.#options.executable, Buffer.alloc(alignedRawSize - writtenSize))\n\t\t\t}\n\n\t\t\t// The checksum is recomputed by the caller (inject()) AFTER the\n\t\t\t// sentinel-fuse byte flip, so it covers every prior header/section\n\t\t\t// change plus the fuse mutation. Return the offset for that call.\n\t\t\treturn optionalOffset\n\t\t} catch (error: unknown) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd)\n\t\t\t} catch {\n\t\t\t\t/* already closed */\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t// --- PE: parse resource directory tree recursively ---\n\n\t#parseResourceDirectory(\n\t\tfd: number,\n\t\tsectionFileOffset: number,\n\t\tsectionRva: number,\n\t\tdirOffset: number,\n\t\tleaves: Array<{\n\t\t\ttypeId: number\n\t\t\ttypeName: string | undefined\n\t\t\tnameId: number\n\t\t\tnameName: string | undefined\n\t\t\tlanguage: number\n\t\t\tcodePage: number\n\t\t\tdataRva: number\n\t\t\tdataSize: number\n\t\t}>,\n\t\tdepth: number,\n\t\tcurrentTypeId: number,\n\t\tcurrentTypeName: string | undefined,\n\t\tcurrentNameId: number,\n\t\tcurrentNameName: string | undefined,\n\t): void {\n\t\tconst absOffset = sectionFileOffset + dirOffset\n\n\t\t// IMAGE_RESOURCE_DIRECTORY: 16 bytes\n\t\tconst numNamedEntries = this.#readU16(fd, absOffset + 12)\n\t\tconst numIdEntries = this.#readU16(fd, absOffset + 14)\n\t\tconst totalEntries = numNamedEntries + numIdEntries\n\n\t\tfor (let i = 0; i < totalEntries; i++) {\n\t\t\tconst entryOffset = absOffset + PE_RESOURCE_DIR_SIZE + i * PE_RESOURCE_ENTRY_SIZE\n\t\t\tconst nameOrId = this.#readU32(fd, entryOffset)\n\t\t\tconst offsetOrData = this.#readU32(fd, entryOffset + 4)\n\n\t\t\t// Resolve name or ID\n\t\t\tlet entryId = 0\n\t\t\tlet entryName: string | undefined\n\n\t\t\tif ((nameOrId & PE_RESOURCE_NAME_FLAG) !== 0) {\n\t\t\t\t// Named entry — offset to IMAGE_RESOURCE_DIR_STRING_U\n\t\t\t\tconst stringOffset = nameOrId & ~PE_RESOURCE_NAME_FLAG\n\t\t\t\tentryName = this.#readResourceString(fd, sectionFileOffset + stringOffset)\n\t\t\t} else {\n\t\t\t\tentryId = nameOrId\n\t\t\t}\n\n\t\t\t// Track current type/name based on depth\n\t\t\tlet typeId = currentTypeId\n\t\t\tlet typeName = currentTypeName\n\t\t\tlet nameId = currentNameId\n\t\t\tlet nameName = currentNameName\n\n\t\t\tif (depth === 0) {\n\t\t\t\ttypeId = entryId\n\t\t\t\ttypeName = entryName\n\t\t\t} else if (depth === 1) {\n\t\t\t\tnameId = entryId\n\t\t\t\tnameName = entryName\n\t\t\t}\n\n\t\t\tif ((offsetOrData & PE_RESOURCE_SUBDIR_FLAG) !== 0) {\n\t\t\t\t// Subdirectory\n\t\t\t\tconst subDirOffset = offsetOrData & ~PE_RESOURCE_SUBDIR_FLAG\n\t\t\t\tthis.#parseResourceDirectory(\n\t\t\t\t\tfd,\n\t\t\t\t\tsectionFileOffset,\n\t\t\t\t\tsectionRva,\n\t\t\t\t\tsubDirOffset,\n\t\t\t\t\tleaves,\n\t\t\t\t\tdepth + 1,\n\t\t\t\t\ttypeId,\n\t\t\t\t\ttypeName,\n\t\t\t\t\tnameId,\n\t\t\t\t\tnameName,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\t// Data entry (leaf)\n\t\t\t\tconst dataEntryFileOffset = sectionFileOffset + offsetOrData\n\t\t\t\tconst dataRva = this.#readU32(fd, dataEntryFileOffset)\n\t\t\t\tconst dataSize = this.#readU32(fd, dataEntryFileOffset + 4)\n\t\t\t\tconst codePage = this.#readU32(fd, dataEntryFileOffset + 8)\n\n\t\t\t\tconst language = depth === 2 ? entryId : 0\n\n\t\t\t\tleaves.push({\n\t\t\t\t\ttypeId,\n\t\t\t\t\ttypeName,\n\t\t\t\t\tnameId,\n\t\t\t\t\tnameName,\n\t\t\t\t\tlanguage,\n\t\t\t\t\tcodePage,\n\t\t\t\t\tdataRva,\n\t\t\t\t\tdataSize,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- PE: read a Unicode resource string ---\n\n\t#readResourceString(fd: number, offset: number): string {\n\t\tconst lenBuf = Buffer.alloc(2)\n\t\treadSync(fd, lenBuf, 0, 2, offset)\n\t\tconst charCount = lenBuf.readUInt16LE(0)\n\t\tif (charCount === 0) return ''\n\t\tconst strBuf = Buffer.alloc(charCount * 2)\n\t\treadSync(fd, strBuf, 0, charCount * 2, offset + 2)\n\t\treturn strBuf.toString('utf16le')\n\t}\n\n\t// --- PE: convert RVA to file offset using section table ---\n\n\t#rvaToFileOffset(\n\t\trva: number,\n\t\tsections: Array<{\n\t\t\tvirtualAddress: number\n\t\t\tvirtualSize: number\n\t\t\trawSize: number\n\t\t\trawOffset: number\n\t\t}>,\n\t): number {\n\t\tfor (const s of sections) {\n\t\t\tconst sectionEnd = s.virtualAddress + Math.max(s.virtualSize, s.rawSize)\n\t\t\tif (rva >= s.virtualAddress && rva < sectionEnd) {\n\t\t\t\treturn rva - s.virtualAddress + s.rawOffset\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\n\t// --- PE: build the resource tree for serialization ---\n\n\t#buildResourceTree(\n\t\texistingLeaves: Array<{\n\t\t\ttypeId: number\n\t\t\ttypeName: string | undefined\n\t\t\tnameId: number\n\t\t\tnameName: string | undefined\n\t\t\tlanguage: number\n\t\t\tcodePage: number\n\t\t\tdataRva: number\n\t\t\tdataSize: number\n\t\t}>,\n\t\tblobName: string,\n\t\tblobSize: number,\n\t): Map<\n\t\tstring,\n\t\tMap<\n\t\t\tstring,\n\t\t\tArray<{\n\t\t\t\tlanguage: number\n\t\t\t\tcodePage: number\n\t\t\t\tleafIndex: number\n\t\t\t\tdataSize: number\n\t\t\t}>\n\t\t>\n\t> {\n\t\t// Tree: typeKey → nameKey → language entries\n\t\t// typeKey/nameKey encode both named and integer IDs\n\t\tconst tree = new Map<\n\t\t\tstring,\n\t\t\tMap<\n\t\t\t\tstring,\n\t\t\t\tArray<{\n\t\t\t\t\tlanguage: number\n\t\t\t\t\tcodePage: number\n\t\t\t\t\tleafIndex: number\n\t\t\t\t\tdataSize: number\n\t\t\t\t}>\n\t\t\t>\n\t\t>()\n\n\t\t// Add existing leaves\n\t\tfor (let i = 0; i < existingLeaves.length; i++) {\n\t\t\tconst leaf = existingLeaves[i]\n\t\t\tif (leaf === undefined) continue\n\t\t\tconst typeKey =\n\t\t\t\tleaf.typeName !== undefined ? `n:${leaf.typeName}` : `i:${String(leaf.typeId)}`\n\t\t\tconst nameKey =\n\t\t\t\tleaf.nameName !== undefined ? `n:${leaf.nameName}` : `i:${String(leaf.nameId)}`\n\n\t\t\tlet typeMap = tree.get(typeKey)\n\t\t\tif (typeMap === undefined) {\n\t\t\t\ttypeMap = new Map()\n\t\t\t\ttree.set(typeKey, typeMap)\n\t\t\t}\n\t\t\tlet langArr = typeMap.get(nameKey)\n\t\t\tif (langArr === undefined) {\n\t\t\t\tlangArr = []\n\t\t\t\ttypeMap.set(nameKey, langArr)\n\t\t\t}\n\t\t\tlangArr.push({\n\t\t\t\tlanguage: leaf.language,\n\t\t\t\tcodePage: leaf.codePage,\n\t\t\t\tleafIndex: i,\n\t\t\t\tdataSize: leaf.dataSize,\n\t\t\t})\n\t\t}\n\n\t\t// Add the new blob entry\n\t\tconst blobTypeKey = `i:${String(PE_RT_RCDATA)}`\n\t\tconst blobNameKey = `n:${blobName}`\n\n\t\tlet typeMap = tree.get(blobTypeKey)\n\t\tif (typeMap === undefined) {\n\t\t\ttypeMap = new Map()\n\t\t\ttree.set(blobTypeKey, typeMap)\n\t\t}\n\t\ttypeMap.set(blobNameKey, [\n\t\t\t{\n\t\t\t\tlanguage: 0,\n\t\t\t\tcodePage: 0,\n\t\t\t\tleafIndex: -1, // -1 signals \"this is the blob\"\n\t\t\t\tdataSize: blobSize,\n\t\t\t},\n\t\t])\n\n\t\treturn tree\n\t}\n\n\t// --- PE: serialize the resource tree into a buffer ---\n\n\t#serializeResourceTree(\n\t\ttree: Map<\n\t\t\tstring,\n\t\t\tMap<\n\t\t\t\tstring,\n\t\t\t\tArray<{\n\t\t\t\t\tlanguage: number\n\t\t\t\t\tcodePage: number\n\t\t\t\t\tleafIndex: number\n\t\t\t\t\tdataSize: number\n\t\t\t\t}>\n\t\t\t>\n\t\t>,\n\t\tleafDataMap: Map<number, Buffer>,\n\t\tblobSize: number,\n\t): {\n\t\tdirectoryBuffer: Buffer\n\t\tdataRegionSize: number\n\t\tblobDataOffset: number\n\t} {\n\t\t// Phase 1: Calculate sizes\n\t\t// Level 0 (root): 1 directory + entries for each type\n\t\t// Level 1 (per type): 1 directory + entries for each name\n\t\t// Level 2 (per name): 1 directory + entries for each language\n\t\t// Then: all name strings, all data entries\n\n\t\tlet dirTableSize = 0\n\t\tlet stringPoolSize = 0\n\t\tlet dataEntryCount = 0\n\n\t\t// Root directory\n\t\tdirTableSize += PE_RESOURCE_DIR_SIZE + tree.size * PE_RESOURCE_ENTRY_SIZE\n\n\t\tconst allStrings: Array<{ key: string; value: string }> = []\n\t\tconst allLeafEntries: Array<{\n\t\t\tleafIndex: number\n\t\t\tdataSize: number\n\t\t\tcodePage: number\n\t\t}> = []\n\n\t\tfor (const [typeKey, nameMap] of tree) {\n\t\t\t// Type directory\n\t\t\tdirTableSize += PE_RESOURCE_DIR_SIZE + nameMap.size * PE_RESOURCE_ENTRY_SIZE\n\n\t\t\t// Collect type name string if named\n\t\t\tif (typeKey.startsWith('n:')) {\n\t\t\t\tconst str = typeKey.slice(2)\n\t\t\t\tallStrings.push({ key: typeKey, value: str })\n\t\t\t\tstringPoolSize += 2 + str.length * 2 // length (u16) + UTF-16LE chars\n\t\t\t\tstringPoolSize = this.#align(stringPoolSize, 2) // WORD align strings\n\t\t\t}\n\n\t\t\tfor (const [nameKey, langEntries] of nameMap) {\n\t\t\t\t// Name directory\n\t\t\t\tdirTableSize += PE_RESOURCE_DIR_SIZE + langEntries.length * PE_RESOURCE_ENTRY_SIZE\n\n\t\t\t\t// Collect name string if named\n\t\t\t\tif (nameKey.startsWith('n:')) {\n\t\t\t\t\tconst str = nameKey.slice(2)\n\t\t\t\t\tallStrings.push({ key: nameKey, value: str })\n\t\t\t\t\tstringPoolSize += 2 + str.length * 2\n\t\t\t\t\tstringPoolSize = this.#align(stringPoolSize, 2)\n\t\t\t\t}\n\n\t\t\t\tfor (const entry of langEntries) {\n\t\t\t\t\tallLeafEntries.push({\n\t\t\t\t\t\tleafIndex: entry.leafIndex,\n\t\t\t\t\t\tdataSize: entry.dataSize,\n\t\t\t\t\t\tcodePage: entry.codePage,\n\t\t\t\t\t})\n\t\t\t\t\tdataEntryCount++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst dataEntriesSize = dataEntryCount * PE_RESOURCE_DATA_ENTRY_SIZE\n\t\tconst headerSize = dirTableSize + stringPoolSize + dataEntriesSize\n\n\t\t// Phase 2: Calculate data region (existing leaves + blob)\n\t\tlet dataRegionOffset = 0\n\t\tconst leafFileOffsets = new Map<number, number>() // leafIndex → offset within data region\n\n\t\tfor (let i = 0; i < allLeafEntries.length; i++) {\n\t\t\tconst entry = allLeafEntries[i]\n\t\t\tif (entry === undefined) continue\n\t\t\tif (entry.leafIndex === -1) continue // blob handled separately\n\n\t\t\tconst data = leafDataMap.get(entry.leafIndex)\n\t\t\tif (data !== undefined) {\n\t\t\t\tleafFileOffsets.set(entry.leafIndex, dataRegionOffset)\n\t\t\t\tdataRegionOffset += this.#align(data.length, 4)\n\t\t\t}\n\t\t}\n\n\t\tconst blobDataOffset = dataRegionOffset\n\t\tdataRegionOffset += blobSize\n\t\tconst dataRegionSize = dataRegionOffset\n\n\t\t// Phase 3: Build the directory buffer with placeholder RVAs\n\t\t// RVAs will be fixed up later with the actual section VA\n\t\tconst buf = Buffer.alloc(headerSize)\n\t\tlet dirPos = 0\n\t\tlet stringPos = dirTableSize\n\t\tlet dataEntryPos = dirTableSize + stringPoolSize\n\n\t\t// String offset lookup: key → offset within directory buffer\n\t\tconst stringOffsets = new Map<string, number>()\n\t\tfor (const { key, value } of allStrings) {\n\t\t\tstringOffsets.set(key, stringPos)\n\t\t\tbuf.writeUInt16LE(value.length, stringPos)\n\t\t\tbuf.write(value, stringPos + 2, value.length * 2, 'utf16le')\n\t\t\tstringPos += 2 + value.length * 2\n\t\t\tstringPos = this.#align(stringPos, 2)\n\t\t}\n\n\t\t// Sort tree entries: named entries first (sorted by name), then ID entries (sorted by ID)\n\t\tconst sortedTypeKeys = this.#sortResourceKeys([...tree.keys()])\n\n\t\t// Helper to track subdirectory offsets for linking\n\t\tconst nextDirOffset = PE_RESOURCE_DIR_SIZE + tree.size * PE_RESOURCE_ENTRY_SIZE\n\n\t\t// --- Write root directory ---\n\t\tconst namedTypes = sortedTypeKeys.filter((k) => k.startsWith('n:'))\n\t\tconst idTypes = sortedTypeKeys.filter((k) => k.startsWith('i:'))\n\n\t\tbuf.writeUInt32LE(0, dirPos) // Characteristics\n\t\tbuf.writeUInt32LE(0, dirPos + 4) // TimeDateStamp\n\t\tbuf.writeUInt16LE(0, dirPos + 8) // MajorVersion\n\t\tbuf.writeUInt16LE(0, dirPos + 10) // MinorVersion\n\t\tbuf.writeUInt16LE(namedTypes.length, dirPos + 12)\n\t\tbuf.writeUInt16LE(idTypes.length, dirPos + 14)\n\t\tdirPos += PE_RESOURCE_DIR_SIZE\n\n\t\t// Pre-calculate all type subdirectory offsets\n\t\tconst typeDirOffsets = new Map<string, number>()\n\t\tlet accDirOffset = nextDirOffset\n\t\tfor (const typeKey of sortedTypeKeys) {\n\t\t\ttypeDirOffsets.set(typeKey, accDirOffset)\n\t\t\tconst nameMap = tree.get(typeKey)\n\t\t\tif (nameMap === undefined) continue\n\t\t\tconst typeEntryCount = nameMap.size\n\t\t\taccDirOffset += PE_RESOURCE_DIR_SIZE + typeEntryCount * PE_RESOURCE_ENTRY_SIZE\n\t\t\tfor (const [, langEntries] of nameMap) {\n\t\t\t\taccDirOffset += PE_RESOURCE_DIR_SIZE + langEntries.length * PE_RESOURCE_ENTRY_SIZE\n\t\t\t}\n\t\t}\n\n\t\t// Write root entries\n\t\tfor (const typeKey of sortedTypeKeys) {\n\t\t\tconst isNamed = typeKey.startsWith('n:')\n\t\t\tconst nameOrId = isNamed\n\t\t\t\t? (stringOffsets.get(typeKey) ?? 0) | PE_RESOURCE_NAME_FLAG\n\t\t\t\t: parseInt(typeKey.slice(2), 10)\n\t\t\tconst subdirOffset = (typeDirOffsets.get(typeKey) ?? 0) | PE_RESOURCE_SUBDIR_FLAG\n\n\t\t\tbuf.writeUInt32LE(nameOrId >>> 0, dirPos)\n\t\t\tbuf.writeUInt32LE(subdirOffset >>> 0, dirPos + 4)\n\t\t\tdirPos += PE_RESOURCE_ENTRY_SIZE\n\t\t}\n\n\t\t// --- Write type subdirectories ---\n\t\tfor (const typeKey of sortedTypeKeys) {\n\t\t\tconst nameMap = tree.get(typeKey)\n\t\t\tif (nameMap === undefined) continue\n\t\t\tconst sortedNameKeys = this.#sortResourceKeys([...nameMap.keys()])\n\t\t\tconst namedNames = sortedNameKeys.filter((k) => k.startsWith('n:'))\n\t\t\tconst idNames = sortedNameKeys.filter((k) => k.startsWith('i:'))\n\n\t\t\tbuf.writeUInt32LE(0, dirPos)\n\t\t\tbuf.writeUInt32LE(0, dirPos + 4)\n\t\t\tbuf.writeUInt16LE(0, dirPos + 8)\n\t\t\tbuf.writeUInt16LE(0, dirPos + 10)\n\t\t\tbuf.writeUInt16LE(namedNames.length, dirPos + 12)\n\t\t\tbuf.writeUInt16LE(idNames.length, dirPos + 14)\n\t\t\tdirPos += PE_RESOURCE_DIR_SIZE\n\n\t\t\t// Calculate offset of each name's language subdirectory\n\t\t\t// These come sequentially after the current type directory and its entries\n\t\t\tlet langSubdirCursor = dirPos + sortedNameKeys.length * PE_RESOURCE_ENTRY_SIZE\n\n\t\t\tfor (const nameKey of sortedNameKeys) {\n\t\t\t\tconst isNamed = nameKey.startsWith('n:')\n\t\t\t\tconst nameOrId = isNamed\n\t\t\t\t\t? (stringOffsets.get(nameKey) ?? 0) | PE_RESOURCE_NAME_FLAG\n\t\t\t\t\t: parseInt(nameKey.slice(2), 10)\n\n\t\t\t\t// The language subdirectory offset is relative to resource section start\n\t\t\t\tconst langSubDirRelOffset = langSubdirCursor | PE_RESOURCE_SUBDIR_FLAG\n\n\t\t\t\tbuf.writeUInt32LE(nameOrId >>> 0, dirPos)\n\t\t\t\tbuf.writeUInt32LE(langSubDirRelOffset >>> 0, dirPos + 4)\n\t\t\t\tdirPos += PE_RESOURCE_ENTRY_SIZE\n\n\t\t\t\tconst langEntries = nameMap.get(nameKey)\n\t\t\t\tif (langEntries !== undefined) {\n\t\t\t\t\tlangSubdirCursor += PE_RESOURCE_DIR_SIZE + langEntries.length * PE_RESOURCE_ENTRY_SIZE\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Write language subdirectories for each name\n\t\t\tfor (const nameKey of sortedNameKeys) {\n\t\t\t\tconst langEntries = nameMap.get(nameKey)\n\t\t\t\tif (langEntries === undefined) continue\n\n\t\t\t\tbuf.writeUInt32LE(0, dirPos)\n\t\t\t\tbuf.writeUInt32LE(0, dirPos + 4)\n\t\t\t\tbuf.writeUInt16LE(0, dirPos + 8)\n\t\t\t\tbuf.writeUInt16LE(0, dirPos + 10)\n\t\t\t\tbuf.writeUInt16LE(0, dirPos + 12) // no named language entries\n\t\t\t\tbuf.writeUInt16LE(langEntries.length, dirPos + 14)\n\t\t\t\tdirPos += PE_RESOURCE_DIR_SIZE\n\n\t\t\t\tfor (const entry of langEntries) {\n\t\t\t\t\t// Language ID\n\t\t\t\t\tbuf.writeUInt32LE(entry.language, dirPos)\n\n\t\t\t\t\t// Data entry offset (not a subdirectory — no high bit)\n\t\t\t\t\tbuf.writeUInt32LE(dataEntryPos, dirPos + 4)\n\t\t\t\t\tdirPos += PE_RESOURCE_ENTRY_SIZE\n\n\t\t\t\t\t// Write the data entry\n\t\t\t\t\t// DataRVA — placeholder, will be fixed up with actual VA\n\t\t\t\t\tlet dataOffset: number\n\t\t\t\t\tif (entry.leafIndex === -1) {\n\t\t\t\t\t\t// Blob\n\t\t\t\t\t\tdataOffset = headerSize + blobDataOffset\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst resolvedOffset = leafFileOffsets.get(entry.leafIndex)\n\t\t\t\t\t\tif (resolvedOffset === undefined) {\n\t\t\t\t\t\t\tthrow new SEAError('INJECT', 'unresolvable resource RVA', {\n\t\t\t\t\t\t\t\texecutable: this.#options.executable,\n\t\t\t\t\t\t\t\tleafIndex: entry.leafIndex,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdataOffset = headerSize + resolvedOffset\n\t\t\t\t\t}\n\n\t\t\t\t\t// Store as relative offset from section start for now;\n\t\t\t\t\t// #fixupDirectoryRvas will add the section VA\n\t\t\t\t\tbuf.writeUInt32LE(dataOffset, dataEntryPos) // DataRVA (placeholder)\n\t\t\t\t\tbuf.writeUInt32LE(entry.dataSize, dataEntryPos + 4) // Size\n\t\t\t\t\tbuf.writeUInt32LE(entry.codePage, dataEntryPos + 8) // CodePage\n\t\t\t\t\tbuf.writeUInt32LE(0, dataEntryPos + 12) // Reserved\n\t\t\t\t\tdataEntryPos += PE_RESOURCE_DATA_ENTRY_SIZE\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { directoryBuffer: buf, dataRegionSize, blobDataOffset }\n\t}\n\n\t// --- PE: fix up all data entry RVAs by adding the section's virtual address ---\n\n\t#fixupDirectoryRvas(directoryBuffer: Buffer, sectionVa: number): void {\n\t\t// Data entries are at the end of the directory buffer.\n\t\t// Each is 16 bytes: DataRVA(4), Size(4), CodePage(4), Reserved(4)\n\t\t// We need to find them and add sectionVa to the DataRVA field.\n\t\t//\n\t\t// Data entries are pointed to by level-2 directory entries.\n\t\t// Rather than re-walking the tree, we know that data entries are\n\t\t// contiguous at the end of the buffer (before strings, which we\n\t\t// placed between directories and data entries — wait, actually\n\t\t// strings come before data entries in our layout).\n\t\t//\n\t\t// Our layout: [directories] [strings] [data entries]\n\t\t// The data entries all need their first DWORD (DataRVA) adjusted.\n\t\t//\n\t\t// We can find them by scanning for references from directory entries.\n\t\t// But a simpler approach: we marked data entry positions during\n\t\t// serialization. Let's just scan the buffer for data entry blocks.\n\t\t//\n\t\t// Actually the simplest: re-walk the level-2 directory entries to\n\t\t// find the data entry offsets, then fix them up.\n\n\t\tthis.#fixupDataEntries(directoryBuffer, 0, 0, sectionVa)\n\t}\n\n\t#fixupDataEntries(buf: Buffer, dirOffset: number, depth: number, sectionVa: number): void {\n\t\tif (dirOffset + PE_RESOURCE_DIR_SIZE > buf.length) return\n\n\t\tconst namedCount = buf.readUInt16LE(dirOffset + 12)\n\t\tconst idCount = buf.readUInt16LE(dirOffset + 14)\n\t\tconst totalEntries = namedCount + idCount\n\n\t\tfor (let i = 0; i < totalEntries; i++) {\n\t\t\tconst entryOffset = dirOffset + PE_RESOURCE_DIR_SIZE + i * PE_RESOURCE_ENTRY_SIZE\n\t\t\tif (entryOffset + PE_RESOURCE_ENTRY_SIZE > buf.length) return\n\n\t\t\tconst offsetOrData = buf.readUInt32LE(entryOffset + 4)\n\n\t\t\tif ((offsetOrData & PE_RESOURCE_SUBDIR_FLAG) !== 0) {\n\t\t\t\t// Subdirectory — recurse\n\t\t\t\tconst subOffset = offsetOrData & ~PE_RESOURCE_SUBDIR_FLAG\n\t\t\t\tthis.#fixupDataEntries(buf, subOffset, depth + 1, sectionVa)\n\t\t\t} else {\n\t\t\t\t// Data entry — fix up the RVA\n\t\t\t\tif (offsetOrData + 4 <= buf.length) {\n\t\t\t\t\tconst currentRva = buf.readUInt32LE(offsetOrData)\n\t\t\t\t\tbuf.writeUInt32LE((currentRva + sectionVa) >>> 0, offsetOrData)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- PE: recompute and write the OptionalHeader.CheckSum ---\n\t//\n\t// The classic Windows IMAGE checksum: sum the whole file as little-endian\n\t// 16-bit words (the existing checksum's 4 bytes treated as zero), fold\n\t// carries into a 16-bit accumulator, then add the file length. Streamed in\n\t// chunks (like #appendFile) so a large SEA binary is never fully buffered.\n\n\t#patchChecksum(optionalOffset: number): void {\n\t\tconst checksumOffset = optionalOffset + 64\n\t\tconst fd = openSync(this.#options.executable, 'r+')\n\t\ttry {\n\t\t\tconst fileSize = statSync(this.#options.executable).size\n\t\t\tconst chunkSize = 4 * 1024 * 1024\n\t\t\tconst chunk = Buffer.alloc(Math.min(chunkSize, fileSize))\n\n\t\t\tlet sum = 0\n\t\t\tlet offset = 0\n\t\t\twhile (offset < fileSize) {\n\t\t\t\tconst toRead = Math.min(chunkSize, fileSize - offset)\n\t\t\t\tconst bytesRead = readSync(fd, chunk, 0, toRead, offset)\n\t\t\t\tif (bytesRead === 0) break\n\n\t\t\t\tfor (let i = 0; i < bytesRead; i += 2) {\n\t\t\t\t\tconst absolute = offset + i\n\t\t\t\t\tlet word: number\n\t\t\t\t\tif (absolute === checksumOffset || absolute === checksumOffset + 2) {\n\t\t\t\t\t\tword = 0\n\t\t\t\t\t} else if (i + 1 < bytesRead) {\n\t\t\t\t\t\tword = chunk.readUInt16LE(i)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tword = chunk.readUInt8(i)\n\t\t\t\t\t}\n\t\t\t\t\tsum += word\n\t\t\t\t\tsum = (sum & 0xffff) + (sum >>> 16)\n\t\t\t\t}\n\n\t\t\t\toffset += bytesRead\n\t\t\t}\n\n\t\t\tsum = (sum & 0xffff) + (sum >>> 16)\n\t\t\tconst checksum = (sum + fileSize) >>> 0\n\n\t\t\tthis.#writeU32(fd, checksumOffset, checksum)\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\t}\n\n\t// --- PE: sort resource keys (named first alphabetically, then IDs numerically) ---\n\n\t#sortResourceKeys(keys: string[]): readonly string[] {\n\t\tconst named = keys\n\t\t\t.filter((k) => k.startsWith('n:'))\n\t\t\t.sort((a, b) => a.slice(2).localeCompare(b.slice(2), 'en', { sensitivity: 'base' }))\n\t\tconst ids = keys\n\t\t\t.filter((k) => k.startsWith('i:'))\n\t\t\t.sort((a, b) => {\n\t\t\t\tconst ia = parseInt(a.slice(2), 10)\n\t\t\t\tconst ib = parseInt(b.slice(2), 10)\n\t\t\t\treturn ia - ib\n\t\t\t})\n\t\treturn [...named, ...ids]\n\t}\n\n\t// =========================================================================\n\t// ELF Injection\n\t// =========================================================================\n\t//\n\t// Strategy: append a PT_NOTE segment to the ELF. The note contains\n\t// the resource name and blob data. We find an existing PT_NOTE in the\n\t// program header table and repurpose it, or find space in the phdr\n\t// table for a new entry.\n\t//\n\t// Node.js SEA on Linux reads PT_NOTE segments via dl_iterate_phdr,\n\t// searching for a note whose name matches the resource name.\n\n\t#injectElf(): void {\n\t\tconst exePath = this.#options.executable\n\t\tconst resource = this.#options.resource\n\t\tconst overwrite = this.#options.overwrite !== false\n\n\t\tconst PT_LOAD = 1\n\t\tconst PT_PHDR = 6\n\t\tconst PF_R = 4\n\t\tconst PAGE = 0x1000\n\n\t\tlet phdrOffset: number\n\t\tlet phdrEntrySize: number\n\t\tlet phdrCount: number\n\t\tlet headers: Array<{\n\t\t\ttype: number\n\t\t\tflags: number\n\t\t\toffset: number\n\t\t\tvaddr: number\n\t\t\tpaddr: number\n\t\t\tfilesz: number\n\t\t\tmemsz: number\n\t\t\talign: number\n\t\t}>\n\n\t\tconst fd = openSync(exePath, 'r')\n\t\ttry {\n\t\t\t// --- Parse ELF header ---\n\t\t\tconst identBuf = Buffer.alloc(16)\n\t\t\treadSync(fd, identBuf, 0, 16, 0)\n\n\t\t\tconst elfClass = identBuf.readUInt8(4)\n\t\t\tconst elfData = identBuf.readUInt8(5)\n\n\t\t\tif (elfClass !== ELF_CLASS_64) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Only 64-bit ELF executables are supported', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\telfClass,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (elfData !== ELF_DATA_LSB) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Only little-endian ELF executables are supported', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\telfData,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tphdrOffset = Number(this.#readU64(fd, 32)) // e_phoff\n\t\t\tphdrEntrySize = this.#readU16(fd, 54) // e_phentsize\n\t\t\tphdrCount = this.#readU16(fd, 56) // e_phnum\n\n\t\t\theaders = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount)\n\n\t\t\t// Neutralize any stale PT_NOTE with a matching name so overwrite\n\t\t\t// never leaves two competing \"NODE_SEA*\" notes visible to\n\t\t\t// postject_find_resource — runtime skips any non-PT_NOTE entry.\n\t\t\tfor (const header of headers) {\n\t\t\t\tif (header.type !== ELF_PT_NOTE) continue\n\t\t\t\tconst existingName = this.#readElfNoteName(fd, header.offset, header.filesz)\n\t\t\t\tif (existingName === undefined || !existingName.startsWith('NODE_SEA')) continue\n\t\t\t\tif (!overwrite) {\n\t\t\t\t\tthrow new SEAError('INJECT', `Note with name \"${resource}\" already exists`, {\n\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t\tresource,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\theader.type = 0 // PT_NULL\n\t\t\t}\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\n\t\t// --- Compute the new PT_LOAD/PT_NOTE placement ---\n\t\t// The note MUST live inside a PT_LOAD so the runtime's dl_iterate_phdr\n\t\t// walk can read it from the mapped virtual address (Node reads\n\t\t// NODE_SEA notes from memory, never from the file).\n\t\tlet maxVaddrEnd = 0\n\t\tfor (const header of headers) {\n\t\t\tif (header.type !== PT_LOAD) continue\n\t\t\tconst end = header.vaddr + header.memsz\n\t\t\tif (end > maxVaddrEnd) maxVaddrEnd = end\n\t\t}\n\t\tconst regionVaddr = this.#align(maxVaddrEnd, PAGE)\n\n\t\tconst blobSize = statSync(this.#options.blob).size\n\t\tconst { header: noteHeader, entryTotal: noteEntryTotal } = buildELFNoteHeader(\n\t\t\tresource,\n\t\t\tblobSize,\n\t\t)\n\t\tconst noteAreaSize = this.#align(noteEntryTotal, 8)\n\n\t\tconst newEntryCount = headers.length + 2\n\t\tconst phtSize = newEntryCount * phdrEntrySize\n\t\tconst regionSize = noteAreaSize + phtSize\n\n\t\tconst fileSize = statSync(exePath).size\n\t\tconst regionStart = this.#align(fileSize, PAGE)\n\t\tconst phtOff = regionStart + noteAreaSize\n\n\t\tconst newLoad = {\n\t\t\ttype: PT_LOAD,\n\t\t\tflags: PF_R,\n\t\t\toffset: regionStart,\n\t\t\tvaddr: regionVaddr,\n\t\t\tpaddr: regionVaddr,\n\t\t\tfilesz: regionSize,\n\t\t\tmemsz: regionSize,\n\t\t\talign: PAGE,\n\t\t}\n\t\tconst newNote = {\n\t\t\ttype: ELF_PT_NOTE,\n\t\t\tflags: PF_R,\n\t\t\toffset: regionStart,\n\t\t\tvaddr: regionVaddr,\n\t\t\tpaddr: regionVaddr,\n\t\t\tfilesz: noteEntryTotal,\n\t\t\tmemsz: noteEntryTotal,\n\t\t\talign: 4,\n\t\t}\n\n\t\t// Relocate PT_PHDR (if present) to point at the enlarged table, which\n\t\t// itself lives inside the new PT_LOAD right after the note — keeping\n\t\t// PT_PHDR's p_vaddr congruent with its covering segment. This relies on\n\t\t// a modern-kernel loader that computes AT_PHDR from the PT_LOAD\n\t\t// covering e_phoff (Linux ~5.x+ / the Node>=24 target); a pre-5.x\n\t\t// kernel that instead computes AT_PHDR = load_addr + e_phoff would\n\t\t// derive a wrong value here since the PHT no longer sits at its\n\t\t// original load-relative offset.\n\t\tconst finalHeaders = headers.map((header) => {\n\t\t\tif (header.type !== PT_PHDR) return header\n\t\t\tconst relVaddr = regionVaddr + (phtOff - regionStart)\n\t\t\treturn {\n\t\t\t\t...header,\n\t\t\t\toffset: phtOff,\n\t\t\t\tvaddr: relVaddr,\n\t\t\t\tpaddr: relVaddr,\n\t\t\t\tfilesz: phtSize,\n\t\t\t\tmemsz: phtSize,\n\t\t\t}\n\t\t})\n\t\tfinalHeaders.push(newLoad, newNote)\n\n\t\tconst phtBuffer = Buffer.alloc(phtSize)\n\t\tfor (let i = 0; i < finalHeaders.length; i++) {\n\t\t\tconst entry = finalHeaders[i]\n\t\t\tif (entry === undefined) continue\n\t\t\tthis.#writeElfProgramHeaderEntry(phtBuffer, i * phdrEntrySize, entry)\n\t\t}\n\n\t\t// --- Append the new region: note header + streamed blob + padding + PHT ---\n\t\tif (regionStart > fileSize) {\n\t\t\tappendFileSync(exePath, Buffer.alloc(regionStart - fileSize))\n\t\t}\n\t\tappendFileSync(exePath, noteHeader)\n\t\tthis.#appendFile(exePath, this.#options.blob)\n\n\t\tconst alignedDescSize = this.#align(blobSize, 4)\n\t\tconst descPadding = alignedDescSize - blobSize\n\t\tif (descPadding > 0) {\n\t\t\tappendFileSync(exePath, Buffer.alloc(descPadding))\n\t\t}\n\n\t\tconst trailingPad = noteAreaSize - noteEntryTotal\n\t\tif (trailingPad > 0) {\n\t\t\tappendFileSync(exePath, Buffer.alloc(trailingPad))\n\t\t}\n\n\t\tappendFileSync(exePath, phtBuffer)\n\n\t\t// --- Point the ELF header at the relocated, enlarged PHT ---\n\t\tconst fd2 = openSync(exePath, 'r+')\n\t\ttry {\n\t\t\tthis.#writeU64(fd2, 32, BigInt(phtOff))\n\t\t\tthis.#writeU16(fd2, 56, newEntryCount)\n\n\t\t\t// Build-time readback: locate the note the SAME way the runtime\n\t\t\t// does (a PT_NOTE inside a PT_LOAD, address-congruent with its\n\t\t\t// file offset) so a passing readback reflects runtime success.\n\t\t\tthis.#verifyElfNoteMapping(fd2, phtOff, newEntryCount, phdrEntrySize)\n\t\t} finally {\n\t\t\tcloseSync(fd2)\n\t\t}\n\t}\n\n\t// --- ELF: read all program header entries into memory ---\n\n\t#readElfProgramHeaders(\n\t\tfd: number,\n\t\tphdrOffset: number,\n\t\tentrySize: number,\n\t\tcount: number,\n\t): Array<{\n\t\ttype: number\n\t\tflags: number\n\t\toffset: number\n\t\tvaddr: number\n\t\tpaddr: number\n\t\tfilesz: number\n\t\tmemsz: number\n\t\talign: number\n\t}> {\n\t\tconst headers: Array<{\n\t\t\ttype: number\n\t\t\tflags: number\n\t\t\toffset: number\n\t\t\tvaddr: number\n\t\t\tpaddr: number\n\t\t\tfilesz: number\n\t\t\tmemsz: number\n\t\t\talign: number\n\t\t}> = []\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst off = phdrOffset + i * entrySize\n\t\t\theaders.push({\n\t\t\t\ttype: this.#readU32(fd, off),\n\t\t\t\tflags: this.#readU32(fd, off + 4),\n\t\t\t\toffset: Number(this.#readU64(fd, off + 8)),\n\t\t\t\tvaddr: Number(this.#readU64(fd, off + 16)),\n\t\t\t\tpaddr: Number(this.#readU64(fd, off + 24)),\n\t\t\t\tfilesz: Number(this.#readU64(fd, off + 32)),\n\t\t\t\tmemsz: Number(this.#readU64(fd, off + 40)),\n\t\t\t\talign: Number(this.#readU64(fd, off + 48)),\n\t\t\t})\n\t\t}\n\t\treturn headers\n\t}\n\n\t// --- ELF: serialize a single program header entry (56 bytes, ELF64) ---\n\n\t#writeElfProgramHeaderEntry(\n\t\tbuf: Buffer,\n\t\tpos: number,\n\t\tentry: {\n\t\t\ttype: number\n\t\t\tflags: number\n\t\t\toffset: number\n\t\t\tvaddr: number\n\t\t\tpaddr: number\n\t\t\tfilesz: number\n\t\t\tmemsz: number\n\t\t\talign: number\n\t\t},\n\t): void {\n\t\tbuf.writeUInt32LE(entry.type >>> 0, pos)\n\t\tbuf.writeUInt32LE(entry.flags >>> 0, pos + 4)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.offset), pos + 8)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.vaddr), pos + 16)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.paddr), pos + 24)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.filesz), pos + 32)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.memsz), pos + 40)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.align), pos + 48)\n\t}\n\n\t// --- ELF: read a note's name at a given file offset (bounds-checked) ---\n\n\t#readElfNoteName(fd: number, offset: number, size: number): string | undefined {\n\t\tif (size < 12) return undefined\n\t\tconst namesz = this.#readU32(fd, offset)\n\t\tconst descsz = this.#readU32(fd, offset + 4)\n\t\tif (namesz === 0 || namesz > 256) return undefined\n\t\tif (12 + this.#align(namesz, 4) + this.#align(descsz, 4) > size) return undefined\n\n\t\tconst nameBuf = Buffer.alloc(namesz)\n\t\treadSync(fd, nameBuf, 0, namesz, offset + 12)\n\t\treturn this.#stripTrailingNulls(nameBuf.toString('utf-8'))\n\t}\n\n\t// --- ELF: build-time readback — confirm the note is runtime-reachable ---\n\n\t#verifyElfNoteMapping(\n\t\tfd: number,\n\t\tphdrOffset: number,\n\t\tphdrCount: number,\n\t\tphdrEntrySize: number,\n\t): void {\n\t\tconst headers = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount)\n\t\tconst loads = headers.filter((h) => h.type === 1)\n\t\tconst notes = headers.filter((h) => h.type === ELF_PT_NOTE)\n\n\t\tfor (const note of notes) {\n\t\t\tconst name = this.#readElfNoteName(fd, note.offset, note.filesz)\n\t\t\tif (name === undefined || !name.startsWith('NODE_SEA')) continue\n\n\t\t\tconst covering = loads.find(\n\t\t\t\t(load) => note.offset >= load.offset && note.offset < load.offset + load.filesz,\n\t\t\t)\n\t\t\tif (covering === undefined) continue\n\n\t\t\tconst expectedVaddr = covering.vaddr + (note.offset - covering.offset)\n\t\t\tif (expectedVaddr === note.vaddr) return\n\t\t}\n\n\t\tthrow new SEAError(\n\t\t\t'INJECT',\n\t\t\t'Injected ELF note is not reachable via a mapped PT_LOAD segment at runtime',\n\t\t\t{ executable: this.#options.executable, resource: this.#options.resource },\n\t\t)\n\t}\n\n\t// =========================================================================\n\t// Mach-O Injection\n\t// =========================================================================\n\t//\n\t// Strategy: append an LC_SEGMENT_64 load command with a single section\n\t// containing the blob data. The segment is placed at the next available\n\t// file offset and virtual address.\n\t//\n\t// Node.js SEA on macOS uses getsectdata(segment, section) to find the\n\t// blob. The segment defaults to \"__POSTJECT\" (or custom via options)\n\t// and the section is \"__\" + resource.\n\n\t#injectMacho(): void {\n\t\tconst exePath = this.#options.executable\n\t\tconst fileSize = statSync(exePath).size\n\t\tlet srcFd: number | undefined = openSync(exePath, 'r')\n\t\tlet destFd: number | undefined\n\t\tlet blobFd: number | undefined\n\t\tlet injTemp: string | undefined\n\n\t\ttry {\n\t\t\t// --- Bounded header read: just enough to cover every header/LC parse\n\t\t\t// and mutation below (headerSize + sizeofcmds) — never the whole file. ---\n\t\t\tconst headerSize = 32 // Mach-O 64-bit header\n\t\t\tconst preHeader = Buffer.alloc(headerSize)\n\t\t\treadSync(srcFd, preHeader, 0, headerSize, 0)\n\t\t\tconst preSizeofcmds = preHeader.readUInt32LE(20)\n\t\t\tif (headerSize + preSizeofcmds > fileSize) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Mach-O load command region exceeds file size', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\theaderSize,\n\t\t\t\t\tsizeofcmds: preSizeofcmds,\n\t\t\t\t\tfileSize,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst buf = Buffer.alloc(headerSize + preSizeofcmds)\n\t\t\treadSync(srcFd, buf, 0, headerSize + preSizeofcmds, 0)\n\n\t\t\t// --- Parse Mach-O header ---\n\t\t\tconst magic = buf.readUInt32LE(0)\n\t\t\tif (magic !== MACHO_MAGIC_64) {\n\t\t\t\tthrow new SEAError('FORMAT', `Unsupported Mach-O magic: 0x${magic.toString(16)}`, {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\tmagic,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst cputype = buf.readUInt32LE(4)\n\t\t\tconst ncmds = buf.readUInt32LE(16)\n\t\t\tconst sizeofcmds = buf.readUInt32LE(20)\n\n\t\t\tconst segmentName = this.#options.macho?.segment ?? 'NODE_SEA'\n\t\t\tlet sectionName = this.#options.resource\n\t\t\tif (!sectionName.startsWith('__')) {\n\t\t\t\tsectionName = `__${sectionName}`\n\t\t\t}\n\n\t\t\t// --- Walk load commands once, collecting their bounds ---\n\t\t\tconst commands: Array<{ type: number; size: number; offset: number }> = []\n\t\t\tlet cmdOffset = headerSize\n\t\t\tfor (let i = 0; i < ncmds; i++) {\n\t\t\t\tif (cmdOffset + 8 > buf.length) {\n\t\t\t\t\tthrow new SEAError('FORMAT', 'Malformed Mach-O load command table', {\n\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst cmdType = buf.readUInt32LE(cmdOffset)\n\t\t\t\tconst cmdSize = buf.readUInt32LE(cmdOffset + 4)\n\t\t\t\tif (cmdSize < 8 || cmdOffset + cmdSize > buf.length) {\n\t\t\t\t\tthrow new SEAError('FORMAT', 'Malformed Mach-O load command table', {\n\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tcommands.push({ type: cmdType, size: cmdSize, offset: cmdOffset })\n\t\t\t\tcmdOffset += cmdSize\n\t\t\t}\n\n\t\t\tlet linkeditIndex = -1\n\t\t\tconst existingSegmentIndices: number[] = []\n\t\t\tfor (let i = 0; i < commands.length; i++) {\n\t\t\t\tconst cmd = commands[i]\n\t\t\t\tif (cmd === undefined || cmd.type !== MACHO_LC_SEGMENT_64) continue\n\t\t\t\tconst segName = this.#stripTrailingNulls(\n\t\t\t\t\tbuf.subarray(cmd.offset + 8, cmd.offset + 24).toString('ascii'),\n\t\t\t\t)\n\t\t\t\tif (segName === '__LINKEDIT') linkeditIndex = i\n\t\t\t\tif (segName === segmentName) existingSegmentIndices.push(i)\n\t\t\t}\n\n\t\t\tif (existingSegmentIndices.length > 0 && this.#options.overwrite === false) {\n\t\t\t\tthrow new SEAError('INJECT', `Segment \"${segmentName}\" already exists`, {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\tsegmentName,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst linkeditCmd = linkeditIndex === -1 ? undefined : commands[linkeditIndex]\n\t\t\tif (linkeditCmd === undefined) {\n\t\t\t\tthrow new SEAError('INJECT', 'Mach-O binary has no __LINKEDIT segment', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst Loff = Number(buf.readBigUInt64LE(linkeditCmd.offset + 40))\n\t\t\tconst Lsize = Number(buf.readBigUInt64LE(linkeditCmd.offset + 48))\n\t\t\tconst Lvm = buf.readBigUInt64LE(linkeditCmd.offset + 24)\n\n\t\t\tconst blobSize = statSync(this.#options.blob).size\n\t\t\t// arm64 (0x0100000c) requires 16K pages; every other architecture (x86_64\n\t\t\t// etc.) uses 4K — 0x4000 is a safe superset alignment for either.\n\t\t\tconst pageSize = cputype === 0x0100000c ? 0x4000 : 0x1000\n\t\t\tconst shift = this.#align(blobSize, pageSize)\n\n\t\t\t// --- Ceiling check BEFORE mutating anything: the enlarged load-command\n\t\t\t// region (plus 16 bytes reserved for codesign re-adding\n\t\t\t// LC_CODE_SIGNATURE) must not overrun the first real section's bytes.\n\t\t\t// The sentinel starts at the FULL file size (not the bounded `buf`\n\t\t\t// size) — it represents \"no section found yet\", not a hard ceiling. ---\n\t\t\tlet firstSectionOffset = fileSize\n\t\t\tfor (const cmd of commands) {\n\t\t\t\tif (cmd.type !== MACHO_LC_SEGMENT_64) continue\n\t\t\t\tconst nsects = buf.readUInt32LE(cmd.offset + 64)\n\t\t\t\tfor (let s = 0; s < nsects; s++) {\n\t\t\t\t\tconst sectOff = cmd.offset + 72 + s * 80\n\t\t\t\t\tif (sectOff + 80 > buf.length) continue\n\t\t\t\t\tconst size = Number(buf.readBigUInt64LE(sectOff + 40))\n\t\t\t\t\tconst offset = buf.readUInt32LE(sectOff + 48)\n\t\t\t\t\tif (size > 0 && offset > 0 && offset < firstSectionOffset) {\n\t\t\t\t\t\tfirstSectionOffset = offset\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst newCmdSize = 72 + 80\n\t\t\tconst removedSize = commands\n\t\t\t\t.filter((_c, i) => existingSegmentIndices.includes(i))\n\t\t\t\t.reduce((sum, c) => sum + c.size, 0)\n\t\t\tconst newNcmds = commands.length - existingSegmentIndices.length + 1\n\t\t\tconst newSizeofcmds = sizeofcmds - removedSize + newCmdSize\n\n\t\t\tif (headerSize + newSizeofcmds + 16 > firstSectionOffset) {\n\t\t\t\tthrow new SEAError(\n\t\t\t\t\t'INJECT',\n\t\t\t\t\t`Not enough header space for new Mach-O load command ` +\n\t\t\t\t\t\t`(need offset ${String(headerSize + newSizeofcmds + 16)}, first section at ${String(firstSectionOffset)})`,\n\t\t\t\t\t{\n\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t\tfirstSectionOffset,\n\t\t\t\t\t\trequiredOffset: headerSize + newSizeofcmds + 16,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// --- Mutate in place: shift __LINKEDIT and every linkedit-relative\n\t\t\t// offset field in the surviving commands, using the ORIGINAL Loff as\n\t\t\t// the \"does this offset point into __LINKEDIT\" threshold. ---\n\t\t\tfor (let i = 0; i < commands.length; i++) {\n\t\t\t\tconst cmd = commands[i]\n\t\t\t\tif (cmd === undefined || existingSegmentIndices.includes(i)) continue\n\n\t\t\t\tif (cmd.type === MACHO_LC_SEGMENT_64) {\n\t\t\t\t\tconst segName = this.#stripTrailingNulls(\n\t\t\t\t\t\tbuf.subarray(cmd.offset + 8, cmd.offset + 24).toString('ascii'),\n\t\t\t\t\t)\n\t\t\t\t\tif (segName === '__LINKEDIT') {\n\t\t\t\t\t\tconst nsects = buf.readUInt32LE(cmd.offset + 64)\n\t\t\t\t\t\tif (nsects > 0) {\n\t\t\t\t\t\t\tthrow new SEAError('INJECT', '__LINKEDIT segment with sections is not supported', {\n\t\t\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbuf.writeBigUInt64LE(Lvm + BigInt(shift), cmd.offset + 24) // vmaddr\n\t\t\t\t\t\tbuf.writeBigUInt64LE(BigInt(Loff + shift), cmd.offset + 40) // fileoff\n\t\t\t\t\t\t// filesize/vmsize unchanged — __LINKEDIT keeps its size, only moves.\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tthis.#shiftMachoLinkeditOffsets(buf, cmd, Loff, shift)\n\t\t\t}\n\n\t\t\tbuf.writeUInt32LE(newNcmds, 16)\n\t\t\tbuf.writeUInt32LE(newSizeofcmds, 20)\n\n\t\t\t// --- Build the new NODE_SEA segment command: it takes __LINKEDIT's\n\t\t\t// OLD slot (before __LINKEDIT), inserted before __LINKEDIT so\n\t\t\t// codesign's appended signature at EOF (inside __LINKEDIT) survives. ---\n\t\t\tconst cmd = Buffer.alloc(newCmdSize)\n\t\t\tcmd.writeUInt32LE(MACHO_LC_SEGMENT_64, 0)\n\t\t\tcmd.writeUInt32LE(newCmdSize, 4)\n\t\t\tcmd.write(segmentName, 8, 16, 'ascii')\n\t\t\tcmd.writeBigUInt64LE(Lvm, 24) // vmaddr\n\t\t\tcmd.writeBigUInt64LE(BigInt(shift), 32) // vmsize\n\t\t\tcmd.writeBigUInt64LE(BigInt(Loff), 40) // fileoff\n\t\t\tcmd.writeBigUInt64LE(BigInt(shift), 48) // filesize\n\t\t\tcmd.writeUInt32LE(1, 56) // maxprot: VM_PROT_READ\n\t\t\tcmd.writeUInt32LE(1, 60) // initprot: VM_PROT_READ\n\t\t\tcmd.writeUInt32LE(1, 64) // nsects\n\t\t\tcmd.writeUInt32LE(0, 68) // flags\n\n\t\t\tconst sectOff = 72\n\t\t\tcmd.write(sectionName, sectOff, 16, 'ascii')\n\t\t\tcmd.write(segmentName, sectOff + 16, 16, 'ascii')\n\t\t\tcmd.writeBigUInt64LE(Lvm, sectOff + 32) // addr\n\t\t\tcmd.writeBigUInt64LE(BigInt(blobSize), sectOff + 40) // size\n\t\t\tcmd.writeUInt32LE(Loff, sectOff + 48) // offset\n\t\t\tcmd.writeUInt32LE(0, sectOff + 52) // align\n\t\t\tcmd.writeUInt32LE(0, sectOff + 56) // reloff\n\t\t\tcmd.writeUInt32LE(0, sectOff + 60) // nreloc\n\t\t\tcmd.writeUInt32LE(0, sectOff + 64) // flags\n\t\t\tcmd.writeUInt32LE(0, sectOff + 68) // reserved1\n\t\t\tcmd.writeUInt32LE(0, sectOff + 72) // reserved2\n\t\t\tcmd.writeUInt32LE(0, sectOff + 76) // reserved3\n\n\t\t\tconst pieces: Buffer[] = []\n\t\t\tfor (let i = 0; i < commands.length; i++) {\n\t\t\t\tif (existingSegmentIndices.includes(i)) continue\n\t\t\t\tconst c = commands[i]\n\t\t\t\tif (c === undefined) continue\n\t\t\t\t// Insert the new NODE_SEA segment command immediately before\n\t\t\t\t// __LINKEDIT so segment commands stay in ascending vmaddr order and\n\t\t\t\t// __LINKEDIT remains the textually-last segment, as dyld/codesign\n\t\t\t\t// require.\n\t\t\t\tif (i === linkeditIndex) {\n\t\t\t\t\tpieces.push(cmd)\n\t\t\t\t}\n\t\t\t\tpieces.push(Buffer.from(buf.subarray(c.offset, c.offset + c.size)))\n\t\t\t}\n\t\t\tconst newLoadCmdsBuf = Buffer.concat(pieces)\n\t\t\tif (newLoadCmdsBuf.length !== newSizeofcmds) {\n\t\t\t\tthrow new SEAError('INJECT', 'Internal Mach-O load command size mismatch', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// --- Stream-write to a sibling temp, then atomically rename over\n\t\t\t// exePath: header+LCs, unchanged body up to Loff (streamed from\n\t\t\t// srcFd), the blob (streamed from its own fd, padded to `shift`),\n\t\t\t// then the relocated __LINKEDIT (streamed from srcFd). The body\n\t\t\t// range starts at the NEW command-region end (not the old\n\t\t\t// sizeofcmds) — the ceiling check above guarantees\n\t\t\t// [headerSize + sizeofcmds, headerSize + newSizeofcmds) lies entirely\n\t\t\t// in inter-command padding, so discarding those bytes absorbs the\n\t\t\t// growth and keeps every recorded section/segment offset (computed\n\t\t\t// assuming no shift) correct. Starting from the OLD sizeofcmds\n\t\t\t// instead would shift the entire __TEXT/__DATA body forward by the\n\t\t\t// growth delta, corrupting every offset already written into the new\n\t\t\t// load commands. ---\n\t\t\tconst mode = fstatSync(srcFd).mode\n\t\t\tinjTemp = join(dirname(exePath), `.inject-${randomUUID()}.tmp`)\n\t\t\tdestFd = openSync(injTemp, 'w', mode)\n\n\t\t\twriteSync(destFd, buf.subarray(0, headerSize))\n\t\t\twriteSync(destFd, newLoadCmdsBuf)\n\t\t\tcopyRange(srcFd, destFd, headerSize + newSizeofcmds, Loff - (headerSize + newSizeofcmds))\n\n\t\t\tblobFd = openSync(this.#options.blob, 'r')\n\t\t\tcopyRange(blobFd, destFd, 0, blobSize)\n\t\t\tcloseSync(blobFd)\n\t\t\tblobFd = undefined\n\n\t\t\tconst blobPadding = shift - blobSize\n\t\t\tif (blobPadding > 0) {\n\t\t\t\twriteSync(destFd, Buffer.alloc(blobPadding))\n\t\t\t}\n\t\t\tcopyRange(srcFd, destFd, Loff, Lsize)\n\n\t\t\tcloseSync(destFd)\n\t\t\tdestFd = undefined\n\n\t\t\t// Windows cannot rename a replacement over a file that still has an open\n\t\t\t// handle; release the source read handle before finalizeExecutable renames.\n\t\t\tcloseSync(srcFd)\n\t\t\tsrcFd = undefined\n\n\t\t\t// openSync's mode is masked by umask, which can silently drop the\n\t\t\t// exec bit; chmod is not masked, so it reproduces the host binary's\n\t\t\t// permissions exactly before the temp replaces the original.\n\t\t\tchmodSync(injTemp, mode & 0o7777)\n\t\t\tfinalizeExecutable(injTemp, exePath)\n\t\t\tinjTemp = undefined\n\n\t\t\t// Build-time readback: verify the section by its section table entry,\n\t\t\t// consistent with what was just written.\n\t\t\tthis.#verifyMachoSection(exePath, segmentName, sectionName, Loff, blobSize)\n\t\t} finally {\n\t\t\t// Guard each close so a throw from one does not skip the rest of the\n\t\t\t// cleanup (a leaked fd or a stray temp masking the original error).\n\t\t\tfor (const fd of [blobFd, destFd, srcFd]) {\n\t\t\t\tif (fd !== undefined) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcloseSync(fd)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// fd may already be closed or invalid; cleanup must not throw.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (injTemp !== undefined) rmSync(injTemp, { force: true })\n\t\t}\n\t}\n\n\t// --- Mach-O: shift every linkedit-relative offset field in a load command\n\t// that points at or past `threshold` by `shift` bytes ---\n\n\t#shiftMachoLinkeditOffsets(\n\t\tbuf: Buffer,\n\t\tcmd: { type: number; offset: number },\n\t\tthreshold: number,\n\t\tshift: number,\n\t): void {\n\t\tlet offsets: readonly number[]\n\t\tswitch (cmd.type) {\n\t\t\tcase 0x2: // LC_SYMTAB: symoff@+8, stroff@+16\n\t\t\t\toffsets = [8, 16]\n\t\t\t\tbreak\n\t\t\tcase 0xb: // LC_DYSYMTAB: tocoff/modtaboff/extrefsymoff/indirectsymoff/extreloff/locreloff\n\t\t\t\toffsets = [32, 40, 48, 56, 64, 72]\n\t\t\t\tbreak\n\t\t\tcase 0x22: // LC_DYLD_INFO\n\t\t\tcase 0x80000022: // LC_DYLD_INFO_ONLY\n\t\t\t\t// rebase_off, bind_off, weak_bind_off, lazy_bind_off, export_off\n\t\t\t\toffsets = [8, 16, 24, 32, 40]\n\t\t\t\tbreak\n\t\t\tcase 0x1d: // LC_CODE_SIGNATURE\n\t\t\tcase 0x1e: // LC_SEGMENT_SPLIT_INFO\n\t\t\tcase 0x26: // LC_FUNCTION_STARTS\n\t\t\tcase 0x29: // LC_DATA_IN_CODE\n\t\t\tcase 0x80000033: // LC_DYLD_EXPORTS_TRIE\n\t\t\tcase 0x80000034: // LC_DYLD_CHAINED_FIXUPS\n\t\t\t\toffsets = [8] // dataoff (linkedit_data_command)\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\t// LC_TWOLEVEL_HINTS (0x16, offset@+8) and LC_ATOM_INFO also\n\t\t\t\t// point into __LINKEDIT but are intentionally not handled here\n\t\t\t\t// because they do not appear in Node.js executables.\n\t\t\t\treturn\n\t\t}\n\t\tfor (const offset of offsets) {\n\t\t\tconst fieldOffset = cmd.offset + offset\n\t\t\tif (fieldOffset + 4 > buf.length) continue\n\t\t\tconst value = buf.readUInt32LE(fieldOffset)\n\t\t\tif (value >= threshold && value > 0) {\n\t\t\t\tbuf.writeUInt32LE(value + shift, fieldOffset)\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- Mach-O: build-time readback — confirm the section table entry\n\t// matches what was written, the same shape the runtime's getsectdata\n\t// lookup relies on ---\n\n\t#verifyMachoSection(\n\t\texePath: string,\n\t\tsegmentName: string,\n\t\tsectionName: string,\n\t\texpectedOffset: number,\n\t\texpectedSize: number,\n\t): void {\n\t\tconst fd = openSync(exePath, 'r')\n\t\ttry {\n\t\t\tconst header = Buffer.alloc(32)\n\t\t\treadSync(fd, header, 0, 32, 0)\n\t\t\tconst ncmds = header.readUInt32LE(16)\n\n\t\t\tlet offset = 32\n\t\t\tfor (let i = 0; i < ncmds; i++) {\n\t\t\t\tconst cmdHead = Buffer.alloc(8)\n\t\t\t\treadSync(fd, cmdHead, 0, 8, offset)\n\t\t\t\tconst cmdType = cmdHead.readUInt32LE(0)\n\t\t\t\tconst cmdSize = cmdHead.readUInt32LE(4)\n\n\t\t\t\tif (cmdType === MACHO_LC_SEGMENT_64 && cmdSize >= 72) {\n\t\t\t\t\tconst segBuf = Buffer.alloc(cmdSize)\n\t\t\t\t\treadSync(fd, segBuf, 0, cmdSize, offset)\n\t\t\t\t\tconst segName = this.#stripTrailingNulls(segBuf.subarray(8, 24).toString('ascii'))\n\t\t\t\t\tif (segName === segmentName) {\n\t\t\t\t\t\tconst nsects = segBuf.readUInt32LE(64)\n\t\t\t\t\t\tfor (let s = 0; s < nsects; s++) {\n\t\t\t\t\t\t\tconst sectOff = 72 + s * 80\n\t\t\t\t\t\t\tif (sectOff + 80 > segBuf.length) continue\n\t\t\t\t\t\t\tconst secName = this.#stripTrailingNulls(\n\t\t\t\t\t\t\t\tsegBuf.subarray(sectOff, sectOff + 16).toString('ascii'),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tif (secName !== sectionName) continue\n\t\t\t\t\t\t\tconst secSize = Number(segBuf.readBigUInt64LE(sectOff + 40))\n\t\t\t\t\t\t\tconst secOffset = segBuf.readUInt32LE(sectOff + 48)\n\t\t\t\t\t\t\tif (secOffset === expectedOffset && secSize === expectedSize) return\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\toffset += cmdSize\n\t\t\t}\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\n\t\tthrow new SEAError('INJECT', 'Injected Mach-O section not found after write', {\n\t\t\texecutable: exePath,\n\t\t\tsegmentName,\n\t\t\tsectionName,\n\t\t})\n\t}\n\n\t// =========================================================================\n\t// Binary I/O Helpers\n\t// =========================================================================\n\n\t#readU16(fd: number, offset: number): number {\n\t\tconst b = Buffer.alloc(2)\n\t\treadSync(fd, b, 0, 2, offset)\n\t\treturn b.readUInt16LE(0)\n\t}\n\n\t#readU32(fd: number, offset: number): number {\n\t\tconst b = Buffer.alloc(4)\n\t\treadSync(fd, b, 0, 4, offset)\n\t\treturn b.readUInt32LE(0)\n\t}\n\n\t#readU64(fd: number, offset: number): bigint {\n\t\tconst b = Buffer.alloc(8)\n\t\treadSync(fd, b, 0, 8, offset)\n\t\treturn b.readBigUInt64LE(0)\n\t}\n\n\t#writeU16(fd: number, offset: number, value: number): void {\n\t\tconst b = Buffer.alloc(2)\n\t\tb.writeUInt16LE(value, 0)\n\t\twriteSync(fd, b, 0, 2, offset)\n\t}\n\n\t#writeU32(fd: number, offset: number, value: number): void {\n\t\tconst b = Buffer.alloc(4)\n\t\tb.writeUInt32LE(value >>> 0, 0)\n\t\twriteSync(fd, b, 0, 4, offset)\n\t}\n\n\t#writeU64(fd: number, offset: number, value: bigint): void {\n\t\tconst b = Buffer.alloc(8)\n\t\tb.writeBigUInt64LE(value, 0)\n\t\twriteSync(fd, b, 0, 8, offset)\n\t}\n\n\t#align(value: number, alignment: number): number {\n\t\tconst remainder = value % alignment\n\t\treturn remainder === 0 ? value : value + (alignment - remainder)\n\t}\n\n\t// --- PE: validate section/file alignment before any #align call uses it\n\t// as a divisor — a malformed 0 value would otherwise silently corrupt\n\t// output via NaN -> #writeU32 coercion. ---\n\n\t#ensureValidPEAlignment(sectionAlignment: number, fileAlignment: number): void {\n\t\tif (!isPowerOfTwo(sectionAlignment) || !isPowerOfTwo(fileAlignment)) {\n\t\t\tthrow new SEAError('FORMAT', 'PE section/file alignment must be a nonzero power of two', {\n\t\t\t\texecutable: this.#options.executable,\n\t\t\t\tsectionAlignment,\n\t\t\t\tfileAlignment,\n\t\t\t})\n\t\t}\n\t\tif (sectionAlignment < fileAlignment) {\n\t\t\tthrow new SEAError('FORMAT', 'PE sectionAlignment must be >= fileAlignment', {\n\t\t\t\texecutable: this.#options.executable,\n\t\t\t\tsectionAlignment,\n\t\t\t\tfileAlignment,\n\t\t\t})\n\t\t}\n\t}\n\n\t/** Append sourceFile to targetFile by streaming in 4 MB chunks */\n\t#appendFile(targetPath: string, sourcePath: string): void {\n\t\tconst chunkSize = 4 * 1024 * 1024\n\t\tconst srcFd = openSync(sourcePath, 'r')\n\t\ttry {\n\t\t\tconst srcSize = statSync(sourcePath).size\n\t\t\tconst chunk = Buffer.alloc(Math.min(chunkSize, srcSize))\n\t\t\tlet offset = 0\n\t\t\twhile (offset < srcSize) {\n\t\t\t\tconst toRead = Math.min(chunkSize, srcSize - offset)\n\t\t\t\tconst bytesRead = readSync(srcFd, chunk, 0, toRead, offset)\n\t\t\t\tif (bytesRead === 0) break\n\t\t\t\tappendFileSync(targetPath, chunk.subarray(0, bytesRead))\n\t\t\t\toffset += bytesRead\n\t\t\t}\n\t\t} finally {\n\t\t\tcloseSync(srcFd)\n\t\t}\n\t}\n\n\t// Strip trailing null characters from a string (used for binary name fields)\n\t#stripTrailingNulls(value: string): string {\n\t\tconst idx = value.indexOf(String.fromCharCode(0))\n\t\treturn idx === -1 ? value : value.slice(0, idx)\n\t}\n}\n","/**\n * SEA\n *\n * Build orchestrator for Node.js Single Executable Applications.\n * Compresses assets, generates the SEA blob, copies the Node binary,\n * injects the blob, and handles platform-specific signing.\n */\n\nimport type {\n\tSEACompressionManifest,\n\tSEAEventMap,\n\tSEAInterface,\n\tSEAOptions,\n\tSEAResult,\n\tSEAStatus,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport {\n\tchmodSync,\n\tcopyFileSync,\n\texistsSync,\n\tmkdirSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tSEA_BLOB_RESOURCE,\n\tSEA_SENTINEL_FUSE,\n\tWINDOWS_SUBSYSTEM_CONSOLE,\n\tWINDOWS_SUBSYSTEM_GUI,\n} from '../constants.js'\nimport {\n\tcompressDirectory,\n\tcreateBlobConfig,\n\tcreateSignCommand,\n\tensureContained,\n\tensureExists,\n\tensureSafeKey,\n\tensureSafeName,\n\tfinalizeExecutable,\n\tisCompressible,\n\tisPEExecutable,\n\tisPlatformSupported,\n\tpatchPESubsystem,\n\tplatformConfig,\n\trunShell,\n\tstripPESignature,\n\twalkDirectory,\n} from '../helpers.js'\nimport { SEAError } from '../errors.js'\nimport { Injector } from '../injectors/Injector.js'\n\n// === SEA\n\nexport class SEA implements SEAInterface {\n\t#status: SEAStatus = 'idle'\n\t#destroyed = false\n\treadonly #options: SEAOptions\n\treadonly #emitter: Emitter<SEAEventMap>\n\n\tconstructor(options: SEAOptions) {\n\t\tthis.#options = options\n\t\tthis.#emitter = new Emitter({\n\t\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<SEAEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget status(): SEAStatus {\n\t\treturn this.#status\n\t}\n\n\tasync execute(): Promise<SEAResult> {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new SEAError('STATE', 'SEA is destroyed')\n\t\t}\n\t\tif (this.#status === 'active') {\n\t\t\tthrow new SEAError('STATE', 'SEA build already in progress')\n\t\t}\n\n\t\tconst platform = platformConfig()\n\t\tif (platform === undefined || !isPlatformSupported()) {\n\t\t\tconst error = new SEAError('PLATFORM', `Unsupported platform: ${process.platform}`, {\n\t\t\t\tplatform: process.platform,\n\t\t\t})\n\t\t\tthis.#status = 'error'\n\t\t\tthis.#emitter.emit('error', error)\n\t\t\tthrow error\n\t\t}\n\n\t\tthis.#status = 'active'\n\t\tconst start = Date.now()\n\t\tconst root = this.#options.root ?? process.cwd()\n\n\t\ttry {\n\t\t\tthis.#check()\n\t\t\tthis.#validate(root)\n\n\t\t\tthis.#check()\n\t\t\tconst compression = this.#compress(root)\n\n\t\t\tthis.#check()\n\t\t\tconst blob = this.#blob(root)\n\n\t\t\tthis.#check()\n\t\t\tconst assembled = this.#assemble(root, blob)\n\t\t\tconst size = statSync(assembled.executable).size\n\t\t\tconst duration = Date.now() - start\n\n\t\t\tconst result: SEAResult = {\n\t\t\t\texecutable: assembled.executable,\n\t\t\t\tplatform: process.platform,\n\t\t\t\tsize,\n\t\t\t\tduration,\n\t\t\t\tsigned: assembled.signed,\n\t\t\t\tstripped: assembled.stripped,\n\t\t\t\t...(compression === undefined ? {} : { compression }),\n\t\t\t\t...(assembled.terminal === undefined ? {} : { terminal: assembled.terminal }),\n\t\t\t}\n\n\t\t\tthis.#status = 'done'\n\t\t\tthis.#emitter.emit('complete', result)\n\t\t\treturn result\n\t\t} catch (thrown: unknown) {\n\t\t\tthis.#status = 'error'\n\t\t\tthis.#emitter.emit('error', thrown)\n\t\t\tthrow thrown\n\t\t}\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// Throws SEAError('ABORT', ...) when the caller's signal has fired.\n\t#check(): void {\n\t\tif (this.#options.signal?.aborted === true) {\n\t\t\tthrow new SEAError('ABORT', 'SEA build aborted')\n\t\t}\n\t}\n\n\t// Validates every asset key/path and compression path before any work runs.\n\t#validate(root: string): void {\n\t\tconst base = resolve(root)\n\n\t\tensureSafeName(this.#options.name)\n\n\t\tfor (const [key, path] of Object.entries(this.#options.assets ?? {})) {\n\t\t\tensureSafeKey(key)\n\t\t\tensureSafeKey(path)\n\t\t\tensureContained(base, path)\n\t\t}\n\n\t\tfor (const path of this.#options.compression?.paths ?? []) {\n\t\t\tensureSafeKey(path)\n\t\t\t// A compression path that does not exist yet is skipped by #compress\n\t\t\t// (existsSync gate below), so validation only enforces containment\n\t\t\t// for paths that actually exist — keep the two stages in agreement.\n\t\t\tif (existsSync(resolve(base, path))) {\n\t\t\t\tensureContained(base, path)\n\t\t\t}\n\t\t}\n\n\t\tconst sign = this.#options.windows?.sign\n\t\tif (sign !== undefined) {\n\t\t\t// Trigger the file-XOR-thumbprint and timestamp-scheme validation\n\t\t\t// fail-fast, before any build work runs. The placeholder target is\n\t\t\t// never executed here — createSignCommand is a pure argv builder.\n\t\t\tcreateSignCommand(sign, 'placeholder')\n\n\t\t\tif (sign.file !== undefined) {\n\t\t\t\tensureExists(resolve(base, sign.file), 'Certificate file not found', 'SIGN')\n\t\t\t}\n\t\t}\n\t}\n\n\t#compress(root: string): SEACompressionManifest | undefined {\n\t\tconst compression = this.#options.compression\n\t\tif (compression === undefined || compression.paths.length === 0) {\n\t\t\tthis.#emitter.emit('compress', undefined)\n\t\t\treturn undefined\n\t\t}\n\n\t\tconst directories: string[] = []\n\t\tlet total = 0\n\t\tfor (const path of compression.paths) {\n\t\t\tconst candidate = resolve(root, path)\n\t\t\tif (!existsSync(candidate)) continue\n\t\t\tthis.#check()\n\t\t\tconst directory = ensureContained(root, path)\n\t\t\tdirectories.push(directory)\n\t\t\ttotal += walkDirectory(directory).filter(isCompressible).length\n\t\t}\n\n\t\tconst assets: SEACompressionManifest['assets'][number][] = []\n\t\tlet original = 0\n\t\tlet compressed = 0\n\t\tlet current = 0\n\n\t\tfor (const directory of directories) {\n\t\t\tthis.#check()\n\t\t\tconst manifest = compressDirectory(directory, compression, (result) => {\n\t\t\t\tcurrent += 1\n\t\t\t\tthis.#emitter.emit('progress', { path: result.input, current, total })\n\t\t\t})\n\t\t\tassets.push(...manifest.assets)\n\t\t\toriginal += manifest.total.original\n\t\t\tcompressed += manifest.total.compressed\n\t\t}\n\n\t\tconst manifest: SEACompressionManifest = {\n\t\t\tassets,\n\t\t\ttotal: {\n\t\t\t\toriginal,\n\t\t\t\tcompressed,\n\t\t\t\tratio: original > 0 ? compressed / original : 0,\n\t\t\t},\n\t\t}\n\n\t\tthis.#emitter.emit('compress', manifest)\n\t\treturn manifest\n\t}\n\n\t#blob(root: string): string {\n\t\tconst entry = resolve(root, this.#options.entry.path)\n\t\tensureExists(entry, `Entry not found: ${this.#options.entry.path}`, 'ENTRY')\n\n\t\tconst output = resolve(root, this.#options.output)\n\t\tmkdirSync(output, { recursive: true })\n\n\t\tconst configPath = join(output, 'sea-config.json')\n\t\tconst blob = join(output, 'sea-prep.blob')\n\t\tconst config = createBlobConfig(\n\t\t\t{\n\t\t\t\tpath: entry,\n\t\t\t\t...(this.#options.entry.format === undefined ? {} : { format: this.#options.entry.format }),\n\t\t\t},\n\t\t\tblob,\n\t\t\tthis.#assets(root),\n\t\t\tthis.#options.blob,\n\t\t)\n\n\t\twriteFileSync(configPath, JSON.stringify(config, null, 2))\n\t\trunShell([process.execPath, '--experimental-sea-config', configPath], {\n\t\t\tcwd: output,\n\t\t\t...(this.#options.signal === undefined ? {} : { signal: this.#options.signal }),\n\t\t})\n\n\t\tif (!existsSync(blob)) {\n\t\t\tthrow new SEAError('BLOB', 'SEA blob generation failed — blob not found', { blob })\n\t\t}\n\n\t\tthis.#emitter.emit('blob', blob)\n\t\treturn blob\n\t}\n\n\t// Assembles the final executable in a same-directory temp file, mutating it\n\t// through strip -> inject -> sign -> verify, then atomically finalizing it\n\t// into place. Any failure removes the temp file and leaves the prior output\n\t// (if any) untouched.\n\t#assemble(\n\t\troot: string,\n\t\tblob: string,\n\t): { executable: string; signed: boolean; stripped: boolean; terminal?: boolean } {\n\t\tconst platform = platformConfig()\n\t\tif (platform === undefined) {\n\t\t\tthrow new SEAError('PLATFORM', `Unsupported platform: ${process.platform}`, {\n\t\t\t\tplatform: process.platform,\n\t\t\t})\n\t\t}\n\n\t\tconst output = resolve(root, this.#options.output)\n\t\tconst ext = process.platform === 'win32' ? '.exe' : ''\n\t\tconst name = process.platform === 'win32' ? `${this.#options.name}.exe` : this.#options.name\n\t\tconst finalOutput = join(output, name)\n\t\tconst temp = join(output, `.${this.#options.name}-${randomUUID()}.tmp${ext}`)\n\t\tconst shell = this.#options.signal === undefined ? {} : { signal: this.#options.signal }\n\n\t\tlet signed = false\n\t\tlet stripped = false\n\t\tlet terminal: boolean | undefined\n\n\t\ttry {\n\t\t\tif (process.platform === 'darwin') {\n\t\t\t\tthis.#check()\n\t\t\t\tcopyFileSync(process.execPath, temp)\n\t\t\t\tchmodSync(temp, 0o755)\n\n\t\t\t\tif (platform.remove !== undefined) {\n\t\t\t\t\tthis.#check()\n\t\t\t\t\ttry {\n\t\t\t\t\t\trunShell([...platform.remove, temp], shell)\n\t\t\t\t\t} catch (thrown: unknown) {\n\t\t\t\t\t\tthrow new SEAError('SIGN', 'Failed to strip existing signature', {\n\t\t\t\t\t\t\tcause: thrown instanceof Error ? thrown.message : String(thrown),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tstripped = true\n\t\t\t\t}\n\n\t\t\t\tthis.#check()\n\t\t\t\tconst injector = new Injector({\n\t\t\t\t\texecutable: temp,\n\t\t\t\t\tresource: SEA_BLOB_RESOURCE,\n\t\t\t\t\tblob,\n\t\t\t\t\tfuse: SEA_SENTINEL_FUSE,\n\t\t\t\t\tmacho: { segment: 'NODE_SEA' },\n\t\t\t\t})\n\t\t\t\tinjector.inject()\n\n\t\t\t\tif (platform.sign !== undefined) {\n\t\t\t\t\tthis.#check()\n\t\t\t\t\ttry {\n\t\t\t\t\t\trunShell([...platform.sign, temp], shell)\n\t\t\t\t\t} catch (thrown: unknown) {\n\t\t\t\t\t\tthrow new SEAError('SIGN', 'Failed to sign executable', {\n\t\t\t\t\t\t\tcause: thrown instanceof Error ? thrown.message : String(thrown),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tif (platform.verify !== undefined) {\n\t\t\t\t\t\tthis.#check()\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trunShell([...platform.verify, temp], shell)\n\t\t\t\t\t\t} catch (thrown: unknown) {\n\t\t\t\t\t\t\tthrow new SEAError('SIGN', 'Signature verification failed', {\n\t\t\t\t\t\t\t\tcause: thrown instanceof Error ? thrown.message : String(thrown),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tsigned = true\n\t\t\t\t}\n\t\t\t} else if (process.platform === 'win32') {\n\t\t\t\tthis.#check()\n\t\t\t\tcopyFileSync(process.execPath, temp)\n\n\t\t\t\tstripPESignature(temp)\n\t\t\t\tstripped = true\n\n\t\t\t\tif (isPEExecutable(temp)) {\n\t\t\t\t\tterminal = this.#options.windows?.terminal !== false\n\t\t\t\t\tconst value = terminal ? WINDOWS_SUBSYSTEM_CONSOLE : WINDOWS_SUBSYSTEM_GUI\n\t\t\t\t\tpatchPESubsystem(temp, value)\n\t\t\t\t}\n\n\t\t\t\tthis.#check()\n\t\t\t\tconst injector = new Injector({\n\t\t\t\t\texecutable: temp,\n\t\t\t\t\tresource: SEA_BLOB_RESOURCE,\n\t\t\t\t\tblob,\n\t\t\t\t\tfuse: SEA_SENTINEL_FUSE,\n\t\t\t\t})\n\t\t\t\tinjector.inject()\n\n\t\t\t\tconst sign = this.#options.windows?.sign\n\t\t\t\tif (sign !== undefined) {\n\t\t\t\t\tthis.#check()\n\t\t\t\t\t// Resolve the certificate file against the SAME base #validate\n\t\t\t\t\t// checked existence against — createSignCommand's argv is passed\n\t\t\t\t\t// through runShell without a cwd, so a relative sign.file would\n\t\t\t\t\t// otherwise resolve against process.cwd(), a different file.\n\t\t\t\t\tconst signInput =\n\t\t\t\t\t\tsign.file !== undefined ? { ...sign, file: resolve(root, sign.file) } : sign\n\t\t\t\t\tconst signArgs = createSignCommand(signInput, temp)\n\t\t\t\t\ttry {\n\t\t\t\t\t\trunShell(signArgs, shell)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new SEAError('SIGN', 'Windows signing failed', { executable: temp })\n\t\t\t\t\t}\n\t\t\t\t\tsigned = true\n\n\t\t\t\t\tif (platform.verify !== undefined) {\n\t\t\t\t\t\tthis.#check()\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trunShell([...platform.verify, temp], shell)\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tthrow new SEAError('SIGN', 'Signature verification failed', { executable: temp })\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.#check()\n\t\t\t\tcopyFileSync(process.execPath, temp)\n\t\t\t\tchmodSync(temp, 0o755)\n\n\t\t\t\tthis.#check()\n\t\t\t\tconst injector = new Injector({\n\t\t\t\t\texecutable: temp,\n\t\t\t\t\tresource: SEA_BLOB_RESOURCE,\n\t\t\t\t\tblob,\n\t\t\t\t\tfuse: SEA_SENTINEL_FUSE,\n\t\t\t\t})\n\t\t\t\tinjector.inject()\n\t\t\t}\n\n\t\t\tfinalizeExecutable(temp, finalOutput)\n\t\t} catch (thrown: unknown) {\n\t\t\trmSync(temp, { force: true })\n\t\t\tthrow thrown\n\t\t}\n\n\t\tthis.#emitter.emit('assemble', finalOutput)\n\t\treturn {\n\t\t\texecutable: finalOutput,\n\t\t\tsigned,\n\t\t\tstripped,\n\t\t\t...(terminal === undefined ? {} : { terminal }),\n\t\t}\n\t}\n\n\t#assets(root: string): Readonly<Record<string, string>> {\n\t\tconst assets: Record<string, string> = {}\n\t\tfor (const [name, path] of Object.entries(this.#options.assets ?? {})) {\n\t\t\tassets[name] = ensureContained(root, path)\n\t\t}\n\t\treturn assets\n\t}\n}\n","/**\n * Asset\n *\n * A single named asset wrapping its key, content buffer, and compression flag.\n * Infers compression from the `.br` extension when not explicitly provided.\n */\n\nimport type { AssetInput, AssetInterface } from '../types.js'\nimport { BROTLI_EXTENSION } from '../constants.js'\n\n// === Asset\n\nexport class Asset implements AssetInterface {\n\treadonly key: string\n\treadonly content: ArrayBuffer\n\treadonly compressed: boolean\n\n\tconstructor(input: AssetInput) {\n\t\tthis.key = input.key\n\t\tthis.content = input.content\n\t\tthis.compressed = input.compressed ?? input.key.endsWith(BROTLI_EXTENSION)\n\t}\n}\n","/**\n * AssetManager\n *\n * Named asset collection with SEA and disk loading.\n * In SEA mode, embedded assets are loaded automatically at construction.\n * In development, `load()` reads client assets from disk.\n */\n\nimport { readFileSync, existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { getAssetKeys, getRawAsset, isSea } from 'node:sea'\nimport type {\n\tAssetInput,\n\tAssetInterface,\n\tAssetManagerEventMap,\n\tAssetManagerInterface,\n\tAssetManagerOptions,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArrayBuffer } from '@orkestrel/contract'\nimport { CLIENT_ASSET_KEY_BR, CLIENT_ASSET_KEY_RAW } from '../constants.js'\nimport { Asset } from './Asset.js'\n\n// === AssetManager\n\nexport class AssetManager implements AssetManagerInterface {\n\treadonly #emitter: Emitter<AssetManagerEventMap>\n\t#assets = new Map<string, AssetInterface>()\n\t#keys: string[] = []\n\treadonly #root: string\n\n\tconstructor(options?: AssetManagerOptions) {\n\t\tthis.#root = options?.root ?? process.cwd()\n\t\tthis.#emitter = new Emitter({\n\t\t\t...(options?.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options?.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t\tthis.#loadSea()\n\t}\n\n\tget emitter(): EmitterInterface<AssetManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#assets.size\n\t}\n\n\tasset(key: string): AssetInterface | undefined {\n\t\treturn this.#assets.get(key)\n\t}\n\n\tassets(): readonly AssetInterface[] {\n\t\treturn [...this.#assets.values()]\n\t}\n\n\tkeys(): readonly string[] {\n\t\treturn [...this.#keys]\n\t}\n\n\tregister(input: AssetInput | AssetInput[]): void {\n\t\tconst items = Array.isArray(input) ? input : [input]\n\t\tfor (const item of items) {\n\t\t\tconst asset: AssetInterface = new Asset(item)\n\t\t\tthis.#add(asset)\n\t\t\tthis.#emitter.emit('register', asset)\n\t\t}\n\t}\n\n\tload(): void {\n\t\tif (isSea()) return\n\n\t\tconst devPath = resolve(this.#root, 'client', CLIENT_ASSET_KEY_RAW)\n\t\tconst builtBrPath = resolve(this.#root, 'dist', 'client', CLIENT_ASSET_KEY_BR)\n\n\t\tif (existsSync(devPath)) {\n\t\t\ttry {\n\t\t\t\tconst raw = readFileSync(devPath, 'utf-8')\n\t\t\t\tconst encoder = new TextEncoder()\n\t\t\t\tconst bytes = encoder.encode(raw)\n\t\t\t\tconst content = bytes.buffer\n\t\t\t\tif (!isArrayBuffer(content)) {\n\t\t\t\t\tthrow new Error('Failed to encode client asset')\n\t\t\t\t}\n\t\t\t\tthis.register({ key: CLIENT_ASSET_KEY_RAW, content, compressed: false })\n\t\t\t\tthis.#emitter.emit('load', [CLIENT_ASSET_KEY_RAW])\n\t\t\t} catch (thrown: unknown) {\n\t\t\t\tthis.#emitter.emit('error', thrown)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif (existsSync(builtBrPath)) {\n\t\t\ttry {\n\t\t\t\tconst buffer = readFileSync(builtBrPath)\n\t\t\t\tconst bufferData = buffer.buffer\n\t\t\t\tif (!isArrayBuffer(bufferData)) {\n\t\t\t\t\tthrow new Error('Failed to read client asset')\n\t\t\t\t}\n\t\t\t\tconst content = bufferData.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)\n\t\t\t\tthis.register({ key: CLIENT_ASSET_KEY_BR, content, compressed: true })\n\t\t\t\tthis.#emitter.emit('load', [CLIENT_ASSET_KEY_BR])\n\t\t\t} catch (thrown: unknown) {\n\t\t\t\tthis.#emitter.emit('error', thrown)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tthis.#emitter.emit('error', new Error('Client assets not found'))\n\t}\n\n\tclear(): void {\n\t\tthis.#assets.clear()\n\t\tthis.#keys = []\n\t\tthis.#emitter.emit('clear')\n\t}\n\n\tdestroy(): void {\n\t\tthis.clear()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// === Private\n\n\t#add(asset: AssetInterface): void {\n\t\tthis.#assets.set(asset.key, asset)\n\t\tif (!this.#keys.includes(asset.key)) {\n\t\t\tthis.#keys.push(asset.key)\n\t\t}\n\t}\n\n\t#loadSea(): void {\n\t\tif (isSea()) {\n\t\t\tconst assetKeys: readonly string[] = getAssetKeys()\n\t\t\tconst registered: string[] = []\n\t\t\tfor (const key of assetKeys) {\n\t\t\t\tconst content: ArrayBuffer = getRawAsset(key)\n\t\t\t\tthis.#add(new Asset({ key, content }))\n\t\t\t\tregistered.push(key)\n\t\t\t}\n\t\t\tif (registered.length > 0) {\n\t\t\t\tthis.#emitter.emit('load', registered)\n\t\t\t}\n\t\t}\n\t}\n}\n","import type {\n\tAssetInput,\n\tAssetInterface,\n\tAssetManagerInterface,\n\tAssetManagerOptions,\n\tInjectorInterface,\n\tInjectorOptions,\n\tSEAInterface,\n\tSEAOptions,\n} from './types.js'\nimport { SEA } from './seals/SEA.js'\nimport { Injector } from './injectors/Injector.js'\nimport { Asset } from './assets/Asset.js'\nimport { AssetManager } from './assets/AssetManager.js'\n\n/**\n * Create a new SEA build orchestrator.\n *\n * @param options - SEA build options\n * @returns a new `SEAInterface`\n *\n * @example\n * ```ts\n * const seal = createSEA({\n * name: 'orkestrel',\n * entry: { path: 'dist/bin/serve.cjs' },\n * output: 'dist/sea',\n * assets: { 'index.html.br': 'dist/client/index.html.br' },\n * compression: { paths: ['dist/client'] },\n * })\n * const result = await seal.execute()\n * ```\n */\nexport function createSEA(options: SEAOptions): SEAInterface {\n\treturn new SEA(options)\n}\n\n/**\n * Create a cross-platform binary resource injector.\n *\n * Detects the executable format (PE, ELF, Mach-O) from the file header\n * and injects the blob using pure TypeScript file I/O — no WASM, no\n * external tools.\n *\n * @param options - Injector options\n * @returns a new `InjectorInterface`\n *\n * @example\n * ```ts\n * const injector = createInjector({\n * executable: 'dist/bin/myapp.exe',\n * resource: 'NODE_SEA_BLOB',\n * blob: 'dist/bin/sea-prep.blob',\n * fuse: 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2',\n * })\n * injector.inject()\n * ```\n */\nexport function createInjector(options: InjectorOptions): InjectorInterface {\n\treturn new Injector(options)\n}\n\n/**\n * Create a single named asset.\n *\n * @param input - Asset key, content, and optional compression flag\n * @returns a new `AssetInterface`\n *\n * @example\n * ```ts\n * const asset = createAsset({ key: 'client.html.br', content: compressedBuffer })\n * ```\n */\nexport function createAsset(input: AssetInput): AssetInterface {\n\treturn new Asset(input)\n}\n\n/**\n * Create an asset manager for SEA-embedded or disk-loaded assets.\n *\n * @param options - Asset manager options (root, event hooks)\n * @returns a new `AssetManagerInterface`\n *\n * @example\n * ```ts\n * const manager = createAssetManager({ root: process.cwd() })\n * manager.load()\n * ```\n */\nexport function createAssetManager(options?: AssetManagerOptions): AssetManagerInterface {\n\treturn new AssetManager(options)\n}\n"],"mappings":";;;;;;;;;;AAGA,IAAa,oBAAoB;;AAGjC,IAAa,oBAAoB;;AAGjC,IAAa,kCAAkC;;AAG/C,IAAa,wBAAwB;;AAGrC,IAAa,4BAA4B;;AAGzC,IAAa,mBAAmB;;AAGhC,IAAa,kCAAkB,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,uBAAuC;;AAGpD,IAAa,uBAAuB;;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injectElf","#injectMacho","#patchChecksum","#readU32","#readU16","#ensureValidPEAlignment","#stripTrailingNulls","#parseResourceDirectory","#rvaToFileOffset","#buildResourceTree","#serializeResourceTree","#align","#writeU16","#writeU32","#fixupDirectoryRvas","#appendFile","#readResourceString","#sortResourceKeys","#fixupDataEntries","#readU64","#readElfProgramHeaders","#readElfNoteName","#writeElfProgramHeaderEntry","#writeU64","#verifyElfNoteMapping","#shiftMachoLinkeditOffsets","#verifyMachoSection","#options","#emitter","#status","#destroyed","#check","#validate","#compress","#blob","#assemble","#assets","#emitter","#root","#loadSea","#assets","#keys","#add"],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/helpers.ts","../../../src/server/injectors/Injector.ts","../../../src/server/seals/SEA.ts","../../../src/server/assets/Asset.ts","../../../src/server/assets/AssetManager.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { SEACompressionMode, SEAEntryFormat, SEAPlatform } from './types.js'\n\n/** SEA sentinel fuse value embedded in the Node.js binary */\nexport const SEA_SENTINEL_FUSE = 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2'\n\n/** Resource name for the SEA blob in the executable */\nexport const SEA_BLOB_RESOURCE = 'NODE_SEA_BLOB'\n\n/** Default Brotli compression quality level (maximum) */\nexport const DEFAULT_SEA_COMPRESSION_QUALITY = 11\n\n/** Windows PE subsystem value: GUI application (no terminal window) */\nexport const WINDOWS_SUBSYSTEM_GUI = 2\n\n/** Windows PE subsystem value: console application */\nexport const WINDOWS_SUBSYSTEM_CONSOLE = 3\n\n/** File extension indicating Brotli compression */\nexport const BROTLI_EXTENSION = '.br'\n\n/** File extensions that should NOT be Brotli-compressed */\nexport const SKIP_EXTENSIONS = new Set([\n\t'.br',\n\t'.gz',\n\t'.zst',\n\t'.png',\n\t'.jpg',\n\t'.jpeg',\n\t'.gif',\n\t'.webp',\n\t'.avif',\n\t'.ico',\n\t'.woff',\n\t'.woff2',\n\t'.ttf',\n\t'.otf',\n\t'.eot',\n\t'.mp3',\n\t'.mp4',\n\t'.webm',\n\t'.ogg',\n\t'.zip',\n\t'.tar',\n])\n\n/** Default SEA entry point module format when none is specified */\nexport const DEFAULT_ENTRY_FORMAT: SEAEntryFormat = 'cjs'\n\n/** Asset key for the raw (uncompressed) client HTML entry */\nexport const CLIENT_ASSET_KEY_RAW = 'client.html'\n\n/** Asset key for the Brotli-compressed client HTML entry */\nexport const CLIENT_ASSET_KEY_BR = 'client.html.br'\n\n// === Binary Format Magic\n\n/** DOS MZ header magic (first 2 bytes of a PE file) */\nexport const PE_MAGIC = 0x5a4d\n\n/** PE signature: \"PE\\0\\0\" as a 32-bit value */\nexport const PE_SIGNATURE = 0x00004550\n\n/** PE32 optional header magic */\nexport const PE32_MAGIC = 0x10b\n\n/** PE32+ (64-bit) optional header magic */\nexport const PE32_PLUS_MAGIC = 0x20b\n\n/** ELF magic: 0x7F 'E' 'L' 'F' as a 32-bit big-endian value */\nexport const ELF_MAGIC = 0x7f454c46\n\n/** ELF 64-bit class identifier */\nexport const ELF_CLASS_64 = 2\n\n/** ELF little-endian data encoding */\nexport const ELF_DATA_LSB = 1\n\n/** ELF program header type: note segment */\nexport const ELF_PT_NOTE = 4\n\n/** Mach-O 64-bit magic (little-endian) */\nexport const MACHO_MAGIC_64 = 0xfeedfacf\n\n/** Mach-O LC_SEGMENT_64 load command */\nexport const MACHO_LC_SEGMENT_64 = 0x19\n\n// === PE Resource Directory\n\n/** PE resource type: RT_RCDATA (raw data) */\nexport const PE_RT_RCDATA = 10\n\n/** Size of IMAGE_RESOURCE_DIRECTORY in bytes */\nexport const PE_RESOURCE_DIR_SIZE = 16\n\n/** Size of IMAGE_RESOURCE_DIRECTORY_ENTRY in bytes */\nexport const PE_RESOURCE_ENTRY_SIZE = 8\n\n/** Size of IMAGE_RESOURCE_DATA_ENTRY in bytes */\nexport const PE_RESOURCE_DATA_ENTRY_SIZE = 16\n\n/** PE section header size in bytes */\nexport const PE_SECTION_HEADER_SIZE = 40\n\n/** High bit mask for resource directory entry offset (indicates subdirectory) */\nexport const PE_RESOURCE_SUBDIR_FLAG = 0x80000000\n\n/** High bit mask for resource name entry (indicates named vs integer ID) */\nexport const PE_RESOURCE_NAME_FLAG = 0x80000000\n\n// === PE Section Characteristics\n\n/** Section contains initialized data */\nexport const PE_SCN_INITIALIZED_DATA = 0x00000040\n\n/** Section is readable */\nexport const PE_SCN_MEM_READ = 0x40000000\n\n// === Platform\n\n/** Platform-specific SEA build configurations */\nexport const SEA_PLATFORMS: Readonly<Record<string, SEAPlatform>> = Object.freeze({\n\twin32: Object.freeze({\n\t\texecutable: 'node.exe',\n\t\tverify: Object.freeze(['signtool', 'verify', '/pa']),\n\t}),\n\tdarwin: Object.freeze({\n\t\texecutable: 'node',\n\t\tremove: Object.freeze(['codesign', '--remove-signature']),\n\t\tsign: Object.freeze(['codesign', '--sign', '-']),\n\t\tverify: Object.freeze(['codesign', '--verify', '--strict']),\n\t}),\n\tlinux: Object.freeze({\n\t\texecutable: 'node',\n\t}),\n})\n\n// === Compression\n\n/** Maps a {@link SEACompressionMode} to its numeric Brotli mode value */\nexport const SEA_COMPRESSION_MODE_VALUES: Readonly<Record<SEACompressionMode, number>> =\n\tObject.freeze({\n\t\tgeneric: 0,\n\t\ttext: 1,\n\t\tfont: 2,\n\t})\n","import type { SEAErrorCode } from './types.js'\n\n// Error surface for the seal build. `SEAError` is the coded base every\n// domain failure throws through, so a caller can branch on `code` rather\n// than parsing a message string. `ShellError` specializes it for the shell\n// boundary — `runShell` maps a failed `execFileSync` invocation to a\n// `ShellError` carrying the captured stdout/stderr, so a caller can inspect\n// the process output rather than parsing the thrown message.\n\n/**\n * The coded base error for every failure raised by the seal build.\n *\n * @remarks\n * Carries a machine-readable {@link SEAErrorCode} and optional `context`\n * for structured diagnostics. Narrow a caught value with {@link isSEAError}.\n *\n * @example\n * ```ts\n * try {\n * seal.execute()\n * } catch (error) {\n * if (isSEAError(error)) {\n * console.error(error.code, error.context)\n * }\n * }\n * ```\n */\nexport class SEAError extends Error {\n\treadonly code: SEAErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(code: SEAErrorCode, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tthis.name = 'SEAError'\n\t\tthis.code = code\n\t\tif (context !== undefined) {\n\t\t\tthis.context = context\n\t\t}\n\t}\n}\n\n/**\n * Whether a value is a {@link SEAError}.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a `SEAError`\n *\n * @example\n * ```ts\n * if (isSEAError(caught)) {\n * console.error(caught.code)\n * }\n * ```\n */\nexport function isSEAError(value: unknown): value is SEAError {\n\treturn value instanceof SEAError\n}\n\n/**\n * An error thrown when a shell command run via `runShell` exits non-zero.\n *\n * @remarks\n * Carries the captured `stdout` and `stderr` buffers from the failed process.\n * Always carries {@link SEAErrorCode} `'SHELL'`. Narrow a caught value with\n * {@link isShellError}.\n *\n * @example\n * ```ts\n * try {\n * runShell(['codesign', '--sign', '-', path])\n * } catch (error) {\n * if (isShellError(error)) {\n * console.error(error.stderr.toString())\n * }\n * }\n * ```\n */\nexport class ShellError extends SEAError {\n\treadonly stdout: Buffer\n\treadonly stderr: Buffer\n\n\tconstructor(message: string, stdout: Buffer, stderr: Buffer) {\n\t\tsuper('SHELL', message)\n\t\tthis.name = 'ShellError'\n\t\tthis.stdout = stdout\n\t\tthis.stderr = stderr\n\t}\n}\n\n/**\n * Whether a value is a {@link ShellError}.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a `ShellError`\n *\n * @example\n * ```ts\n * if (isShellError(caught)) {\n * console.error(caught.stdout.toString())\n * }\n * ```\n */\nexport function isShellError(value: unknown): value is ShellError {\n\treturn value instanceof ShellError\n}\n","import type {\n\tExecutableFormat,\n\tSEABlobOptions,\n\tSEACompressionManifest,\n\tSEACompressionOptions,\n\tSEACompressionResult,\n\tSEACompressionSize,\n\tSEAEntryOptions,\n\tSEAErrorCode,\n\tSEAPlatform,\n\tSEAProgressHandler,\n\tSEAShellOptions,\n\tSEAWindowsSignOptions,\n} from './types.js'\nimport {\n\texistsSync,\n\topenSync,\n\treadSync,\n\treaddirSync,\n\treadFileSync,\n\trealpathSync,\n\twriteSync,\n\tcloseSync,\n\twriteFileSync,\n\tfsyncSync,\n\trenameSync,\n\tftruncateSync,\n\tfstatSync,\n\tlstatSync,\n} from 'node:fs'\nimport { brotliCompressSync, constants as zlibConstants } from 'node:zlib'\nimport { resolve, relative, join, extname, isAbsolute, sep, dirname } from 'node:path'\nimport { execFileSync, spawn } from 'node:child_process'\nimport {\n\tBROTLI_EXTENSION,\n\tDEFAULT_SEA_COMPRESSION_QUALITY,\n\tSEA_COMPRESSION_MODE_VALUES,\n\tSEA_PLATFORMS,\n\tSKIP_EXTENSIONS,\n} from './constants.js'\nimport { SEAError, ShellError } from './errors.js'\n\n// === Type Guards\n\n/**\n * Check if a value is a valid {@link ExecutableFormat}.\n *\n * @param value - Value to check\n * @returns True when value is `'pe'`, `'elf'`, or `'macho'`\n */\nexport function isExecutableFormat(value: unknown): value is ExecutableFormat {\n\treturn value === 'pe' || value === 'elf' || value === 'macho'\n}\n\n// === Platform Helpers\n\n/**\n * Get the platform configuration for the current OS.\n *\n * @param platform - Platform identifier. Default: `process.platform`.\n * @returns Platform configuration, or undefined if unsupported\n */\nexport function platformConfig(platform?: string): SEAPlatform | undefined {\n\treturn SEA_PLATFORMS[platform ?? process.platform]\n}\n\n/**\n * Check if the current or specified platform is supported for SEA builds.\n *\n * @param platform - Platform identifier to check\n * @returns True when the platform has a known configuration\n */\nexport function isPlatformSupported(platform?: string): boolean {\n\treturn (platform ?? process.platform) in SEA_PLATFORMS\n}\n\n// === Filesystem Helpers\n\n/**\n * Assert that a path exists, throwing a coded {@link SEAError} if not.\n *\n * @param path - Absolute or relative path to check\n * @param message - Error message when path is missing\n * @param code - Error code to throw with. Default: `'STATE'`.\n */\nexport function ensureExists(path: string, message: string, code?: SEAErrorCode): void {\n\tif (!existsSync(path)) {\n\t\tthrow new SEAError(code ?? 'STATE', message, { path })\n\t}\n}\n\n/**\n * Check if a file should be Brotli-compressed based on its extension.\n *\n * @param path - Path to the file\n * @returns True when the file type benefits from compression\n */\nexport function isCompressible(path: string): boolean {\n\tconst ext = extname(path).toLowerCase()\n\treturn !SKIP_EXTENSIONS.has(ext)\n}\n\n/**\n * Recursively walk a directory and return all file paths.\n *\n * @param directory - Directory to walk\n * @param base - Base directory for relative path calculation\n * @returns Array of relative file paths\n */\nexport function walkDirectory(directory: string, base?: string): readonly string[] {\n\tconst root = base ?? directory\n\tconst result: string[] = []\n\tconst entries = readdirSync(directory, { withFileTypes: true })\n\t// Sort by byte order (not localeCompare, which is locale-dependent) so\n\t// asset order is deterministic across platforms and Node builds.\n\tentries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n\n\tfor (const entry of entries) {\n\t\t// Symlinks can escape the compression root (point outside `directory`),\n\t\t// which would make the walk non-deterministic across platforms/filesystems.\n\t\tif (entry.isSymbolicLink()) continue\n\t\tconst fullPath = join(directory, entry.name)\n\t\tif (entry.isDirectory()) {\n\t\t\tresult.push(...walkDirectory(fullPath, root))\n\t\t} else if (entry.isFile()) {\n\t\t\tresult.push(relative(root, fullPath))\n\t\t}\n\t}\n\n\treturn result\n}\n\n// === Shell Helpers\n\n/**\n * Redact password arguments from a shell command.\n *\n * @param command - Command arguments to redact\n * @returns A copy with values following password flags replaced by a marker\n */\nexport function redactCommand(command: readonly string[]): readonly string[] {\n\tconst secretFlags = new Set(['/p', '-p', '--password'])\n\treturn command.map((token, index) => {\n\t\tconst previous = command[index - 1]\n\t\tif (previous !== undefined && secretFlags.has(previous.toLowerCase())) {\n\t\t\treturn '***'\n\t\t}\n\t\treturn token\n\t})\n}\n\n/**\n * Run a command synchronously and return stdout.\n *\n * @param command - Command to execute (first element is the binary)\n * @param options - Shell options (cwd, env, timeout, signal)\n * @returns stdout as a Buffer\n * @throws SEAError with code `'STATE'` when `command` is empty\n * @throws SEAError with code `'ABORT'` when `options.signal` is already aborted\n * @throws SEAError with code `'TIMEOUT'` when the command exceeds `options.timeout`\n * @throws ShellError when the command exits with non-zero status\n */\nexport function runShell(command: string[], options?: SEAShellOptions): Buffer {\n\tconst [cmd, ...args] = command\n\tif (cmd === undefined) {\n\t\tthrow new SEAError('STATE', 'Command array must not be empty')\n\t}\n\tif (options?.signal?.aborted === true) {\n\t\tthrow new SEAError('ABORT', 'Shell command aborted', { command: redactCommand(command) })\n\t}\n\t// Node v22+ blocks direct execFileSync of .cmd/.bat files without a shell (EINVAL)\n\tconst useShell = cmd.endsWith('.cmd') || cmd.endsWith('.bat')\n\ttry {\n\t\treturn execFileSync(cmd, args, {\n\t\t\tcwd: options?.cwd,\n\t\t\tenv: options?.env !== undefined ? { ...process.env, ...options.env } : undefined,\n\t\t\tstdio: ['pipe', 'pipe', 'pipe'],\n\t\t\tshell: useShell,\n\t\t\ttimeout: options?.timeout,\n\t\t})\n\t} catch (thrown: unknown) {\n\t\tif (!(thrown instanceof Error)) {\n\t\t\tthrow thrown\n\t\t}\n\t\tconst redacted = redactCommand(command)\n\t\tconst code = 'code' in thrown && typeof thrown.code === 'string' ? thrown.code : undefined\n\t\tif (code === 'ETIMEDOUT') {\n\t\t\tthrow new SEAError('TIMEOUT', 'Shell command timed out', {\n\t\t\t\tcommand: redacted,\n\t\t\t\ttimeout: options?.timeout,\n\t\t\t})\n\t\t}\n\t\tconst stdout =\n\t\t\t'stdout' in thrown && Buffer.isBuffer(thrown.stdout) ? thrown.stdout : Buffer.alloc(0)\n\t\tconst stderr =\n\t\t\t'stderr' in thrown && Buffer.isBuffer(thrown.stderr) ? thrown.stderr : Buffer.alloc(0)\n\t\tthrow new ShellError('Command failed: ' + redacted.join(' '), stdout, stderr)\n\t}\n}\n\n// === Compression Helpers\n\n/**\n * Compute a size comparison between original and compressed byte counts.\n *\n * @param original - Original byte count\n * @param compressed - Compressed byte count\n * @returns SEACompressionSize with ratio\n */\nexport function computeSize(original: number, compressed: number): SEACompressionSize {\n\tconst ratio = original > 0 ? compressed / original : 0\n\treturn { original, compressed, ratio }\n}\n\n/**\n * Brotli-compress a single file, writing the output alongside it.\n *\n * @param input - Absolute path to the source file\n * @param output - Absolute path for the compressed output\n * @param options - Compression options (quality, mode)\n * @returns Compression result with size comparison\n */\nexport function compressFile(\n\tinput: string,\n\toutput: string,\n\toptions?: SEACompressionOptions,\n): SEACompressionResult {\n\tconst quality = options?.quality ?? DEFAULT_SEA_COMPRESSION_QUALITY\n\tconst mode = SEA_COMPRESSION_MODE_VALUES[options?.mode ?? 'generic']\n\n\tconst raw = readFileSync(input)\n\tconst compressed = brotliCompressSync(raw, {\n\t\tparams: {\n\t\t\t[zlibConstants.BROTLI_PARAM_QUALITY]: quality,\n\t\t\t[zlibConstants.BROTLI_PARAM_MODE]: mode,\n\t\t},\n\t})\n\n\t// walkDirectory already skips symlinks on the read side; mirror that here\n\t// on the write side so a planted symlink at `output` (e.g. `X.br -> /victim`)\n\t// cannot redirect this write to an arbitrary file.\n\tlet outputStat: ReturnType<typeof lstatSync> | undefined\n\ttry {\n\t\toutputStat = lstatSync(output)\n\t} catch {\n\t\toutputStat = undefined\n\t}\n\tif (outputStat !== undefined && outputStat.isSymbolicLink()) {\n\t\tthrow new SEAError('OUTPUT', 'Refusing to write compressed output through a symlink', {\n\t\t\toutput,\n\t\t})\n\t}\n\n\twriteFileSync(output, compressed)\n\n\treturn {\n\t\tinput,\n\t\toutput,\n\t\tsize: computeSize(raw.length, compressed.length),\n\t}\n}\n\n/**\n * Compress all compressible files in a directory tree.\n *\n * @param directory - Absolute path to the directory\n * @param options - Compression options\n * @param progress - Optional callback invoked after each file is compressed\n * @returns Compression manifest with all results\n */\nexport function compressDirectory(\n\tdirectory: string,\n\toptions?: SEACompressionOptions,\n\tprogress?: SEAProgressHandler,\n): SEACompressionManifest {\n\tconst files = walkDirectory(directory)\n\tconst results: SEACompressionResult[] = []\n\tlet totalOriginal = 0\n\tlet totalCompressed = 0\n\n\tfor (const relativePath of files) {\n\t\tconst fullPath = resolve(directory, relativePath)\n\t\tif (!isCompressible(fullPath)) continue\n\n\t\tconst outputPath = fullPath + BROTLI_EXTENSION\n\t\tconst result = compressFile(fullPath, outputPath, options)\n\t\tresults.push(result)\n\t\ttotalOriginal += result.size.original\n\t\ttotalCompressed += result.size.compressed\n\t\tprogress?.(result)\n\t}\n\n\treturn {\n\t\tassets: results,\n\t\ttotal: computeSize(totalOriginal, totalCompressed),\n\t}\n}\n\n// === PE Helpers\n\n/**\n * Check whether a number is a nonzero power of two.\n *\n * @param value - Number to check\n * @returns True when the value is a positive power of two\n */\nexport function isPowerOfTwo(value: number): boolean {\n\treturn value > 0 && (value & (value - 1)) === 0\n}\n\n/**\n * Parse the PE header offset from a Windows executable.\n *\n * @param fd - Open file descriptor\n * @returns The offset to the PE signature\n */\nexport function parsePEOffset(fd: number): number {\n\tconst buf = Buffer.alloc(4)\n\treadSync(fd, buf, 0, 4, 0x3c)\n\treturn buf.readUInt32LE(0)\n}\n\n/**\n * Read a 16-bit unsigned integer from a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to read from\n * @returns The 16-bit value\n */\nexport function readU16(fd: number, offset: number): number {\n\tconst buf = Buffer.alloc(2)\n\treadSync(fd, buf, 0, 2, offset)\n\treturn buf.readUInt16LE(0)\n}\n\n/**\n * Write a 16-bit unsigned integer to a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to write at\n * @param value - The 16-bit value to write\n */\nexport function writeU16(fd: number, offset: number, value: number): void {\n\tconst buf = Buffer.alloc(2)\n\tbuf.writeUInt16LE(value, 0)\n\twriteSync(fd, buf, 0, 2, offset)\n}\n\n/**\n * Check if a file is a Windows PE executable.\n *\n * @param path - Path to the file\n * @returns True when the file has a valid PE signature\n */\nexport function isPEExecutable(path: string): boolean {\n\tlet fd: number | undefined\n\ttry {\n\t\tfd = openSync(path, 'r')\n\t\tconst peOffset = parsePEOffset(fd)\n\t\tconst sig = Buffer.alloc(4)\n\t\treadSync(fd, sig, 0, 4, peOffset)\n\t\treturn sig.toString('ascii') === 'PE\\0\\0'\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tif (fd !== undefined) closeSync(fd)\n\t}\n}\n\n/**\n * Patch the PE subsystem field in a Windows executable.\n *\n * @param path - Path to the executable\n * @param subsystem - Numeric subsystem value (2 = GUI, 3 = Console)\n */\nexport function patchPESubsystem(path: string, subsystem: number): void {\n\tconst fd = openSync(path, 'r+')\n\ttry {\n\t\tconst peOffset = parsePEOffset(fd)\n\t\t// Subsystem field is at PE offset + 0x5C (in the Optional Header)\n\t\twriteU16(fd, peOffset + 0x5c, subsystem)\n\t} finally {\n\t\tcloseSync(fd)\n\t}\n}\n\n/**\n * Remove the Authenticode signature from a PE executable by zeroing\n * the security directory entry in the optional header.\n *\n * @remarks\n * If the certificate overlay described by the security directory sits at the\n * very end of the file (the common case for `signtool`-signed binaries), the\n * file is truncated to the certificate's start FIRST so the overlay bytes are\n * discarded rather than left as dead weight for a downstream injector to\n * bury mid-file. The directory read is bounds-checked so a malformed or\n * truncated security directory cannot throw unexpectedly — it is simply\n * skipped and only the directory entry is zeroed.\n *\n * @param path - Path to the executable\n */\nexport function stripPESignature(path: string): void {\n\tconst fd = openSync(path, 'r+')\n\ttry {\n\t\tconst peOffset = parsePEOffset(fd)\n\t\t// COFF header: 24 bytes from PE signature\n\t\t// Optional header magic at peOffset + 24\n\t\tconst magic = readU16(fd, peOffset + 24)\n\t\t// PE32+ has security dir at different offset than PE32\n\t\tconst securityDirOffset = magic === 0x20b ? peOffset + 168 : peOffset + 152\n\n\t\tconst dirBuf = Buffer.alloc(8)\n\t\tconst dirRead = readSync(fd, dirBuf, 0, 8, securityDirOffset)\n\t\tif (dirRead === 8) {\n\t\t\tconst certOffset = dirBuf.readUInt32LE(0)\n\t\t\tconst certSize = dirBuf.readUInt32LE(4)\n\t\t\tif (certOffset > 0 && certSize > 0) {\n\t\t\t\tconst fileSize = fstatSync(fd).size\n\t\t\t\tif (certOffset <= fileSize && certOffset + certSize === fileSize) {\n\t\t\t\t\tftruncateSync(fd, certOffset)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Zero out the 8-byte security directory entry (VirtualAddress + Size)\n\t\tconst zeroes = Buffer.alloc(8)\n\t\twriteSync(fd, zeroes, 0, 8, securityDirOffset)\n\t} finally {\n\t\tcloseSync(fd)\n\t}\n}\n\n// === Signing Helpers\n\n/**\n * Build the `signtool sign` argv for signing a Windows executable.\n *\n * @remarks\n * Requires EXACTLY ONE certificate source — `sign.file` (a `.pfx`/`.p12`\n * file, paired with `sign.password` when present) XOR `sign.thumbprint` (a\n * certificate already installed in the Windows store). When `sign.timestamp`\n * is set it is parsed with the `URL` constructor and must be an `http:` or\n * `https:` URL. The returned argv is passed directly to `runShell` — never\n * through a shell — so nothing in `sign` can be interpreted as a flag or\n * injected into a command line. `sign.password` is NEVER included in a\n * thrown error's message or `context`.\n *\n * @param sign - Windows signing options\n * @param target - Absolute path to the executable to sign\n * @returns The `signtool` argv, ready for `runShell`\n * @throws SEAError with code `'SIGN'` when neither `file` nor `thumbprint` is set\n * @throws SEAError with code `'SIGN'` when both `file` and `thumbprint` are set\n * @throws SEAError with code `'SIGN'` when `timestamp` is not a parseable http(s) URL\n * @throws SEAError with code `'SIGN'` when `digest` is not `'sha1'`, `'sha256'`, `'sha384'`, or `'sha512'`\n *\n * @example\n * ```ts\n * createSignCommand({ thumbprint: 'AABBCCDDEEFF00112233445566778899AABBCCDD' }, 'dist/sea/app.exe')\n * // ['signtool', 'sign', '/fd', 'sha256', '/sha1', 'AABBCCDDEEFF00112233445566778899AABBCCDD', 'dist/sea/app.exe']\n * ```\n */\nexport function createSignCommand(sign: SEAWindowsSignOptions, target: string): string[] {\n\tconst hasFile = sign.file !== undefined\n\tconst hasThumbprint = sign.thumbprint !== undefined\n\n\tif (!hasFile && !hasThumbprint) {\n\t\tthrow new SEAError(\n\t\t\t'SIGN',\n\t\t\t'Windows signing requires exactly one of sign.file or sign.thumbprint',\n\t\t)\n\t}\n\tif (hasFile && hasThumbprint) {\n\t\tthrow new SEAError(\n\t\t\t'SIGN',\n\t\t\t'Windows signing accepts only one of sign.file or sign.thumbprint, not both',\n\t\t)\n\t}\n\n\tif (sign.timestamp !== undefined) {\n\t\tlet parsed: URL\n\t\ttry {\n\t\t\tparsed = new URL(sign.timestamp)\n\t\t} catch {\n\t\t\tthrow new SEAError('SIGN', 'Windows signing timestamp must be an http(s) URL', {\n\t\t\t\ttimestamp: sign.timestamp,\n\t\t\t})\n\t\t}\n\t\tif (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n\t\t\tthrow new SEAError('SIGN', 'Windows signing timestamp must be an http(s) URL', {\n\t\t\t\ttimestamp: sign.timestamp,\n\t\t\t})\n\t\t}\n\t}\n\n\tconst digest = sign.digest ?? 'sha256'\n\tconst supportedDigests = new Set(['sha1', 'sha256', 'sha384', 'sha512'])\n\tif (!supportedDigests.has(digest)) {\n\t\tthrow new SEAError('SIGN', 'Unsupported signing digest', { digest: sign.digest })\n\t}\n\n\treturn [\n\t\t'signtool',\n\t\t'sign',\n\t\t'/fd',\n\t\tdigest,\n\t\t...(sign.file !== undefined\n\t\t\t? ['/f', sign.file, ...(sign.password !== undefined ? ['/p', sign.password] : [])]\n\t\t\t: []),\n\t\t...(sign.thumbprint !== undefined ? ['/sha1', sign.thumbprint] : []),\n\t\t...(sign.timestamp !== undefined ? ['/tr', sign.timestamp, '/td', digest] : []),\n\t\ttarget,\n\t]\n}\n\n// === Formatting Helpers\n\n/**\n * Format a byte count as a human-readable string.\n *\n * @param bytes - Byte count\n * @returns Formatted string (e.g. `\"1.23 MB\"`, `\"456 KB\"`)\n */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) return `${String(bytes)} B`\n\tif (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`\n\treturn `${(bytes / (1024 * 1024)).toFixed(2)} MB`\n}\n\n/**\n * Assert that an asset key is safe to use as a relative filesystem/archive key.\n *\n * @remarks\n * Rejects an empty key, an absolute path, a key containing a backslash, a\n * Windows drive-relative specifier (e.g. `'C:foo'`), or any `/`-separated\n * segment equal to `'..'` — all of which could escape the intended asset root.\n *\n * @param key - Asset key to validate\n * @throws SEAError with code `'ASSET'` when the key is unsafe\n *\n * @example\n * ```ts\n * ensureSafeKey('client.html.br') // ok\n * ensureSafeKey('../secrets') // throws SEAError('ASSET', ...)\n * ensureSafeKey('C:foo') // throws SEAError('ASSET', ...)\n * ```\n */\nexport function ensureSafeKey(key: string): void {\n\tif (key.length === 0) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not be empty', { key })\n\t}\n\tif (isAbsolute(key)) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not be an absolute path', { key })\n\t}\n\tif (key.includes('\\\\')) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not contain a backslash', { key })\n\t}\n\tif (/^[A-Za-z]:/.test(key)) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not be a drive-relative specifier', { key })\n\t}\n\tif (key.split('/').includes('..')) {\n\t\tthrow new SEAError('ASSET', 'Asset key must not contain a \"..\" segment', { key })\n\t}\n}\n\n/**\n * Assert that `path` (resolved against `base`) real-path-resolves to a\n * location inside `base`, defeating a symlink escape.\n *\n * @remarks\n * Resolves `path` against `base`, then dereferences both the resolved path\n * and `base` with `realpathSync` and requires the real resolved path to\n * equal the real base or begin with the real base plus a path separator.\n * Dereferencing BOTH sides means a symlinked base itself (e.g. macOS `/tmp`\n * -> `/private/tmp`) still matches, while a symlink inside the tree that\n * points outside the real base is correctly rejected. A `realpathSync`\n * failure (e.g. `ENOENT`) is wrapped as a coded `SEAError` rather than\n * leaking the raw Node error.\n *\n * @param base - Absolute path to the containing root\n * @param path - Path to validate, resolved against `base` if relative\n * @returns The real (symlink-resolved) contained path\n * @throws SEAError with code `'ASSET'` when the real path escapes `base`\n * @throws SEAError with code `'ASSET'` when the path cannot be resolved\n *\n * @example\n * ```ts\n * ensureContained('/dist/app', 'browser') // '/dist/app/browser' (real path)\n * ensureContained('/dist/app', '../../etc') // throws SEAError('ASSET', ...)\n * ```\n */\nexport function ensureContained(base: string, path: string): string {\n\tconst resolved = resolve(base, path)\n\n\tlet real: string\n\tlet realBase: string\n\ttry {\n\t\treal = realpathSync(resolved)\n\t\trealBase = realpathSync(base)\n\t} catch (thrown: unknown) {\n\t\tconst cause = thrown instanceof Error ? thrown.message : String(thrown)\n\t\tthrow new SEAError('ASSET', 'Path not found or unresolvable', { path, cause })\n\t}\n\n\tif (real !== realBase && !real.startsWith(realBase + sep)) {\n\t\tthrow new SEAError('ASSET', 'Path escapes the build root', { base, path })\n\t}\n\n\treturn real\n}\n\n/**\n * Assert that `name` is a single safe path segment suitable as an output\n * executable base name.\n *\n * @remarks\n * Rejects an empty name, `'.'`, `'..'`, a name containing a `/` or `\\`\n * separator, an absolute path, or a Windows drive-relative specifier (e.g.\n * `'C:foo'`) — all of which could redirect the output executable outside\n * the intended output directory.\n *\n * @param name - Output executable base name to validate\n * @throws SEAError with code `'ASSET'` when the name is unsafe\n *\n * @example\n * ```ts\n * ensureSafeName('myapp') // ok\n * ensureSafeName('../evil') // throws SEAError('ASSET', ...)\n * ```\n */\nexport function ensureSafeName(name: string): void {\n\tif (name.length === 0 || name === '.' || name === '..') {\n\t\tthrow new SEAError('ASSET', 'Executable name must be a single path segment', { name })\n\t}\n\tif (name.includes('/') || name.includes('\\\\')) {\n\t\tthrow new SEAError('ASSET', 'Executable name must not contain a path separator', { name })\n\t}\n\tif (isAbsolute(name)) {\n\t\tthrow new SEAError('ASSET', 'Executable name must not be an absolute path', { name })\n\t}\n\tif (/^[A-Za-z]:/.test(name)) {\n\t\tthrow new SEAError('ASSET', 'Executable name must not be a drive-relative specifier', {\n\t\t\tname,\n\t\t})\n\t}\n}\n\n/**\n * Fsync a directory to durably persist a prior file rename/create within it.\n *\n * @remarks\n * A `rename`/`create` is only durable once its CONTAINING directory entry is\n * flushed — fsyncing the file itself is not enough. `path` is the directory\n * to fsync (callers pass `dirname(target)`, not the file itself). On Windows\n * there is no directory file handle to fsync, so this is a no-op there (the\n * platform lacks the primitive, not a failure). Some filesystems/platforms\n * return a benign errno for a directory fsync attempt (`EINVAL`, `ENOTSUP`,\n * `EISDIR`, `EPERM`, `EACCES`) — those are treated as \"fsync unsupported\n * here\" and swallowed; anything else (e.g. `ENOENT`, meaning the directory\n * itself is missing) is a genuine failure and is thrown as a coded `SEAError`.\n *\n * @param path - Directory path to fsync\n * @throws SEAError with code `'OUTPUT'` when the directory sync fails for an\n * unrecognized reason\n *\n * @example\n * ```ts\n * syncDirectory('/dist/app/bin')\n * ```\n */\nexport function syncDirectory(path: string): void {\n\t// Windows has no directory file handle to fsync — nothing to do there.\n\tif (process.platform === 'win32') return\n\n\ttry {\n\t\tconst fd = openSync(path, 'r')\n\t\ttry {\n\t\t\tfsyncSync(fd)\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\t} catch (thrown: unknown) {\n\t\tconst code =\n\t\t\tthrown instanceof Error && 'code' in thrown && typeof thrown.code === 'string'\n\t\t\t\t? thrown.code\n\t\t\t\t: undefined\n\t\t// These codes mean \"this filesystem/platform doesn't support directory\n\t\t// fsync\" — benign and safe to ignore. Anything else (e.g. ENOENT, the\n\t\t// directory truly doesn't exist) is a genuine failure.\n\t\tif (\n\t\t\tcode === 'EINVAL' ||\n\t\t\tcode === 'ENOTSUP' ||\n\t\t\tcode === 'EISDIR' ||\n\t\t\tcode === 'EPERM' ||\n\t\t\tcode === 'EACCES'\n\t\t) {\n\t\t\treturn\n\t\t}\n\t\tconst cause = thrown instanceof Error ? thrown.message : String(thrown)\n\t\tthrow new SEAError('OUTPUT', 'Failed to sync output directory', { path, cause })\n\t}\n}\n\n/**\n * Finalize a built executable by durably flushing it to disk and atomically\n * moving it into place.\n *\n * @remarks\n * Opens `source` for read/write, `fsync`s it to force the OS to flush buffered\n * writes, closes it, then `rename`s it to `target`. Never deletes `target` on\n * failure — the caller retains whatever was previously there. After the file\n * is already in place, the containing directory is fsynced ({@link syncDirectory})\n * as a further durability step so the rename itself survives a crash.\n *\n * @param source - Absolute path to the built (temporary) executable\n * @param target - Absolute path to move the finalized executable to\n * @throws SEAError with code `'OUTPUT'` when any step fails\n *\n * @example\n * ```ts\n * finalizeExecutable('/tmp/build/app.tmp', '/dist/app')\n * ```\n */\nexport function finalizeExecutable(source: string, target: string): void {\n\ttry {\n\t\tconst fd = openSync(source, 'r+')\n\t\ttry {\n\t\t\tfsyncSync(fd)\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\t\trenameSync(source, target)\n\t} catch (thrown: unknown) {\n\t\tconst cause = thrown instanceof Error ? thrown.message : String(thrown)\n\t\tthrow new SEAError('OUTPUT', 'Failed to finalize executable', { source, target, cause })\n\t}\n\tsyncDirectory(dirname(target))\n}\n\n/**\n * Build the Node.js `--experimental-sea-config` JSON object for a SEA blob.\n *\n * @remarks\n * A pure leaf extracted from the SEA build orchestrator. The `mainFormat`\n * field (`'commonjs' | 'module'`) exists only in Node >= 25.7 — for a `'cjs'`\n * entry (the default) `mainFormat` is OMITTED entirely so the config still\n * builds on older Node hosts where `'commonjs'` is already the implicit\n * default; for an `'esm'` entry `mainFormat: 'module'` is set explicitly\n * (this requires a Node >= 25.7 build host). Node also documents that\n * `useSnapshot` is incompatible with an ESM entry — combining the two throws.\n *\n * @param entry - SEA entry point options\n * @param blob - Absolute output path for the generated blob\n * @param assets - Optional key→path mapping for embedded assets\n * @param options - Optional blob behavior overrides (cache, snapshot)\n * @returns the SEA config object, ready to be written to disk as JSON\n * @throws SEAError with code `'BLOB'` when `useSnapshot` is combined with an ESM entry\n *\n * @example\n * ```ts\n * const config = createBlobConfig({ path: 'dist/bin/serve.cjs' }, 'dist/bin/sea-prep.blob', undefined)\n * ```\n */\nexport function createBlobConfig(\n\tentry: SEAEntryOptions,\n\tblob: string,\n\tassets: Readonly<Record<string, string>> | undefined,\n\toptions?: SEABlobOptions,\n): Readonly<Record<string, unknown>> {\n\tconst format = entry.format ?? 'cjs'\n\tconst snapshot = options?.snapshot ?? false\n\n\tif (format === 'esm' && snapshot) {\n\t\tthrow new SEAError(\n\t\t\t'BLOB',\n\t\t\t'useSnapshot cannot be combined with an ESM entry (mainFormat module)',\n\t\t)\n\t}\n\n\treturn {\n\t\tmain: entry.path,\n\t\toutput: blob,\n\t\tdisableExperimentalSEAWarning: true,\n\t\tuseSnapshot: snapshot,\n\t\tuseCodeCache: options?.cache ?? true,\n\t\t...(assets ? { assets } : {}),\n\t\t...(format === 'esm' ? { mainFormat: 'module' } : {}),\n\t}\n}\n\n// === ELF Helpers\n\n/**\n * Align an ELF note component size to its four-byte boundary.\n *\n * @param value - Component size to align\n * @returns The value rounded up to the next multiple of four\n */\nexport function alignELFNoteSize(value: number): number {\n\tconst remainder = value % 4\n\treturn remainder === 0 ? value : value + (4 - remainder)\n}\n\n/**\n * Build an ELF `PT_NOTE` entry's header bytes (namesz/descsz/type + padded\n * name) for the SEA blob note, without the blob body itself.\n *\n * @remarks\n * A pure leaf extracted from the ELF injector: the blob body is streamed\n * from disk separately (never buffered here) so this only produces the\n * fixed-size note header and reports the total on-disk size the complete\n * note entry (header + 4-byte-padded blob) will occupy, so the caller can\n * size the covering `PT_LOAD`/`PT_NOTE` segments before writing anything.\n * The Node.js SEA runtime matches a note by the first 8 bytes of its name\n * (`strncmp(name, \"NODE_SEA\", 8)`), so `resource` is written in full but\n * only needs to begin with those 8 bytes to be found at runtime.\n *\n * @param resource - Note name (SEA resource identifier, e.g. `NODE_SEA_BLOB`)\n * @param blobSize - Size in bytes of the SEA blob that will follow the header\n * @returns The note header bytes and the total on-disk size of header + blob\n *\n * @example\n * ```ts\n * const { header, entryTotal } = buildELFNoteHeader('NODE_SEA_BLOB', 4096)\n * ```\n */\nexport function buildELFNoteHeader(\n\tresource: string,\n\tblobSize: number,\n): { readonly header: Buffer; readonly entryTotal: number } {\n\tconst nameBytes = Buffer.from(`${resource}\\0`, 'utf-8')\n\tconst alignedNameSize = alignELFNoteSize(nameBytes.length)\n\n\tconst header = Buffer.alloc(12 + alignedNameSize)\n\theader.writeUInt32LE(nameBytes.length, 0) // namesz\n\theader.writeUInt32LE(blobSize, 4) // descsz\n\theader.writeUInt32LE(0, 8) // type\n\tnameBytes.copy(header, 12)\n\n\tconst alignedDescSize = alignELFNoteSize(blobSize)\n\treturn { header, entryTotal: header.length + alignedDescSize }\n}\n\n/**\n * Copy a byte range from one open file descriptor to another, streaming in\n * fixed-size chunks instead of buffering the whole range in memory.\n *\n * @remarks\n * Reads `length` bytes from `source` starting at file offset `start`, in\n * `chunk`-sized reads, and writes each chunk to `target` with a `null`\n * write position so writes land sequentially at `target`'s current file\n * position (rather than at `start`, which is meaningless for `target`). A\n * short read from `source` (fewer bytes returned than requested, including\n * `0` before `length` is exhausted) is treated as a genuine failure and\n * throws rather than silently writing a truncated range.\n *\n * @param source - Open, readable file descriptor to copy from\n * @param target - Open, writable file descriptor to copy to\n * @param start - Byte offset in `source` to begin reading from\n * @param length - Number of bytes to copy; `0` is a no-op\n * @param chunk - Read/write chunk size in bytes, for tuning memory use and\n * exercising the streaming loop in tests. Default: 4 MB.\n * @throws SEAError with code `'OUTPUT'` when `source` is exhausted before\n * `length` bytes have been copied\n *\n * @example\n * ```ts\n * const srcFd = openSync('big.bin', 'r')\n * const dstFd = openSync('out.bin', 'w')\n * copyRange(srcFd, dstFd, 1024, 4096)\n * ```\n */\nexport function copyRange(\n\tsource: number,\n\ttarget: number,\n\tstart: number,\n\tlength: number,\n\tchunk = 4 * 1024 * 1024,\n): void {\n\tif (length <= 0) return\n\n\tconst bufferSize = Math.min(chunk, length)\n\tconst buffer = Buffer.alloc(bufferSize)\n\tlet position = start\n\tlet remaining = length\n\n\twhile (remaining > 0) {\n\t\tconst toRead = Math.min(chunk, remaining)\n\t\tconst bytesRead = readSync(source, buffer, 0, toRead, position)\n\t\tif (bytesRead === 0) {\n\t\t\tthrow new SEAError('OUTPUT', 'Unexpected end of file while copying byte range', {\n\t\t\t\tstart,\n\t\t\t\tlength,\n\t\t\t\tposition,\n\t\t\t\tremaining,\n\t\t\t})\n\t\t}\n\t\twriteSync(target, buffer, 0, bytesRead, null)\n\t\tposition += bytesRead\n\t\tremaining -= bytesRead\n\t}\n}\n\n// === SEA Helpers\n\n/**\n * Patch the sentinel fuse in a binary from `:0` to `:1`.\n *\n * Searches the file in 64 MB chunks with overlap to handle any file size.\n * The fuse signals to the Node.js runtime that a SEA blob is present.\n * This is normally handled by the Injector but is also available standalone\n * when using native PE resource injection.\n *\n * @param executable - Absolute path to the executable\n * @param fuse - Sentinel fuse string (without the `:0` suffix)\n */\nexport function patchSentinelFuse(executable: string, fuse: string): void {\n\tconst fd = openSync(executable, 'r+')\n\ttry {\n\t\tconst needle = Buffer.from(fuse, 'utf-8')\n\t\tconst chunkSize = 64 * 1024 * 1024 // 64 MB\n\t\tconst readSize = chunkSize + needle.length\n\t\tconst buffer = Buffer.alloc(readSize)\n\n\t\tlet offset = 0\n\t\twhile (true) {\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, readSize, offset)\n\t\t\tif (bytesRead === 0) break\n\n\t\t\tconst chunk = buffer.subarray(0, bytesRead)\n\t\t\tconst idx = chunk.indexOf(needle)\n\n\t\t\tif (idx !== -1) {\n\t\t\t\tconst fuseEnd = offset + idx + needle.length\n\t\t\t\tconst valueBuf = Buffer.alloc(2)\n\t\t\t\tconst valueRead = readSync(fd, valueBuf, 0, 2, fuseEnd)\n\n\t\t\t\tif (valueRead < 2) {\n\t\t\t\t\tthrow new SEAError('FUSE', 'Could not read sentinel fuse value', { executable, fuse })\n\t\t\t\t}\n\n\t\t\t\tconst value = valueBuf.toString('utf-8')\n\n\t\t\t\tif (value === ':0') {\n\t\t\t\t\twriteSync(fd, Buffer.from('1', 'utf-8'), 0, 1, fuseEnd + 1)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif (value === ':1') {\n\t\t\t\t\treturn // Already patched\n\t\t\t\t}\n\n\t\t\t\tthrow new SEAError('FUSE', `Unexpected sentinel fuse value: ${value}`, {\n\t\t\t\t\texecutable,\n\t\t\t\t\tfuse,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\toffset += chunkSize\n\t\t}\n\n\t\tthrow new SEAError('FUSE', `Sentinel fuse not found in executable: ${fuse}`, {\n\t\t\texecutable,\n\t\t\tfuse,\n\t\t})\n\t} finally {\n\t\tcloseSync(fd)\n\t}\n}\n\n// === Runtime Helpers\n\n/**\n * Launch the system default browser at an http(s) URL.\n *\n * @remarks\n * A best-effort launch for bundled local-UI apps: dispatches by\n * `process.platform` (`win32` -> `rundll32 url.dll,FileProtocolHandler`,\n * `darwin` -> `open`, else -> `xdg-open`), each invoked with an argv array\n * (never a shell) so the URL cannot be interpreted as a flag or injected\n * into a command line. The child process is spawned `detached` with\n * `stdio: 'ignore'` and immediately `unref()`d so it never keeps the host\n * app alive. Only `http:` and `https:` URLs are accepted — any other\n * scheme (including a string that merely looks like a CLI flag, e.g.\n * `'-e ...'`) fails to parse as an http(s) URL and is rejected before\n * anything is spawned.\n *\n * @param url - Absolute http or https URL to open\n * @throws SEAError with code `'BROWSER'` when `url` is not a parseable absolute URL\n * @throws SEAError with code `'BROWSER'` when `url` is not an `http:`/`https:` URL\n *\n * @example\n * ```ts\n * openBrowser('http://localhost:3000')\n * ```\n */\nexport function openBrowser(url: string): void {\n\tlet parsed: URL\n\ttry {\n\t\tparsed = new URL(url)\n\t} catch {\n\t\tthrow new SEAError('BROWSER', 'openBrowser requires a valid absolute URL', { url })\n\t}\n\n\tif (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n\t\tthrow new SEAError('BROWSER', 'openBrowser only supports http and https URLs', {\n\t\t\turl,\n\t\t\tprotocol: parsed.protocol,\n\t\t})\n\t}\n\n\tconst child =\n\t\tprocess.platform === 'win32'\n\t\t\t? spawn('rundll32', ['url.dll,FileProtocolHandler', parsed.href], {\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: 'ignore',\n\t\t\t\t})\n\t\t\t: process.platform === 'darwin'\n\t\t\t\t? spawn('open', [parsed.href], { detached: true, stdio: 'ignore' })\n\t\t\t\t: spawn('xdg-open', [parsed.href], { detached: true, stdio: 'ignore' })\n\n\t// Best-effort launch: if the target browser opener binary is absent, the\n\t// child emits an async 'error' (ENOENT) event. There is nothing to recover\n\t// here (unlike the build pipeline, there is no coded failure to surface to\n\t// a caller who has already returned) — an unhandled 'error' event would\n\t// otherwise crash the host app, so this is a deliberate, documented no-op.\n\tchild.on('error', () => {})\n\tchild.unref()\n}\n","/**\n * Injector\n *\n * Cross-platform binary resource injector for PE, ELF, and Mach-O executables.\n * Pure TypeScript file I/O — no WASM, no external tools, no size ceiling.\n *\n * PE — adds an RT_RCDATA resource via resource directory rebuild.\n * ELF — appends a PT_NOTE segment with the blob as note data.\n * Mach-O — appends an LC_SEGMENT_64 load command with a section.\n */\n\nimport type { ExecutableFormat, InjectorInterface, InjectorOptions } from '../types.js'\nimport {\n\topenSync,\n\treadSync,\n\twriteSync,\n\tcloseSync,\n\tstatSync,\n\tfstatSync,\n\tchmodSync,\n\trmSync,\n\tappendFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport {\n\tPE_MAGIC,\n\tPE_SIGNATURE,\n\tPE32_MAGIC,\n\tPE32_PLUS_MAGIC,\n\tPE_RT_RCDATA,\n\tPE_RESOURCE_DIR_SIZE,\n\tPE_RESOURCE_ENTRY_SIZE,\n\tPE_RESOURCE_DATA_ENTRY_SIZE,\n\tPE_SECTION_HEADER_SIZE,\n\tPE_RESOURCE_SUBDIR_FLAG,\n\tPE_RESOURCE_NAME_FLAG,\n\tPE_SCN_INITIALIZED_DATA,\n\tPE_SCN_MEM_READ,\n\tELF_MAGIC,\n\tELF_CLASS_64,\n\tELF_DATA_LSB,\n\tELF_PT_NOTE,\n\tMACHO_MAGIC_64,\n\tMACHO_LC_SEGMENT_64,\n} from '../constants.js'\nimport {\n\tpatchSentinelFuse,\n\tbuildELFNoteHeader,\n\tfinalizeExecutable,\n\tcopyRange,\n\tisPowerOfTwo,\n} from '../helpers.js'\nimport { SEAError } from '../errors.js'\n\n// === Injector\n\nexport class Injector implements InjectorInterface {\n\t#options: InjectorOptions\n\t#format: ExecutableFormat\n\n\tconstructor(options: InjectorOptions) {\n\t\tthis.#options = options\n\t\tthis.#format = this.#detect()\n\t}\n\n\tget format(): ExecutableFormat {\n\t\treturn this.#format\n\t}\n\n\tinject(): void {\n\t\tlet peOptionalOffset: number | undefined\n\t\tswitch (this.#format) {\n\t\t\tcase 'pe':\n\t\t\t\tpeOptionalOffset = this.#injectPe()\n\t\t\t\tbreak\n\t\t\tcase 'elf':\n\t\t\t\tthis.#injectElf()\n\t\t\t\tbreak\n\t\t\tcase 'macho':\n\t\t\t\tthis.#injectMacho()\n\t\t\t\tbreak\n\t\t}\n\n\t\tif (this.#options.fuse !== undefined) {\n\t\t\tpatchSentinelFuse(this.#options.executable, this.#options.fuse)\n\t\t}\n\n\t\t// The checksum must be the TRUE last PE write — computed after the\n\t\t// sentinel-fuse byte flip above — or an unsigned build ships a stale\n\t\t// checksum that doesn't cover the fuse mutation.\n\t\tif (peOptionalOffset !== undefined) {\n\t\t\tthis.#patchChecksum(peOptionalOffset)\n\t\t}\n\t}\n\n\t// === Format Detection\n\n\t#detect(): ExecutableFormat {\n\t\tconst fd = openSync(this.#options.executable, 'r')\n\t\ttry {\n\t\t\tconst header = Buffer.alloc(4)\n\t\t\treadSync(fd, header, 0, 4, 0)\n\t\t\tconst magic16 = header.readUInt16LE(0)\n\t\t\tconst magic32 = header.readUInt32BE(0)\n\t\t\tconst magic32le = header.readUInt32LE(0)\n\n\t\t\tif (magic16 === PE_MAGIC) return 'pe'\n\t\t\tif (magic32 === ELF_MAGIC) return 'elf'\n\t\t\tif (magic32le === MACHO_MAGIC_64) return 'macho'\n\n\t\t\t// Fat/universal Mach-O (either byte order) — dedicated message so\n\t\t\t// callers know exactly why: this injector only handles thin binaries.\n\t\t\tif (magic32 === 0xcafebabe || magic32 === 0xbebafeca) {\n\t\t\t\tthrow new SEAError(\n\t\t\t\t\t'FORMAT',\n\t\t\t\t\t'Mach-O universal/fat binaries are not supported; provide a thin arm64 or x86_64 binary',\n\t\t\t\t\t{ executable: this.#options.executable, magic: magic32 },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// 32-bit or big-endian thin Mach-O (magic 0xfeedface / 0xcefaedfe) —\n\t\t\t// only 64-bit little-endian Mach-O (0xfeedfacf) is supported.\n\t\t\tif (\n\t\t\t\tmagic32le === 0xfeedface ||\n\t\t\t\tmagic32le === 0xcefaedfe ||\n\t\t\t\tmagic32 === 0xfeedface ||\n\t\t\t\tmagic32 === 0xcefaedfe\n\t\t\t) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Only 64-bit little-endian Mach-O is supported', {\n\t\t\t\t\texecutable: this.#options.executable,\n\t\t\t\t\tmagic: magic32,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tthrow new SEAError(\n\t\t\t\t'FORMAT',\n\t\t\t\t`Unknown executable format (magic: 0x${magic32.toString(16).padStart(8, '0')})`,\n\t\t\t\t{ executable: this.#options.executable, magic: magic32 },\n\t\t\t)\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// PE Injection\n\t// =========================================================================\n\t//\n\t// Strategy: parse the existing PE structure, gather all current resource\n\t// entries (preserving icons, manifests, version info), build a new .rsrc\n\t// section that includes the existing resources plus the injected blob,\n\t// append it to the file, add a new section header entry, and update the\n\t// PE headers (resource data directory, SizeOfImage, NumberOfSections).\n\t//\n\t// The blob data is streamed from disk — never held in memory.\n\n\t#injectPe(): number {\n\t\tconst fd = openSync(this.#options.executable, 'r+')\n\t\ttry {\n\t\t\t// --- Parse PE headers ---\n\t\t\tconst peOffset = this.#readU32(fd, 0x3c)\n\t\t\tconst sig = this.#readU32(fd, peOffset)\n\t\t\tif (sig !== PE_SIGNATURE) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Invalid PE signature', {\n\t\t\t\t\texecutable: this.#options.executable,\n\t\t\t\t\tsignature: sig,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst coffOffset = peOffset + 4\n\t\t\tconst numberOfSections = this.#readU16(fd, coffOffset + 2)\n\t\t\tconst optionalHeaderSize = this.#readU16(fd, coffOffset + 16)\n\t\t\tconst optionalOffset = coffOffset + 20\n\n\t\t\tconst optMagic = this.#readU16(fd, optionalOffset)\n\t\t\tconst is64 = optMagic === PE32_PLUS_MAGIC\n\t\t\tif (optMagic !== PE32_MAGIC && optMagic !== PE32_PLUS_MAGIC) {\n\t\t\t\tthrow new SEAError(\n\t\t\t\t\t'FORMAT',\n\t\t\t\t\t`Unsupported PE optional header magic: 0x${optMagic.toString(16)}`,\n\t\t\t\t\t{ executable: this.#options.executable, optionalHeaderMagic: optMagic },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst sectionAlignment = this.#readU32(fd, optionalOffset + 32)\n\t\t\tconst fileAlignment = this.#readU32(fd, optionalOffset + 36)\n\t\t\tthis.#ensureValidPEAlignment(sectionAlignment, fileAlignment)\n\n\t\t\t// SizeOfImage offset: same in PE32 and PE32+\n\t\t\tconst sizeOfImageOffset = optionalOffset + 56\n\n\t\t\t// Data directory starts after the fixed optional header fields\n\t\t\t// PE32: 96 bytes fixed + data dirs; PE32+: 112 bytes fixed + data dirs\n\t\t\tconst dataDirOffset = optionalOffset + (is64 ? 112 : 96)\n\n\t\t\t// Resource table is data directory entry index 2\n\t\t\tconst resourceDirRvaOffset = dataDirOffset + 2 * 8\n\t\t\tconst resourceDirSizeOffset = resourceDirRvaOffset + 4\n\t\t\tconst existingResourceRva = this.#readU32(fd, resourceDirRvaOffset)\n\n\t\t\t// --- Parse section table ---\n\t\t\tconst sectionTableOffset = optionalOffset + optionalHeaderSize\n\n\t\t\t// Collect all sections and find the resource section\n\t\t\tconst sections: Array<{\n\t\t\t\tname: string\n\t\t\t\tvirtualSize: number\n\t\t\t\tvirtualAddress: number\n\t\t\t\trawSize: number\n\t\t\t\trawOffset: number\n\t\t\t\tcharacteristics: number\n\t\t\t\theaderOffset: number\n\t\t\t}> = []\n\n\t\t\tlet rsrcSectionIndex = -1\n\n\t\t\tfor (let i = 0; i < numberOfSections; i++) {\n\t\t\t\tconst off = sectionTableOffset + i * PE_SECTION_HEADER_SIZE\n\t\t\t\tconst nameBuf = Buffer.alloc(8)\n\t\t\t\treadSync(fd, nameBuf, 0, 8, off)\n\t\t\t\tconst name = this.#stripTrailingNulls(nameBuf.toString('ascii'))\n\t\t\t\tconst virtualSize = this.#readU32(fd, off + 8)\n\t\t\t\tconst virtualAddress = this.#readU32(fd, off + 12)\n\t\t\t\tconst rawSize = this.#readU32(fd, off + 16)\n\t\t\t\tconst rawOffset = this.#readU32(fd, off + 20)\n\t\t\t\tconst characteristics = this.#readU32(fd, off + 36)\n\n\t\t\t\tsections.push({\n\t\t\t\t\tname,\n\t\t\t\t\tvirtualSize,\n\t\t\t\t\tvirtualAddress,\n\t\t\t\t\trawSize,\n\t\t\t\t\trawOffset,\n\t\t\t\t\tcharacteristics,\n\t\t\t\t\theaderOffset: off,\n\t\t\t\t})\n\n\t\t\t\tif (\n\t\t\t\t\texistingResourceRva >= virtualAddress &&\n\t\t\t\t\texistingResourceRva < virtualAddress + Math.max(virtualSize, rawSize)\n\t\t\t\t) {\n\t\t\t\t\trsrcSectionIndex = i\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// --- Check space for a new section header entry ---\n\t\t\tconst sectionTableEnd = sectionTableOffset + numberOfSections * PE_SECTION_HEADER_SIZE\n\t\t\tconst firstSectionFileOffset = sections.reduce(\n\t\t\t\t(min, s) => (s.rawOffset > 0 && s.rawOffset < min ? s.rawOffset : min),\n\t\t\t\tInfinity,\n\t\t\t)\n\t\t\tconst availableHeaderSpace = firstSectionFileOffset - sectionTableEnd\n\t\t\tif (availableHeaderSpace < PE_SECTION_HEADER_SIZE) {\n\t\t\t\tthrow new SEAError(\n\t\t\t\t\t'INJECT',\n\t\t\t\t\t'No room in PE header for a new section entry ' +\n\t\t\t\t\t\t`(${String(availableHeaderSpace)} bytes available, need ${String(PE_SECTION_HEADER_SIZE)})`,\n\t\t\t\t\t{\n\t\t\t\t\t\texecutable: this.#options.executable,\n\t\t\t\t\t\tavailableHeaderSpace,\n\t\t\t\t\t\trequiredHeaderSpace: PE_SECTION_HEADER_SIZE,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// --- Gather existing resource leaves ---\n\t\t\tconst existingLeaves: Array<{\n\t\t\t\ttypeId: number\n\t\t\t\ttypeName: string | undefined\n\t\t\t\tnameId: number\n\t\t\t\tnameName: string | undefined\n\t\t\t\tlanguage: number\n\t\t\t\tcodePage: number\n\t\t\t\tdataRva: number\n\t\t\t\tdataSize: number\n\t\t\t}> = []\n\n\t\t\tif (rsrcSectionIndex !== -1 && existingResourceRva !== 0) {\n\t\t\t\tconst rsrc = sections[rsrcSectionIndex]\n\t\t\t\tif (rsrc !== undefined) {\n\t\t\t\t\tthis.#parseResourceDirectory(\n\t\t\t\t\t\tfd,\n\t\t\t\t\t\trsrc.rawOffset,\n\t\t\t\t\t\texistingResourceRva,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\texistingLeaves,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// --- Remove old blob entry if overwriting ---\n\t\t\tconst overwrite = this.#options.overwrite !== false\n\t\t\tconst upperName = this.#options.resource.toUpperCase()\n\t\t\tconst filteredLeaves = existingLeaves.filter((leaf) => {\n\t\t\t\tif (!overwrite) return true\n\t\t\t\tif (leaf.typeId !== PE_RT_RCDATA) return true\n\t\t\t\treturn leaf.nameName?.toUpperCase() !== upperName\n\t\t\t})\n\n\t\t\t// --- Read existing resource data ---\n\t\t\t// For each existing leaf, read its data from the original file\n\t\t\tconst leafDataMap = new Map<number, Buffer>()\n\t\t\tfor (let i = 0; i < filteredLeaves.length; i++) {\n\t\t\t\tconst leaf = filteredLeaves[i]\n\t\t\t\tif (leaf === undefined) continue\n\t\t\t\t// Convert data RVA to file offset\n\t\t\t\tconst fileOffset = this.#rvaToFileOffset(leaf.dataRva, sections)\n\t\t\t\tif (fileOffset >= 0) {\n\t\t\t\t\tconst buf = Buffer.alloc(leaf.dataSize)\n\t\t\t\t\treadSync(fd, buf, 0, leaf.dataSize, fileOffset)\n\t\t\t\t\tleafDataMap.set(i, buf)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// --- Build new resource section ---\n\t\t\tconst blobSize = statSync(this.#options.blob).size\n\n\t\t\t// Build resource tree: group by type → name → language\n\t\t\tconst tree = this.#buildResourceTree(filteredLeaves, upperName, blobSize)\n\n\t\t\t// Serialize the resource directory + data entries (without blob data)\n\t\t\tconst { directoryBuffer, dataRegionSize } = this.#serializeResourceTree(\n\t\t\t\ttree,\n\t\t\t\tleafDataMap,\n\t\t\t\tblobSize,\n\t\t\t)\n\n\t\t\t// Total section raw size = directory + data region (existing data + blob)\n\t\t\tconst totalRawSize = directoryBuffer.length + dataRegionSize\n\t\t\tconst alignedRawSize = this.#align(totalRawSize, fileAlignment)\n\n\t\t\t// --- Determine new section placement ---\n\t\t\t// Virtual address: highest VA end of all sections, aligned\n\t\t\tlet highestVaEnd = 0\n\t\t\tfor (const s of sections) {\n\t\t\t\tconst end = s.virtualAddress + Math.max(s.virtualSize, s.rawSize)\n\t\t\t\tif (end > highestVaEnd) highestVaEnd = end\n\t\t\t}\n\t\t\tconst newVa = this.#align(highestVaEnd, sectionAlignment)\n\t\t\tconst newVirtualSize = totalRawSize\n\n\t\t\t// File offset: end of file, aligned\n\t\t\tconst fileSize = statSync(this.#options.executable).size\n\t\t\tconst newRawOffset = this.#align(fileSize, fileAlignment)\n\n\t\t\t// --- Write new section header ---\n\t\t\tconst newHeaderOffset = sectionTableEnd\n\t\t\tconst headerBuf = Buffer.alloc(PE_SECTION_HEADER_SIZE)\n\n\t\t\t// Section name: .rsrc2 (avoids confusion with existing .rsrc)\n\t\t\theaderBuf.write('.rsrc2', 0, 6, 'ascii')\n\t\t\theaderBuf.writeUInt32LE(newVirtualSize, 8) // VirtualSize\n\t\t\theaderBuf.writeUInt32LE(newVa, 12) // VirtualAddress\n\t\t\theaderBuf.writeUInt32LE(alignedRawSize, 16) // SizeOfRawData\n\t\t\theaderBuf.writeUInt32LE(newRawOffset, 20) // PointerToRawData\n\t\t\theaderBuf.writeUInt32LE(0, 24) // PointerToRelocations\n\t\t\theaderBuf.writeUInt32LE(0, 28) // PointerToLinenumbers\n\t\t\theaderBuf.writeUInt16LE(0, 32) // NumberOfRelocations\n\t\t\theaderBuf.writeUInt16LE(0, 34) // NumberOfLinenumbers\n\t\t\theaderBuf.writeUInt32LE(PE_SCN_INITIALIZED_DATA | PE_SCN_MEM_READ, 36) // Characteristics\n\n\t\t\twriteSync(fd, headerBuf, 0, PE_SECTION_HEADER_SIZE, newHeaderOffset)\n\n\t\t\t// --- Update PE headers ---\n\t\t\t// NumberOfSections\n\t\t\tthis.#writeU16(fd, coffOffset + 2, numberOfSections + 1)\n\n\t\t\t// Resource data directory → point to new section\n\t\t\tthis.#writeU32(fd, resourceDirRvaOffset, newVa)\n\t\t\tthis.#writeU32(fd, resourceDirSizeOffset, directoryBuffer.length)\n\n\t\t\t// SizeOfImage — must cover the new section\n\t\t\tconst newSizeOfImage = this.#align(\n\t\t\t\tnewVa + Math.max(newVirtualSize, alignedRawSize),\n\t\t\t\tsectionAlignment,\n\t\t\t)\n\t\t\tthis.#writeU32(fd, sizeOfImageOffset, newSizeOfImage)\n\n\t\t\tcloseSync(fd)\n\n\t\t\t// --- Write new section data to file ---\n\t\t\t// Pad file to aligned offset\n\t\t\tconst currentFileSize = statSync(this.#options.executable).size\n\t\t\tif (newRawOffset > currentFileSize) {\n\t\t\t\tconst padding = Buffer.alloc(newRawOffset - currentFileSize)\n\t\t\t\tappendFileSync(this.#options.executable, padding)\n\t\t\t}\n\n\t\t\t// Fixup RVAs in the directory buffer: add newVa as base\n\t\t\tthis.#fixupDirectoryRvas(directoryBuffer, newVa)\n\n\t\t\t// Write the directory buffer\n\t\t\tappendFileSync(this.#options.executable, directoryBuffer)\n\n\t\t\t// Write existing resource data\n\t\t\tfor (let i = 0; i < filteredLeaves.length; i++) {\n\t\t\t\tconst data = leafDataMap.get(i)\n\t\t\t\tif (data !== undefined) {\n\t\t\t\t\tappendFileSync(this.#options.executable, data)\n\t\t\t\t\t// Pad to DWORD alignment\n\t\t\t\t\tconst padLen = this.#align(data.length, 4) - data.length\n\t\t\t\t\tif (padLen > 0) {\n\t\t\t\t\t\tappendFileSync(this.#options.executable, Buffer.alloc(padLen))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Stream the blob from disk\n\t\t\tthis.#appendFile(this.#options.executable, this.#options.blob)\n\n\t\t\t// Pad the section to aligned raw size\n\t\t\tconst writtenSize = statSync(this.#options.executable).size - newRawOffset\n\t\t\tif (writtenSize < alignedRawSize) {\n\t\t\t\tappendFileSync(this.#options.executable, Buffer.alloc(alignedRawSize - writtenSize))\n\t\t\t}\n\n\t\t\t// The checksum is recomputed by the caller (inject()) AFTER the\n\t\t\t// sentinel-fuse byte flip, so it covers every prior header/section\n\t\t\t// change plus the fuse mutation. Return the offset for that call.\n\t\t\treturn optionalOffset\n\t\t} catch (error: unknown) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd)\n\t\t\t} catch {\n\t\t\t\t/* already closed */\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t// --- PE: parse resource directory tree recursively ---\n\n\t#parseResourceDirectory(\n\t\tfd: number,\n\t\tsectionFileOffset: number,\n\t\tsectionRva: number,\n\t\tdirOffset: number,\n\t\tleaves: Array<{\n\t\t\ttypeId: number\n\t\t\ttypeName: string | undefined\n\t\t\tnameId: number\n\t\t\tnameName: string | undefined\n\t\t\tlanguage: number\n\t\t\tcodePage: number\n\t\t\tdataRva: number\n\t\t\tdataSize: number\n\t\t}>,\n\t\tdepth: number,\n\t\tcurrentTypeId: number,\n\t\tcurrentTypeName: string | undefined,\n\t\tcurrentNameId: number,\n\t\tcurrentNameName: string | undefined,\n\t): void {\n\t\tconst absOffset = sectionFileOffset + dirOffset\n\n\t\t// IMAGE_RESOURCE_DIRECTORY: 16 bytes\n\t\tconst numNamedEntries = this.#readU16(fd, absOffset + 12)\n\t\tconst numIdEntries = this.#readU16(fd, absOffset + 14)\n\t\tconst totalEntries = numNamedEntries + numIdEntries\n\n\t\tfor (let i = 0; i < totalEntries; i++) {\n\t\t\tconst entryOffset = absOffset + PE_RESOURCE_DIR_SIZE + i * PE_RESOURCE_ENTRY_SIZE\n\t\t\tconst nameOrId = this.#readU32(fd, entryOffset)\n\t\t\tconst offsetOrData = this.#readU32(fd, entryOffset + 4)\n\n\t\t\t// Resolve name or ID\n\t\t\tlet entryId = 0\n\t\t\tlet entryName: string | undefined\n\n\t\t\tif ((nameOrId & PE_RESOURCE_NAME_FLAG) !== 0) {\n\t\t\t\t// Named entry — offset to IMAGE_RESOURCE_DIR_STRING_U\n\t\t\t\tconst stringOffset = nameOrId & ~PE_RESOURCE_NAME_FLAG\n\t\t\t\tentryName = this.#readResourceString(fd, sectionFileOffset + stringOffset)\n\t\t\t} else {\n\t\t\t\tentryId = nameOrId\n\t\t\t}\n\n\t\t\t// Track current type/name based on depth\n\t\t\tlet typeId = currentTypeId\n\t\t\tlet typeName = currentTypeName\n\t\t\tlet nameId = currentNameId\n\t\t\tlet nameName = currentNameName\n\n\t\t\tif (depth === 0) {\n\t\t\t\ttypeId = entryId\n\t\t\t\ttypeName = entryName\n\t\t\t} else if (depth === 1) {\n\t\t\t\tnameId = entryId\n\t\t\t\tnameName = entryName\n\t\t\t}\n\n\t\t\tif ((offsetOrData & PE_RESOURCE_SUBDIR_FLAG) !== 0) {\n\t\t\t\t// Subdirectory\n\t\t\t\tconst subDirOffset = offsetOrData & ~PE_RESOURCE_SUBDIR_FLAG\n\t\t\t\tthis.#parseResourceDirectory(\n\t\t\t\t\tfd,\n\t\t\t\t\tsectionFileOffset,\n\t\t\t\t\tsectionRva,\n\t\t\t\t\tsubDirOffset,\n\t\t\t\t\tleaves,\n\t\t\t\t\tdepth + 1,\n\t\t\t\t\ttypeId,\n\t\t\t\t\ttypeName,\n\t\t\t\t\tnameId,\n\t\t\t\t\tnameName,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\t// Data entry (leaf)\n\t\t\t\tconst dataEntryFileOffset = sectionFileOffset + offsetOrData\n\t\t\t\tconst dataRva = this.#readU32(fd, dataEntryFileOffset)\n\t\t\t\tconst dataSize = this.#readU32(fd, dataEntryFileOffset + 4)\n\t\t\t\tconst codePage = this.#readU32(fd, dataEntryFileOffset + 8)\n\n\t\t\t\tconst language = depth === 2 ? entryId : 0\n\n\t\t\t\tleaves.push({\n\t\t\t\t\ttypeId,\n\t\t\t\t\ttypeName,\n\t\t\t\t\tnameId,\n\t\t\t\t\tnameName,\n\t\t\t\t\tlanguage,\n\t\t\t\t\tcodePage,\n\t\t\t\t\tdataRva,\n\t\t\t\t\tdataSize,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- PE: read a Unicode resource string ---\n\n\t#readResourceString(fd: number, offset: number): string {\n\t\tconst lenBuf = Buffer.alloc(2)\n\t\treadSync(fd, lenBuf, 0, 2, offset)\n\t\tconst charCount = lenBuf.readUInt16LE(0)\n\t\tif (charCount === 0) return ''\n\t\tconst strBuf = Buffer.alloc(charCount * 2)\n\t\treadSync(fd, strBuf, 0, charCount * 2, offset + 2)\n\t\treturn strBuf.toString('utf16le')\n\t}\n\n\t// --- PE: convert RVA to file offset using section table ---\n\n\t#rvaToFileOffset(\n\t\trva: number,\n\t\tsections: Array<{\n\t\t\tvirtualAddress: number\n\t\t\tvirtualSize: number\n\t\t\trawSize: number\n\t\t\trawOffset: number\n\t\t}>,\n\t): number {\n\t\tfor (const s of sections) {\n\t\t\tconst sectionEnd = s.virtualAddress + Math.max(s.virtualSize, s.rawSize)\n\t\t\tif (rva >= s.virtualAddress && rva < sectionEnd) {\n\t\t\t\treturn rva - s.virtualAddress + s.rawOffset\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\n\t// --- PE: build the resource tree for serialization ---\n\n\t#buildResourceTree(\n\t\texistingLeaves: Array<{\n\t\t\ttypeId: number\n\t\t\ttypeName: string | undefined\n\t\t\tnameId: number\n\t\t\tnameName: string | undefined\n\t\t\tlanguage: number\n\t\t\tcodePage: number\n\t\t\tdataRva: number\n\t\t\tdataSize: number\n\t\t}>,\n\t\tblobName: string,\n\t\tblobSize: number,\n\t): Map<\n\t\tstring,\n\t\tMap<\n\t\t\tstring,\n\t\t\tArray<{\n\t\t\t\tlanguage: number\n\t\t\t\tcodePage: number\n\t\t\t\tleafIndex: number\n\t\t\t\tdataSize: number\n\t\t\t}>\n\t\t>\n\t> {\n\t\t// Tree: typeKey → nameKey → language entries\n\t\t// typeKey/nameKey encode both named and integer IDs\n\t\tconst tree = new Map<\n\t\t\tstring,\n\t\t\tMap<\n\t\t\t\tstring,\n\t\t\t\tArray<{\n\t\t\t\t\tlanguage: number\n\t\t\t\t\tcodePage: number\n\t\t\t\t\tleafIndex: number\n\t\t\t\t\tdataSize: number\n\t\t\t\t}>\n\t\t\t>\n\t\t>()\n\n\t\t// Add existing leaves\n\t\tfor (let i = 0; i < existingLeaves.length; i++) {\n\t\t\tconst leaf = existingLeaves[i]\n\t\t\tif (leaf === undefined) continue\n\t\t\tconst typeKey =\n\t\t\t\tleaf.typeName !== undefined ? `n:${leaf.typeName}` : `i:${String(leaf.typeId)}`\n\t\t\tconst nameKey =\n\t\t\t\tleaf.nameName !== undefined ? `n:${leaf.nameName}` : `i:${String(leaf.nameId)}`\n\n\t\t\tlet typeMap = tree.get(typeKey)\n\t\t\tif (typeMap === undefined) {\n\t\t\t\ttypeMap = new Map()\n\t\t\t\ttree.set(typeKey, typeMap)\n\t\t\t}\n\t\t\tlet langArr = typeMap.get(nameKey)\n\t\t\tif (langArr === undefined) {\n\t\t\t\tlangArr = []\n\t\t\t\ttypeMap.set(nameKey, langArr)\n\t\t\t}\n\t\t\tlangArr.push({\n\t\t\t\tlanguage: leaf.language,\n\t\t\t\tcodePage: leaf.codePage,\n\t\t\t\tleafIndex: i,\n\t\t\t\tdataSize: leaf.dataSize,\n\t\t\t})\n\t\t}\n\n\t\t// Add the new blob entry\n\t\tconst blobTypeKey = `i:${String(PE_RT_RCDATA)}`\n\t\tconst blobNameKey = `n:${blobName}`\n\n\t\tlet typeMap = tree.get(blobTypeKey)\n\t\tif (typeMap === undefined) {\n\t\t\ttypeMap = new Map()\n\t\t\ttree.set(blobTypeKey, typeMap)\n\t\t}\n\t\ttypeMap.set(blobNameKey, [\n\t\t\t{\n\t\t\t\tlanguage: 0,\n\t\t\t\tcodePage: 0,\n\t\t\t\tleafIndex: -1, // -1 signals \"this is the blob\"\n\t\t\t\tdataSize: blobSize,\n\t\t\t},\n\t\t])\n\n\t\treturn tree\n\t}\n\n\t// --- PE: serialize the resource tree into a buffer ---\n\n\t#serializeResourceTree(\n\t\ttree: Map<\n\t\t\tstring,\n\t\t\tMap<\n\t\t\t\tstring,\n\t\t\t\tArray<{\n\t\t\t\t\tlanguage: number\n\t\t\t\t\tcodePage: number\n\t\t\t\t\tleafIndex: number\n\t\t\t\t\tdataSize: number\n\t\t\t\t}>\n\t\t\t>\n\t\t>,\n\t\tleafDataMap: Map<number, Buffer>,\n\t\tblobSize: number,\n\t): {\n\t\tdirectoryBuffer: Buffer\n\t\tdataRegionSize: number\n\t\tblobDataOffset: number\n\t} {\n\t\t// Phase 1: Calculate sizes\n\t\t// Level 0 (root): 1 directory + entries for each type\n\t\t// Level 1 (per type): 1 directory + entries for each name\n\t\t// Level 2 (per name): 1 directory + entries for each language\n\t\t// Then: all name strings, all data entries\n\n\t\tlet dirTableSize = 0\n\t\tlet stringPoolSize = 0\n\t\tlet dataEntryCount = 0\n\n\t\t// Root directory\n\t\tdirTableSize += PE_RESOURCE_DIR_SIZE + tree.size * PE_RESOURCE_ENTRY_SIZE\n\n\t\tconst allStrings: Array<{ key: string; value: string }> = []\n\t\tconst allLeafEntries: Array<{\n\t\t\tleafIndex: number\n\t\t\tdataSize: number\n\t\t\tcodePage: number\n\t\t}> = []\n\n\t\tfor (const [typeKey, nameMap] of tree) {\n\t\t\t// Type directory\n\t\t\tdirTableSize += PE_RESOURCE_DIR_SIZE + nameMap.size * PE_RESOURCE_ENTRY_SIZE\n\n\t\t\t// Collect type name string if named\n\t\t\tif (typeKey.startsWith('n:')) {\n\t\t\t\tconst str = typeKey.slice(2)\n\t\t\t\tallStrings.push({ key: typeKey, value: str })\n\t\t\t\tstringPoolSize += 2 + str.length * 2 // length (u16) + UTF-16LE chars\n\t\t\t\tstringPoolSize = this.#align(stringPoolSize, 2) // WORD align strings\n\t\t\t}\n\n\t\t\tfor (const [nameKey, langEntries] of nameMap) {\n\t\t\t\t// Name directory\n\t\t\t\tdirTableSize += PE_RESOURCE_DIR_SIZE + langEntries.length * PE_RESOURCE_ENTRY_SIZE\n\n\t\t\t\t// Collect name string if named\n\t\t\t\tif (nameKey.startsWith('n:')) {\n\t\t\t\t\tconst str = nameKey.slice(2)\n\t\t\t\t\tallStrings.push({ key: nameKey, value: str })\n\t\t\t\t\tstringPoolSize += 2 + str.length * 2\n\t\t\t\t\tstringPoolSize = this.#align(stringPoolSize, 2)\n\t\t\t\t}\n\n\t\t\t\tfor (const entry of langEntries) {\n\t\t\t\t\tallLeafEntries.push({\n\t\t\t\t\t\tleafIndex: entry.leafIndex,\n\t\t\t\t\t\tdataSize: entry.dataSize,\n\t\t\t\t\t\tcodePage: entry.codePage,\n\t\t\t\t\t})\n\t\t\t\t\tdataEntryCount++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst dataEntriesSize = dataEntryCount * PE_RESOURCE_DATA_ENTRY_SIZE\n\t\tconst headerSize = dirTableSize + stringPoolSize + dataEntriesSize\n\n\t\t// Phase 2: Calculate data region (existing leaves + blob)\n\t\tlet dataRegionOffset = 0\n\t\tconst leafFileOffsets = new Map<number, number>() // leafIndex → offset within data region\n\n\t\tfor (let i = 0; i < allLeafEntries.length; i++) {\n\t\t\tconst entry = allLeafEntries[i]\n\t\t\tif (entry === undefined) continue\n\t\t\tif (entry.leafIndex === -1) continue // blob handled separately\n\n\t\t\tconst data = leafDataMap.get(entry.leafIndex)\n\t\t\tif (data !== undefined) {\n\t\t\t\tleafFileOffsets.set(entry.leafIndex, dataRegionOffset)\n\t\t\t\tdataRegionOffset += this.#align(data.length, 4)\n\t\t\t}\n\t\t}\n\n\t\tconst blobDataOffset = dataRegionOffset\n\t\tdataRegionOffset += blobSize\n\t\tconst dataRegionSize = dataRegionOffset\n\n\t\t// Phase 3: Build the directory buffer with placeholder RVAs\n\t\t// RVAs will be fixed up later with the actual section VA\n\t\tconst buf = Buffer.alloc(headerSize)\n\t\tlet dirPos = 0\n\t\tlet stringPos = dirTableSize\n\t\tlet dataEntryPos = dirTableSize + stringPoolSize\n\n\t\t// String offset lookup: key → offset within directory buffer\n\t\tconst stringOffsets = new Map<string, number>()\n\t\tfor (const { key, value } of allStrings) {\n\t\t\tstringOffsets.set(key, stringPos)\n\t\t\tbuf.writeUInt16LE(value.length, stringPos)\n\t\t\tbuf.write(value, stringPos + 2, value.length * 2, 'utf16le')\n\t\t\tstringPos += 2 + value.length * 2\n\t\t\tstringPos = this.#align(stringPos, 2)\n\t\t}\n\n\t\t// Sort tree entries: named entries first (sorted by name), then ID entries (sorted by ID)\n\t\tconst sortedTypeKeys = this.#sortResourceKeys([...tree.keys()])\n\n\t\t// Helper to track subdirectory offsets for linking\n\t\tconst nextDirOffset = PE_RESOURCE_DIR_SIZE + tree.size * PE_RESOURCE_ENTRY_SIZE\n\n\t\t// --- Write root directory ---\n\t\tconst namedTypes = sortedTypeKeys.filter((k) => k.startsWith('n:'))\n\t\tconst idTypes = sortedTypeKeys.filter((k) => k.startsWith('i:'))\n\n\t\tbuf.writeUInt32LE(0, dirPos) // Characteristics\n\t\tbuf.writeUInt32LE(0, dirPos + 4) // TimeDateStamp\n\t\tbuf.writeUInt16LE(0, dirPos + 8) // MajorVersion\n\t\tbuf.writeUInt16LE(0, dirPos + 10) // MinorVersion\n\t\tbuf.writeUInt16LE(namedTypes.length, dirPos + 12)\n\t\tbuf.writeUInt16LE(idTypes.length, dirPos + 14)\n\t\tdirPos += PE_RESOURCE_DIR_SIZE\n\n\t\t// Pre-calculate all type subdirectory offsets\n\t\tconst typeDirOffsets = new Map<string, number>()\n\t\tlet accDirOffset = nextDirOffset\n\t\tfor (const typeKey of sortedTypeKeys) {\n\t\t\ttypeDirOffsets.set(typeKey, accDirOffset)\n\t\t\tconst nameMap = tree.get(typeKey)\n\t\t\tif (nameMap === undefined) continue\n\t\t\tconst typeEntryCount = nameMap.size\n\t\t\taccDirOffset += PE_RESOURCE_DIR_SIZE + typeEntryCount * PE_RESOURCE_ENTRY_SIZE\n\t\t\tfor (const [, langEntries] of nameMap) {\n\t\t\t\taccDirOffset += PE_RESOURCE_DIR_SIZE + langEntries.length * PE_RESOURCE_ENTRY_SIZE\n\t\t\t}\n\t\t}\n\n\t\t// Write root entries\n\t\tfor (const typeKey of sortedTypeKeys) {\n\t\t\tconst isNamed = typeKey.startsWith('n:')\n\t\t\tconst nameOrId = isNamed\n\t\t\t\t? (stringOffsets.get(typeKey) ?? 0) | PE_RESOURCE_NAME_FLAG\n\t\t\t\t: parseInt(typeKey.slice(2), 10)\n\t\t\tconst subdirOffset = (typeDirOffsets.get(typeKey) ?? 0) | PE_RESOURCE_SUBDIR_FLAG\n\n\t\t\tbuf.writeUInt32LE(nameOrId >>> 0, dirPos)\n\t\t\tbuf.writeUInt32LE(subdirOffset >>> 0, dirPos + 4)\n\t\t\tdirPos += PE_RESOURCE_ENTRY_SIZE\n\t\t}\n\n\t\t// --- Write type subdirectories ---\n\t\tfor (const typeKey of sortedTypeKeys) {\n\t\t\tconst nameMap = tree.get(typeKey)\n\t\t\tif (nameMap === undefined) continue\n\t\t\tconst sortedNameKeys = this.#sortResourceKeys([...nameMap.keys()])\n\t\t\tconst namedNames = sortedNameKeys.filter((k) => k.startsWith('n:'))\n\t\t\tconst idNames = sortedNameKeys.filter((k) => k.startsWith('i:'))\n\n\t\t\tbuf.writeUInt32LE(0, dirPos)\n\t\t\tbuf.writeUInt32LE(0, dirPos + 4)\n\t\t\tbuf.writeUInt16LE(0, dirPos + 8)\n\t\t\tbuf.writeUInt16LE(0, dirPos + 10)\n\t\t\tbuf.writeUInt16LE(namedNames.length, dirPos + 12)\n\t\t\tbuf.writeUInt16LE(idNames.length, dirPos + 14)\n\t\t\tdirPos += PE_RESOURCE_DIR_SIZE\n\n\t\t\t// Calculate offset of each name's language subdirectory\n\t\t\t// These come sequentially after the current type directory and its entries\n\t\t\tlet langSubdirCursor = dirPos + sortedNameKeys.length * PE_RESOURCE_ENTRY_SIZE\n\n\t\t\tfor (const nameKey of sortedNameKeys) {\n\t\t\t\tconst isNamed = nameKey.startsWith('n:')\n\t\t\t\tconst nameOrId = isNamed\n\t\t\t\t\t? (stringOffsets.get(nameKey) ?? 0) | PE_RESOURCE_NAME_FLAG\n\t\t\t\t\t: parseInt(nameKey.slice(2), 10)\n\n\t\t\t\t// The language subdirectory offset is relative to resource section start\n\t\t\t\tconst langSubDirRelOffset = langSubdirCursor | PE_RESOURCE_SUBDIR_FLAG\n\n\t\t\t\tbuf.writeUInt32LE(nameOrId >>> 0, dirPos)\n\t\t\t\tbuf.writeUInt32LE(langSubDirRelOffset >>> 0, dirPos + 4)\n\t\t\t\tdirPos += PE_RESOURCE_ENTRY_SIZE\n\n\t\t\t\tconst langEntries = nameMap.get(nameKey)\n\t\t\t\tif (langEntries !== undefined) {\n\t\t\t\t\tlangSubdirCursor += PE_RESOURCE_DIR_SIZE + langEntries.length * PE_RESOURCE_ENTRY_SIZE\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Write language subdirectories for each name\n\t\t\tfor (const nameKey of sortedNameKeys) {\n\t\t\t\tconst langEntries = nameMap.get(nameKey)\n\t\t\t\tif (langEntries === undefined) continue\n\n\t\t\t\tbuf.writeUInt32LE(0, dirPos)\n\t\t\t\tbuf.writeUInt32LE(0, dirPos + 4)\n\t\t\t\tbuf.writeUInt16LE(0, dirPos + 8)\n\t\t\t\tbuf.writeUInt16LE(0, dirPos + 10)\n\t\t\t\tbuf.writeUInt16LE(0, dirPos + 12) // no named language entries\n\t\t\t\tbuf.writeUInt16LE(langEntries.length, dirPos + 14)\n\t\t\t\tdirPos += PE_RESOURCE_DIR_SIZE\n\n\t\t\t\tfor (const entry of langEntries) {\n\t\t\t\t\t// Language ID\n\t\t\t\t\tbuf.writeUInt32LE(entry.language, dirPos)\n\n\t\t\t\t\t// Data entry offset (not a subdirectory — no high bit)\n\t\t\t\t\tbuf.writeUInt32LE(dataEntryPos, dirPos + 4)\n\t\t\t\t\tdirPos += PE_RESOURCE_ENTRY_SIZE\n\n\t\t\t\t\t// Write the data entry\n\t\t\t\t\t// DataRVA — placeholder, will be fixed up with actual VA\n\t\t\t\t\tlet dataOffset: number\n\t\t\t\t\tif (entry.leafIndex === -1) {\n\t\t\t\t\t\t// Blob\n\t\t\t\t\t\tdataOffset = headerSize + blobDataOffset\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst resolvedOffset = leafFileOffsets.get(entry.leafIndex)\n\t\t\t\t\t\tif (resolvedOffset === undefined) {\n\t\t\t\t\t\t\tthrow new SEAError('INJECT', 'unresolvable resource RVA', {\n\t\t\t\t\t\t\t\texecutable: this.#options.executable,\n\t\t\t\t\t\t\t\tleafIndex: entry.leafIndex,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdataOffset = headerSize + resolvedOffset\n\t\t\t\t\t}\n\n\t\t\t\t\t// Store as relative offset from section start for now;\n\t\t\t\t\t// #fixupDirectoryRvas will add the section VA\n\t\t\t\t\tbuf.writeUInt32LE(dataOffset, dataEntryPos) // DataRVA (placeholder)\n\t\t\t\t\tbuf.writeUInt32LE(entry.dataSize, dataEntryPos + 4) // Size\n\t\t\t\t\tbuf.writeUInt32LE(entry.codePage, dataEntryPos + 8) // CodePage\n\t\t\t\t\tbuf.writeUInt32LE(0, dataEntryPos + 12) // Reserved\n\t\t\t\t\tdataEntryPos += PE_RESOURCE_DATA_ENTRY_SIZE\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { directoryBuffer: buf, dataRegionSize, blobDataOffset }\n\t}\n\n\t// --- PE: fix up all data entry RVAs by adding the section's virtual address ---\n\n\t#fixupDirectoryRvas(directoryBuffer: Buffer, sectionVa: number): void {\n\t\t// Data entries are at the end of the directory buffer.\n\t\t// Each is 16 bytes: DataRVA(4), Size(4), CodePage(4), Reserved(4)\n\t\t// We need to find them and add sectionVa to the DataRVA field.\n\t\t//\n\t\t// Data entries are pointed to by level-2 directory entries.\n\t\t// Rather than re-walking the tree, we know that data entries are\n\t\t// contiguous at the end of the buffer (before strings, which we\n\t\t// placed between directories and data entries — wait, actually\n\t\t// strings come before data entries in our layout).\n\t\t//\n\t\t// Our layout: [directories] [strings] [data entries]\n\t\t// The data entries all need their first DWORD (DataRVA) adjusted.\n\t\t//\n\t\t// We can find them by scanning for references from directory entries.\n\t\t// But a simpler approach: we marked data entry positions during\n\t\t// serialization. Let's just scan the buffer for data entry blocks.\n\t\t//\n\t\t// Actually the simplest: re-walk the level-2 directory entries to\n\t\t// find the data entry offsets, then fix them up.\n\n\t\tthis.#fixupDataEntries(directoryBuffer, 0, 0, sectionVa)\n\t}\n\n\t#fixupDataEntries(buf: Buffer, dirOffset: number, depth: number, sectionVa: number): void {\n\t\tif (dirOffset + PE_RESOURCE_DIR_SIZE > buf.length) return\n\n\t\tconst namedCount = buf.readUInt16LE(dirOffset + 12)\n\t\tconst idCount = buf.readUInt16LE(dirOffset + 14)\n\t\tconst totalEntries = namedCount + idCount\n\n\t\tfor (let i = 0; i < totalEntries; i++) {\n\t\t\tconst entryOffset = dirOffset + PE_RESOURCE_DIR_SIZE + i * PE_RESOURCE_ENTRY_SIZE\n\t\t\tif (entryOffset + PE_RESOURCE_ENTRY_SIZE > buf.length) return\n\n\t\t\tconst offsetOrData = buf.readUInt32LE(entryOffset + 4)\n\n\t\t\tif ((offsetOrData & PE_RESOURCE_SUBDIR_FLAG) !== 0) {\n\t\t\t\t// Subdirectory — recurse\n\t\t\t\tconst subOffset = offsetOrData & ~PE_RESOURCE_SUBDIR_FLAG\n\t\t\t\tthis.#fixupDataEntries(buf, subOffset, depth + 1, sectionVa)\n\t\t\t} else {\n\t\t\t\t// Data entry — fix up the RVA\n\t\t\t\tif (offsetOrData + 4 <= buf.length) {\n\t\t\t\t\tconst currentRva = buf.readUInt32LE(offsetOrData)\n\t\t\t\t\tbuf.writeUInt32LE((currentRva + sectionVa) >>> 0, offsetOrData)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- PE: recompute and write the OptionalHeader.CheckSum ---\n\t//\n\t// The classic Windows IMAGE checksum: sum the whole file as little-endian\n\t// 16-bit words (the existing checksum's 4 bytes treated as zero), fold\n\t// carries into a 16-bit accumulator, then add the file length. Streamed in\n\t// chunks (like #appendFile) so a large SEA binary is never fully buffered.\n\n\t#patchChecksum(optionalOffset: number): void {\n\t\tconst checksumOffset = optionalOffset + 64\n\t\tconst fd = openSync(this.#options.executable, 'r+')\n\t\ttry {\n\t\t\tconst fileSize = statSync(this.#options.executable).size\n\t\t\tconst chunkSize = 4 * 1024 * 1024\n\t\t\tconst chunk = Buffer.alloc(Math.min(chunkSize, fileSize))\n\n\t\t\tlet sum = 0\n\t\t\tlet offset = 0\n\t\t\twhile (offset < fileSize) {\n\t\t\t\tconst toRead = Math.min(chunkSize, fileSize - offset)\n\t\t\t\tconst bytesRead = readSync(fd, chunk, 0, toRead, offset)\n\t\t\t\tif (bytesRead === 0) break\n\n\t\t\t\tfor (let i = 0; i < bytesRead; i += 2) {\n\t\t\t\t\tconst absolute = offset + i\n\t\t\t\t\tlet word: number\n\t\t\t\t\tif (absolute === checksumOffset || absolute === checksumOffset + 2) {\n\t\t\t\t\t\tword = 0\n\t\t\t\t\t} else if (i + 1 < bytesRead) {\n\t\t\t\t\t\tword = chunk.readUInt16LE(i)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tword = chunk.readUInt8(i)\n\t\t\t\t\t}\n\t\t\t\t\tsum += word\n\t\t\t\t\tsum = (sum & 0xffff) + (sum >>> 16)\n\t\t\t\t}\n\n\t\t\t\toffset += bytesRead\n\t\t\t}\n\n\t\t\tsum = (sum & 0xffff) + (sum >>> 16)\n\t\t\tconst checksum = (sum + fileSize) >>> 0\n\n\t\t\tthis.#writeU32(fd, checksumOffset, checksum)\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\t}\n\n\t// --- PE: sort resource keys (named first alphabetically, then IDs numerically) ---\n\n\t#sortResourceKeys(keys: string[]): readonly string[] {\n\t\tconst named = keys\n\t\t\t.filter((k) => k.startsWith('n:'))\n\t\t\t.sort((a, b) => a.slice(2).localeCompare(b.slice(2), 'en', { sensitivity: 'base' }))\n\t\tconst ids = keys\n\t\t\t.filter((k) => k.startsWith('i:'))\n\t\t\t.sort((a, b) => {\n\t\t\t\tconst ia = parseInt(a.slice(2), 10)\n\t\t\t\tconst ib = parseInt(b.slice(2), 10)\n\t\t\t\treturn ia - ib\n\t\t\t})\n\t\treturn [...named, ...ids]\n\t}\n\n\t// =========================================================================\n\t// ELF Injection\n\t// =========================================================================\n\t//\n\t// Strategy: append a PT_NOTE segment to the ELF. The note contains\n\t// the resource name and blob data. We find an existing PT_NOTE in the\n\t// program header table and repurpose it, or find space in the phdr\n\t// table for a new entry.\n\t//\n\t// Node.js SEA on Linux reads PT_NOTE segments via dl_iterate_phdr,\n\t// searching for a note whose name matches the resource name.\n\n\t#injectElf(): void {\n\t\tconst exePath = this.#options.executable\n\t\tconst resource = this.#options.resource\n\t\tconst overwrite = this.#options.overwrite !== false\n\n\t\tconst PT_LOAD = 1\n\t\tconst PT_PHDR = 6\n\t\tconst PF_R = 4\n\t\tconst PAGE = 0x1000\n\n\t\tlet phdrOffset: number\n\t\tlet phdrEntrySize: number\n\t\tlet phdrCount: number\n\t\tlet headers: Array<{\n\t\t\ttype: number\n\t\t\tflags: number\n\t\t\toffset: number\n\t\t\tvaddr: number\n\t\t\tpaddr: number\n\t\t\tfilesz: number\n\t\t\tmemsz: number\n\t\t\talign: number\n\t\t}>\n\n\t\tconst fd = openSync(exePath, 'r')\n\t\ttry {\n\t\t\t// --- Parse ELF header ---\n\t\t\tconst identBuf = Buffer.alloc(16)\n\t\t\treadSync(fd, identBuf, 0, 16, 0)\n\n\t\t\tconst elfClass = identBuf.readUInt8(4)\n\t\t\tconst elfData = identBuf.readUInt8(5)\n\n\t\t\tif (elfClass !== ELF_CLASS_64) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Only 64-bit ELF executables are supported', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\telfClass,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (elfData !== ELF_DATA_LSB) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Only little-endian ELF executables are supported', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\telfData,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tphdrOffset = Number(this.#readU64(fd, 32)) // e_phoff\n\t\t\tphdrEntrySize = this.#readU16(fd, 54) // e_phentsize\n\t\t\tphdrCount = this.#readU16(fd, 56) // e_phnum\n\n\t\t\theaders = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount)\n\n\t\t\t// Neutralize any stale PT_NOTE with a matching name so overwrite\n\t\t\t// never leaves two competing \"NODE_SEA*\" notes visible to\n\t\t\t// postject_find_resource — runtime skips any non-PT_NOTE entry.\n\t\t\tfor (const header of headers) {\n\t\t\t\tif (header.type !== ELF_PT_NOTE) continue\n\t\t\t\tconst existingName = this.#readElfNoteName(fd, header.offset, header.filesz)\n\t\t\t\tif (existingName === undefined || !existingName.startsWith('NODE_SEA')) continue\n\t\t\t\tif (!overwrite) {\n\t\t\t\t\tthrow new SEAError('INJECT', `Note with name \"${resource}\" already exists`, {\n\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t\tresource,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\theader.type = 0 // PT_NULL\n\t\t\t}\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\n\t\t// --- Compute the new PT_LOAD/PT_NOTE placement ---\n\t\t// The note MUST live inside a PT_LOAD so the runtime's dl_iterate_phdr\n\t\t// walk can read it from the mapped virtual address (Node reads\n\t\t// NODE_SEA notes from memory, never from the file).\n\t\tlet maxVaddrEnd = 0\n\t\tfor (const header of headers) {\n\t\t\tif (header.type !== PT_LOAD) continue\n\t\t\tconst end = header.vaddr + header.memsz\n\t\t\tif (end > maxVaddrEnd) maxVaddrEnd = end\n\t\t}\n\t\tconst regionVaddr = this.#align(maxVaddrEnd, PAGE)\n\n\t\tconst blobSize = statSync(this.#options.blob).size\n\t\tconst { header: noteHeader, entryTotal: noteEntryTotal } = buildELFNoteHeader(\n\t\t\tresource,\n\t\t\tblobSize,\n\t\t)\n\t\tconst noteAreaSize = this.#align(noteEntryTotal, 8)\n\n\t\tconst newEntryCount = headers.length + 2\n\t\tconst phtSize = newEntryCount * phdrEntrySize\n\t\tconst regionSize = noteAreaSize + phtSize\n\n\t\tconst fileSize = statSync(exePath).size\n\t\tconst regionStart = this.#align(fileSize, PAGE)\n\t\tconst phtOff = regionStart + noteAreaSize\n\n\t\tconst newLoad = {\n\t\t\ttype: PT_LOAD,\n\t\t\tflags: PF_R,\n\t\t\toffset: regionStart,\n\t\t\tvaddr: regionVaddr,\n\t\t\tpaddr: regionVaddr,\n\t\t\tfilesz: regionSize,\n\t\t\tmemsz: regionSize,\n\t\t\talign: PAGE,\n\t\t}\n\t\tconst newNote = {\n\t\t\ttype: ELF_PT_NOTE,\n\t\t\tflags: PF_R,\n\t\t\toffset: regionStart,\n\t\t\tvaddr: regionVaddr,\n\t\t\tpaddr: regionVaddr,\n\t\t\tfilesz: noteEntryTotal,\n\t\t\tmemsz: noteEntryTotal,\n\t\t\talign: 4,\n\t\t}\n\n\t\t// Relocate PT_PHDR (if present) to point at the enlarged table, which\n\t\t// itself lives inside the new PT_LOAD right after the note — keeping\n\t\t// PT_PHDR's p_vaddr congruent with its covering segment. This relies on\n\t\t// a modern-kernel loader that computes AT_PHDR from the PT_LOAD\n\t\t// covering e_phoff (Linux ~5.x+ / the Node>=24 target); a pre-5.x\n\t\t// kernel that instead computes AT_PHDR = load_addr + e_phoff would\n\t\t// derive a wrong value here since the PHT no longer sits at its\n\t\t// original load-relative offset.\n\t\tconst finalHeaders = headers.map((header) => {\n\t\t\tif (header.type !== PT_PHDR) return header\n\t\t\tconst relVaddr = regionVaddr + (phtOff - regionStart)\n\t\t\treturn {\n\t\t\t\t...header,\n\t\t\t\toffset: phtOff,\n\t\t\t\tvaddr: relVaddr,\n\t\t\t\tpaddr: relVaddr,\n\t\t\t\tfilesz: phtSize,\n\t\t\t\tmemsz: phtSize,\n\t\t\t}\n\t\t})\n\t\tfinalHeaders.push(newLoad, newNote)\n\n\t\tconst phtBuffer = Buffer.alloc(phtSize)\n\t\tfor (let i = 0; i < finalHeaders.length; i++) {\n\t\t\tconst entry = finalHeaders[i]\n\t\t\tif (entry === undefined) continue\n\t\t\tthis.#writeElfProgramHeaderEntry(phtBuffer, i * phdrEntrySize, entry)\n\t\t}\n\n\t\t// --- Append the new region: note header + streamed blob + padding + PHT ---\n\t\tif (regionStart > fileSize) {\n\t\t\tappendFileSync(exePath, Buffer.alloc(regionStart - fileSize))\n\t\t}\n\t\tappendFileSync(exePath, noteHeader)\n\t\tthis.#appendFile(exePath, this.#options.blob)\n\n\t\tconst alignedDescSize = this.#align(blobSize, 4)\n\t\tconst descPadding = alignedDescSize - blobSize\n\t\tif (descPadding > 0) {\n\t\t\tappendFileSync(exePath, Buffer.alloc(descPadding))\n\t\t}\n\n\t\tconst trailingPad = noteAreaSize - noteEntryTotal\n\t\tif (trailingPad > 0) {\n\t\t\tappendFileSync(exePath, Buffer.alloc(trailingPad))\n\t\t}\n\n\t\tappendFileSync(exePath, phtBuffer)\n\n\t\t// --- Point the ELF header at the relocated, enlarged PHT ---\n\t\tconst fd2 = openSync(exePath, 'r+')\n\t\ttry {\n\t\t\tthis.#writeU64(fd2, 32, BigInt(phtOff))\n\t\t\tthis.#writeU16(fd2, 56, newEntryCount)\n\n\t\t\t// Build-time readback: locate the note the SAME way the runtime\n\t\t\t// does (a PT_NOTE inside a PT_LOAD, address-congruent with its\n\t\t\t// file offset) so a passing readback reflects runtime success.\n\t\t\tthis.#verifyElfNoteMapping(fd2, phtOff, newEntryCount, phdrEntrySize)\n\t\t} finally {\n\t\t\tcloseSync(fd2)\n\t\t}\n\t}\n\n\t// --- ELF: read all program header entries into memory ---\n\n\t#readElfProgramHeaders(\n\t\tfd: number,\n\t\tphdrOffset: number,\n\t\tentrySize: number,\n\t\tcount: number,\n\t): Array<{\n\t\ttype: number\n\t\tflags: number\n\t\toffset: number\n\t\tvaddr: number\n\t\tpaddr: number\n\t\tfilesz: number\n\t\tmemsz: number\n\t\talign: number\n\t}> {\n\t\tconst headers: Array<{\n\t\t\ttype: number\n\t\t\tflags: number\n\t\t\toffset: number\n\t\t\tvaddr: number\n\t\t\tpaddr: number\n\t\t\tfilesz: number\n\t\t\tmemsz: number\n\t\t\talign: number\n\t\t}> = []\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst off = phdrOffset + i * entrySize\n\t\t\theaders.push({\n\t\t\t\ttype: this.#readU32(fd, off),\n\t\t\t\tflags: this.#readU32(fd, off + 4),\n\t\t\t\toffset: Number(this.#readU64(fd, off + 8)),\n\t\t\t\tvaddr: Number(this.#readU64(fd, off + 16)),\n\t\t\t\tpaddr: Number(this.#readU64(fd, off + 24)),\n\t\t\t\tfilesz: Number(this.#readU64(fd, off + 32)),\n\t\t\t\tmemsz: Number(this.#readU64(fd, off + 40)),\n\t\t\t\talign: Number(this.#readU64(fd, off + 48)),\n\t\t\t})\n\t\t}\n\t\treturn headers\n\t}\n\n\t// --- ELF: serialize a single program header entry (56 bytes, ELF64) ---\n\n\t#writeElfProgramHeaderEntry(\n\t\tbuf: Buffer,\n\t\tpos: number,\n\t\tentry: {\n\t\t\ttype: number\n\t\t\tflags: number\n\t\t\toffset: number\n\t\t\tvaddr: number\n\t\t\tpaddr: number\n\t\t\tfilesz: number\n\t\t\tmemsz: number\n\t\t\talign: number\n\t\t},\n\t): void {\n\t\tbuf.writeUInt32LE(entry.type >>> 0, pos)\n\t\tbuf.writeUInt32LE(entry.flags >>> 0, pos + 4)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.offset), pos + 8)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.vaddr), pos + 16)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.paddr), pos + 24)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.filesz), pos + 32)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.memsz), pos + 40)\n\t\tbuf.writeBigUInt64LE(BigInt(entry.align), pos + 48)\n\t}\n\n\t// --- ELF: read a note's name at a given file offset (bounds-checked) ---\n\n\t#readElfNoteName(fd: number, offset: number, size: number): string | undefined {\n\t\tif (size < 12) return undefined\n\t\tconst namesz = this.#readU32(fd, offset)\n\t\tconst descsz = this.#readU32(fd, offset + 4)\n\t\tif (namesz === 0 || namesz > 256) return undefined\n\t\tif (12 + this.#align(namesz, 4) + this.#align(descsz, 4) > size) return undefined\n\n\t\tconst nameBuf = Buffer.alloc(namesz)\n\t\treadSync(fd, nameBuf, 0, namesz, offset + 12)\n\t\treturn this.#stripTrailingNulls(nameBuf.toString('utf-8'))\n\t}\n\n\t// --- ELF: build-time readback — confirm the note is runtime-reachable ---\n\n\t#verifyElfNoteMapping(\n\t\tfd: number,\n\t\tphdrOffset: number,\n\t\tphdrCount: number,\n\t\tphdrEntrySize: number,\n\t): void {\n\t\tconst headers = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount)\n\t\tconst loads = headers.filter((h) => h.type === 1)\n\t\tconst notes = headers.filter((h) => h.type === ELF_PT_NOTE)\n\n\t\tfor (const note of notes) {\n\t\t\tconst name = this.#readElfNoteName(fd, note.offset, note.filesz)\n\t\t\tif (name === undefined || !name.startsWith('NODE_SEA')) continue\n\n\t\t\tconst covering = loads.find(\n\t\t\t\t(load) => note.offset >= load.offset && note.offset < load.offset + load.filesz,\n\t\t\t)\n\t\t\tif (covering === undefined) continue\n\n\t\t\tconst expectedVaddr = covering.vaddr + (note.offset - covering.offset)\n\t\t\tif (expectedVaddr === note.vaddr) return\n\t\t}\n\n\t\tthrow new SEAError(\n\t\t\t'INJECT',\n\t\t\t'Injected ELF note is not reachable via a mapped PT_LOAD segment at runtime',\n\t\t\t{ executable: this.#options.executable, resource: this.#options.resource },\n\t\t)\n\t}\n\n\t// =========================================================================\n\t// Mach-O Injection\n\t// =========================================================================\n\t//\n\t// Strategy: append an LC_SEGMENT_64 load command with a single section\n\t// containing the blob data. The segment is placed at the next available\n\t// file offset and virtual address.\n\t//\n\t// Node.js SEA on macOS uses getsectdata(segment, section) to find the\n\t// blob. The segment defaults to \"__POSTJECT\" (or custom via options)\n\t// and the section is \"__\" + resource.\n\n\t#injectMacho(): void {\n\t\tconst exePath = this.#options.executable\n\t\tconst fileSize = statSync(exePath).size\n\t\tlet srcFd: number | undefined = openSync(exePath, 'r')\n\t\tlet destFd: number | undefined\n\t\tlet blobFd: number | undefined\n\t\tlet injTemp: string | undefined\n\n\t\ttry {\n\t\t\t// --- Bounded header read: just enough to cover every header/LC parse\n\t\t\t// and mutation below (headerSize + sizeofcmds) — never the whole file. ---\n\t\t\tconst headerSize = 32 // Mach-O 64-bit header\n\t\t\tconst preHeader = Buffer.alloc(headerSize)\n\t\t\treadSync(srcFd, preHeader, 0, headerSize, 0)\n\t\t\tconst preSizeofcmds = preHeader.readUInt32LE(20)\n\t\t\tif (headerSize + preSizeofcmds > fileSize) {\n\t\t\t\tthrow new SEAError('FORMAT', 'Mach-O load command region exceeds file size', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\theaderSize,\n\t\t\t\t\tsizeofcmds: preSizeofcmds,\n\t\t\t\t\tfileSize,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst buf = Buffer.alloc(headerSize + preSizeofcmds)\n\t\t\treadSync(srcFd, buf, 0, headerSize + preSizeofcmds, 0)\n\n\t\t\t// --- Parse Mach-O header ---\n\t\t\tconst magic = buf.readUInt32LE(0)\n\t\t\tif (magic !== MACHO_MAGIC_64) {\n\t\t\t\tthrow new SEAError('FORMAT', `Unsupported Mach-O magic: 0x${magic.toString(16)}`, {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\tmagic,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst cputype = buf.readUInt32LE(4)\n\t\t\tconst ncmds = buf.readUInt32LE(16)\n\t\t\tconst sizeofcmds = buf.readUInt32LE(20)\n\n\t\t\tconst segmentName = this.#options.macho?.segment ?? 'NODE_SEA'\n\t\t\tlet sectionName = this.#options.resource\n\t\t\tif (!sectionName.startsWith('__')) {\n\t\t\t\tsectionName = `__${sectionName}`\n\t\t\t}\n\n\t\t\t// --- Walk load commands once, collecting their bounds ---\n\t\t\tconst commands: Array<{ type: number; size: number; offset: number }> = []\n\t\t\tlet cmdOffset = headerSize\n\t\t\tfor (let i = 0; i < ncmds; i++) {\n\t\t\t\tif (cmdOffset + 8 > buf.length) {\n\t\t\t\t\tthrow new SEAError('FORMAT', 'Malformed Mach-O load command table', {\n\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst cmdType = buf.readUInt32LE(cmdOffset)\n\t\t\t\tconst cmdSize = buf.readUInt32LE(cmdOffset + 4)\n\t\t\t\tif (cmdSize < 8 || cmdOffset + cmdSize > buf.length) {\n\t\t\t\t\tthrow new SEAError('FORMAT', 'Malformed Mach-O load command table', {\n\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tcommands.push({ type: cmdType, size: cmdSize, offset: cmdOffset })\n\t\t\t\tcmdOffset += cmdSize\n\t\t\t}\n\n\t\t\tlet linkeditIndex = -1\n\t\t\tconst existingSegmentIndices: number[] = []\n\t\t\tfor (let i = 0; i < commands.length; i++) {\n\t\t\t\tconst cmd = commands[i]\n\t\t\t\tif (cmd === undefined || cmd.type !== MACHO_LC_SEGMENT_64) continue\n\t\t\t\tconst segName = this.#stripTrailingNulls(\n\t\t\t\t\tbuf.subarray(cmd.offset + 8, cmd.offset + 24).toString('ascii'),\n\t\t\t\t)\n\t\t\t\tif (segName === '__LINKEDIT') linkeditIndex = i\n\t\t\t\tif (segName === segmentName) existingSegmentIndices.push(i)\n\t\t\t}\n\n\t\t\tif (existingSegmentIndices.length > 0 && this.#options.overwrite === false) {\n\t\t\t\tthrow new SEAError('INJECT', `Segment \"${segmentName}\" already exists`, {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t\tsegmentName,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst linkeditCmd = linkeditIndex === -1 ? undefined : commands[linkeditIndex]\n\t\t\tif (linkeditCmd === undefined) {\n\t\t\t\tthrow new SEAError('INJECT', 'Mach-O binary has no __LINKEDIT segment', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst Loff = Number(buf.readBigUInt64LE(linkeditCmd.offset + 40))\n\t\t\tconst Lsize = Number(buf.readBigUInt64LE(linkeditCmd.offset + 48))\n\t\t\tconst Lvm = buf.readBigUInt64LE(linkeditCmd.offset + 24)\n\n\t\t\tconst blobSize = statSync(this.#options.blob).size\n\t\t\t// arm64 (0x0100000c) requires 16K pages; every other architecture (x86_64\n\t\t\t// etc.) uses 4K — 0x4000 is a safe superset alignment for either.\n\t\t\tconst pageSize = cputype === 0x0100000c ? 0x4000 : 0x1000\n\t\t\tconst shift = this.#align(blobSize, pageSize)\n\n\t\t\t// --- Ceiling check BEFORE mutating anything: the enlarged load-command\n\t\t\t// region (plus 16 bytes reserved for codesign re-adding\n\t\t\t// LC_CODE_SIGNATURE) must not overrun the first real section's bytes.\n\t\t\t// The sentinel starts at the FULL file size (not the bounded `buf`\n\t\t\t// size) — it represents \"no section found yet\", not a hard ceiling. ---\n\t\t\tlet firstSectionOffset = fileSize\n\t\t\tfor (const cmd of commands) {\n\t\t\t\tif (cmd.type !== MACHO_LC_SEGMENT_64) continue\n\t\t\t\tconst nsects = buf.readUInt32LE(cmd.offset + 64)\n\t\t\t\tfor (let s = 0; s < nsects; s++) {\n\t\t\t\t\tconst sectOff = cmd.offset + 72 + s * 80\n\t\t\t\t\tif (sectOff + 80 > buf.length) continue\n\t\t\t\t\tconst size = Number(buf.readBigUInt64LE(sectOff + 40))\n\t\t\t\t\tconst offset = buf.readUInt32LE(sectOff + 48)\n\t\t\t\t\tif (size > 0 && offset > 0 && offset < firstSectionOffset) {\n\t\t\t\t\t\tfirstSectionOffset = offset\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst newCmdSize = 72 + 80\n\t\t\tconst removedSize = commands\n\t\t\t\t.filter((_c, i) => existingSegmentIndices.includes(i))\n\t\t\t\t.reduce((sum, c) => sum + c.size, 0)\n\t\t\tconst newNcmds = commands.length - existingSegmentIndices.length + 1\n\t\t\tconst newSizeofcmds = sizeofcmds - removedSize + newCmdSize\n\n\t\t\tif (headerSize + newSizeofcmds + 16 > firstSectionOffset) {\n\t\t\t\tthrow new SEAError(\n\t\t\t\t\t'INJECT',\n\t\t\t\t\t`Not enough header space for new Mach-O load command ` +\n\t\t\t\t\t\t`(need offset ${String(headerSize + newSizeofcmds + 16)}, first section at ${String(firstSectionOffset)})`,\n\t\t\t\t\t{\n\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t\tfirstSectionOffset,\n\t\t\t\t\t\trequiredOffset: headerSize + newSizeofcmds + 16,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// --- Mutate in place: shift __LINKEDIT and every linkedit-relative\n\t\t\t// offset field in the surviving commands, using the ORIGINAL Loff as\n\t\t\t// the \"does this offset point into __LINKEDIT\" threshold. ---\n\t\t\tfor (let i = 0; i < commands.length; i++) {\n\t\t\t\tconst cmd = commands[i]\n\t\t\t\tif (cmd === undefined || existingSegmentIndices.includes(i)) continue\n\n\t\t\t\tif (cmd.type === MACHO_LC_SEGMENT_64) {\n\t\t\t\t\tconst segName = this.#stripTrailingNulls(\n\t\t\t\t\t\tbuf.subarray(cmd.offset + 8, cmd.offset + 24).toString('ascii'),\n\t\t\t\t\t)\n\t\t\t\t\tif (segName === '__LINKEDIT') {\n\t\t\t\t\t\tconst nsects = buf.readUInt32LE(cmd.offset + 64)\n\t\t\t\t\t\tif (nsects > 0) {\n\t\t\t\t\t\t\tthrow new SEAError('INJECT', '__LINKEDIT segment with sections is not supported', {\n\t\t\t\t\t\t\t\texecutable: exePath,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbuf.writeBigUInt64LE(Lvm + BigInt(shift), cmd.offset + 24) // vmaddr\n\t\t\t\t\t\tbuf.writeBigUInt64LE(BigInt(Loff + shift), cmd.offset + 40) // fileoff\n\t\t\t\t\t\t// filesize/vmsize unchanged — __LINKEDIT keeps its size, only moves.\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tthis.#shiftMachoLinkeditOffsets(buf, cmd, Loff, shift)\n\t\t\t}\n\n\t\t\tbuf.writeUInt32LE(newNcmds, 16)\n\t\t\tbuf.writeUInt32LE(newSizeofcmds, 20)\n\n\t\t\t// --- Build the new NODE_SEA segment command: it takes __LINKEDIT's\n\t\t\t// OLD slot (before __LINKEDIT), inserted before __LINKEDIT so\n\t\t\t// codesign's appended signature at EOF (inside __LINKEDIT) survives. ---\n\t\t\tconst cmd = Buffer.alloc(newCmdSize)\n\t\t\tcmd.writeUInt32LE(MACHO_LC_SEGMENT_64, 0)\n\t\t\tcmd.writeUInt32LE(newCmdSize, 4)\n\t\t\tcmd.write(segmentName, 8, 16, 'ascii')\n\t\t\tcmd.writeBigUInt64LE(Lvm, 24) // vmaddr\n\t\t\tcmd.writeBigUInt64LE(BigInt(shift), 32) // vmsize\n\t\t\tcmd.writeBigUInt64LE(BigInt(Loff), 40) // fileoff\n\t\t\tcmd.writeBigUInt64LE(BigInt(shift), 48) // filesize\n\t\t\tcmd.writeUInt32LE(1, 56) // maxprot: VM_PROT_READ\n\t\t\tcmd.writeUInt32LE(1, 60) // initprot: VM_PROT_READ\n\t\t\tcmd.writeUInt32LE(1, 64) // nsects\n\t\t\tcmd.writeUInt32LE(0, 68) // flags\n\n\t\t\tconst sectOff = 72\n\t\t\tcmd.write(sectionName, sectOff, 16, 'ascii')\n\t\t\tcmd.write(segmentName, sectOff + 16, 16, 'ascii')\n\t\t\tcmd.writeBigUInt64LE(Lvm, sectOff + 32) // addr\n\t\t\tcmd.writeBigUInt64LE(BigInt(blobSize), sectOff + 40) // size\n\t\t\tcmd.writeUInt32LE(Loff, sectOff + 48) // offset\n\t\t\tcmd.writeUInt32LE(0, sectOff + 52) // align\n\t\t\tcmd.writeUInt32LE(0, sectOff + 56) // reloff\n\t\t\tcmd.writeUInt32LE(0, sectOff + 60) // nreloc\n\t\t\tcmd.writeUInt32LE(0, sectOff + 64) // flags\n\t\t\tcmd.writeUInt32LE(0, sectOff + 68) // reserved1\n\t\t\tcmd.writeUInt32LE(0, sectOff + 72) // reserved2\n\t\t\tcmd.writeUInt32LE(0, sectOff + 76) // reserved3\n\n\t\t\tconst pieces: Buffer[] = []\n\t\t\tfor (let i = 0; i < commands.length; i++) {\n\t\t\t\tif (existingSegmentIndices.includes(i)) continue\n\t\t\t\tconst c = commands[i]\n\t\t\t\tif (c === undefined) continue\n\t\t\t\t// Insert the new NODE_SEA segment command immediately before\n\t\t\t\t// __LINKEDIT so segment commands stay in ascending vmaddr order and\n\t\t\t\t// __LINKEDIT remains the textually-last segment, as dyld/codesign\n\t\t\t\t// require.\n\t\t\t\tif (i === linkeditIndex) {\n\t\t\t\t\tpieces.push(cmd)\n\t\t\t\t}\n\t\t\t\tpieces.push(Buffer.from(buf.subarray(c.offset, c.offset + c.size)))\n\t\t\t}\n\t\t\tconst newLoadCmdsBuf = Buffer.concat(pieces)\n\t\t\tif (newLoadCmdsBuf.length !== newSizeofcmds) {\n\t\t\t\tthrow new SEAError('INJECT', 'Internal Mach-O load command size mismatch', {\n\t\t\t\t\texecutable: exePath,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// --- Stream-write to a sibling temp, then atomically rename over\n\t\t\t// exePath: header+LCs, unchanged body up to Loff (streamed from\n\t\t\t// srcFd), the blob (streamed from its own fd, padded to `shift`),\n\t\t\t// then the relocated __LINKEDIT (streamed from srcFd). The body\n\t\t\t// range starts at the NEW command-region end (not the old\n\t\t\t// sizeofcmds) — the ceiling check above guarantees\n\t\t\t// [headerSize + sizeofcmds, headerSize + newSizeofcmds) lies entirely\n\t\t\t// in inter-command padding, so discarding those bytes absorbs the\n\t\t\t// growth and keeps every recorded section/segment offset (computed\n\t\t\t// assuming no shift) correct. Starting from the OLD sizeofcmds\n\t\t\t// instead would shift the entire __TEXT/__DATA body forward by the\n\t\t\t// growth delta, corrupting every offset already written into the new\n\t\t\t// load commands. ---\n\t\t\tconst mode = fstatSync(srcFd).mode\n\t\t\tinjTemp = join(dirname(exePath), `.inject-${randomUUID()}.tmp`)\n\t\t\tdestFd = openSync(injTemp, 'w', mode)\n\n\t\t\twriteSync(destFd, buf.subarray(0, headerSize))\n\t\t\twriteSync(destFd, newLoadCmdsBuf)\n\t\t\tcopyRange(srcFd, destFd, headerSize + newSizeofcmds, Loff - (headerSize + newSizeofcmds))\n\n\t\t\tblobFd = openSync(this.#options.blob, 'r')\n\t\t\tcopyRange(blobFd, destFd, 0, blobSize)\n\t\t\tcloseSync(blobFd)\n\t\t\tblobFd = undefined\n\n\t\t\tconst blobPadding = shift - blobSize\n\t\t\tif (blobPadding > 0) {\n\t\t\t\twriteSync(destFd, Buffer.alloc(blobPadding))\n\t\t\t}\n\t\t\tcopyRange(srcFd, destFd, Loff, Lsize)\n\n\t\t\tcloseSync(destFd)\n\t\t\tdestFd = undefined\n\n\t\t\t// Windows cannot rename a replacement over a file that still has an open\n\t\t\t// handle; release the source read handle before finalizeExecutable renames.\n\t\t\tcloseSync(srcFd)\n\t\t\tsrcFd = undefined\n\n\t\t\t// openSync's mode is masked by umask, which can silently drop the\n\t\t\t// exec bit; chmod is not masked, so it reproduces the host binary's\n\t\t\t// permissions exactly before the temp replaces the original.\n\t\t\tchmodSync(injTemp, mode & 0o7777)\n\t\t\tfinalizeExecutable(injTemp, exePath)\n\t\t\tinjTemp = undefined\n\n\t\t\t// Build-time readback: verify the section by its section table entry,\n\t\t\t// consistent with what was just written.\n\t\t\tthis.#verifyMachoSection(exePath, segmentName, sectionName, Loff, blobSize)\n\t\t} finally {\n\t\t\t// Guard each close so a throw from one does not skip the rest of the\n\t\t\t// cleanup (a leaked fd or a stray temp masking the original error).\n\t\t\tfor (const fd of [blobFd, destFd, srcFd]) {\n\t\t\t\tif (fd !== undefined) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcloseSync(fd)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// fd may already be closed or invalid; cleanup must not throw.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (injTemp !== undefined) rmSync(injTemp, { force: true })\n\t\t}\n\t}\n\n\t// --- Mach-O: shift every linkedit-relative offset field in a load command\n\t// that points at or past `threshold` by `shift` bytes ---\n\n\t#shiftMachoLinkeditOffsets(\n\t\tbuf: Buffer,\n\t\tcmd: { type: number; offset: number },\n\t\tthreshold: number,\n\t\tshift: number,\n\t): void {\n\t\tlet offsets: readonly number[]\n\t\tswitch (cmd.type) {\n\t\t\tcase 0x2: // LC_SYMTAB: symoff@+8, stroff@+16\n\t\t\t\toffsets = [8, 16]\n\t\t\t\tbreak\n\t\t\tcase 0xb: // LC_DYSYMTAB: tocoff/modtaboff/extrefsymoff/indirectsymoff/extreloff/locreloff\n\t\t\t\toffsets = [32, 40, 48, 56, 64, 72]\n\t\t\t\tbreak\n\t\t\tcase 0x22: // LC_DYLD_INFO\n\t\t\tcase 0x80000022: // LC_DYLD_INFO_ONLY\n\t\t\t\t// rebase_off, bind_off, weak_bind_off, lazy_bind_off, export_off\n\t\t\t\toffsets = [8, 16, 24, 32, 40]\n\t\t\t\tbreak\n\t\t\tcase 0x1d: // LC_CODE_SIGNATURE\n\t\t\tcase 0x1e: // LC_SEGMENT_SPLIT_INFO\n\t\t\tcase 0x26: // LC_FUNCTION_STARTS\n\t\t\tcase 0x29: // LC_DATA_IN_CODE\n\t\t\tcase 0x80000033: // LC_DYLD_EXPORTS_TRIE\n\t\t\tcase 0x80000034: // LC_DYLD_CHAINED_FIXUPS\n\t\t\t\toffsets = [8] // dataoff (linkedit_data_command)\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\t// LC_TWOLEVEL_HINTS (0x16, offset@+8) and LC_ATOM_INFO also\n\t\t\t\t// point into __LINKEDIT but are intentionally not handled here\n\t\t\t\t// because they do not appear in Node.js executables.\n\t\t\t\treturn\n\t\t}\n\t\tfor (const offset of offsets) {\n\t\t\tconst fieldOffset = cmd.offset + offset\n\t\t\tif (fieldOffset + 4 > buf.length) continue\n\t\t\tconst value = buf.readUInt32LE(fieldOffset)\n\t\t\tif (value >= threshold && value > 0) {\n\t\t\t\tbuf.writeUInt32LE(value + shift, fieldOffset)\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- Mach-O: build-time readback — confirm the section table entry\n\t// matches what was written, the same shape the runtime's getsectdata\n\t// lookup relies on ---\n\n\t#verifyMachoSection(\n\t\texePath: string,\n\t\tsegmentName: string,\n\t\tsectionName: string,\n\t\texpectedOffset: number,\n\t\texpectedSize: number,\n\t): void {\n\t\tconst fd = openSync(exePath, 'r')\n\t\ttry {\n\t\t\tconst header = Buffer.alloc(32)\n\t\t\treadSync(fd, header, 0, 32, 0)\n\t\t\tconst ncmds = header.readUInt32LE(16)\n\n\t\t\tlet offset = 32\n\t\t\tfor (let i = 0; i < ncmds; i++) {\n\t\t\t\tconst cmdHead = Buffer.alloc(8)\n\t\t\t\treadSync(fd, cmdHead, 0, 8, offset)\n\t\t\t\tconst cmdType = cmdHead.readUInt32LE(0)\n\t\t\t\tconst cmdSize = cmdHead.readUInt32LE(4)\n\n\t\t\t\tif (cmdType === MACHO_LC_SEGMENT_64 && cmdSize >= 72) {\n\t\t\t\t\tconst segBuf = Buffer.alloc(cmdSize)\n\t\t\t\t\treadSync(fd, segBuf, 0, cmdSize, offset)\n\t\t\t\t\tconst segName = this.#stripTrailingNulls(segBuf.subarray(8, 24).toString('ascii'))\n\t\t\t\t\tif (segName === segmentName) {\n\t\t\t\t\t\tconst nsects = segBuf.readUInt32LE(64)\n\t\t\t\t\t\tfor (let s = 0; s < nsects; s++) {\n\t\t\t\t\t\t\tconst sectOff = 72 + s * 80\n\t\t\t\t\t\t\tif (sectOff + 80 > segBuf.length) continue\n\t\t\t\t\t\t\tconst secName = this.#stripTrailingNulls(\n\t\t\t\t\t\t\t\tsegBuf.subarray(sectOff, sectOff + 16).toString('ascii'),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tif (secName !== sectionName) continue\n\t\t\t\t\t\t\tconst secSize = Number(segBuf.readBigUInt64LE(sectOff + 40))\n\t\t\t\t\t\t\tconst secOffset = segBuf.readUInt32LE(sectOff + 48)\n\t\t\t\t\t\t\tif (secOffset === expectedOffset && secSize === expectedSize) return\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\toffset += cmdSize\n\t\t\t}\n\t\t} finally {\n\t\t\tcloseSync(fd)\n\t\t}\n\n\t\tthrow new SEAError('INJECT', 'Injected Mach-O section not found after write', {\n\t\t\texecutable: exePath,\n\t\t\tsegmentName,\n\t\t\tsectionName,\n\t\t})\n\t}\n\n\t// =========================================================================\n\t// Binary I/O Helpers\n\t// =========================================================================\n\n\t#readU16(fd: number, offset: number): number {\n\t\tconst b = Buffer.alloc(2)\n\t\treadSync(fd, b, 0, 2, offset)\n\t\treturn b.readUInt16LE(0)\n\t}\n\n\t#readU32(fd: number, offset: number): number {\n\t\tconst b = Buffer.alloc(4)\n\t\treadSync(fd, b, 0, 4, offset)\n\t\treturn b.readUInt32LE(0)\n\t}\n\n\t#readU64(fd: number, offset: number): bigint {\n\t\tconst b = Buffer.alloc(8)\n\t\treadSync(fd, b, 0, 8, offset)\n\t\treturn b.readBigUInt64LE(0)\n\t}\n\n\t#writeU16(fd: number, offset: number, value: number): void {\n\t\tconst b = Buffer.alloc(2)\n\t\tb.writeUInt16LE(value, 0)\n\t\twriteSync(fd, b, 0, 2, offset)\n\t}\n\n\t#writeU32(fd: number, offset: number, value: number): void {\n\t\tconst b = Buffer.alloc(4)\n\t\tb.writeUInt32LE(value >>> 0, 0)\n\t\twriteSync(fd, b, 0, 4, offset)\n\t}\n\n\t#writeU64(fd: number, offset: number, value: bigint): void {\n\t\tconst b = Buffer.alloc(8)\n\t\tb.writeBigUInt64LE(value, 0)\n\t\twriteSync(fd, b, 0, 8, offset)\n\t}\n\n\t#align(value: number, alignment: number): number {\n\t\tconst remainder = value % alignment\n\t\treturn remainder === 0 ? value : value + (alignment - remainder)\n\t}\n\n\t// --- PE: validate section/file alignment before any #align call uses it\n\t// as a divisor — a malformed 0 value would otherwise silently corrupt\n\t// output via NaN -> #writeU32 coercion. ---\n\n\t#ensureValidPEAlignment(sectionAlignment: number, fileAlignment: number): void {\n\t\tif (!isPowerOfTwo(sectionAlignment) || !isPowerOfTwo(fileAlignment)) {\n\t\t\tthrow new SEAError('FORMAT', 'PE section/file alignment must be a nonzero power of two', {\n\t\t\t\texecutable: this.#options.executable,\n\t\t\t\tsectionAlignment,\n\t\t\t\tfileAlignment,\n\t\t\t})\n\t\t}\n\t\tif (sectionAlignment < fileAlignment) {\n\t\t\tthrow new SEAError('FORMAT', 'PE sectionAlignment must be >= fileAlignment', {\n\t\t\t\texecutable: this.#options.executable,\n\t\t\t\tsectionAlignment,\n\t\t\t\tfileAlignment,\n\t\t\t})\n\t\t}\n\t}\n\n\t/** Append sourceFile to targetFile by streaming in 4 MB chunks */\n\t#appendFile(targetPath: string, sourcePath: string): void {\n\t\tconst chunkSize = 4 * 1024 * 1024\n\t\tconst srcFd = openSync(sourcePath, 'r')\n\t\ttry {\n\t\t\tconst srcSize = statSync(sourcePath).size\n\t\t\tconst chunk = Buffer.alloc(Math.min(chunkSize, srcSize))\n\t\t\tlet offset = 0\n\t\t\twhile (offset < srcSize) {\n\t\t\t\tconst toRead = Math.min(chunkSize, srcSize - offset)\n\t\t\t\tconst bytesRead = readSync(srcFd, chunk, 0, toRead, offset)\n\t\t\t\tif (bytesRead === 0) break\n\t\t\t\tappendFileSync(targetPath, chunk.subarray(0, bytesRead))\n\t\t\t\toffset += bytesRead\n\t\t\t}\n\t\t} finally {\n\t\t\tcloseSync(srcFd)\n\t\t}\n\t}\n\n\t// Strip trailing null characters from a string (used for binary name fields)\n\t#stripTrailingNulls(value: string): string {\n\t\tconst idx = value.indexOf(String.fromCharCode(0))\n\t\treturn idx === -1 ? value : value.slice(0, idx)\n\t}\n}\n","/**\n * SEA\n *\n * Build orchestrator for Node.js Single Executable Applications.\n * Compresses assets, generates the SEA blob, copies the Node binary,\n * injects the blob, and handles platform-specific signing.\n */\n\nimport type {\n\tSEACompressionManifest,\n\tSEAEventMap,\n\tSEAInterface,\n\tSEAOptions,\n\tSEAResult,\n\tSEAStatus,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport {\n\tchmodSync,\n\tcopyFileSync,\n\texistsSync,\n\tmkdirSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tSEA_BLOB_RESOURCE,\n\tSEA_SENTINEL_FUSE,\n\tWINDOWS_SUBSYSTEM_CONSOLE,\n\tWINDOWS_SUBSYSTEM_GUI,\n} from '../constants.js'\nimport {\n\tcompressDirectory,\n\tcreateBlobConfig,\n\tcreateSignCommand,\n\tensureContained,\n\tensureExists,\n\tensureSafeKey,\n\tensureSafeName,\n\tfinalizeExecutable,\n\tisCompressible,\n\tisPEExecutable,\n\tisPlatformSupported,\n\tpatchPESubsystem,\n\tplatformConfig,\n\trunShell,\n\tstripPESignature,\n\twalkDirectory,\n} from '../helpers.js'\nimport { SEAError } from '../errors.js'\nimport { Injector } from '../injectors/Injector.js'\n\n// === SEA\n\nexport class SEA implements SEAInterface {\n\t#status: SEAStatus = 'idle'\n\t#destroyed = false\n\treadonly #options: SEAOptions\n\treadonly #emitter: Emitter<SEAEventMap>\n\n\tconstructor(options: SEAOptions) {\n\t\tthis.#options = options\n\t\tthis.#emitter = new Emitter({\n\t\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<SEAEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget status(): SEAStatus {\n\t\treturn this.#status\n\t}\n\n\tasync execute(): Promise<SEAResult> {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new SEAError('STATE', 'SEA is destroyed')\n\t\t}\n\t\tif (this.#status === 'active') {\n\t\t\tthrow new SEAError('STATE', 'SEA build already in progress')\n\t\t}\n\n\t\tconst platform = platformConfig()\n\t\tif (platform === undefined || !isPlatformSupported()) {\n\t\t\tconst error = new SEAError('PLATFORM', `Unsupported platform: ${process.platform}`, {\n\t\t\t\tplatform: process.platform,\n\t\t\t})\n\t\t\tthis.#status = 'error'\n\t\t\tthis.#emitter.emit('error', error)\n\t\t\tthrow error\n\t\t}\n\n\t\tthis.#status = 'active'\n\t\tconst start = Date.now()\n\t\tconst root = this.#options.root ?? process.cwd()\n\n\t\ttry {\n\t\t\tthis.#check()\n\t\t\tthis.#validate(root)\n\n\t\t\tthis.#check()\n\t\t\tconst compression = this.#compress(root)\n\n\t\t\tthis.#check()\n\t\t\tconst blob = this.#blob(root)\n\n\t\t\tthis.#check()\n\t\t\tconst assembled = this.#assemble(root, blob)\n\t\t\tconst size = statSync(assembled.executable).size\n\t\t\tconst duration = Date.now() - start\n\n\t\t\tconst result: SEAResult = {\n\t\t\t\texecutable: assembled.executable,\n\t\t\t\tplatform: process.platform,\n\t\t\t\tsize,\n\t\t\t\tduration,\n\t\t\t\tsigned: assembled.signed,\n\t\t\t\tstripped: assembled.stripped,\n\t\t\t\t...(compression === undefined ? {} : { compression }),\n\t\t\t\t...(assembled.terminal === undefined ? {} : { terminal: assembled.terminal }),\n\t\t\t}\n\n\t\t\tthis.#status = 'done'\n\t\t\tthis.#emitter.emit('complete', result)\n\t\t\treturn result\n\t\t} catch (thrown: unknown) {\n\t\t\tthis.#status = 'error'\n\t\t\tthis.#emitter.emit('error', thrown)\n\t\t\tthrow thrown\n\t\t}\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// Throws SEAError('ABORT', ...) when the caller's signal has fired.\n\t#check(): void {\n\t\tif (this.#options.signal?.aborted === true) {\n\t\t\tthrow new SEAError('ABORT', 'SEA build aborted')\n\t\t}\n\t}\n\n\t// Validates every asset key/path and compression path before any work runs.\n\t#validate(root: string): void {\n\t\tconst base = resolve(root)\n\n\t\tensureSafeName(this.#options.name)\n\n\t\tfor (const [key, path] of Object.entries(this.#options.assets ?? {})) {\n\t\t\tensureSafeKey(key)\n\t\t\tensureSafeKey(path)\n\t\t\tensureContained(base, path)\n\t\t}\n\n\t\tfor (const path of this.#options.compression?.paths ?? []) {\n\t\t\tensureSafeKey(path)\n\t\t\t// A compression path that does not exist yet is skipped by #compress\n\t\t\t// (existsSync gate below), so validation only enforces containment\n\t\t\t// for paths that actually exist — keep the two stages in agreement.\n\t\t\tif (existsSync(resolve(base, path))) {\n\t\t\t\tensureContained(base, path)\n\t\t\t}\n\t\t}\n\n\t\tconst sign = this.#options.windows?.sign\n\t\tif (sign !== undefined) {\n\t\t\t// Trigger the file-XOR-thumbprint and timestamp-scheme validation\n\t\t\t// fail-fast, before any build work runs. The placeholder target is\n\t\t\t// never executed here — createSignCommand is a pure argv builder.\n\t\t\tcreateSignCommand(sign, 'placeholder')\n\n\t\t\tif (sign.file !== undefined) {\n\t\t\t\tensureExists(resolve(base, sign.file), 'Certificate file not found', 'SIGN')\n\t\t\t}\n\t\t}\n\t}\n\n\t#compress(root: string): SEACompressionManifest | undefined {\n\t\tconst compression = this.#options.compression\n\t\tif (compression === undefined || compression.paths.length === 0) {\n\t\t\tthis.#emitter.emit('compress', undefined)\n\t\t\treturn undefined\n\t\t}\n\n\t\tconst directories: string[] = []\n\t\tlet total = 0\n\t\tfor (const path of compression.paths) {\n\t\t\tconst candidate = resolve(root, path)\n\t\t\tif (!existsSync(candidate)) continue\n\t\t\tthis.#check()\n\t\t\tconst directory = ensureContained(root, path)\n\t\t\tdirectories.push(directory)\n\t\t\ttotal += walkDirectory(directory).filter(isCompressible).length\n\t\t}\n\n\t\tconst assets: SEACompressionManifest['assets'][number][] = []\n\t\tlet original = 0\n\t\tlet compressed = 0\n\t\tlet current = 0\n\n\t\tfor (const directory of directories) {\n\t\t\tthis.#check()\n\t\t\tconst manifest = compressDirectory(directory, compression, (result) => {\n\t\t\t\tcurrent += 1\n\t\t\t\tthis.#emitter.emit('progress', { path: result.input, current, total })\n\t\t\t})\n\t\t\tassets.push(...manifest.assets)\n\t\t\toriginal += manifest.total.original\n\t\t\tcompressed += manifest.total.compressed\n\t\t}\n\n\t\tconst manifest: SEACompressionManifest = {\n\t\t\tassets,\n\t\t\ttotal: {\n\t\t\t\toriginal,\n\t\t\t\tcompressed,\n\t\t\t\tratio: original > 0 ? compressed / original : 0,\n\t\t\t},\n\t\t}\n\n\t\tthis.#emitter.emit('compress', manifest)\n\t\treturn manifest\n\t}\n\n\t#blob(root: string): string {\n\t\tconst entry = resolve(root, this.#options.entry.path)\n\t\tensureExists(entry, `Entry not found: ${this.#options.entry.path}`, 'ENTRY')\n\n\t\tconst output = resolve(root, this.#options.output)\n\t\tmkdirSync(output, { recursive: true })\n\n\t\tconst configPath = join(output, 'sea-config.json')\n\t\tconst blob = join(output, 'sea-prep.blob')\n\t\tconst config = createBlobConfig(\n\t\t\t{\n\t\t\t\tpath: entry,\n\t\t\t\t...(this.#options.entry.format === undefined ? {} : { format: this.#options.entry.format }),\n\t\t\t},\n\t\t\tblob,\n\t\t\tthis.#assets(root),\n\t\t\tthis.#options.blob,\n\t\t)\n\n\t\twriteFileSync(configPath, JSON.stringify(config, null, 2))\n\t\trunShell([process.execPath, '--experimental-sea-config', configPath], {\n\t\t\tcwd: output,\n\t\t\t...(this.#options.signal === undefined ? {} : { signal: this.#options.signal }),\n\t\t})\n\n\t\tif (!existsSync(blob)) {\n\t\t\tthrow new SEAError('BLOB', 'SEA blob generation failed — blob not found', { blob })\n\t\t}\n\n\t\tthis.#emitter.emit('blob', blob)\n\t\treturn blob\n\t}\n\n\t// Assembles the final executable in a same-directory temp file, mutating it\n\t// through strip -> inject -> sign -> verify, then atomically finalizing it\n\t// into place. Any failure removes the temp file and leaves the prior output\n\t// (if any) untouched.\n\t#assemble(\n\t\troot: string,\n\t\tblob: string,\n\t): { executable: string; signed: boolean; stripped: boolean; terminal?: boolean } {\n\t\tconst platform = platformConfig()\n\t\tif (platform === undefined) {\n\t\t\tthrow new SEAError('PLATFORM', `Unsupported platform: ${process.platform}`, {\n\t\t\t\tplatform: process.platform,\n\t\t\t})\n\t\t}\n\n\t\tconst output = resolve(root, this.#options.output)\n\t\tconst ext = process.platform === 'win32' ? '.exe' : ''\n\t\tconst name = process.platform === 'win32' ? `${this.#options.name}.exe` : this.#options.name\n\t\tconst finalOutput = join(output, name)\n\t\tconst temp = join(output, `.${this.#options.name}-${randomUUID()}.tmp${ext}`)\n\t\tconst shell = this.#options.signal === undefined ? {} : { signal: this.#options.signal }\n\n\t\tlet signed = false\n\t\tlet stripped = false\n\t\tlet terminal: boolean | undefined\n\n\t\ttry {\n\t\t\tif (process.platform === 'darwin') {\n\t\t\t\tthis.#check()\n\t\t\t\tcopyFileSync(process.execPath, temp)\n\t\t\t\tchmodSync(temp, 0o755)\n\n\t\t\t\tif (platform.remove !== undefined) {\n\t\t\t\t\tthis.#check()\n\t\t\t\t\ttry {\n\t\t\t\t\t\trunShell([...platform.remove, temp], shell)\n\t\t\t\t\t} catch (thrown: unknown) {\n\t\t\t\t\t\tthrow new SEAError('SIGN', 'Failed to strip existing signature', {\n\t\t\t\t\t\t\tcause: thrown instanceof Error ? thrown.message : String(thrown),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tstripped = true\n\t\t\t\t}\n\n\t\t\t\tthis.#check()\n\t\t\t\tconst injector = new Injector({\n\t\t\t\t\texecutable: temp,\n\t\t\t\t\tresource: SEA_BLOB_RESOURCE,\n\t\t\t\t\tblob,\n\t\t\t\t\tfuse: SEA_SENTINEL_FUSE,\n\t\t\t\t\tmacho: { segment: 'NODE_SEA' },\n\t\t\t\t})\n\t\t\t\tinjector.inject()\n\n\t\t\t\tif (platform.sign !== undefined) {\n\t\t\t\t\tthis.#check()\n\t\t\t\t\ttry {\n\t\t\t\t\t\trunShell([...platform.sign, temp], shell)\n\t\t\t\t\t} catch (thrown: unknown) {\n\t\t\t\t\t\tthrow new SEAError('SIGN', 'Failed to sign executable', {\n\t\t\t\t\t\t\tcause: thrown instanceof Error ? thrown.message : String(thrown),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tif (platform.verify !== undefined) {\n\t\t\t\t\t\tthis.#check()\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trunShell([...platform.verify, temp], shell)\n\t\t\t\t\t\t} catch (thrown: unknown) {\n\t\t\t\t\t\t\tthrow new SEAError('SIGN', 'Signature verification failed', {\n\t\t\t\t\t\t\t\tcause: thrown instanceof Error ? thrown.message : String(thrown),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tsigned = true\n\t\t\t\t}\n\t\t\t} else if (process.platform === 'win32') {\n\t\t\t\tthis.#check()\n\t\t\t\tcopyFileSync(process.execPath, temp)\n\n\t\t\t\tstripPESignature(temp)\n\t\t\t\tstripped = true\n\n\t\t\t\tif (isPEExecutable(temp)) {\n\t\t\t\t\tterminal = this.#options.windows?.terminal !== false\n\t\t\t\t\tconst value = terminal ? WINDOWS_SUBSYSTEM_CONSOLE : WINDOWS_SUBSYSTEM_GUI\n\t\t\t\t\tpatchPESubsystem(temp, value)\n\t\t\t\t}\n\n\t\t\t\tthis.#check()\n\t\t\t\tconst injector = new Injector({\n\t\t\t\t\texecutable: temp,\n\t\t\t\t\tresource: SEA_BLOB_RESOURCE,\n\t\t\t\t\tblob,\n\t\t\t\t\tfuse: SEA_SENTINEL_FUSE,\n\t\t\t\t})\n\t\t\t\tinjector.inject()\n\n\t\t\t\tconst sign = this.#options.windows?.sign\n\t\t\t\tif (sign !== undefined) {\n\t\t\t\t\tthis.#check()\n\t\t\t\t\t// Resolve the certificate file against the SAME base #validate\n\t\t\t\t\t// checked existence against — createSignCommand's argv is passed\n\t\t\t\t\t// through runShell without a cwd, so a relative sign.file would\n\t\t\t\t\t// otherwise resolve against process.cwd(), a different file.\n\t\t\t\t\tconst signInput =\n\t\t\t\t\t\tsign.file !== undefined ? { ...sign, file: resolve(root, sign.file) } : sign\n\t\t\t\t\tconst signArgs = createSignCommand(signInput, temp)\n\t\t\t\t\ttry {\n\t\t\t\t\t\trunShell(signArgs, shell)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new SEAError('SIGN', 'Windows signing failed', { executable: temp })\n\t\t\t\t\t}\n\t\t\t\t\tsigned = true\n\n\t\t\t\t\tif (platform.verify !== undefined) {\n\t\t\t\t\t\tthis.#check()\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trunShell([...platform.verify, temp], shell)\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tthrow new SEAError('SIGN', 'Signature verification failed', { executable: temp })\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.#check()\n\t\t\t\tcopyFileSync(process.execPath, temp)\n\t\t\t\tchmodSync(temp, 0o755)\n\n\t\t\t\tthis.#check()\n\t\t\t\tconst injector = new Injector({\n\t\t\t\t\texecutable: temp,\n\t\t\t\t\tresource: SEA_BLOB_RESOURCE,\n\t\t\t\t\tblob,\n\t\t\t\t\tfuse: SEA_SENTINEL_FUSE,\n\t\t\t\t})\n\t\t\t\tinjector.inject()\n\t\t\t}\n\n\t\t\tfinalizeExecutable(temp, finalOutput)\n\t\t} catch (thrown: unknown) {\n\t\t\trmSync(temp, { force: true })\n\t\t\tthrow thrown\n\t\t}\n\n\t\tthis.#emitter.emit('assemble', finalOutput)\n\t\treturn {\n\t\t\texecutable: finalOutput,\n\t\t\tsigned,\n\t\t\tstripped,\n\t\t\t...(terminal === undefined ? {} : { terminal }),\n\t\t}\n\t}\n\n\t#assets(root: string): Readonly<Record<string, string>> {\n\t\tconst assets: Record<string, string> = {}\n\t\tfor (const [name, path] of Object.entries(this.#options.assets ?? {})) {\n\t\t\tassets[name] = ensureContained(root, path)\n\t\t}\n\t\treturn assets\n\t}\n}\n","/**\n * Asset\n *\n * A single named asset wrapping its key, content buffer, and compression flag.\n * Infers compression from the `.br` extension when not explicitly provided.\n */\n\nimport type { AssetInput, AssetInterface } from '../types.js'\nimport { BROTLI_EXTENSION } from '../constants.js'\n\n// === Asset\n\nexport class Asset implements AssetInterface {\n\treadonly key: string\n\treadonly content: ArrayBuffer\n\treadonly compressed: boolean\n\n\tconstructor(input: AssetInput) {\n\t\tthis.key = input.key\n\t\tthis.content = input.content\n\t\tthis.compressed = input.compressed ?? input.key.endsWith(BROTLI_EXTENSION)\n\t}\n}\n","/**\n * AssetManager\n *\n * Named asset collection with SEA and disk loading.\n * In SEA mode, embedded assets are loaded automatically at construction.\n * In development, `load()` reads client assets from disk.\n */\n\nimport { readFileSync, existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { getAssetKeys, getRawAsset, isSea } from 'node:sea'\nimport type {\n\tAssetInput,\n\tAssetInterface,\n\tAssetManagerEventMap,\n\tAssetManagerInterface,\n\tAssetManagerOptions,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArrayBuffer } from '@orkestrel/contract'\nimport { CLIENT_ASSET_KEY_BR, CLIENT_ASSET_KEY_RAW } from '../constants.js'\nimport { Asset } from './Asset.js'\n\n// === AssetManager\n\nexport class AssetManager implements AssetManagerInterface {\n\treadonly #emitter: Emitter<AssetManagerEventMap>\n\t#assets = new Map<string, AssetInterface>()\n\t#keys: string[] = []\n\treadonly #root: string\n\n\tconstructor(options?: AssetManagerOptions) {\n\t\tthis.#root = options?.root ?? process.cwd()\n\t\tthis.#emitter = new Emitter({\n\t\t\t...(options?.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options?.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t\tthis.#loadSea()\n\t}\n\n\tget emitter(): EmitterInterface<AssetManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#assets.size\n\t}\n\n\tasset(key: string): AssetInterface | undefined {\n\t\treturn this.#assets.get(key)\n\t}\n\n\tassets(): readonly AssetInterface[] {\n\t\treturn [...this.#assets.values()]\n\t}\n\n\tkeys(): readonly string[] {\n\t\treturn [...this.#keys]\n\t}\n\n\tregister(input: AssetInput | AssetInput[]): void {\n\t\tconst items = Array.isArray(input) ? input : [input]\n\t\tfor (const item of items) {\n\t\t\tconst asset: AssetInterface = new Asset(item)\n\t\t\tthis.#add(asset)\n\t\t\tthis.#emitter.emit('register', asset)\n\t\t}\n\t}\n\n\tload(): void {\n\t\tif (isSea()) return\n\n\t\tconst devPath = resolve(this.#root, 'client', CLIENT_ASSET_KEY_RAW)\n\t\tconst builtBrPath = resolve(this.#root, 'dist', 'client', CLIENT_ASSET_KEY_BR)\n\n\t\tif (existsSync(devPath)) {\n\t\t\ttry {\n\t\t\t\tconst raw = readFileSync(devPath, 'utf-8')\n\t\t\t\tconst encoder = new TextEncoder()\n\t\t\t\tconst bytes = encoder.encode(raw)\n\t\t\t\tconst content = bytes.buffer\n\t\t\t\tif (!isArrayBuffer(content)) {\n\t\t\t\t\tthrow new Error('Failed to encode client asset')\n\t\t\t\t}\n\t\t\t\tthis.register({ key: CLIENT_ASSET_KEY_RAW, content, compressed: false })\n\t\t\t\tthis.#emitter.emit('load', [CLIENT_ASSET_KEY_RAW])\n\t\t\t} catch (thrown: unknown) {\n\t\t\t\tthis.#emitter.emit('error', thrown)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif (existsSync(builtBrPath)) {\n\t\t\ttry {\n\t\t\t\tconst buffer = readFileSync(builtBrPath)\n\t\t\t\tconst bufferData = buffer.buffer\n\t\t\t\tif (!isArrayBuffer(bufferData)) {\n\t\t\t\t\tthrow new Error('Failed to read client asset')\n\t\t\t\t}\n\t\t\t\tconst content = bufferData.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)\n\t\t\t\tthis.register({ key: CLIENT_ASSET_KEY_BR, content, compressed: true })\n\t\t\t\tthis.#emitter.emit('load', [CLIENT_ASSET_KEY_BR])\n\t\t\t} catch (thrown: unknown) {\n\t\t\t\tthis.#emitter.emit('error', thrown)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tthis.#emitter.emit('error', new Error('Client assets not found'))\n\t}\n\n\tclear(): void {\n\t\tthis.#assets.clear()\n\t\tthis.#keys = []\n\t\tthis.#emitter.emit('clear')\n\t}\n\n\tdestroy(): void {\n\t\tthis.clear()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// === Private\n\n\t#add(asset: AssetInterface): void {\n\t\tthis.#assets.set(asset.key, asset)\n\t\tif (!this.#keys.includes(asset.key)) {\n\t\t\tthis.#keys.push(asset.key)\n\t\t}\n\t}\n\n\t#loadSea(): void {\n\t\tif (isSea()) {\n\t\t\tconst assetKeys: readonly string[] = getAssetKeys()\n\t\t\tconst registered: string[] = []\n\t\t\tfor (const key of assetKeys) {\n\t\t\t\tconst content: ArrayBuffer = getRawAsset(key)\n\t\t\t\tthis.#add(new Asset({ key, content }))\n\t\t\t\tregistered.push(key)\n\t\t\t}\n\t\t\tif (registered.length > 0) {\n\t\t\t\tthis.#emitter.emit('load', registered)\n\t\t\t}\n\t\t}\n\t}\n}\n","import type {\n\tAssetInput,\n\tAssetInterface,\n\tAssetManagerInterface,\n\tAssetManagerOptions,\n\tInjectorInterface,\n\tInjectorOptions,\n\tSEAInterface,\n\tSEAOptions,\n} from './types.js'\nimport { SEA } from './seals/SEA.js'\nimport { Injector } from './injectors/Injector.js'\nimport { Asset } from './assets/Asset.js'\nimport { AssetManager } from './assets/AssetManager.js'\n\n/**\n * Create a new SEA build orchestrator.\n *\n * @param options - SEA build options\n * @returns a new `SEAInterface`\n *\n * @example\n * ```ts\n * const seal = createSEA({\n * name: 'orkestrel',\n * entry: { path: 'dist/bin/serve.cjs' },\n * output: 'dist/sea',\n * assets: { 'index.html.br': 'dist/client/index.html.br' },\n * compression: { paths: ['dist/client'] },\n * })\n * const result = await seal.execute()\n * ```\n */\nexport function createSEA(options: SEAOptions): SEAInterface {\n\treturn new SEA(options)\n}\n\n/**\n * Create a cross-platform binary resource injector.\n *\n * Detects the executable format (PE, ELF, Mach-O) from the file header\n * and injects the blob using pure TypeScript file I/O — no WASM, no\n * external tools.\n *\n * @param options - Injector options\n * @returns a new `InjectorInterface`\n *\n * @example\n * ```ts\n * const injector = createInjector({\n * executable: 'dist/bin/myapp.exe',\n * resource: 'NODE_SEA_BLOB',\n * blob: 'dist/bin/sea-prep.blob',\n * fuse: 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2',\n * })\n * injector.inject()\n * ```\n */\nexport function createInjector(options: InjectorOptions): InjectorInterface {\n\treturn new Injector(options)\n}\n\n/**\n * Create a single named asset.\n *\n * @param input - Asset key, content, and optional compression flag\n * @returns a new `AssetInterface`\n *\n * @example\n * ```ts\n * const asset = createAsset({ key: 'client.html.br', content: compressedBuffer })\n * ```\n */\nexport function createAsset(input: AssetInput): AssetInterface {\n\treturn new Asset(input)\n}\n\n/**\n * Create an asset manager for SEA-embedded or disk-loaded assets.\n *\n * @param options - Asset manager options (root, event hooks)\n * @returns a new `AssetManagerInterface`\n *\n * @example\n * ```ts\n * const manager = createAssetManager({ root: process.cwd() })\n * manager.load()\n * ```\n */\nexport function createAssetManager(options?: AssetManagerOptions): AssetManagerInterface {\n\treturn new AssetManager(options)\n}\n"],"mappings":";;;;;;;;;;AAGA,IAAa,oBAAoB;;AAGjC,IAAa,oBAAoB;;AAGjC,IAAa,kCAAkC;;AAG/C,IAAa,wBAAwB;;AAGrC,IAAa,4BAA4B;;AAGzC,IAAa,mBAAmB;;AAGhC,IAAa,kCAAkB,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,uBAAuC;;AAGpD,IAAa,uBAAuB;;AAGpC,IAAa,sBAAsB;;AAKnC,IAAa,WAAW;;AAGxB,IAAa,eAAe;;AAG5B,IAAa,aAAa;;AAG1B,IAAa,kBAAkB;;AAG/B,IAAa,YAAY;;AAGzB,IAAa,eAAe;;AAG5B,IAAa,eAAe;;AA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