@orkestrel/sea 0.0.17 → 0.0.19

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":[],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/validators.ts","../../../src/server/helpers.ts","../../../src/server/injectors/Injector.ts","../../../src/server/seas/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/**\n * Holds the SEA sentinel fuse value embedded in the Node.js binary,\n * `NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2`.\n */\nexport const SEA_SENTINEL_FUSE = 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2'\n\n/** Names the SEA blob resource in the executable, `NODE_SEA_BLOB`. */\nexport const SEA_BLOB_RESOURCE = 'NODE_SEA_BLOB'\n\n/** Holds the default Brotli compression quality level, 11, the maximum Brotli accepts. */\nexport const DEFAULT_SEA_COMPRESSION_QUALITY = 11\n\n/**\n * Holds the Windows PE subsystem value for a GUI application, 2, which launches\n * without a terminal window.\n */\nexport const WINDOWS_SUBSYSTEM_GUI = 2\n\n/** Holds the Windows PE subsystem value for a console application, 3. */\nexport const WINDOWS_SUBSYSTEM_CONSOLE = 3\n\n/** Names the file extension indicating Brotli compression, `.br`. */\nexport const BROTLI_EXTENSION = '.br'\n\n/**\n * Lists the file extensions Brotli compression skips, the already-compressed\n * archive, image, font, and media formats.\n */\nexport const SKIP_EXTENSIONS: ReadonlySet<string> = 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/** Names the default SEA entry point module format when none is specified, `cjs`. */\nexport const DEFAULT_ENTRY_FORMAT: SEAEntryFormat = 'cjs'\n\n// === Binary Format Magic\n\n/** Holds the DOS MZ header magic, 0x5a4d, the first two bytes of a PE file. */\nexport const PE_MAGIC = 0x5a4d\n\n/** Holds the PE signature, 0x00004550, the bytes `PE\\0\\0` read as a 32-bit value. */\nexport const PE_SIGNATURE = 0x00004550\n\n/** Holds the PE32 optional header magic, 0x10b. */\nexport const PE32_MAGIC = 0x10b\n\n/** Holds the PE32+ optional header magic, 0x20b, the 64-bit form. */\nexport const PE32_PLUS_MAGIC = 0x20b\n\n/**\n * Holds the ELF magic, 0x7f454c46, the bytes 0x7F `E` `L` `F` read as a 32-bit\n * big-endian value.\n */\nexport const ELF_MAGIC = 0x7f454c46\n\n/** Holds the ELF 64-bit class identifier, 2. */\nexport const ELF_CLASS_64 = 2\n\n/** Holds the ELF little-endian data encoding, 1. */\nexport const ELF_DATA_LSB = 1\n\n/** Holds the ELF program header type for a note segment, 4. */\nexport const ELF_PT_NOTE = 4\n\n/** Holds the ELF program header type for a loadable segment, 1. */\nexport const ELF_PT_LOAD = 1\n\n/** Holds the ELF program header type for the program header table itself, 6. */\nexport const ELF_PT_PHDR = 6\n\n/** Holds the ELF segment permission flag marking a segment readable, 4. */\nexport const ELF_PF_R = 4\n\n/** Holds the page size an injected ELF segment is aligned to, 0x1000. */\nexport const ELF_PAGE_SIZE = 0x1000\n\n/** Holds the Mach-O 64-bit magic, 0xfeedfacf, in little-endian byte order. */\nexport const MACHO_MAGIC_64 = 0xfeedfacf\n\n/** Holds the Mach-O `LC_SEGMENT_64` load command, 0x19. */\nexport const MACHO_LC_SEGMENT_64 = 0x19\n\n// === PE Resource Directory\n\n/** Holds the PE resource type `RT_RCDATA` for raw data, 10. */\nexport const PE_RT_RCDATA = 10\n\n/** Holds the size of `IMAGE_RESOURCE_DIRECTORY` in bytes, 16. */\nexport const PE_RESOURCE_DIR_SIZE = 16\n\n/** Holds the size of `IMAGE_RESOURCE_DIRECTORY_ENTRY` in bytes, 8. */\nexport const PE_RESOURCE_ENTRY_SIZE = 8\n\n/** Holds the size of `IMAGE_RESOURCE_DATA_ENTRY` in bytes, 16. */\nexport const PE_RESOURCE_DATA_ENTRY_SIZE = 16\n\n/** Holds the PE section header size in bytes, 40. */\nexport const PE_SECTION_HEADER_SIZE = 40\n\n/**\n * Holds the high bit mask marking a resource directory entry offset as a\n * subdirectory, 0x80000000.\n */\nexport const PE_RESOURCE_SUBDIR_FLAG = 0x80000000\n\n/**\n * Holds the high bit mask marking a resource entry as named rather than\n * integer-identified, 0x80000000.\n */\nexport const PE_RESOURCE_NAME_FLAG = 0x80000000\n\n// === PE Section Characteristics\n\n/** Marks a section as containing initialized data, 0x00000040. */\nexport const PE_SCN_INITIALIZED_DATA = 0x00000040\n\n/** Marks a section as readable, 0x40000000. */\nexport const PE_SCN_MEM_READ = 0x40000000\n\n// === Platform\n\n/**\n * Holds the platform-specific SEA build configurations, keyed by\n * `process.platform` for `win32`, `darwin`, and `linux`.\n */\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/**\n * Maps a {@link SEACompressionMode} to its numeric Brotli mode value: `generic`\n * to 0, `text` to 1, and `font` to 2.\n */\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'\nimport { isInstance } from '@orkestrel/contract'\n\n// Error surface for the SEA 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 — `executeShell` maps a failed `executeSync` 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 * Represents the coded base error for every failure raised by the SEA 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 * sea.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 * Checks whether a value is a {@link SEAError}.\n *\n * @param value - The value to test\n * @returns True if `value` is a `SEAError`; false otherwise\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 isInstance(value, SEAError)\n}\n\n/**\n * Represents an error thrown when a shell command executed through `executeShell` 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 * executeShell(['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 * Checks whether a value is a {@link ShellError}.\n *\n * @param value - The value to test\n * @returns True if `value` is a `ShellError`; false otherwise\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 isInstance(value, ShellError)\n}\n","import type { ExecutableFormat } from './types.js'\nimport { literalOf } from '@orkestrel/contract'\n\n// === Type Guards\n\n/**\n * Checks whether a value is a valid {@link ExecutableFormat}.\n *\n * @param value - Value to check\n * @returns True if value is `'pe'`, `'elf'`, or `'macho'`; false otherwise\n *\n * @example\n * ```ts\n * isExecutableFormat('elf') // true\n * isExecutableFormat('coff') // false\n * ```\n */\nexport function isExecutableFormat(value: unknown): value is ExecutableFormat {\n\treturn literalOf('pe', 'elf', 'macho')(value)\n}\n","import type {\n\tELFNoteHeader,\n\tSEABlobOptions,\n\tSEABrotliOptions,\n\tSEACompressionHandler,\n\tSEACompressionManifest,\n\tSEACompressionResult,\n\tSEACompressionSize,\n\tSEAEntryOptions,\n\tSEAErrorCode,\n\tSEAPlatform,\n\tSEAShellOptions,\n\tSEAWindowsSignOptions,\n} from './types.js'\nimport {\n\tappendFileSync,\n\texistsSync,\n\topenSync,\n\treadSync,\n\treaddirSync,\n\treadFileSync,\n\trealpathSync,\n\tstatSync,\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 { detach, executeSync } from '@orkestrel/process/server'\nimport { isError, isString } from '@orkestrel/contract'\nimport {\n\tBROTLI_EXTENSION,\n\tDEFAULT_ENTRY_FORMAT,\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// === Platform Helpers\n\n/**\n * Resolves the effective platform configuration.\n *\n * @param platform - Platform identifier. Default: `process.platform`.\n * @returns Platform configuration, or undefined if unsupported\n */\nexport function resolvePlatform(platform?: string): SEAPlatform | undefined {\n\treturn SEA_PLATFORMS[platform ?? process.platform]\n}\n\n/**\n * Checks whether the current or named platform is supported for SEA builds.\n *\n * @param platform - Platform identifier to check\n * @returns True if the platform has a known configuration; false otherwise\n */\nexport function isPlatformSupported(platform?: string): boolean {\n\treturn (platform ?? process.platform) in SEA_PLATFORMS\n}\n\n// === Filesystem Helpers\n\n/**\n * Asserts 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 * @throws SEAError with `code` (default `'STATE'`) when `path` does not exist\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 * Checks whether a file's extension is outside `SKIP_EXTENSIONS`, so Brotli\n * compression applies to it.\n *\n * @param path - Path to the file\n * @returns True if the file type benefits from compression; false otherwise\n */\nexport function isCompressible(path: string): boolean {\n\tconst ext = extname(path).toLowerCase()\n\treturn !SKIP_EXTENSIONS.has(ext)\n}\n\n/**\n * Walks a directory recursively and returns every file path it finds, relative to\n * the base and skipping symlinks.\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 * Redacts password arguments from a shell command, so the command is safe to\n * include in an error message.\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 * Executes a command synchronously and returns 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 executeShell(command: readonly 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// `executeSync` spawns through the process package's own resolver and never through a\n\t// shell, and it refuses a batch-bound argument as `invalid` rather than passing it on.\n\t// Both streams are captured. `strict: false` returns the outcome so the failure is\n\t// mapped onto this module's coded errors.\n\tconst result = executeSync(\n\t\t{\n\t\t\tfile: cmd,\n\t\t\targuments: args,\n\t\t\t...(options?.env !== undefined ? { environment: options.env } : {}),\n\t\t},\n\t\t{\n\t\t\t...(options?.cwd !== undefined ? { workspace: options.cwd } : {}),\n\t\t\t...(options?.timeout !== undefined ? { timeout: options.timeout } : {}),\n\t\t\tstrict: false,\n\t\t},\n\t)\n\tif (result.expired) {\n\t\tthrow new SEAError('TIMEOUT', 'Shell command timed out', {\n\t\t\tcommand: redactCommand(command),\n\t\t\ttimeout: options?.timeout,\n\t\t})\n\t}\n\tif (result.failed) {\n\t\tconst redacted = redactCommand(command)\n\t\tthrow new ShellError(\n\t\t\t'Command failed: ' + redacted.join(' '),\n\t\t\tBuffer.from(result.stdout, 'utf-8'),\n\t\t\tBuffer.from(result.stderr, 'utf-8'),\n\t\t)\n\t}\n\treturn Buffer.from(result.stdout, 'utf-8')\n}\n\n// === Compression Helpers\n\n/**\n * Computes 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-compresses 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 - Brotli options (quality, mode)\n * @returns Compression result with size comparison\n * @throws SEAError with code `'OUTPUT'` when `output` is an existing symlink\n */\nexport function compressFile(\n\tinput: string,\n\toutput: string,\n\toptions?: SEABrotliOptions,\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` (for example `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 * Compresses all compressible files in a directory tree.\n *\n * @param directory - Absolute path to the directory\n * @param options - Brotli options (quality, mode)\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?: SEABrotliOptions,\n\tprogress?: SEACompressionHandler,\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// === Binary Helpers\n\n/**\n * Rounds a value up to the next multiple of an alignment boundary.\n *\n * @remarks\n * The shared alignment leaf behind every binary-format writer in this package:\n * PE section and file alignment, ELF note and page alignment, and Mach-O page\n * alignment all round the same way. `alignment` must be a nonzero power of two\n * ({@link isPowerOfTwo} is the guard the PE injector applies before using a\n * value read out of a header as a divisor).\n *\n * @param value - Value to align\n * @param alignment - Alignment boundary to round up to\n * @returns The value rounded up to the next multiple of `alignment`\n *\n * @example\n * ```ts\n * alignTo(10, 4) // 12\n * alignTo(4096, 4096) // 4096 — already aligned\n * ```\n */\nexport function alignTo(value: number, alignment: number): number {\n\tconst remainder = value % alignment\n\treturn remainder === 0 ? value : value + (alignment - remainder)\n}\n\n/**\n * Reads a 32-bit unsigned little-endian integer from a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to read from\n * @returns The 32-bit value\n * @throws SEAError with code `'FORMAT'` when fewer than four bytes are readable at `offset`\n *\n * @example\n * ```ts\n * const fd = openSync('app.exe', 'r')\n * readU32(fd, 0x3c) // the PE header offset\n * ```\n */\nexport function readU32(fd: number, offset: number): number {\n\tconst buf = Buffer.alloc(4)\n\tconst read = readSync(fd, buf, 0, 4, offset)\n\tif (read < 4) {\n\t\tthrow new SEAError('FORMAT', 'Short read', { offset, expected: 4, read })\n\t}\n\treturn buf.readUInt32LE(0)\n}\n\n/**\n * Reads a 64-bit unsigned little-endian integer from a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to read from\n * @returns The 64-bit value, as a `bigint`\n * @throws SEAError with code `'FORMAT'` when fewer than eight bytes are readable at `offset`\n *\n * @example\n * ```ts\n * const fd = openSync('app', 'r')\n * readU64(fd, 32) // the ELF program header table offset\n * ```\n */\nexport function readU64(fd: number, offset: number): bigint {\n\tconst buf = Buffer.alloc(8)\n\tconst read = readSync(fd, buf, 0, 8, offset)\n\tif (read < 8) {\n\t\tthrow new SEAError('FORMAT', 'Short read', { offset, expected: 8, read })\n\t}\n\treturn buf.readBigUInt64LE(0)\n}\n\n/**\n * Writes a 32-bit unsigned little-endian integer to a file descriptor.\n *\n * @remarks\n * Coerces `value` with `>>> 0` before writing, so a negative or out-of-range\n * number lands as its unsigned 32-bit representation rather than throwing.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to write at\n * @param value - The 32-bit value to write\n *\n * @example\n * ```ts\n * const fd = openSync('app.exe', 'r+')\n * writeU32(fd, 0x3c, 0x100)\n * ```\n */\nexport function writeU32(fd: number, offset: number, value: number): void {\n\tconst buf = Buffer.alloc(4)\n\tbuf.writeUInt32LE(value >>> 0, 0)\n\twriteSync(fd, buf, 0, 4, offset)\n}\n\n/**\n * Writes a 64-bit unsigned little-endian integer to a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to write at\n * @param value - The 64-bit value to write\n *\n * @example\n * ```ts\n * const fd = openSync('app', 'r+')\n * writeU64(fd, 32, 8192n)\n * ```\n */\nexport function writeU64(fd: number, offset: number, value: bigint): void {\n\tconst buf = Buffer.alloc(8)\n\tbuf.writeBigUInt64LE(value, 0)\n\twriteSync(fd, buf, 0, 8, offset)\n}\n\n/**\n * Appends a source file to a target file, streaming in fixed-size chunks.\n *\n * @remarks\n * Reads `source` in `chunk`-sized reads and appends each chunk to `target`, so\n * a multi-hundred-megabyte blob is never fully buffered. A read returning zero\n * bytes ends the copy, which is the normal end-of-file signal for a source that\n * shrank between the size read and the copy.\n *\n * @param target - Path of the file to append to\n * @param source - Path of the file to append\n * @param chunk - Read/append chunk size in bytes. Default: 4 MB.\n *\n * @example\n * ```ts\n * appendFile('dist/sea/app', 'dist/sea/sea-prep.blob')\n * ```\n */\nexport function appendFile(target: string, source: string, chunk = 4 * 1024 * 1024): void {\n\tconst fd = openSync(source, 'r')\n\ttry {\n\t\tconst size = statSync(source).size\n\t\tconst buffer = Buffer.alloc(Math.min(chunk, size))\n\t\tlet offset = 0\n\t\twhile (offset < size) {\n\t\t\tconst toRead = Math.min(chunk, size - offset)\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, toRead, offset)\n\t\t\tif (bytesRead === 0) break\n\t\t\tappendFileSync(target, buffer.subarray(0, bytesRead))\n\t\t\toffset += bytesRead\n\t\t}\n\t} finally {\n\t\tcloseSync(fd)\n\t}\n}\n\n/**\n * Truncates a NUL-padded binary name field at its first NUL character.\n *\n * @remarks\n * Binary name fields (PE section names, Mach-O segment and section names, ELF\n * note names) are fixed-width and NUL-padded, so the decoded string carries\n * trailing NUL characters that no comparison against a literal name matches.\n *\n * @param value - Decoded fixed-width name field\n * @returns The value up to, but excluding, its first NUL character\n *\n * @example\n * ```ts\n * stripTrailingNulls('.rsrc\\0\\0\\0') // '.rsrc'\n * ```\n */\nexport function stripTrailingNulls(value: string): string {\n\tconst index = value.indexOf('\\0')\n\treturn index === -1 ? value : value.slice(0, index)\n}\n\n// === PE Helpers\n\n/**\n * Checks whether a number is a nonzero power of two.\n *\n * @param value - Number to check\n * @returns True if the value is a positive power of two; false otherwise\n */\nexport function isPowerOfTwo(value: number): boolean {\n\treturn value > 0 && (value & (value - 1)) === 0\n}\n\n/**\n * Reads the PE header offset from a Windows executable.\n *\n * @param fd - Open file descriptor\n * @returns The offset to the PE signature\n * @throws SEAError with code `'FORMAT'` when fewer than four bytes are readable at `0x3c`\n */\nexport function readPEOffset(fd: number): number {\n\tconst buf = Buffer.alloc(4)\n\tconst read = readSync(fd, buf, 0, 4, 0x3c)\n\tif (read < 4) {\n\t\tthrow new SEAError('FORMAT', 'Short read', { offset: 0x3c, expected: 4, read })\n\t}\n\treturn buf.readUInt32LE(0)\n}\n\n/**\n * Reads 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 * @throws SEAError with code `'FORMAT'` when fewer than two bytes are readable at `offset`\n */\nexport function readU16(fd: number, offset: number): number {\n\tconst buf = Buffer.alloc(2)\n\tconst read = readSync(fd, buf, 0, 2, offset)\n\tif (read < 2) {\n\t\tthrow new SEAError('FORMAT', 'Short read', { offset, expected: 2, read })\n\t}\n\treturn buf.readUInt16LE(0)\n}\n\n/**\n * Writes 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 * Checks whether a file is a Windows PE executable.\n *\n * @param path - Path to the file\n * @returns True if the file has a valid PE signature; false otherwise\n */\nexport function isPEExecutable(path: string): boolean {\n\tlet fd: number | undefined\n\ttry {\n\t\tfd = openSync(path, 'r')\n\t\tconst peOffset = readPEOffset(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 * Patches 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 = readPEOffset(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 * Removes 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 skipped\n * 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 = readPEOffset(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 * Builds 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 `executeShell` — 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 `executeShell`\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 * buildSignCommand({ thumbprint: 'AABBCCDDEEFF00112233445566778899AABBCCDD' }, 'dist/sea/app.exe')\n * // ['signtool', 'sign', '/fd', 'sha256', '/sha1', 'AABBCCDDEEFF00112233445566778899AABBCCDD', 'dist/sea/app.exe']\n * ```\n */\nexport function buildSignCommand(sign: SEAWindowsSignOptions, target: string): readonly 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 * Formats a byte count as a human-readable string.\n *\n * @param bytes - Byte count\n * @returns Formatted string (for example `\"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 * Asserts 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 (for example `'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 * Asserts 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 (for example 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 (for example `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 = isError(thrown) ? 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 * Asserts 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 (for\n * example `'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 * Fsyncs 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 (for example `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\tisError(thrown) && 'code' in thrown && isString(thrown.code) ? thrown.code : 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 (for example 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 = isError(thrown) ? thrown.message : String(thrown)\n\t\tthrow new SEAError('OUTPUT', 'Failed to sync output directory', { path, cause })\n\t}\n}\n\n/**\n * Finalizes 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 = isError(thrown) ? 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 * Builds 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 = buildBlobConfig({ path: 'dist/bin/serve.cjs' }, 'dist/bin/sea-prep.blob', undefined)\n * ```\n */\nexport function buildBlobConfig(\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 ?? DEFAULT_ENTRY_FORMAT\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 * Aligns 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\treturn alignTo(value, 4)\n}\n\n/**\n * Builds 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, for example `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, total } = buildELFNoteHeader('NODE_SEA_BLOB', 4096)\n * ```\n */\nexport function buildELFNoteHeader(resource: string, blobSize: number): ELFNoteHeader {\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, total: header.length + alignedDescSize }\n}\n\n/**\n * Copies 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 * Patches the sentinel fuse in a binary from `:0` to `:1`.\n *\n * @remarks\n * Searches the file in 64 MB chunks with overlap to handle any file size. The fuse\n * signals to the Node.js runtime that a SEA blob is present. The `Injector` class\n * normally applies this patch, and it stays available standalone for a build that\n * injects the PE resource natively instead.\n *\n * @param executable - Absolute path to the executable\n * @param fuse - Sentinel fuse string (without the `:0` suffix)\n * @throws SEAError with code `'FUSE'` when the fuse value cannot be read\n * @throws SEAError with code `'FUSE'` when the fuse carries a value other than `:0` or `:1`\n * @throws SEAError with code `'FUSE'` when the fuse is not found in the executable\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 * Launches 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 * through `@orkestrel/process`'s `detach` (never a shell) so the URL cannot be\n * interpreted as a flag or injected into a command line. `detach` spawns the\n * child detached, with its stdio discarded and unreferenced, so the opener\n * outlives the host app and never keeps it alive, and it swallows the async\n * host fault an absent opener binary raises. Only `http:` and `https:` URLs\n * are accepted — any other scheme (including a string that merely looks like a\n * CLI flag, for example `'-e ...'`) fails to parse as an http(s) URL and is rejected\n * before 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 command =\n\t\tprocess.platform === 'win32'\n\t\t\t? { file: 'rundll32', arguments: ['url.dll,FileProtocolHandler', parsed.href] }\n\t\t\t: process.platform === 'darwin'\n\t\t\t\t? { file: 'open', arguments: [parsed.href] }\n\t\t\t\t: { file: 'xdg-open', arguments: [parsed.href] }\n\n\t// Best-effort fire-and-forget launch: `detach` refuses only a structurally\n\t// invalid command (an empty file name or a NUL character), which neither the\n\t// literal opener names nor a parsed http(s) `href` can carry, so the coded\n\t// `invalid` failure is unreachable from here. An absent opener binary raises\n\t// an async host fault instead, which `detach` swallows — a deliberate,\n\t// documented no-op, because there is no caller left to surface it to.\n\tdetach(command)\n}\n","import type {\n\tELFProgramHeader,\n\tExecutableFormat,\n\tInjectorInterface,\n\tInjectorOptions,\n\tPEResourceEntry,\n\tPEResourceLeaf,\n\tPESection,\n} 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\tELF_PT_LOAD,\n\tELF_PT_PHDR,\n\tELF_PF_R,\n\tELF_PAGE_SIZE,\n\tMACHO_MAGIC_64,\n\tMACHO_LC_SEGMENT_64,\n} from '../constants.js'\nimport {\n\talignTo,\n\tappendFile,\n\tbuildELFNoteHeader,\n\tcopyRange,\n\tfinalizeExecutable,\n\tisPowerOfTwo,\n\tpatchSentinelFuse,\n\treadU16,\n\treadU32,\n\treadU64,\n\tstripTrailingNulls,\n\twriteU16,\n\twriteU32,\n\twriteU64,\n} from '../helpers.js'\nimport { SEAError } from '../errors.js'\n\n/**\n * Writes a named resource into a PE, ELF, or Mach-O executable in place.\n *\n * @remarks\n * The format is detected from the file's magic bytes at construction, and each\n * format takes its own strategy: PE adds an `RT_RCDATA` resource by rebuilding the\n * resource directory, ELF appends a `PT_NOTE` segment carrying the blob as note\n * data, and Mach-O appends an `LC_SEGMENT_64` load command with one section. The\n * blob is streamed from disk in every case, so its size is bounded by the\n * filesystem rather than by memory.\n *\n * @param options - Injector options: the target executable, the resource name, the\n * blob path, and the optional sentinel fuse and Mach-O segment\n *\n * @example\n * ```ts\n * const injector = new Injector({\n * executable: 'dist/sea/myapp.exe',\n * resource: 'NODE_SEA_BLOB',\n * blob: 'dist/sea/sea-prep.blob',\n * fuse: 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2',\n * })\n * injector.format // 'pe' | 'elf' | 'macho'\n * injector.inject()\n * ```\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 = readU32(fd, 0x3c)\n\t\t\tconst sig = 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 = readU16(fd, coffOffset + 2)\n\t\t\tconst optionalHeaderSize = readU16(fd, coffOffset + 16)\n\t\t\tconst optionalOffset = coffOffset + 20\n\n\t\t\tconst optMagic = 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 = readU32(fd, optionalOffset + 32)\n\t\t\tconst fileAlignment = 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 = 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: PESection[] = []\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 = stripTrailingNulls(nameBuf.toString('ascii'))\n\t\t\t\tconst virtualSize = readU32(fd, off + 8)\n\t\t\t\tconst virtualAddress = readU32(fd, off + 12)\n\t\t\t\tconst rawSize = readU32(fd, off + 16)\n\t\t\t\tconst rawOffset = readU32(fd, off + 20)\n\t\t\t\tconst characteristics = 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'ROOM',\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: PEResourceLeaf[] = []\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 = alignTo(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 = alignTo(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 = alignTo(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\twriteU16(fd, coffOffset + 2, numberOfSections + 1)\n\n\t\t\t// Resource data directory → point to new section\n\t\t\twriteU32(fd, resourceDirRvaOffset, newVa)\n\t\t\twriteU32(fd, resourceDirSizeOffset, directoryBuffer.length)\n\n\t\t\t// SizeOfImage — must cover the new section\n\t\t\tconst newSizeOfImage = alignTo(\n\t\t\t\tnewVa + Math.max(newVirtualSize, alignedRawSize),\n\t\t\t\tsectionAlignment,\n\t\t\t)\n\t\t\twriteU32(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.#fixupDataEntries(directoryBuffer, 0, 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 = alignTo(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\tappendFile(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: PEResourceLeaf[],\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 = readU16(fd, absOffset + 12)\n\t\tconst numIdEntries = 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 = readU32(fd, entryOffset)\n\t\t\tconst offsetOrData = 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 = readU32(fd, dataEntryFileOffset)\n\t\t\t\tconst dataSize = readU32(fd, dataEntryFileOffset + 4)\n\t\t\t\tconst codePage = 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(rva: number, sections: readonly PESection[]): 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: readonly PEResourceLeaf[],\n\t\tblobName: string,\n\t\tblobSize: number,\n\t): Map<string, Map<string, PEResourceEntry[]>> {\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<string, Map<string, PEResourceEntry[]>>()\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: ReadonlyMap<string, ReadonlyMap<string, readonly PEResourceEntry[]>>,\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 = alignTo(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 = alignTo(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 += alignTo(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 = alignTo(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// #fixupDataEntries 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\t//\n\t// The serialized layout is [directories] [strings] [data entries], and each\n\t// data entry's first DWORD is the DataRVA that gains the section VA. The\n\t// entries are reached by re-walking the directory tree, whose level-2 entries\n\t// point at them.\n\n\t#fixupDataEntries(buf: Buffer, dirOffset: 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, 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\twriteU32(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 through 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\tlet phdrOffset: number\n\t\tlet phdrEntrySize: number\n\t\tlet phdrCount: number\n\t\tlet headers: readonly ELFProgramHeader[]\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(readU64(fd, 32)) // e_phoff\n\t\t\tphdrEntrySize = readU16(fd, 54) // e_phentsize\n\t\t\tphdrCount = readU16(fd, 56) // e_phnum\n\n\t\t\theaders = this.#readELFProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount)\n\n\t\t\t// Collect any stale PT_NOTE with a matching name, refusing the whole\n\t\t\t// injection first when the caller forbade an overwrite.\n\t\t\tconst stale = new Set<number>()\n\t\t\tfor (let i = 0; i < headers.length; i++) {\n\t\t\t\tconst header = headers[i]\n\t\t\t\tif (header === undefined || 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\tstale.add(i)\n\t\t\t}\n\n\t\t\t// Neutralize each stale note so overwrite never leaves two competing\n\t\t\t// \"NODE_SEA*\" notes visible to postject_find_resource — runtime skips\n\t\t\t// any non-PT_NOTE entry.\n\t\t\theaders = headers.map((header, index) => (stale.has(index) ? { ...header, type: 0 } : header))\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 !== ELF_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 = alignTo(maxVaddrEnd, ELF_PAGE_SIZE)\n\n\t\tconst blobSize = statSync(this.#options.blob).size\n\t\tconst { header: noteHeader, total: noteTotal } = buildELFNoteHeader(resource, blobSize)\n\t\tconst noteAreaSize = alignTo(noteTotal, 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 = alignTo(fileSize, ELF_PAGE_SIZE)\n\t\tconst phtOff = regionStart + noteAreaSize\n\n\t\tconst newLoad: ELFProgramHeader = {\n\t\t\ttype: ELF_PT_LOAD,\n\t\t\tflags: ELF_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: ELF_PAGE_SIZE,\n\t\t}\n\t\tconst newNote: ELFProgramHeader = {\n\t\t\ttype: ELF_PT_NOTE,\n\t\t\tflags: ELF_PF_R,\n\t\t\toffset: regionStart,\n\t\t\tvaddr: regionVaddr,\n\t\t\tpaddr: regionVaddr,\n\t\t\tfilesz: noteTotal,\n\t\t\tmemsz: noteTotal,\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 !== ELF_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\tappendFile(exePath, this.#options.blob)\n\n\t\tconst alignedDescSize = alignTo(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 - noteTotal\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\twriteU64(fd2, 32, BigInt(phtOff))\n\t\t\twriteU16(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): readonly ELFProgramHeader[] {\n\t\tconst headers: ELFProgramHeader[] = []\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: readU32(fd, off),\n\t\t\t\tflags: readU32(fd, off + 4),\n\t\t\t\toffset: Number(readU64(fd, off + 8)),\n\t\t\t\tvaddr: Number(readU64(fd, off + 16)),\n\t\t\t\tpaddr: Number(readU64(fd, off + 24)),\n\t\t\t\tfilesz: Number(readU64(fd, off + 32)),\n\t\t\t\tmemsz: Number(readU64(fd, off + 40)),\n\t\t\t\talign: Number(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(buf: Buffer, pos: number, entry: ELFProgramHeader): 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 = readU32(fd, offset)\n\t\tconst descsz = readU32(fd, offset + 4)\n\t\tif (namesz === 0 || namesz > 256) return undefined\n\t\tif (12 + alignTo(namesz, 4) + alignTo(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 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 === ELF_PT_LOAD)\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 to a custom name the\n\t// options carry, 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: only 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 = 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('ROOM', '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 linkeditOffset = Number(buf.readBigUInt64LE(linkeditCmd.offset + 40))\n\t\t\tconst linkeditSize = Number(buf.readBigUInt64LE(linkeditCmd.offset + 48))\n\t\t\tconst linkeditAddress = 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,\n\t\t\t// including x86_64, uses 4K — 0x4000 is a safe superset alignment for either.\n\t\t\tconst pageSize = cputype === 0x0100000c ? 0x4000 : 0x1000\n\t\t\tconst shift = alignTo(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'ROOM',\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\n\t\t\t// linkeditOffset as the \"does this offset point into __LINKEDIT\"\n\t\t\t// 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 = 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('ROOM', '__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(linkeditAddress + BigInt(shift), cmd.offset + 24) // vmaddr\n\t\t\t\t\t\tbuf.writeBigUInt64LE(BigInt(linkeditOffset + 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, linkeditOffset, 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(linkeditAddress, 24) // vmaddr\n\t\t\tcmd.writeBigUInt64LE(BigInt(shift), 32) // vmsize\n\t\t\tcmd.writeBigUInt64LE(BigInt(linkeditOffset), 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(linkeditAddress, sectOff + 32) // addr\n\t\t\tcmd.writeBigUInt64LE(BigInt(blobSize), sectOff + 40) // size\n\t\t\tcmd.writeUInt32LE(linkeditOffset, 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 linkeditOffset (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(\n\t\t\t\tsrcFd,\n\t\t\t\tdestFd,\n\t\t\t\theaderSize + newSizeofcmds,\n\t\t\t\tlinkeditOffset - (headerSize + newSizeofcmds),\n\t\t\t)\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, linkeditOffset, linkeditSize)\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 written.\n\t\t\tthis.#verifyMachOSection(exePath, segmentName, sectionName, linkeditOffset, 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 = 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 = 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// --- PE: validate section/file alignment before any `alignTo` call uses it\n\t// as a divisor — a malformed 0 value would otherwise silently corrupt\n\t// output through 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","import 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 { isError } from '@orkestrel/contract'\nimport {\n\tSEA_BLOB_RESOURCE,\n\tSEA_SENTINEL_FUSE,\n\tWINDOWS_SUBSYSTEM_CONSOLE,\n\tWINDOWS_SUBSYSTEM_GUI,\n} from '../constants.js'\nimport {\n\tbuildBlobConfig,\n\tbuildSignCommand,\n\tcompressDirectory,\n\tensureContained,\n\tensureExists,\n\tensureSafeKey,\n\tensureSafeName,\n\texecuteShell,\n\tfinalizeExecutable,\n\tisCompressible,\n\tisPEExecutable,\n\tpatchPESubsystem,\n\tresolvePlatform,\n\tstripPESignature,\n\twalkDirectory,\n} from '../helpers.js'\nimport { SEAError } from '../errors.js'\nimport { Injector } from '../injectors/Injector.js'\n\n/**\n * Runs a Node.js single executable application build to completion.\n *\n * @remarks\n * `execute` compresses the configured directories, generates the SEA blob, copies\n * the host Node binary, injects the blob with an {@link Injector}, signs the\n * result where the platform supports it, and moves the finished executable into\n * place atomically. Each stage reports on `emitter`, and every failure throws a\n * coded `SEAError` after an `error` event carrying it.\n *\n * @param options - SEA build options: the output name, the entry point, the output\n * directory, and the optional assets, compression, Windows, and blob settings\n *\n * @example\n * ```ts\n * const sea = new SEA({\n * name: 'myapp',\n * entry: { path: 'dist/server/serve.cjs' },\n * output: 'dist/sea',\n * })\n * const result = await sea.execute()\n * sea.destroy()\n * ```\n */\nexport class SEA implements SEAInterface {\n\t#status: SEAStatus = 'idle'\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.#emitter.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 = resolvePlatform()\n\t\tif (platform === undefined) {\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.#buildBlob(root, compression)\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\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\tensureContained(base, path)\n\t\t}\n\n\t\tfor (const path of this.#options.compression?.paths ?? []) {\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 — buildSignCommand is a pure argv builder.\n\t\t\tbuildSignCommand(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: Array<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#buildBlob(root: string, compression: SEACompressionManifest | undefined): 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 = buildBlobConfig(\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.#resolveAssets(root, compression),\n\t\t\tthis.#options.blob,\n\t\t)\n\n\t\twriteFileSync(configPath, JSON.stringify(config, null, 2))\n\t\texecuteShell([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\t...(this.#options.timeout === undefined ? {} : { timeout: this.#options.timeout }),\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 = resolvePlatform()\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 = {\n\t\t\t...(this.#options.signal === undefined ? {} : { signal: this.#options.signal }),\n\t\t\t...(this.#options.timeout === undefined ? {} : { timeout: this.#options.timeout }),\n\t\t}\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\texecuteShell([...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: isError(thrown) ? 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\texecuteShell([...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: isError(thrown) ? 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\texecuteShell([...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: isError(thrown) ? 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 — buildSignCommand's argv is passed\n\t\t\t\t\t// through executeShell 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 = buildSignCommand(signInput, temp)\n\t\t\t\t\ttry {\n\t\t\t\t\t\texecuteShell(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\texecuteShell([...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#resolveAssets(\n\t\troot: string,\n\t\tcompression: SEACompressionManifest | undefined,\n\t): Readonly<Record<string, string>> {\n\t\tconst outputs = new Map<string, string>()\n\t\tfor (const result of compression?.assets ?? []) {\n\t\t\toutputs.set(result.input, result.output)\n\t\t}\n\n\t\tconst assets: Record<string, string> = {}\n\t\tfor (const [name, path] of Object.entries(this.#options.assets ?? {})) {\n\t\t\tconst input = ensureContained(root, path)\n\t\t\tassets[name] = outputs.get(input) ?? input\n\t\t}\n\t\treturn assets\n\t}\n}\n","import type { AssetInput, AssetInterface } from '../types.js'\nimport { BROTLI_EXTENSION } from '../constants.js'\n\n/**\n * Holds one named asset's key, bytes, and compression state.\n *\n * @remarks\n * `compressed` is inferred from a `.br` suffix on the key whenever the input\n * leaves it unset, so a Brotli output registered under its own name reports itself\n * correctly without the caller restating it.\n *\n * @param input - The asset's key, content bytes, and optional compression flag\n *\n * @example\n * ```ts\n * const asset = new Asset({ key: 'client.html.br', content: compressedBuffer })\n * asset.key // 'client.html.br'\n * asset.compressed // true\n * ```\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","import type {\n\tAssetInput,\n\tAssetInterface,\n\tAssetManagerEventMap,\n\tAssetManagerInterface,\n\tAssetManagerOptions,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { getAssetKeys, getRawAsset, isSea } from 'node:sea'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArrayBuffer } from '@orkestrel/contract'\nimport { Asset } from './Asset.js'\n\n/**\n * Collects named assets from a SEA blob or from disk and serves them by key.\n *\n * @remarks\n * Construction registers every asset embedded in the running SEA blob, so an\n * executable built by this package reaches its assets without touching the\n * filesystem. Outside SEA mode that step registers nothing, and `load()` reads\n * the paths `options.assets` configures instead.\n *\n * @param options - Asset manager options: the project root, the key→path mapping\n * `load()` reads, and the event hooks\n *\n * @example\n * ```ts\n * const manager = new AssetManager({\n * root: process.cwd(),\n * assets: { 'client.html.br': 'dist/client/client.html.br' },\n * })\n * manager.load()\n * manager.asset('client.html.br')\n * manager.destroy()\n * ```\n */\nexport class AssetManager implements AssetManagerInterface {\n\treadonly #emitter: Emitter<AssetManagerEventMap>\n\t#assets = new Map<string, AssetInterface>()\n\treadonly #root: string\n\treadonly #paths: Readonly<Record<string, string>>\n\n\tconstructor(options?: AssetManagerOptions) {\n\t\tthis.#root = options?.root ?? process.cwd()\n\t\tthis.#paths = options?.assets ?? {}\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.#assets.keys()]\n\t}\n\n\tregister(input: AssetInput | readonly 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 registered: string[] = []\n\t\tfor (const [key, path] of Object.entries(this.#paths)) {\n\t\t\tconst resolved = resolve(this.#root, path)\n\t\t\tif (!existsSync(resolved)) {\n\t\t\t\tthis.#emitter.emit('error', new Error(`Asset not found: ${path}`))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst buffer = readFileSync(resolved)\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 asset: ${path}`)\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, content })\n\t\t\t\tregistered.push(key)\n\t\t\t} catch (thrown: unknown) {\n\t\t\t\tthis.#emitter.emit('error', thrown)\n\t\t\t}\n\t\t}\n\n\t\tif (registered.length > 0) {\n\t\t\tthis.#emitter.emit('load', registered)\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis.#assets.clear()\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}\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 './seas/SEA.js'\nimport { Injector } from './injectors/Injector.js'\nimport { Asset } from './assets/Asset.js'\nimport { AssetManager } from './assets/AssetManager.js'\n\n/**\n * Creates a SEA build orchestrator over the given options and returns it as a\n * `SEAInterface`, the published contract a caller holds instead of the `SEA` class.\n *\n * @param options - SEA build options\n * @returns a new `SEAInterface`\n *\n * @example Build a single executable\n * ```ts\n * import { createSEA, formatSize } from '@orkestrel/sea'\n *\n * const sea = createSEA({\n * \tname: 'myapp',\n * \tentry: { path: 'dist/server/serve.cjs' },\n * \toutput: 'dist/sea',\n * \tassets: { 'model.gguf': 'models/model.gguf' },\n * \tcompression: { paths: ['dist/app/browser'], mode: 'text' },\n * \twindows: { terminal: false },\n * \ttimeout: 30_000,\n * })\n *\n * const result = await sea.execute()\n * process.stdout.write(\n * \t`${result.executable} ${formatSize(result.size)} ${String(result.duration)}ms\\n`,\n * )\n * ```\n */\nexport function createSEA(options: SEAOptions): SEAInterface {\n\treturn new SEA(options)\n}\n\n/**\n * Creates a resource injector bound to one target executable and returns it as an\n * `InjectorInterface`, with the executable's format already detected from its header.\n *\n * @remarks\n * The format detected at construction — PE, ELF, or Mach-O — selects the strategy\n * `inject` takes. Every write runs through pure TypeScript file I/O, so the injector\n * needs no WASM and no external tool.\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 * Creates one named asset from a key and a content buffer and returns it as an\n * `AssetInterface`, with `compressed` inferred from the key where the input leaves\n * it unset.\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 * Creates an asset collection and returns it as an `AssetManagerInterface`, already\n * carrying whatever assets the running SEA blob embeds.\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":";;;;;;;;;;;;;AAMA,IAAa,oBAAoB;;AAGjC,IAAa,oBAAoB;;AAGjC,IAAa,kCAAkC;;;;;AAM/C,IAAa,wBAAwB;;AAGrC,IAAa,4BAA4B;;AAGzC,IAAa,mBAAmB;;;;;AAMhC,IAAa,kCAAuC,IAAI,IAAI;CAC3D;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;;AAKpD,IAAa,WAAW;;AAGxB,IAAa,eAAe;;AAG5B,IAAa,aAAa;;AAG1B,IAAa,kBAAkB;;;;;AAM/B,IAAa,YAAY;;AAGzB,IAAa,eAAe;;AAG5B,IAAa,eAAe;;AAG5B,IAAa,cAAc;;AAG3B,IAAa,cAAc;;AAG3B,IAAa,cAAc;;AAG3B,IAAa,WAAW;;AAGxB,IAAa,gBAAgB;;AAG7B,IAAa,iBAAiB;;AAG9B,IAAa,sBAAsB;;AAKnC,IAAa,eAAe;;AAG5B,IAAa,uBAAuB;;AAGpC,IAAa,yBAAyB;;AAGtC,IAAa,8BAA8B;;AAG3C,IAAa,yBAAyB;;;;;AAMtC,IAAa,0BAA0B;;;;;AAMvC,IAAa,wBAAwB;;AAKrC,IAAa,0BAA0B;;AAGvC,IAAa,kBAAkB;;;;;AAQ/B,IAAa,gBAAuD,OAAO,OAAO;CACjF,OAAO,OAAO,OAAO;EACpB,YAAY;EACZ,QAAQ,OAAO,OAAO;GAAC;GAAY;GAAU;EAAK,CAAC;CACpD,CAAC;CACD,QAAQ,OAAO,OAAO;EACrB,YAAY;EACZ,QAAQ,OAAO,OAAO,CAAC,YAAY,oBAAoB,CAAC;EACxD,MAAM,OAAO,OAAO;GAAC;GAAY;G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zlibConstants"],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/validators.ts","../../../src/server/helpers.ts","../../../src/server/injectors/Injector.ts","../../../src/server/seas/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/**\n * Holds the SEA sentinel fuse value embedded in the Node.js binary,\n * `NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2`.\n */\nexport const SEA_SENTINEL_FUSE = 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2'\n\n/** Names the SEA blob resource in the executable, `NODE_SEA_BLOB`. */\nexport const SEA_BLOB_RESOURCE = 'NODE_SEA_BLOB'\n\n/** Holds the default Brotli compression quality level, 11, the maximum Brotli accepts. */\nexport const DEFAULT_SEA_COMPRESSION_QUALITY = 11\n\n/**\n * Holds the Windows PE subsystem value for a GUI application, 2, which launches\n * without a terminal window.\n */\nexport const WINDOWS_SUBSYSTEM_GUI = 2\n\n/** Holds the Windows PE subsystem value for a console application, 3. */\nexport const WINDOWS_SUBSYSTEM_CONSOLE = 3\n\n/** Names the file extension indicating Brotli compression, `.br`. */\nexport const BROTLI_EXTENSION = '.br'\n\n/**\n * Lists the file extensions Brotli compression skips, the already-compressed\n * archive, image, font, and media formats.\n */\nexport const SKIP_EXTENSIONS: ReadonlySet<string> = 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/** Names the default SEA entry point module format when none is specified, `cjs`. */\nexport const DEFAULT_ENTRY_FORMAT: SEAEntryFormat = 'cjs'\n\n// === Binary Format Magic\n\n/** Holds the DOS MZ header magic, 0x5a4d, the first two bytes of a PE file. */\nexport const PE_MAGIC = 0x5a4d\n\n/** Holds the PE signature, 0x00004550, the bytes `PE\\0\\0` read as a 32-bit value. */\nexport const PE_SIGNATURE = 0x00004550\n\n/** Holds the PE32 optional header magic, 0x10b. */\nexport const PE32_MAGIC = 0x10b\n\n/** Holds the PE32+ optional header magic, 0x20b, the 64-bit form. */\nexport const PE32_PLUS_MAGIC = 0x20b\n\n/**\n * Holds the ELF magic, 0x7f454c46, the bytes 0x7F `E` `L` `F` read as a 32-bit\n * big-endian value.\n */\nexport const ELF_MAGIC = 0x7f454c46\n\n/** Holds the ELF 64-bit class identifier, 2. */\nexport const ELF_CLASS_64 = 2\n\n/** Holds the ELF little-endian data encoding, 1. */\nexport const ELF_DATA_LSB = 1\n\n/** Holds the ELF program header type for a note segment, 4. */\nexport const ELF_PT_NOTE = 4\n\n/** Holds the ELF program header type for a loadable segment, 1. */\nexport const ELF_PT_LOAD = 1\n\n/** Holds the ELF program header type for the program header table itself, 6. */\nexport const ELF_PT_PHDR = 6\n\n/** Holds the ELF segment permission flag marking a segment readable, 4. */\nexport const ELF_PF_R = 4\n\n/** Holds the page size an injected ELF segment is aligned to, 0x1000. */\nexport const ELF_PAGE_SIZE = 0x1000\n\n/** Holds the Mach-O 64-bit magic, 0xfeedfacf, in little-endian byte order. */\nexport const MACHO_MAGIC_64 = 0xfeedfacf\n\n/** Holds the Mach-O `LC_SEGMENT_64` load command, 0x19. */\nexport const MACHO_LC_SEGMENT_64 = 0x19\n\n// === PE Resource Directory\n\n/** Holds the PE resource type `RT_RCDATA` for raw data, 10. */\nexport const PE_RT_RCDATA = 10\n\n/** Holds the size of `IMAGE_RESOURCE_DIRECTORY` in bytes, 16. */\nexport const PE_RESOURCE_DIR_SIZE = 16\n\n/** Holds the size of `IMAGE_RESOURCE_DIRECTORY_ENTRY` in bytes, 8. */\nexport const PE_RESOURCE_ENTRY_SIZE = 8\n\n/** Holds the size of `IMAGE_RESOURCE_DATA_ENTRY` in bytes, 16. */\nexport const PE_RESOURCE_DATA_ENTRY_SIZE = 16\n\n/** Holds the PE section header size in bytes, 40. */\nexport const PE_SECTION_HEADER_SIZE = 40\n\n/**\n * Holds the high bit mask marking a resource directory entry offset as a\n * subdirectory, 0x80000000.\n */\nexport const PE_RESOURCE_SUBDIR_FLAG = 0x80000000\n\n/**\n * Holds the high bit mask marking a resource entry as named rather than\n * integer-identified, 0x80000000.\n */\nexport const PE_RESOURCE_NAME_FLAG = 0x80000000\n\n// === PE Section Characteristics\n\n/** Marks a section as containing initialized data, 0x00000040. */\nexport const PE_SCN_INITIALIZED_DATA = 0x00000040\n\n/** Marks a section as readable, 0x40000000. */\nexport const PE_SCN_MEM_READ = 0x40000000\n\n// === Platform\n\n/**\n * Holds the platform-specific SEA build configurations, keyed by\n * `process.platform` for `win32`, `darwin`, and `linux`.\n */\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/**\n * Maps a {@link SEACompressionMode} to its numeric Brotli mode value: `generic`\n * to 0, `text` to 1, and `font` to 2.\n */\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'\nimport { isInstance } from '@orkestrel/contract'\n\n// Error surface for the SEA 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 — `executeShell` maps a failed `executeSync` 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 * Represents the coded base error for every failure raised by the SEA 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 * sea.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 * Checks whether a value is a {@link SEAError}.\n *\n * @param value - The value to test\n * @returns True if `value` is a `SEAError`; false otherwise\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 isInstance(value, SEAError)\n}\n\n/**\n * Represents an error thrown when a shell command executed through `executeShell` 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 * executeShell(['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 * Checks whether a value is a {@link ShellError}.\n *\n * @param value - The value to test\n * @returns True if `value` is a `ShellError`; false otherwise\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 isInstance(value, ShellError)\n}\n","import type { ExecutableFormat } from './types.js'\nimport { literalOf } from '@orkestrel/contract'\n\n// === Type Guards\n\n/**\n * Checks whether a value is a valid {@link ExecutableFormat}.\n *\n * @param value - Value to check\n * @returns True if value is `'pe'`, `'elf'`, or `'macho'`; false otherwise\n *\n * @example\n * ```ts\n * isExecutableFormat('elf') // true\n * isExecutableFormat('coff') // false\n * ```\n */\nexport function isExecutableFormat(value: unknown): value is ExecutableFormat {\n\treturn literalOf('pe', 'elf', 'macho')(value)\n}\n","import type {\n\tELFNoteHeader,\n\tSEABlobOptions,\n\tSEABrotliOptions,\n\tSEACompressionHandler,\n\tSEACompressionManifest,\n\tSEACompressionResult,\n\tSEACompressionSize,\n\tSEAEntryOptions,\n\tSEAErrorCode,\n\tSEAPlatform,\n\tSEAShellOptions,\n\tSEAWindowsSignOptions,\n} from './types.js'\nimport {\n\tappendFileSync,\n\texistsSync,\n\topenSync,\n\treadSync,\n\treaddirSync,\n\treadFileSync,\n\trealpathSync,\n\tstatSync,\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 { detach, executeSync } from '@orkestrel/process/server'\nimport { isError, isString } from '@orkestrel/contract'\nimport {\n\tBROTLI_EXTENSION,\n\tDEFAULT_ENTRY_FORMAT,\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// === Platform Helpers\n\n/**\n * Resolves the effective platform configuration.\n *\n * @param platform - Platform identifier. Default: `process.platform`.\n * @returns Platform configuration, or undefined if unsupported\n */\nexport function resolvePlatform(platform?: string): SEAPlatform | undefined {\n\treturn SEA_PLATFORMS[platform ?? process.platform]\n}\n\n/**\n * Checks whether the current or named platform is supported for SEA builds.\n *\n * @param platform - Platform identifier to check\n * @returns True if the platform has a known configuration; false otherwise\n */\nexport function isPlatformSupported(platform?: string): boolean {\n\treturn (platform ?? process.platform) in SEA_PLATFORMS\n}\n\n// === Filesystem Helpers\n\n/**\n * Asserts 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 * @throws SEAError with `code` (default `'STATE'`) when `path` does not exist\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 * Checks whether a file's extension is outside `SKIP_EXTENSIONS`, so Brotli\n * compression applies to it.\n *\n * @param path - Path to the file\n * @returns True if the file type benefits from compression; false otherwise\n */\nexport function isCompressible(path: string): boolean {\n\tconst ext = extname(path).toLowerCase()\n\treturn !SKIP_EXTENSIONS.has(ext)\n}\n\n/**\n * Walks a directory recursively and returns every file path it finds, relative to\n * the base and skipping symlinks.\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 * Redacts password arguments from a shell command, so the command is safe to\n * include in an error message.\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 * Executes a command synchronously and returns 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 executeShell(command: readonly 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// `executeSync` spawns through the process package's own resolver and never through a\n\t// shell, and it refuses a batch-bound argument as `invalid` rather than passing it on.\n\t// Both streams are captured. `strict: false` returns the outcome so the failure is\n\t// mapped onto this module's coded errors.\n\tconst result = executeSync(\n\t\t{\n\t\t\tfile: cmd,\n\t\t\targuments: args,\n\t\t\t...(options?.env !== undefined ? { environment: options.env } : {}),\n\t\t},\n\t\t{\n\t\t\t...(options?.cwd !== undefined ? { workspace: options.cwd } : {}),\n\t\t\t...(options?.timeout !== undefined ? { timeout: options.timeout } : {}),\n\t\t\tstrict: false,\n\t\t},\n\t)\n\tif (result.expired) {\n\t\tthrow new SEAError('TIMEOUT', 'Shell command timed out', {\n\t\t\tcommand: redactCommand(command),\n\t\t\ttimeout: options?.timeout,\n\t\t})\n\t}\n\tif (result.failed) {\n\t\tconst redacted = redactCommand(command)\n\t\tthrow new ShellError(\n\t\t\t'Command failed: ' + redacted.join(' '),\n\t\t\tBuffer.from(result.stdout, 'utf-8'),\n\t\t\tBuffer.from(result.stderr, 'utf-8'),\n\t\t)\n\t}\n\treturn Buffer.from(result.stdout, 'utf-8')\n}\n\n// === Compression Helpers\n\n/**\n * Computes 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-compresses 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 - Brotli options (quality, mode)\n * @returns Compression result with size comparison\n * @throws SEAError with code `'OUTPUT'` when `output` is an existing symlink\n */\nexport function compressFile(\n\tinput: string,\n\toutput: string,\n\toptions?: SEABrotliOptions,\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` (for example `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 * Compresses all compressible files in a directory tree.\n *\n * @param directory - Absolute path to the directory\n * @param options - Brotli options (quality, mode)\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?: SEABrotliOptions,\n\tprogress?: SEACompressionHandler,\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// === Binary Helpers\n\n/**\n * Rounds a value up to the next multiple of an alignment boundary.\n *\n * @remarks\n * The shared alignment leaf behind every binary-format writer in this package:\n * PE section and file alignment, ELF note and page alignment, and Mach-O page\n * alignment all round the same way. `alignment` must be a nonzero power of two\n * ({@link isPowerOfTwo} is the guard the PE injector applies before using a\n * value read out of a header as a divisor).\n *\n * @param value - Value to align\n * @param alignment - Alignment boundary to round up to\n * @returns The value rounded up to the next multiple of `alignment`\n *\n * @example\n * ```ts\n * alignTo(10, 4) // 12\n * alignTo(4096, 4096) // 4096 — already aligned\n * ```\n */\nexport function alignTo(value: number, alignment: number): number {\n\tconst remainder = value % alignment\n\treturn remainder === 0 ? value : value + (alignment - remainder)\n}\n\n/**\n * Reads a 32-bit unsigned little-endian integer from a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to read from\n * @returns The 32-bit value\n * @throws SEAError with code `'FORMAT'` when fewer than four bytes are readable at `offset`\n *\n * @example\n * ```ts\n * const fd = openSync('app.exe', 'r')\n * readU32(fd, 0x3c) // the PE header offset\n * ```\n */\nexport function readU32(fd: number, offset: number): number {\n\tconst buf = Buffer.alloc(4)\n\tconst read = readSync(fd, buf, 0, 4, offset)\n\tif (read < 4) {\n\t\tthrow new SEAError('FORMAT', 'Short read', { offset, expected: 4, read })\n\t}\n\treturn buf.readUInt32LE(0)\n}\n\n/**\n * Reads a 64-bit unsigned little-endian integer from a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to read from\n * @returns The 64-bit value, as a `bigint`\n * @throws SEAError with code `'FORMAT'` when fewer than eight bytes are readable at `offset`\n *\n * @example\n * ```ts\n * const fd = openSync('app', 'r')\n * readU64(fd, 32) // the ELF program header table offset\n * ```\n */\nexport function readU64(fd: number, offset: number): bigint {\n\tconst buf = Buffer.alloc(8)\n\tconst read = readSync(fd, buf, 0, 8, offset)\n\tif (read < 8) {\n\t\tthrow new SEAError('FORMAT', 'Short read', { offset, expected: 8, read })\n\t}\n\treturn buf.readBigUInt64LE(0)\n}\n\n/**\n * Writes a 32-bit unsigned little-endian integer to a file descriptor.\n *\n * @remarks\n * Coerces `value` with `>>> 0` before writing, so a negative or out-of-range\n * number lands as its unsigned 32-bit representation rather than throwing.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to write at\n * @param value - The 32-bit value to write\n *\n * @example\n * ```ts\n * const fd = openSync('app.exe', 'r+')\n * writeU32(fd, 0x3c, 0x100)\n * ```\n */\nexport function writeU32(fd: number, offset: number, value: number): void {\n\tconst buf = Buffer.alloc(4)\n\tbuf.writeUInt32LE(value >>> 0, 0)\n\twriteSync(fd, buf, 0, 4, offset)\n}\n\n/**\n * Writes a 64-bit unsigned little-endian integer to a file descriptor.\n *\n * @param fd - Open file descriptor\n * @param offset - Byte offset to write at\n * @param value - The 64-bit value to write\n *\n * @example\n * ```ts\n * const fd = openSync('app', 'r+')\n * writeU64(fd, 32, 8192n)\n * ```\n */\nexport function writeU64(fd: number, offset: number, value: bigint): void {\n\tconst buf = Buffer.alloc(8)\n\tbuf.writeBigUInt64LE(value, 0)\n\twriteSync(fd, buf, 0, 8, offset)\n}\n\n/**\n * Appends a source file to a target file, streaming in fixed-size chunks.\n *\n * @remarks\n * Reads `source` in `chunk`-sized reads and appends each chunk to `target`, so\n * a multi-hundred-megabyte blob is never fully buffered. A read returning zero\n * bytes ends the copy, which is the normal end-of-file signal for a source that\n * shrank between the size read and the copy.\n *\n * @param target - Path of the file to append to\n * @param source - Path of the file to append\n * @param chunk - Read/append chunk size in bytes. Default: 4 MB.\n *\n * @example\n * ```ts\n * appendFile('dist/sea/app', 'dist/sea/sea-prep.blob')\n * ```\n */\nexport function appendFile(target: string, source: string, chunk = 4 * 1024 * 1024): void {\n\tconst fd = openSync(source, 'r')\n\ttry {\n\t\tconst size = statSync(source).size\n\t\tconst buffer = Buffer.alloc(Math.min(chunk, size))\n\t\tlet offset = 0\n\t\twhile (offset < size) {\n\t\t\tconst toRead = Math.min(chunk, size - offset)\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, toRead, offset)\n\t\t\tif (bytesRead === 0) break\n\t\t\tappendFileSync(target, buffer.subarray(0, bytesRead))\n\t\t\toffset += bytesRead\n\t\t}\n\t} finally {\n\t\tcloseSync(fd)\n\t}\n}\n\n/**\n * Truncates a NUL-padded binary name field at its first NUL character.\n *\n * @remarks\n * Binary name fields (PE section names, Mach-O segment and section names, ELF\n * note names) are fixed-width and NUL-padded, so the decoded string carries\n * trailing NUL characters that no comparison against a literal name matches.\n *\n * @param value - Decoded fixed-width name field\n * @returns The value up to, but excluding, its first NUL character\n *\n * @example\n * ```ts\n * stripTrailingNulls('.rsrc\\0\\0\\0') // '.rsrc'\n * ```\n */\nexport function stripTrailingNulls(value: string): string {\n\tconst index = value.indexOf('\\0')\n\treturn index === -1 ? value : value.slice(0, index)\n}\n\n// === PE Helpers\n\n/**\n * Checks whether a number is a nonzero power of two.\n *\n * @param value - Number to check\n * @returns True if the value is a positive power of two; false otherwise\n */\nexport function isPowerOfTwo(value: number): boolean {\n\treturn value > 0 && (value & (value - 1)) === 0\n}\n\n/**\n * Reads the PE header offset from a Windows executable.\n *\n * @param fd - Open file descriptor\n * @returns The offset to the PE signature\n * @throws SEAError with code `'FORMAT'` when fewer than four bytes are readable at `0x3c`\n */\nexport function readPEOffset(fd: number): number {\n\tconst buf = Buffer.alloc(4)\n\tconst read = readSync(fd, buf, 0, 4, 0x3c)\n\tif (read < 4) {\n\t\tthrow new SEAError('FORMAT', 'Short read', { offset: 0x3c, expected: 4, read })\n\t}\n\treturn buf.readUInt32LE(0)\n}\n\n/**\n * Reads 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 * @throws SEAError with code `'FORMAT'` when fewer than two bytes are readable at `offset`\n */\nexport function readU16(fd: number, offset: number): number {\n\tconst buf = Buffer.alloc(2)\n\tconst read = readSync(fd, buf, 0, 2, offset)\n\tif (read < 2) {\n\t\tthrow new SEAError('FORMAT', 'Short read', { offset, expected: 2, read })\n\t}\n\treturn buf.readUInt16LE(0)\n}\n\n/**\n * Writes 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 * Checks whether a file is a Windows PE executable.\n *\n * @param path - Path to the file\n * @returns True if the file has a valid PE signature; false otherwise\n */\nexport function isPEExecutable(path: string): boolean {\n\tlet fd: number | undefined\n\ttry {\n\t\tfd = openSync(path, 'r')\n\t\tconst peOffset = readPEOffset(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 * Patches 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 = readPEOffset(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 * Removes 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 skipped\n * 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 = readPEOffset(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 * Builds 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 `executeShell` — 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 `executeShell`\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 * buildSignCommand({ thumbprint: 'AABBCCDDEEFF00112233445566778899AABBCCDD' }, 'dist/sea/app.exe')\n * // ['signtool', 'sign', '/fd', 'sha256', '/sha1', 'AABBCCDDEEFF00112233445566778899AABBCCDD', 'dist/sea/app.exe']\n * ```\n */\nexport function buildSignCommand(sign: SEAWindowsSignOptions, target: string): readonly 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 * Formats a byte count as a human-readable string.\n *\n * @param bytes - Byte count\n * @returns Formatted string (for example `\"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 * Asserts 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 (for example `'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 * Asserts 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 (for example 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 (for example `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 = isError(thrown) ? 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 * Asserts 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 (for\n * example `'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 * Fsyncs 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 (for example `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\tisError(thrown) && 'code' in thrown && isString(thrown.code) ? thrown.code : 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 (for example 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 = isError(thrown) ? thrown.message : String(thrown)\n\t\tthrow new SEAError('OUTPUT', 'Failed to sync output directory', { path, cause })\n\t}\n}\n\n/**\n * Finalizes 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 = isError(thrown) ? 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 * Builds 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 = buildBlobConfig({ path: 'dist/bin/serve.cjs' }, 'dist/bin/sea-prep.blob', undefined)\n * ```\n */\nexport function buildBlobConfig(\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 ?? DEFAULT_ENTRY_FORMAT\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 * Aligns 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\treturn alignTo(value, 4)\n}\n\n/**\n * Builds 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, for example `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, total } = buildELFNoteHeader('NODE_SEA_BLOB', 4096)\n * ```\n */\nexport function buildELFNoteHeader(resource: string, blobSize: number): ELFNoteHeader {\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, total: header.length + alignedDescSize }\n}\n\n/**\n * Copies 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 * Patches the sentinel fuse in a binary from `:0` to `:1`.\n *\n * @remarks\n * Searches the file in 64 MB chunks with overlap to handle any file size. The fuse\n * signals to the Node.js runtime that a SEA blob is present. The `Injector` class\n * normally applies this patch, and it stays available standalone for a build that\n * injects the PE resource natively instead.\n *\n * @param executable - Absolute path to the executable\n * @param fuse - Sentinel fuse string (without the `:0` suffix)\n * @throws SEAError with code `'FUSE'` when the fuse value cannot be read\n * @throws SEAError with code `'FUSE'` when the fuse carries a value other than `:0` or `:1`\n * @throws SEAError with code `'FUSE'` when the fuse is not found in the executable\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 * Launches 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 * through `@orkestrel/process`'s `detach` (never a shell) so the URL cannot be\n * interpreted as a flag or injected into a command line. `detach` spawns the\n * child detached, with its stdio discarded and unreferenced, so the opener\n * outlives the host app and never keeps it alive, and it swallows the async\n * host fault an absent opener binary raises. Only `http:` and `https:` URLs\n * are accepted — any other scheme (including a string that merely looks like a\n * CLI flag, for example `'-e ...'`) fails to parse as an http(s) URL and is rejected\n * before 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 command =\n\t\tprocess.platform === 'win32'\n\t\t\t? { file: 'rundll32', arguments: ['url.dll,FileProtocolHandler', parsed.href] }\n\t\t\t: process.platform === 'darwin'\n\t\t\t\t? { file: 'open', arguments: [parsed.href] }\n\t\t\t\t: { file: 'xdg-open', arguments: [parsed.href] }\n\n\t// Best-effort fire-and-forget launch: `detach` refuses only a structurally\n\t// invalid command (an empty file name or a NUL character), which neither the\n\t// literal opener names nor a parsed http(s) `href` can carry, so the coded\n\t// `invalid` failure is unreachable from here. An absent opener binary raises\n\t// an async host fault instead, which `detach` swallows — a deliberate,\n\t// documented no-op, because there is no caller left to surface it to.\n\tdetach(command)\n}\n","import type {\n\tELFProgramHeader,\n\tExecutableFormat,\n\tInjectorInterface,\n\tInjectorOptions,\n\tPEResourceEntry,\n\tPEResourceLeaf,\n\tPESection,\n} 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\tELF_PT_LOAD,\n\tELF_PT_PHDR,\n\tELF_PF_R,\n\tELF_PAGE_SIZE,\n\tMACHO_MAGIC_64,\n\tMACHO_LC_SEGMENT_64,\n} from '../constants.js'\nimport {\n\talignTo,\n\tappendFile,\n\tbuildELFNoteHeader,\n\tcopyRange,\n\tfinalizeExecutable,\n\tisPowerOfTwo,\n\tpatchSentinelFuse,\n\treadU16,\n\treadU32,\n\treadU64,\n\tstripTrailingNulls,\n\twriteU16,\n\twriteU32,\n\twriteU64,\n} from '../helpers.js'\nimport { SEAError } from '../errors.js'\n\n/**\n * Writes a named resource into a PE, ELF, or Mach-O executable in place.\n *\n * @remarks\n * The format is detected from the file's magic bytes at construction, and each\n * format takes its own strategy: PE adds an `RT_RCDATA` resource by rebuilding the\n * resource directory, ELF appends a `PT_NOTE` segment carrying the blob as note\n * data, and Mach-O appends an `LC_SEGMENT_64` load command with one section. The\n * blob is streamed from disk in every case, so its size is bounded by the\n * filesystem rather than by memory.\n *\n * @param options - Injector options: the target executable, the resource name, the\n * blob path, and the optional sentinel fuse and Mach-O segment\n *\n * @example\n * ```ts\n * const injector = new Injector({\n * executable: 'dist/sea/myapp.exe',\n * resource: 'NODE_SEA_BLOB',\n * blob: 'dist/sea/sea-prep.blob',\n * fuse: 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2',\n * })\n * injector.format // 'pe' | 'elf' | 'macho'\n * injector.inject()\n * ```\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 = readU32(fd, 0x3c)\n\t\t\tconst sig = 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 = readU16(fd, coffOffset + 2)\n\t\t\tconst optionalHeaderSize = readU16(fd, coffOffset + 16)\n\t\t\tconst optionalOffset = coffOffset + 20\n\n\t\t\tconst optMagic = 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 = readU32(fd, optionalOffset + 32)\n\t\t\tconst fileAlignment = 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 = 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: PESection[] = []\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 = stripTrailingNulls(nameBuf.toString('ascii'))\n\t\t\t\tconst virtualSize = readU32(fd, off + 8)\n\t\t\t\tconst virtualAddress = readU32(fd, off + 12)\n\t\t\t\tconst rawSize = readU32(fd, off + 16)\n\t\t\t\tconst rawOffset = readU32(fd, off + 20)\n\t\t\t\tconst characteristics = 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'ROOM',\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: PEResourceLeaf[] = []\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 = alignTo(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 = alignTo(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 = alignTo(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\twriteU16(fd, coffOffset + 2, numberOfSections + 1)\n\n\t\t\t// Resource data directory → point to new section\n\t\t\twriteU32(fd, resourceDirRvaOffset, newVa)\n\t\t\twriteU32(fd, resourceDirSizeOffset, directoryBuffer.length)\n\n\t\t\t// SizeOfImage — must cover the new section\n\t\t\tconst newSizeOfImage = alignTo(\n\t\t\t\tnewVa + Math.max(newVirtualSize, alignedRawSize),\n\t\t\t\tsectionAlignment,\n\t\t\t)\n\t\t\twriteU32(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.#fixupDataEntries(directoryBuffer, 0, 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 = alignTo(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\tappendFile(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: PEResourceLeaf[],\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 = readU16(fd, absOffset + 12)\n\t\tconst numIdEntries = 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 = readU32(fd, entryOffset)\n\t\t\tconst offsetOrData = 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 = readU32(fd, dataEntryFileOffset)\n\t\t\t\tconst dataSize = readU32(fd, dataEntryFileOffset + 4)\n\t\t\t\tconst codePage = 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(rva: number, sections: readonly PESection[]): 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: readonly PEResourceLeaf[],\n\t\tblobName: string,\n\t\tblobSize: number,\n\t): Map<string, Map<string, PEResourceEntry[]>> {\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<string, Map<string, PEResourceEntry[]>>()\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: ReadonlyMap<string, ReadonlyMap<string, readonly PEResourceEntry[]>>,\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 = alignTo(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 = alignTo(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 += alignTo(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 = alignTo(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// #fixupDataEntries 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\t//\n\t// The serialized layout is [directories] [strings] [data entries], and each\n\t// data entry's first DWORD is the DataRVA that gains the section VA. The\n\t// entries are reached by re-walking the directory tree, whose level-2 entries\n\t// point at them.\n\n\t#fixupDataEntries(buf: Buffer, dirOffset: 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, 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\twriteU32(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 through 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\tlet phdrOffset: number\n\t\tlet phdrEntrySize: number\n\t\tlet phdrCount: number\n\t\tlet headers: readonly ELFProgramHeader[]\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(readU64(fd, 32)) // e_phoff\n\t\t\tphdrEntrySize = readU16(fd, 54) // e_phentsize\n\t\t\tphdrCount = readU16(fd, 56) // e_phnum\n\n\t\t\theaders = this.#readELFProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount)\n\n\t\t\t// Collect any stale PT_NOTE with a matching name, refusing the whole\n\t\t\t// injection first when the caller forbade an overwrite.\n\t\t\tconst stale = new Set<number>()\n\t\t\tfor (let i = 0; i < headers.length; i++) {\n\t\t\t\tconst header = headers[i]\n\t\t\t\tif (header === undefined || 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\tstale.add(i)\n\t\t\t}\n\n\t\t\t// Neutralize each stale note so overwrite never leaves two competing\n\t\t\t// \"NODE_SEA*\" notes visible to postject_find_resource — runtime skips\n\t\t\t// any non-PT_NOTE entry.\n\t\t\theaders = headers.map((header, index) => (stale.has(index) ? { ...header, type: 0 } : header))\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 !== ELF_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 = alignTo(maxVaddrEnd, ELF_PAGE_SIZE)\n\n\t\tconst blobSize = statSync(this.#options.blob).size\n\t\tconst { header: noteHeader, total: noteTotal } = buildELFNoteHeader(resource, blobSize)\n\t\tconst noteAreaSize = alignTo(noteTotal, 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 = alignTo(fileSize, ELF_PAGE_SIZE)\n\t\tconst phtOff = regionStart + noteAreaSize\n\n\t\tconst newLoad: ELFProgramHeader = {\n\t\t\ttype: ELF_PT_LOAD,\n\t\t\tflags: ELF_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: ELF_PAGE_SIZE,\n\t\t}\n\t\tconst newNote: ELFProgramHeader = {\n\t\t\ttype: ELF_PT_NOTE,\n\t\t\tflags: ELF_PF_R,\n\t\t\toffset: regionStart,\n\t\t\tvaddr: regionVaddr,\n\t\t\tpaddr: regionVaddr,\n\t\t\tfilesz: noteTotal,\n\t\t\tmemsz: noteTotal,\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 !== ELF_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\tappendFile(exePath, this.#options.blob)\n\n\t\tconst alignedDescSize = alignTo(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 - noteTotal\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\twriteU64(fd2, 32, BigInt(phtOff))\n\t\t\twriteU16(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): readonly ELFProgramHeader[] {\n\t\tconst headers: ELFProgramHeader[] = []\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: readU32(fd, off),\n\t\t\t\tflags: readU32(fd, off + 4),\n\t\t\t\toffset: Number(readU64(fd, off + 8)),\n\t\t\t\tvaddr: Number(readU64(fd, off + 16)),\n\t\t\t\tpaddr: Number(readU64(fd, off + 24)),\n\t\t\t\tfilesz: Number(readU64(fd, off + 32)),\n\t\t\t\tmemsz: Number(readU64(fd, off + 40)),\n\t\t\t\talign: Number(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(buf: Buffer, pos: number, entry: ELFProgramHeader): 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 = readU32(fd, offset)\n\t\tconst descsz = readU32(fd, offset + 4)\n\t\tif (namesz === 0 || namesz > 256) return undefined\n\t\tif (12 + alignTo(namesz, 4) + alignTo(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 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 === ELF_PT_LOAD)\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 to a custom name the\n\t// options carry, 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: only 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 = 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('ROOM', '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 linkeditOffset = Number(buf.readBigUInt64LE(linkeditCmd.offset + 40))\n\t\t\tconst linkeditSize = Number(buf.readBigUInt64LE(linkeditCmd.offset + 48))\n\t\t\tconst linkeditAddress = 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,\n\t\t\t// including x86_64, uses 4K — 0x4000 is a safe superset alignment for either.\n\t\t\tconst pageSize = cputype === 0x0100000c ? 0x4000 : 0x1000\n\t\t\tconst shift = alignTo(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'ROOM',\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\n\t\t\t// linkeditOffset as the \"does this offset point into __LINKEDIT\"\n\t\t\t// 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 = 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('ROOM', '__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(linkeditAddress + BigInt(shift), cmd.offset + 24) // vmaddr\n\t\t\t\t\t\tbuf.writeBigUInt64LE(BigInt(linkeditOffset + 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, linkeditOffset, 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(linkeditAddress, 24) // vmaddr\n\t\t\tcmd.writeBigUInt64LE(BigInt(shift), 32) // vmsize\n\t\t\tcmd.writeBigUInt64LE(BigInt(linkeditOffset), 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(linkeditAddress, sectOff + 32) // addr\n\t\t\tcmd.writeBigUInt64LE(BigInt(blobSize), sectOff + 40) // size\n\t\t\tcmd.writeUInt32LE(linkeditOffset, 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 linkeditOffset (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(\n\t\t\t\tsrcFd,\n\t\t\t\tdestFd,\n\t\t\t\theaderSize + newSizeofcmds,\n\t\t\t\tlinkeditOffset - (headerSize + newSizeofcmds),\n\t\t\t)\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, linkeditOffset, linkeditSize)\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 written.\n\t\t\tthis.#verifyMachOSection(exePath, segmentName, sectionName, linkeditOffset, 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 = 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 = 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// --- PE: validate section/file alignment before any `alignTo` call uses it\n\t// as a divisor — a malformed 0 value would otherwise silently corrupt\n\t// output through 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","import 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 { isError } from '@orkestrel/contract'\nimport {\n\tSEA_BLOB_RESOURCE,\n\tSEA_SENTINEL_FUSE,\n\tWINDOWS_SUBSYSTEM_CONSOLE,\n\tWINDOWS_SUBSYSTEM_GUI,\n} from '../constants.js'\nimport {\n\tbuildBlobConfig,\n\tbuildSignCommand,\n\tcompressDirectory,\n\tensureContained,\n\tensureExists,\n\tensureSafeKey,\n\tensureSafeName,\n\texecuteShell,\n\tfinalizeExecutable,\n\tisCompressible,\n\tisPEExecutable,\n\tpatchPESubsystem,\n\tresolvePlatform,\n\tstripPESignature,\n\twalkDirectory,\n} from '../helpers.js'\nimport { SEAError } from '../errors.js'\nimport { Injector } from '../injectors/Injector.js'\n\n/**\n * Runs a Node.js single executable application build to completion.\n *\n * @remarks\n * `execute` compresses the configured directories, generates the SEA blob, copies\n * the host Node binary, injects the blob with an {@link Injector}, signs the\n * result where the platform supports it, and moves the finished executable into\n * place atomically. Each stage reports on `emitter`, and every failure throws a\n * coded `SEAError` after an `error` event carrying it.\n *\n * @param options - SEA build options: the output name, the entry point, the output\n * directory, and the optional assets, compression, Windows, and blob settings\n *\n * @example\n * ```ts\n * const sea = new SEA({\n * name: 'myapp',\n * entry: { path: 'dist/server/serve.cjs' },\n * output: 'dist/sea',\n * })\n * const result = await sea.execute()\n * sea.destroy()\n * ```\n */\nexport class SEA implements SEAInterface {\n\t#status: SEAStatus = 'idle'\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.#emitter.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 = resolvePlatform()\n\t\tif (platform === undefined) {\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.#buildBlob(root, compression)\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\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\tensureContained(base, path)\n\t\t}\n\n\t\tfor (const path of this.#options.compression?.paths ?? []) {\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 — buildSignCommand is a pure argv builder.\n\t\t\tbuildSignCommand(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: Array<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#buildBlob(root: string, compression: SEACompressionManifest | undefined): 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 = buildBlobConfig(\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.#resolveAssets(root, compression),\n\t\t\tthis.#options.blob,\n\t\t)\n\n\t\twriteFileSync(configPath, JSON.stringify(config, null, 2))\n\t\texecuteShell([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\t...(this.#options.timeout === undefined ? {} : { timeout: this.#options.timeout }),\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 = resolvePlatform()\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 = {\n\t\t\t...(this.#options.signal === undefined ? {} : { signal: this.#options.signal }),\n\t\t\t...(this.#options.timeout === undefined ? {} : { timeout: this.#options.timeout }),\n\t\t}\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\texecuteShell([...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: isError(thrown) ? 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\texecuteShell([...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: isError(thrown) ? 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\texecuteShell([...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: isError(thrown) ? 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 — buildSignCommand's argv is passed\n\t\t\t\t\t// through executeShell 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 = buildSignCommand(signInput, temp)\n\t\t\t\t\ttry {\n\t\t\t\t\t\texecuteShell(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\texecuteShell([...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#resolveAssets(\n\t\troot: string,\n\t\tcompression: SEACompressionManifest | undefined,\n\t): Readonly<Record<string, string>> {\n\t\tconst outputs = new Map<string, string>()\n\t\tfor (const result of compression?.assets ?? []) {\n\t\t\toutputs.set(result.input, result.output)\n\t\t}\n\n\t\tconst assets: Record<string, string> = {}\n\t\tfor (const [name, path] of Object.entries(this.#options.assets ?? {})) {\n\t\t\tconst input = ensureContained(root, path)\n\t\t\tassets[name] = outputs.get(input) ?? input\n\t\t}\n\t\treturn assets\n\t}\n}\n","import type { AssetInput, AssetInterface } from '../types.js'\nimport { BROTLI_EXTENSION } from '../constants.js'\n\n/**\n * Holds one named asset's key, bytes, and compression state.\n *\n * @remarks\n * `compressed` is inferred from a `.br` suffix on the key whenever the input\n * leaves it unset, so a Brotli output registered under its own name reports itself\n * correctly without the caller restating it.\n *\n * @param input - The asset's key, content bytes, and optional compression flag\n *\n * @example\n * ```ts\n * const asset = new Asset({ key: 'client.html.br', content: compressedBuffer })\n * asset.key // 'client.html.br'\n * asset.compressed // true\n * ```\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","import type {\n\tAssetInput,\n\tAssetInterface,\n\tAssetManagerEventMap,\n\tAssetManagerInterface,\n\tAssetManagerOptions,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { getAssetKeys, getRawAsset, isSea } from 'node:sea'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArrayBuffer } from '@orkestrel/contract'\nimport { Asset } from './Asset.js'\n\n/**\n * Collects named assets from a SEA blob or from disk and serves them by key.\n *\n * @remarks\n * Construction registers every asset embedded in the running SEA blob, so an\n * executable built by this package reaches its assets without touching the\n * filesystem. Outside SEA mode that step registers nothing, and `load()` reads\n * the paths `options.assets` configures instead.\n *\n * @param options - Asset manager options: the project root, the key→path mapping\n * `load()` reads, and the event hooks\n *\n * @example\n * ```ts\n * const manager = new AssetManager({\n * root: process.cwd(),\n * assets: { 'client.html.br': 'dist/client/client.html.br' },\n * })\n * manager.load()\n * manager.asset('client.html.br')\n * manager.destroy()\n * ```\n */\nexport class AssetManager implements AssetManagerInterface {\n\treadonly #emitter: Emitter<AssetManagerEventMap>\n\t#assets = new Map<string, AssetInterface>()\n\treadonly #root: string\n\treadonly #paths: Readonly<Record<string, string>>\n\n\tconstructor(options?: AssetManagerOptions) {\n\t\tthis.#root = options?.root ?? process.cwd()\n\t\tthis.#paths = options?.assets ?? {}\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.#assets.keys()]\n\t}\n\n\tregister(input: AssetInput | readonly 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 registered: string[] = []\n\t\tfor (const [key, path] of Object.entries(this.#paths)) {\n\t\t\tconst resolved = resolve(this.#root, path)\n\t\t\tif (!existsSync(resolved)) {\n\t\t\t\tthis.#emitter.emit('error', new Error(`Asset not found: ${path}`))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst buffer = readFileSync(resolved)\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 asset: ${path}`)\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, content })\n\t\t\t\tregistered.push(key)\n\t\t\t} catch (thrown: unknown) {\n\t\t\t\tthis.#emitter.emit('error', thrown)\n\t\t\t}\n\t\t}\n\n\t\tif (registered.length > 0) {\n\t\t\tthis.#emitter.emit('load', registered)\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis.#assets.clear()\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}\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 './seas/SEA.js'\nimport { Injector } from './injectors/Injector.js'\nimport { Asset } from './assets/Asset.js'\nimport { AssetManager } from './assets/AssetManager.js'\n\n/**\n * Creates a SEA build orchestrator over the given options and returns it as a\n * `SEAInterface`, the published contract a caller holds instead of the `SEA` class.\n *\n * @param options - SEA build options\n * @returns a new `SEAInterface`\n *\n * @example Build a single executable\n * ```ts\n * import { createSEA, formatSize } from '@orkestrel/sea'\n *\n * const sea = createSEA({\n * \tname: 'myapp',\n * \tentry: { path: 'dist/server/serve.cjs' },\n * \toutput: 'dist/sea',\n * \tassets: { 'model.gguf': 'models/model.gguf' },\n * \tcompression: { paths: ['dist/app/browser'], mode: 'text' },\n * \twindows: { terminal: false },\n * \ttimeout: 30_000,\n * })\n *\n * const result = await sea.execute()\n * process.stdout.write(\n * \t`${result.executable} ${formatSize(result.size)} ${String(result.duration)}ms\\n`,\n * )\n * ```\n */\nexport function createSEA(options: SEAOptions): SEAInterface {\n\treturn new SEA(options)\n}\n\n/**\n * Creates a resource injector bound to one target executable and returns it as an\n * `InjectorInterface`, with the executable's format already detected from its header.\n *\n * @remarks\n * The format detected at construction — PE, ELF, or Mach-O — selects the strategy\n * `inject` takes. Every write runs through pure TypeScript file I/O, so the injector\n * needs no WASM and no external tool.\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 * Creates one named asset from a key and a content buffer and returns it as an\n * `AssetInterface`, with `compressed` inferred from the key where the input leaves\n * it unset.\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 * Creates an asset collection and returns it as an `AssetManagerInterface`, already\n * carrying whatever assets the running SEA blob embeds.\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":";;;;;;;;;;;;;A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