@orkestrel/sea 0.0.13 → 0.0.15

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.
@@ -8,19 +8,28 @@ let _orkestrel_emitter = require("@orkestrel/emitter");
8
8
  let node_sea = require("node:sea");
9
9
  let _orkestrel_contract = require("@orkestrel/contract");
10
10
  //#region src/server/constants.ts
11
- /** SEA sentinel fuse value embedded in the Node.js binary */
11
+ /**
12
+ * Holds the SEA sentinel fuse value embedded in the Node.js binary,
13
+ * `NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2`.
14
+ */
12
15
  var SEA_SENTINEL_FUSE = "NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2";
13
- /** Resource name for the SEA blob in the executable */
16
+ /** Names the SEA blob resource in the executable, `NODE_SEA_BLOB`. */
14
17
  var SEA_BLOB_RESOURCE = "NODE_SEA_BLOB";
15
- /** Default Brotli compression quality level (maximum) */
18
+ /** Holds the default Brotli compression quality level, 11, the maximum Brotli accepts. */
16
19
  var DEFAULT_SEA_COMPRESSION_QUALITY = 11;
17
- /** Windows PE subsystem value: GUI application (no terminal window) */
20
+ /**
21
+ * Holds the Windows PE subsystem value for a GUI application, 2, which launches
22
+ * without a terminal window.
23
+ */
18
24
  var WINDOWS_SUBSYSTEM_GUI = 2;
19
- /** Windows PE subsystem value: console application */
25
+ /** Holds the Windows PE subsystem value for a console application, 3. */
20
26
  var WINDOWS_SUBSYSTEM_CONSOLE = 3;
21
- /** File extension indicating Brotli compression */
27
+ /** Names the file extension indicating Brotli compression, `.br`. */
22
28
  var BROTLI_EXTENSION = ".br";
23
- /** File extensions that should NOT be Brotli-compressed */
29
+ /**
30
+ * Lists the file extensions Brotli compression skips, the already-compressed
31
+ * archive, image, font, and media formats.
32
+ */
24
33
  var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
25
34
  ".br",
26
35
  ".gz",
@@ -44,51 +53,67 @@ var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
44
53
  ".zip",
45
54
  ".tar"
46
55
  ]);
47
- /** Default SEA entry point module format when none is specified */
56
+ /** Names the default SEA entry point module format when none is specified, `cjs`. */
48
57
  var DEFAULT_ENTRY_FORMAT = "cjs";
49
- /** Asset key for the raw (uncompressed) client HTML entry */
50
- var CLIENT_ASSET_KEY_RAW = "client.html";
51
- /** Asset key for the Brotli-compressed client HTML entry */
52
- var CLIENT_ASSET_KEY_BR = "client.html.br";
53
- /** DOS MZ header magic (first 2 bytes of a PE file) */
58
+ /** Holds the DOS MZ header magic, 0x5a4d, the first two bytes of a PE file. */
54
59
  var PE_MAGIC = 23117;
55
- /** PE signature: "PE\0\0" as a 32-bit value */
60
+ /** Holds the PE signature, 0x00004550, the bytes `PE\0\0` read as a 32-bit value. */
56
61
  var PE_SIGNATURE = 17744;
57
- /** PE32 optional header magic */
62
+ /** Holds the PE32 optional header magic, 0x10b. */
58
63
  var PE32_MAGIC = 267;
59
- /** PE32+ (64-bit) optional header magic */
64
+ /** Holds the PE32+ optional header magic, 0x20b, the 64-bit form. */
60
65
  var PE32_PLUS_MAGIC = 523;
61
- /** ELF magic: 0x7F 'E' 'L' 'F' as a 32-bit big-endian value */
66
+ /**
67
+ * Holds the ELF magic, 0x7f454c46, the bytes 0x7F `E` `L` `F` read as a 32-bit
68
+ * big-endian value.
69
+ */
62
70
  var ELF_MAGIC = 2135247942;
63
- /** ELF 64-bit class identifier */
71
+ /** Holds the ELF 64-bit class identifier, 2. */
64
72
  var ELF_CLASS_64 = 2;
65
- /** ELF little-endian data encoding */
73
+ /** Holds the ELF little-endian data encoding, 1. */
66
74
  var ELF_DATA_LSB = 1;
67
- /** ELF program header type: note segment */
75
+ /** Holds the ELF program header type for a note segment, 4. */
68
76
  var ELF_PT_NOTE = 4;
69
- /** Mach-O 64-bit magic (little-endian) */
77
+ /** Holds the ELF program header type for a loadable segment, 1. */
78
+ var ELF_PT_LOAD = 1;
79
+ /** Holds the ELF program header type for the program header table itself, 6. */
80
+ var ELF_PT_PHDR = 6;
81
+ /** Holds the ELF segment permission flag marking a segment readable, 4. */
82
+ var ELF_PF_R = 4;
83
+ /** Holds the page size an injected ELF segment is aligned to, 0x1000. */
84
+ var ELF_PAGE_SIZE = 4096;
85
+ /** Holds the Mach-O 64-bit magic, 0xfeedfacf, in little-endian byte order. */
70
86
  var MACHO_MAGIC_64 = 4277009103;
71
- /** Mach-O LC_SEGMENT_64 load command */
87
+ /** Holds the Mach-O `LC_SEGMENT_64` load command, 0x19. */
72
88
  var MACHO_LC_SEGMENT_64 = 25;
73
- /** PE resource type: RT_RCDATA (raw data) */
89
+ /** Holds the PE resource type `RT_RCDATA` for raw data, 10. */
74
90
  var PE_RT_RCDATA = 10;
75
- /** Size of IMAGE_RESOURCE_DIRECTORY in bytes */
91
+ /** Holds the size of `IMAGE_RESOURCE_DIRECTORY` in bytes, 16. */
76
92
  var PE_RESOURCE_DIR_SIZE = 16;
77
- /** Size of IMAGE_RESOURCE_DIRECTORY_ENTRY in bytes */
93
+ /** Holds the size of `IMAGE_RESOURCE_DIRECTORY_ENTRY` in bytes, 8. */
78
94
  var PE_RESOURCE_ENTRY_SIZE = 8;
79
- /** Size of IMAGE_RESOURCE_DATA_ENTRY in bytes */
95
+ /** Holds the size of `IMAGE_RESOURCE_DATA_ENTRY` in bytes, 16. */
80
96
  var PE_RESOURCE_DATA_ENTRY_SIZE = 16;
81
- /** PE section header size in bytes */
97
+ /** Holds the PE section header size in bytes, 40. */
82
98
  var PE_SECTION_HEADER_SIZE = 40;
83
- /** High bit mask for resource directory entry offset (indicates subdirectory) */
99
+ /**
100
+ * Holds the high bit mask marking a resource directory entry offset as a
101
+ * subdirectory, 0x80000000.
102
+ */
84
103
  var PE_RESOURCE_SUBDIR_FLAG = 2147483648;
85
- /** High bit mask for resource name entry (indicates named vs integer ID) */
104
+ /**
105
+ * Holds the high bit mask marking a resource entry as named rather than
106
+ * integer-identified, 0x80000000.
107
+ */
86
108
  var PE_RESOURCE_NAME_FLAG = 2147483648;
87
- /** Section contains initialized data */
109
+ /** Marks a section as containing initialized data, 0x00000040. */
88
110
  var PE_SCN_INITIALIZED_DATA = 64;
89
- /** Section is readable */
111
+ /** Marks a section as readable, 0x40000000. */
90
112
  var PE_SCN_MEM_READ = 1073741824;
91
- /** Platform-specific SEA build configurations */
113
+ /**
114
+ * Holds the platform-specific SEA build configurations, keyed by
115
+ * `process.platform` for `win32`, `darwin`, and `linux`.
116
+ */
92
117
  var SEA_PLATFORMS = Object.freeze({
93
118
  win32: Object.freeze({
94
119
  executable: "node.exe",
@@ -114,7 +139,10 @@ var SEA_PLATFORMS = Object.freeze({
114
139
  }),
115
140
  linux: Object.freeze({ executable: "node" })
116
141
  });
117
- /** Maps a {@link SEACompressionMode} to its numeric Brotli mode value */
142
+ /**
143
+ * Maps a {@link SEACompressionMode} to its numeric Brotli mode value: `generic`
144
+ * to 0, `text` to 1, and `font` to 2.
145
+ */
118
146
  var SEA_COMPRESSION_MODE_VALUES = Object.freeze({
119
147
  generic: 0,
120
148
  text: 1,
@@ -123,7 +151,7 @@ var SEA_COMPRESSION_MODE_VALUES = Object.freeze({
123
151
  //#endregion
124
152
  //#region src/server/errors.ts
125
153
  /**
126
- * The coded base error for every failure raised by the seal build.
154
+ * Represents the coded base error for every failure raised by the SEA build.
127
155
  *
128
156
  * @remarks
129
157
  * Carries a machine-readable {@link SEAErrorCode} and optional `context`
@@ -132,7 +160,7 @@ var SEA_COMPRESSION_MODE_VALUES = Object.freeze({
132
160
  * @example
133
161
  * ```ts
134
162
  * try {
135
- * seal.execute()
163
+ * sea.execute()
136
164
  * } catch (error) {
137
165
  * if (isSEAError(error)) {
138
166
  * console.error(error.code, error.context)
@@ -151,10 +179,10 @@ var SEAError = class extends Error {
151
179
  }
152
180
  };
153
181
  /**
154
- * Whether a value is a {@link SEAError}.
182
+ * Checks whether a value is a {@link SEAError}.
155
183
  *
156
184
  * @param value - The value to test
157
- * @returns `true` when `value` is a `SEAError`
185
+ * @returns True if `value` is a `SEAError`; false otherwise
158
186
  *
159
187
  * @example
160
188
  * ```ts
@@ -167,7 +195,7 @@ function isSEAError(value) {
167
195
  return value instanceof SEAError;
168
196
  }
169
197
  /**
170
- * An error thrown when a shell command run via `runShell` exits non-zero.
198
+ * Represents an error thrown when a shell command executed through `executeShell` exits non-zero.
171
199
  *
172
200
  * @remarks
173
201
  * Carries the captured `stdout` and `stderr` buffers from the failed process.
@@ -177,7 +205,7 @@ function isSEAError(value) {
177
205
  * @example
178
206
  * ```ts
179
207
  * try {
180
- * runShell(['codesign', '--sign', '-', path])
208
+ * executeShell(['codesign', '--sign', '-', path])
181
209
  * } catch (error) {
182
210
  * if (isShellError(error)) {
183
211
  * console.error(error.stderr.toString())
@@ -196,10 +224,10 @@ var ShellError = class extends SEAError {
196
224
  }
197
225
  };
198
226
  /**
199
- * Whether a value is a {@link ShellError}.
227
+ * Checks whether a value is a {@link ShellError}.
200
228
  *
201
229
  * @param value - The value to test
202
- * @returns `true` when `value` is a `ShellError`
230
+ * @returns True if `value` is a `ShellError`; false otherwise
203
231
  *
204
232
  * @example
205
233
  * ```ts
@@ -212,56 +240,67 @@ function isShellError(value) {
212
240
  return value instanceof ShellError;
213
241
  }
214
242
  //#endregion
215
- //#region src/server/helpers.ts
243
+ //#region src/server/validators.ts
216
244
  /**
217
- * Check if a value is a valid {@link ExecutableFormat}.
245
+ * Checks whether a value is a valid {@link ExecutableFormat}.
218
246
  *
219
247
  * @param value - Value to check
220
- * @returns True when value is `'pe'`, `'elf'`, or `'macho'`
248
+ * @returns True if value is `'pe'`, `'elf'`, or `'macho'`; false otherwise
249
+ *
250
+ * @example
251
+ * ```ts
252
+ * isExecutableFormat('elf') // true
253
+ * isExecutableFormat('coff') // false
254
+ * ```
221
255
  */
222
256
  function isExecutableFormat(value) {
223
257
  return value === "pe" || value === "elf" || value === "macho";
224
258
  }
259
+ //#endregion
260
+ //#region src/server/helpers.ts
225
261
  /**
226
- * Get the platform configuration for the current OS.
262
+ * Resolves the effective platform configuration.
227
263
  *
228
264
  * @param platform - Platform identifier. Default: `process.platform`.
229
265
  * @returns Platform configuration, or undefined if unsupported
230
266
  */
231
- function platformConfig(platform) {
267
+ function resolvePlatform(platform) {
232
268
  return SEA_PLATFORMS[platform ?? process.platform];
233
269
  }
234
270
  /**
235
- * Check if the current or specified platform is supported for SEA builds.
271
+ * Checks whether the current or named platform is supported for SEA builds.
236
272
  *
237
273
  * @param platform - Platform identifier to check
238
- * @returns True when the platform has a known configuration
274
+ * @returns True if the platform has a known configuration; false otherwise
239
275
  */
240
276
  function isPlatformSupported(platform) {
241
277
  return (platform ?? process.platform) in SEA_PLATFORMS;
242
278
  }
243
279
  /**
244
- * Assert that a path exists, throwing a coded {@link SEAError} if not.
280
+ * Asserts that a path exists, throwing a coded {@link SEAError} if not.
245
281
  *
246
282
  * @param path - Absolute or relative path to check
247
283
  * @param message - Error message when path is missing
248
284
  * @param code - Error code to throw with. Default: `'STATE'`.
285
+ * @throws SEAError with `code` (default `'STATE'`) when `path` does not exist
249
286
  */
250
287
  function ensureExists(path, message, code) {
251
288
  if (!(0, node_fs.existsSync)(path)) throw new SEAError(code ?? "STATE", message, { path });
252
289
  }
253
290
  /**
254
- * Check if a file should be Brotli-compressed based on its extension.
291
+ * Checks whether a file's extension is outside `SKIP_EXTENSIONS`, so Brotli
292
+ * compression applies to it.
255
293
  *
256
294
  * @param path - Path to the file
257
- * @returns True when the file type benefits from compression
295
+ * @returns True if the file type benefits from compression; false otherwise
258
296
  */
259
297
  function isCompressible(path) {
260
298
  const ext = (0, node_path.extname)(path).toLowerCase();
261
299
  return !SKIP_EXTENSIONS.has(ext);
262
300
  }
263
301
  /**
264
- * Recursively walk a directory and return all file paths.
302
+ * Walks a directory recursively and returns every file path it finds, relative to
303
+ * the base and skipping symlinks.
265
304
  *
266
305
  * @param directory - Directory to walk
267
306
  * @param base - Base directory for relative path calculation
@@ -281,7 +320,8 @@ function walkDirectory(directory, base) {
281
320
  return result;
282
321
  }
283
322
  /**
284
- * Redact password arguments from a shell command.
323
+ * Redacts password arguments from a shell command, so the command is safe to
324
+ * include in an error message.
285
325
  *
286
326
  * @param command - Command arguments to redact
287
327
  * @returns A copy with values following password flags replaced by a marker
@@ -299,7 +339,7 @@ function redactCommand(command) {
299
339
  });
300
340
  }
301
341
  /**
302
- * Run a command synchronously and return stdout.
342
+ * Executes a command synchronously and returns stdout.
303
343
  *
304
344
  * @param command - Command to execute (first element is the binary)
305
345
  * @param options - Shell options (cwd, env, timeout, signal)
@@ -309,7 +349,7 @@ function redactCommand(command) {
309
349
  * @throws SEAError with code `'TIMEOUT'` when the command exceeds `options.timeout`
310
350
  * @throws ShellError when the command exits with non-zero status
311
351
  */
312
- function runShell(command, options) {
352
+ function executeShell(command, options) {
313
353
  const [cmd, ...args] = command;
314
354
  if (cmd === void 0) throw new SEAError("STATE", "Command array must not be empty");
315
355
  if (options?.signal?.aborted === true) throw new SEAError("ABORT", "Shell command aborted", { command: redactCommand(command) });
@@ -330,7 +370,7 @@ function runShell(command, options) {
330
370
  return Buffer.from(result.stdout, "utf-8");
331
371
  }
332
372
  /**
333
- * Compute a size comparison between original and compressed byte counts.
373
+ * Computes a size comparison between original and compressed byte counts.
334
374
  *
335
375
  * @param original - Original byte count
336
376
  * @param compressed - Compressed byte count
@@ -344,12 +384,13 @@ function computeSize(original, compressed) {
344
384
  };
345
385
  }
346
386
  /**
347
- * Brotli-compress a single file, writing the output alongside it.
387
+ * Brotli-compresses a single file, writing the output alongside it.
348
388
  *
349
389
  * @param input - Absolute path to the source file
350
390
  * @param output - Absolute path for the compressed output
351
- * @param options - Compression options (quality, mode)
391
+ * @param options - Brotli options (quality, mode)
352
392
  * @returns Compression result with size comparison
393
+ * @throws SEAError with code `'OUTPUT'` when `output` is an existing symlink
353
394
  */
354
395
  function compressFile(input, output, options) {
355
396
  const quality = options?.quality ?? 11;
@@ -374,10 +415,10 @@ function compressFile(input, output, options) {
374
415
  };
375
416
  }
376
417
  /**
377
- * Compress all compressible files in a directory tree.
418
+ * Compresses all compressible files in a directory tree.
378
419
  *
379
420
  * @param directory - Absolute path to the directory
380
- * @param options - Compression options
421
+ * @param options - Brotli options (quality, mode)
381
422
  * @param progress - Optional callback invoked after each file is compressed
382
423
  * @returns Compression manifest with all results
383
424
  */
@@ -401,39 +442,218 @@ function compressDirectory(directory, options, progress) {
401
442
  };
402
443
  }
403
444
  /**
404
- * Check whether a number is a nonzero power of two.
445
+ * Rounds a value up to the next multiple of an alignment boundary.
446
+ *
447
+ * @remarks
448
+ * The shared alignment leaf behind every binary-format writer in this package:
449
+ * PE section and file alignment, ELF note and page alignment, and Mach-O page
450
+ * alignment all round the same way. `alignment` must be a nonzero power of two
451
+ * ({@link isPowerOfTwo} is the guard the PE injector applies before using a
452
+ * value read out of a header as a divisor).
453
+ *
454
+ * @param value - Value to align
455
+ * @param alignment - Alignment boundary to round up to
456
+ * @returns The value rounded up to the next multiple of `alignment`
457
+ *
458
+ * @example
459
+ * ```ts
460
+ * alignTo(10, 4) // 12
461
+ * alignTo(4096, 4096) // 4096 — already aligned
462
+ * ```
463
+ */
464
+ function alignTo(value, alignment) {
465
+ const remainder = value % alignment;
466
+ return remainder === 0 ? value : value + (alignment - remainder);
467
+ }
468
+ /**
469
+ * Reads a 32-bit unsigned little-endian integer from a file descriptor.
470
+ *
471
+ * @param fd - Open file descriptor
472
+ * @param offset - Byte offset to read from
473
+ * @returns The 32-bit value
474
+ * @throws SEAError with code `'FORMAT'` when fewer than four bytes are readable at `offset`
475
+ *
476
+ * @example
477
+ * ```ts
478
+ * const fd = openSync('app.exe', 'r')
479
+ * readU32(fd, 0x3c) // the PE header offset
480
+ * ```
481
+ */
482
+ function readU32(fd, offset) {
483
+ const buf = Buffer.alloc(4);
484
+ const read = (0, node_fs.readSync)(fd, buf, 0, 4, offset);
485
+ if (read < 4) throw new SEAError("FORMAT", "Short read", {
486
+ offset,
487
+ expected: 4,
488
+ read
489
+ });
490
+ return buf.readUInt32LE(0);
491
+ }
492
+ /**
493
+ * Reads a 64-bit unsigned little-endian integer from a file descriptor.
494
+ *
495
+ * @param fd - Open file descriptor
496
+ * @param offset - Byte offset to read from
497
+ * @returns The 64-bit value, as a `bigint`
498
+ * @throws SEAError with code `'FORMAT'` when fewer than eight bytes are readable at `offset`
499
+ *
500
+ * @example
501
+ * ```ts
502
+ * const fd = openSync('app', 'r')
503
+ * readU64(fd, 32) // the ELF program header table offset
504
+ * ```
505
+ */
506
+ function readU64(fd, offset) {
507
+ const buf = Buffer.alloc(8);
508
+ const read = (0, node_fs.readSync)(fd, buf, 0, 8, offset);
509
+ if (read < 8) throw new SEAError("FORMAT", "Short read", {
510
+ offset,
511
+ expected: 8,
512
+ read
513
+ });
514
+ return buf.readBigUInt64LE(0);
515
+ }
516
+ /**
517
+ * Writes a 32-bit unsigned little-endian integer to a file descriptor.
518
+ *
519
+ * @remarks
520
+ * Coerces `value` with `>>> 0` before writing, so a negative or out-of-range
521
+ * number lands as its unsigned 32-bit representation rather than throwing.
522
+ *
523
+ * @param fd - Open file descriptor
524
+ * @param offset - Byte offset to write at
525
+ * @param value - The 32-bit value to write
526
+ *
527
+ * @example
528
+ * ```ts
529
+ * const fd = openSync('app.exe', 'r+')
530
+ * writeU32(fd, 0x3c, 0x100)
531
+ * ```
532
+ */
533
+ function writeU32(fd, offset, value) {
534
+ const buf = Buffer.alloc(4);
535
+ buf.writeUInt32LE(value >>> 0, 0);
536
+ (0, node_fs.writeSync)(fd, buf, 0, 4, offset);
537
+ }
538
+ /**
539
+ * Writes a 64-bit unsigned little-endian integer to a file descriptor.
540
+ *
541
+ * @param fd - Open file descriptor
542
+ * @param offset - Byte offset to write at
543
+ * @param value - The 64-bit value to write
544
+ *
545
+ * @example
546
+ * ```ts
547
+ * const fd = openSync('app', 'r+')
548
+ * writeU64(fd, 32, 8192n)
549
+ * ```
550
+ */
551
+ function writeU64(fd, offset, value) {
552
+ const buf = Buffer.alloc(8);
553
+ buf.writeBigUInt64LE(value, 0);
554
+ (0, node_fs.writeSync)(fd, buf, 0, 8, offset);
555
+ }
556
+ /**
557
+ * Appends a source file to a target file, streaming in fixed-size chunks.
558
+ *
559
+ * @remarks
560
+ * Reads `source` in `chunk`-sized reads and appends each chunk to `target`, so
561
+ * a multi-hundred-megabyte blob is never fully buffered. A read returning zero
562
+ * bytes ends the copy, which is the normal end-of-file signal for a source that
563
+ * shrank between the size read and the copy.
564
+ *
565
+ * @param target - Path of the file to append to
566
+ * @param source - Path of the file to append
567
+ * @param chunk - Read/append chunk size in bytes. Default: 4 MB.
568
+ *
569
+ * @example
570
+ * ```ts
571
+ * appendFile('dist/sea/app', 'dist/sea/sea-prep.blob')
572
+ * ```
573
+ */
574
+ function appendFile(target, source, chunk = 4194304) {
575
+ const fd = (0, node_fs.openSync)(source, "r");
576
+ try {
577
+ const size = (0, node_fs.statSync)(source).size;
578
+ const buffer = Buffer.alloc(Math.min(chunk, size));
579
+ let offset = 0;
580
+ while (offset < size) {
581
+ const toRead = Math.min(chunk, size - offset);
582
+ const bytesRead = (0, node_fs.readSync)(fd, buffer, 0, toRead, offset);
583
+ if (bytesRead === 0) break;
584
+ (0, node_fs.appendFileSync)(target, buffer.subarray(0, bytesRead));
585
+ offset += bytesRead;
586
+ }
587
+ } finally {
588
+ (0, node_fs.closeSync)(fd);
589
+ }
590
+ }
591
+ /**
592
+ * Truncates a NUL-padded binary name field at its first NUL character.
593
+ *
594
+ * @remarks
595
+ * Binary name fields (PE section names, Mach-O segment and section names, ELF
596
+ * note names) are fixed-width and NUL-padded, so the decoded string carries
597
+ * trailing NUL characters that no comparison against a literal name matches.
598
+ *
599
+ * @param value - Decoded fixed-width name field
600
+ * @returns The value up to, but excluding, its first NUL character
601
+ *
602
+ * @example
603
+ * ```ts
604
+ * stripTrailingNulls('.rsrc\0\0\0') // '.rsrc'
605
+ * ```
606
+ */
607
+ function stripTrailingNulls(value) {
608
+ const index = value.indexOf("\0");
609
+ return index === -1 ? value : value.slice(0, index);
610
+ }
611
+ /**
612
+ * Checks whether a number is a nonzero power of two.
405
613
  *
406
614
  * @param value - Number to check
407
- * @returns True when the value is a positive power of two
615
+ * @returns True if the value is a positive power of two; false otherwise
408
616
  */
409
617
  function isPowerOfTwo(value) {
410
618
  return value > 0 && (value & value - 1) === 0;
411
619
  }
412
620
  /**
413
- * Parse the PE header offset from a Windows executable.
621
+ * Reads the PE header offset from a Windows executable.
414
622
  *
415
623
  * @param fd - Open file descriptor
416
624
  * @returns The offset to the PE signature
625
+ * @throws SEAError with code `'FORMAT'` when fewer than four bytes are readable at `0x3c`
417
626
  */
418
- function parsePEOffset(fd) {
627
+ function readPEOffset(fd) {
419
628
  const buf = Buffer.alloc(4);
420
- (0, node_fs.readSync)(fd, buf, 0, 4, 60);
629
+ const read = (0, node_fs.readSync)(fd, buf, 0, 4, 60);
630
+ if (read < 4) throw new SEAError("FORMAT", "Short read", {
631
+ offset: 60,
632
+ expected: 4,
633
+ read
634
+ });
421
635
  return buf.readUInt32LE(0);
422
636
  }
423
637
  /**
424
- * Read a 16-bit unsigned integer from a file descriptor.
638
+ * Reads a 16-bit unsigned integer from a file descriptor.
425
639
  *
426
640
  * @param fd - Open file descriptor
427
641
  * @param offset - Byte offset to read from
428
642
  * @returns The 16-bit value
643
+ * @throws SEAError with code `'FORMAT'` when fewer than two bytes are readable at `offset`
429
644
  */
430
645
  function readU16(fd, offset) {
431
646
  const buf = Buffer.alloc(2);
432
- (0, node_fs.readSync)(fd, buf, 0, 2, offset);
647
+ const read = (0, node_fs.readSync)(fd, buf, 0, 2, offset);
648
+ if (read < 2) throw new SEAError("FORMAT", "Short read", {
649
+ offset,
650
+ expected: 2,
651
+ read
652
+ });
433
653
  return buf.readUInt16LE(0);
434
654
  }
435
655
  /**
436
- * Write a 16-bit unsigned integer to a file descriptor.
656
+ * Writes a 16-bit unsigned integer to a file descriptor.
437
657
  *
438
658
  * @param fd - Open file descriptor
439
659
  * @param offset - Byte offset to write at
@@ -445,16 +665,16 @@ function writeU16(fd, offset, value) {
445
665
  (0, node_fs.writeSync)(fd, buf, 0, 2, offset);
446
666
  }
447
667
  /**
448
- * Check if a file is a Windows PE executable.
668
+ * Checks whether a file is a Windows PE executable.
449
669
  *
450
670
  * @param path - Path to the file
451
- * @returns True when the file has a valid PE signature
671
+ * @returns True if the file has a valid PE signature; false otherwise
452
672
  */
453
673
  function isPEExecutable(path) {
454
674
  let fd;
455
675
  try {
456
676
  fd = (0, node_fs.openSync)(path, "r");
457
- const peOffset = parsePEOffset(fd);
677
+ const peOffset = readPEOffset(fd);
458
678
  const sig = Buffer.alloc(4);
459
679
  (0, node_fs.readSync)(fd, sig, 0, 4, peOffset);
460
680
  return sig.toString("ascii") === "PE\0\0";
@@ -465,7 +685,7 @@ function isPEExecutable(path) {
465
685
  }
466
686
  }
467
687
  /**
468
- * Patch the PE subsystem field in a Windows executable.
688
+ * Patches the PE subsystem field in a Windows executable.
469
689
  *
470
690
  * @param path - Path to the executable
471
691
  * @param subsystem - Numeric subsystem value (2 = GUI, 3 = Console)
@@ -473,30 +693,30 @@ function isPEExecutable(path) {
473
693
  function patchPESubsystem(path, subsystem) {
474
694
  const fd = (0, node_fs.openSync)(path, "r+");
475
695
  try {
476
- writeU16(fd, parsePEOffset(fd) + 92, subsystem);
696
+ writeU16(fd, readPEOffset(fd) + 92, subsystem);
477
697
  } finally {
478
698
  (0, node_fs.closeSync)(fd);
479
699
  }
480
700
  }
481
701
  /**
482
- * Remove the Authenticode signature from a PE executable by zeroing
702
+ * Removes the Authenticode signature from a PE executable by zeroing
483
703
  * the security directory entry in the optional header.
484
704
  *
485
705
  * @remarks
486
706
  * If the certificate overlay described by the security directory sits at the
487
707
  * very end of the file (the common case for `signtool`-signed binaries), the
488
- * file is truncated to the certificate's start FIRST so the overlay bytes are
708
+ * file is truncated to the certificate's start first so the overlay bytes are
489
709
  * discarded rather than left as dead weight for a downstream injector to
490
710
  * bury mid-file. The directory read is bounds-checked so a malformed or
491
- * truncated security directory cannot throw unexpectedly — it is simply
492
- * skipped and only the directory entry is zeroed.
711
+ * truncated security directory cannot throw unexpectedly — it is skipped
712
+ * and only the directory entry is zeroed.
493
713
  *
494
714
  * @param path - Path to the executable
495
715
  */
496
716
  function stripPESignature(path) {
497
717
  const fd = (0, node_fs.openSync)(path, "r+");
498
718
  try {
499
- const peOffset = parsePEOffset(fd);
719
+ const peOffset = readPEOffset(fd);
500
720
  const securityDirOffset = readU16(fd, peOffset + 24) === 523 ? peOffset + 168 : peOffset + 152;
501
721
  const dirBuf = Buffer.alloc(8);
502
722
  if ((0, node_fs.readSync)(fd, dirBuf, 0, 8, securityDirOffset) === 8) {
@@ -514,21 +734,21 @@ function stripPESignature(path) {
514
734
  }
515
735
  }
516
736
  /**
517
- * Build the `signtool sign` argv for signing a Windows executable.
737
+ * Builds the `signtool sign` argv for signing a Windows executable.
518
738
  *
519
739
  * @remarks
520
- * Requires EXACTLY ONE certificate source — `sign.file` (a `.pfx`/`.p12`
740
+ * Requires exactly one certificate source — `sign.file` (a `.pfx`/`.p12`
521
741
  * file, paired with `sign.password` when present) XOR `sign.thumbprint` (a
522
742
  * certificate already installed in the Windows store). When `sign.timestamp`
523
743
  * is set it is parsed with the `URL` constructor and must be an `http:` or
524
- * `https:` URL. The returned argv is passed directly to `runShell` — never
744
+ * `https:` URL. The returned argv is passed directly to `executeShell` — never
525
745
  * through a shell — so nothing in `sign` can be interpreted as a flag or
526
- * injected into a command line. `sign.password` is NEVER included in a
746
+ * injected into a command line. `sign.password` is never included in a
527
747
  * thrown error's message or `context`.
528
748
  *
529
749
  * @param sign - Windows signing options
530
750
  * @param target - Absolute path to the executable to sign
531
- * @returns The `signtool` argv, ready for `runShell`
751
+ * @returns The `signtool` argv, ready for `executeShell`
532
752
  * @throws SEAError with code `'SIGN'` when neither `file` nor `thumbprint` is set
533
753
  * @throws SEAError with code `'SIGN'` when both `file` and `thumbprint` are set
534
754
  * @throws SEAError with code `'SIGN'` when `timestamp` is not a parseable http(s) URL
@@ -536,11 +756,11 @@ function stripPESignature(path) {
536
756
  *
537
757
  * @example
538
758
  * ```ts
539
- * createSignCommand({ thumbprint: 'AABBCCDDEEFF00112233445566778899AABBCCDD' }, 'dist/sea/app.exe')
759
+ * buildSignCommand({ thumbprint: 'AABBCCDDEEFF00112233445566778899AABBCCDD' }, 'dist/sea/app.exe')
540
760
  * // ['signtool', 'sign', '/fd', 'sha256', '/sha1', 'AABBCCDDEEFF00112233445566778899AABBCCDD', 'dist/sea/app.exe']
541
761
  * ```
542
762
  */
543
- function createSignCommand(sign, target) {
763
+ function buildSignCommand(sign, target) {
544
764
  const hasFile = sign.file !== void 0;
545
765
  const hasThumbprint = sign.thumbprint !== void 0;
546
766
  if (!hasFile && !hasThumbprint) throw new SEAError("SIGN", "Windows signing requires exactly one of sign.file or sign.thumbprint");
@@ -582,10 +802,10 @@ function createSignCommand(sign, target) {
582
802
  ];
583
803
  }
584
804
  /**
585
- * Format a byte count as a human-readable string.
805
+ * Formats a byte count as a human-readable string.
586
806
  *
587
807
  * @param bytes - Byte count
588
- * @returns Formatted string (e.g. `"1.23 MB"`, `"456 KB"`)
808
+ * @returns Formatted string (for example `"1.23 MB"`, `"456 KB"`)
589
809
  */
590
810
  function formatSize(bytes) {
591
811
  if (bytes < 1024) return `${String(bytes)} B`;
@@ -593,11 +813,11 @@ function formatSize(bytes) {
593
813
  return `${(bytes / 1048576).toFixed(2)} MB`;
594
814
  }
595
815
  /**
596
- * Assert that an asset key is safe to use as a relative filesystem/archive key.
816
+ * Asserts that an asset key is safe to use as a relative filesystem/archive key.
597
817
  *
598
818
  * @remarks
599
819
  * Rejects an empty key, an absolute path, a key containing a backslash, a
600
- * Windows drive-relative specifier (e.g. `'C:foo'`), or any `/`-separated
820
+ * Windows drive-relative specifier (for example `'C:foo'`), or any `/`-separated
601
821
  * segment equal to `'..'` — all of which could escape the intended asset root.
602
822
  *
603
823
  * @param key - Asset key to validate
@@ -618,17 +838,17 @@ function ensureSafeKey(key) {
618
838
  if (key.split("/").includes("..")) throw new SEAError("ASSET", "Asset key must not contain a \"..\" segment", { key });
619
839
  }
620
840
  /**
621
- * Assert that `path` (resolved against `base`) real-path-resolves to a
841
+ * Asserts that `path` (resolved against `base`) real-path-resolves to a
622
842
  * location inside `base`, defeating a symlink escape.
623
843
  *
624
844
  * @remarks
625
845
  * Resolves `path` against `base`, then dereferences both the resolved path
626
846
  * and `base` with `realpathSync` and requires the real resolved path to
627
847
  * equal the real base or begin with the real base plus a path separator.
628
- * Dereferencing BOTH sides means a symlinked base itself (e.g. macOS `/tmp`
848
+ * Dereferencing both sides means a symlinked base itself (for example macOS `/tmp`
629
849
  * -> `/private/tmp`) still matches, while a symlink inside the tree that
630
850
  * points outside the real base is correctly rejected. A `realpathSync`
631
- * failure (e.g. `ENOENT`) is wrapped as a coded `SEAError` rather than
851
+ * failure (for example `ENOENT`) is wrapped as a coded `SEAError` rather than
632
852
  * leaking the raw Node error.
633
853
  *
634
854
  * @param base - Absolute path to the containing root
@@ -663,13 +883,13 @@ function ensureContained(base, path) {
663
883
  return real;
664
884
  }
665
885
  /**
666
- * Assert that `name` is a single safe path segment suitable as an output
886
+ * Asserts that `name` is a single safe path segment suitable as an output
667
887
  * executable base name.
668
888
  *
669
889
  * @remarks
670
890
  * Rejects an empty name, `'.'`, `'..'`, a name containing a `/` or `\`
671
- * separator, an absolute path, or a Windows drive-relative specifier (e.g.
672
- * `'C:foo'`) — all of which could redirect the output executable outside
891
+ * separator, an absolute path, or a Windows drive-relative specifier (for
892
+ * example `'C:foo'`) — all of which could redirect the output executable outside
673
893
  * the intended output directory.
674
894
  *
675
895
  * @param name - Output executable base name to validate
@@ -688,17 +908,17 @@ function ensureSafeName(name) {
688
908
  if (/^[A-Za-z]:/.test(name)) throw new SEAError("ASSET", "Executable name must not be a drive-relative specifier", { name });
689
909
  }
690
910
  /**
691
- * Fsync a directory to durably persist a prior file rename/create within it.
911
+ * Fsyncs a directory to durably persist a prior file rename/create within it.
692
912
  *
693
913
  * @remarks
694
- * A `rename`/`create` is only durable once its CONTAINING directory entry is
914
+ * A `rename`/`create` is only durable once its containing directory entry is
695
915
  * flushed — fsyncing the file itself is not enough. `path` is the directory
696
916
  * to fsync (callers pass `dirname(target)`, not the file itself). On Windows
697
917
  * there is no directory file handle to fsync, so this is a no-op there (the
698
918
  * platform lacks the primitive, not a failure). Some filesystems/platforms
699
919
  * return a benign errno for a directory fsync attempt (`EINVAL`, `ENOTSUP`,
700
920
  * `EISDIR`, `EPERM`, `EACCES`) — those are treated as "fsync unsupported
701
- * here" and swallowed; anything else (e.g. `ENOENT`, meaning the directory
921
+ * here" and swallowed; anything else (for example `ENOENT`, meaning the directory
702
922
  * itself is missing) is a genuine failure and is thrown as a coded `SEAError`.
703
923
  *
704
924
  * @param path - Directory path to fsync
@@ -729,7 +949,7 @@ function syncDirectory(path) {
729
949
  }
730
950
  }
731
951
  /**
732
- * Finalize a built executable by durably flushing it to disk and atomically
952
+ * Finalizes a built executable by durably flushing it to disk and atomically
733
953
  * moving it into place.
734
954
  *
735
955
  * @remarks
@@ -767,12 +987,12 @@ function finalizeExecutable(source, target) {
767
987
  syncDirectory((0, node_path.dirname)(target));
768
988
  }
769
989
  /**
770
- * Build the Node.js `--experimental-sea-config` JSON object for a SEA blob.
990
+ * Builds the Node.js `--experimental-sea-config` JSON object for a SEA blob.
771
991
  *
772
992
  * @remarks
773
993
  * A pure leaf extracted from the SEA build orchestrator. The `mainFormat`
774
994
  * field (`'commonjs' | 'module'`) exists only in Node >= 25.7 — for a `'cjs'`
775
- * entry (the default) `mainFormat` is OMITTED entirely so the config still
995
+ * entry (the default) `mainFormat` is omitted entirely so the config still
776
996
  * builds on older Node hosts where `'commonjs'` is already the implicit
777
997
  * default; for an `'esm'` entry `mainFormat: 'module'` is set explicitly
778
998
  * (this requires a Node >= 25.7 build host). Node also documents that
@@ -787,10 +1007,10 @@ function finalizeExecutable(source, target) {
787
1007
  *
788
1008
  * @example
789
1009
  * ```ts
790
- * const config = createBlobConfig({ path: 'dist/bin/serve.cjs' }, 'dist/bin/sea-prep.blob', undefined)
1010
+ * const config = buildBlobConfig({ path: 'dist/bin/serve.cjs' }, 'dist/bin/sea-prep.blob', undefined)
791
1011
  * ```
792
1012
  */
793
- function createBlobConfig(entry, blob, assets, options) {
1013
+ function buildBlobConfig(entry, blob, assets, options) {
794
1014
  const format = entry.format ?? "cjs";
795
1015
  const snapshot = options?.snapshot ?? false;
796
1016
  if (format === "esm" && snapshot) throw new SEAError("BLOB", "useSnapshot cannot be combined with an ESM entry (mainFormat module)");
@@ -805,17 +1025,16 @@ function createBlobConfig(entry, blob, assets, options) {
805
1025
  };
806
1026
  }
807
1027
  /**
808
- * Align an ELF note component size to its four-byte boundary.
1028
+ * Aligns an ELF note component size to its four-byte boundary.
809
1029
  *
810
1030
  * @param value - Component size to align
811
1031
  * @returns The value rounded up to the next multiple of four
812
1032
  */
813
1033
  function alignELFNoteSize(value) {
814
- const remainder = value % 4;
815
- return remainder === 0 ? value : value + (4 - remainder);
1034
+ return alignTo(value, 4);
816
1035
  }
817
1036
  /**
818
- * Build an ELF `PT_NOTE` entry's header bytes (namesz/descsz/type + padded
1037
+ * Builds an ELF `PT_NOTE` entry's header bytes (namesz/descsz/type + padded
819
1038
  * name) for the SEA blob note, without the blob body itself.
820
1039
  *
821
1040
  * @remarks
@@ -828,13 +1047,13 @@ function alignELFNoteSize(value) {
828
1047
  * (`strncmp(name, "NODE_SEA", 8)`), so `resource` is written in full but
829
1048
  * only needs to begin with those 8 bytes to be found at runtime.
830
1049
  *
831
- * @param resource - Note name (SEA resource identifier, e.g. `NODE_SEA_BLOB`)
1050
+ * @param resource - Note name (SEA resource identifier, for example `NODE_SEA_BLOB`)
832
1051
  * @param blobSize - Size in bytes of the SEA blob that will follow the header
833
1052
  * @returns The note header bytes and the total on-disk size of header + blob
834
1053
  *
835
1054
  * @example
836
1055
  * ```ts
837
- * const { header, entryTotal } = buildELFNoteHeader('NODE_SEA_BLOB', 4096)
1056
+ * const { header, total } = buildELFNoteHeader('NODE_SEA_BLOB', 4096)
838
1057
  * ```
839
1058
  */
840
1059
  function buildELFNoteHeader(resource, blobSize) {
@@ -848,11 +1067,11 @@ function buildELFNoteHeader(resource, blobSize) {
848
1067
  const alignedDescSize = alignELFNoteSize(blobSize);
849
1068
  return {
850
1069
  header,
851
- entryTotal: header.length + alignedDescSize
1070
+ total: header.length + alignedDescSize
852
1071
  };
853
1072
  }
854
1073
  /**
855
- * Copy a byte range from one open file descriptor to another, streaming in
1074
+ * Copies a byte range from one open file descriptor to another, streaming in
856
1075
  * fixed-size chunks instead of buffering the whole range in memory.
857
1076
  *
858
1077
  * @remarks
@@ -900,15 +1119,19 @@ function copyRange(source, target, start, length, chunk = 4194304) {
900
1119
  }
901
1120
  }
902
1121
  /**
903
- * Patch the sentinel fuse in a binary from `:0` to `:1`.
1122
+ * Patches the sentinel fuse in a binary from `:0` to `:1`.
904
1123
  *
905
- * Searches the file in 64 MB chunks with overlap to handle any file size.
906
- * The fuse signals to the Node.js runtime that a SEA blob is present.
907
- * This is normally handled by the Injector but is also available standalone
908
- * when using native PE resource injection.
1124
+ * @remarks
1125
+ * Searches the file in 64 MB chunks with overlap to handle any file size. The fuse
1126
+ * signals to the Node.js runtime that a SEA blob is present. The `Injector` class
1127
+ * normally applies this patch, and it stays available standalone for a build that
1128
+ * injects the PE resource natively instead.
909
1129
  *
910
1130
  * @param executable - Absolute path to the executable
911
1131
  * @param fuse - Sentinel fuse string (without the `:0` suffix)
1132
+ * @throws SEAError with code `'FUSE'` when the fuse value cannot be read
1133
+ * @throws SEAError with code `'FUSE'` when the fuse carries a value other than `:0` or `:1`
1134
+ * @throws SEAError with code `'FUSE'` when the fuse is not found in the executable
912
1135
  */
913
1136
  function patchSentinelFuse(executable, fuse) {
914
1137
  const fd = (0, node_fs.openSync)(executable, "r+");
@@ -951,7 +1174,7 @@ function patchSentinelFuse(executable, fuse) {
951
1174
  }
952
1175
  }
953
1176
  /**
954
- * Launch the system default browser at an http(s) URL.
1177
+ * Launches the system default browser at an http(s) URL.
955
1178
  *
956
1179
  * @remarks
957
1180
  * A best-effort launch for bundled local-UI apps: dispatches by
@@ -963,7 +1186,7 @@ function patchSentinelFuse(executable, fuse) {
963
1186
  * outlives the host app and never keeps it alive, and it swallows the async
964
1187
  * host fault an absent opener binary raises. Only `http:` and `https:` URLs
965
1188
  * are accepted — any other scheme (including a string that merely looks like a
966
- * CLI flag, e.g. `'-e ...'`) fails to parse as an http(s) URL and is rejected
1189
+ * CLI flag, for example `'-e ...'`) fails to parse as an http(s) URL and is rejected
967
1190
  * before anything is spawned.
968
1191
  *
969
1192
  * @param url - Absolute http or https URL to open
@@ -1000,6 +1223,32 @@ function openBrowser(url) {
1000
1223
  }
1001
1224
  //#endregion
1002
1225
  //#region src/server/injectors/Injector.ts
1226
+ /**
1227
+ * Writes a named resource into a PE, ELF, or Mach-O executable in place.
1228
+ *
1229
+ * @remarks
1230
+ * The format is detected from the file's magic bytes at construction, and each
1231
+ * format takes its own strategy: PE adds an `RT_RCDATA` resource by rebuilding the
1232
+ * resource directory, ELF appends a `PT_NOTE` segment carrying the blob as note
1233
+ * data, and Mach-O appends an `LC_SEGMENT_64` load command with one section. The
1234
+ * blob is streamed from disk in every case, so its size is bounded by the
1235
+ * filesystem rather than by memory.
1236
+ *
1237
+ * @param options - Injector options: the target executable, the resource name, the
1238
+ * blob path, and the optional sentinel fuse and Mach-O segment
1239
+ *
1240
+ * @example
1241
+ * ```ts
1242
+ * const injector = new Injector({
1243
+ * executable: 'dist/sea/myapp.exe',
1244
+ * resource: 'NODE_SEA_BLOB',
1245
+ * blob: 'dist/sea/sea-prep.blob',
1246
+ * fuse: 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2',
1247
+ * })
1248
+ * injector.format // 'pe' | 'elf' | 'macho'
1249
+ * injector.inject()
1250
+ * ```
1251
+ */
1003
1252
  var Injector = class {
1004
1253
  #options;
1005
1254
  #format;
@@ -1014,12 +1263,12 @@ var Injector = class {
1014
1263
  let peOptionalOffset;
1015
1264
  switch (this.#format) {
1016
1265
  case "pe":
1017
- peOptionalOffset = this.#injectPe();
1266
+ peOptionalOffset = this.#injectPE();
1018
1267
  break;
1019
1268
  case "elf":
1020
- this.#injectElf();
1269
+ this.#injectELF();
1021
1270
  break;
1022
- case "macho": this.#injectMacho();
1271
+ case "macho": this.#injectMachO();
1023
1272
  }
1024
1273
  if (this.#options.fuse !== void 0) patchSentinelFuse(this.#options.executable, this.#options.fuse);
1025
1274
  if (peOptionalOffset !== void 0) this.#patchChecksum(peOptionalOffset);
@@ -1051,32 +1300,32 @@ var Injector = class {
1051
1300
  (0, node_fs.closeSync)(fd);
1052
1301
  }
1053
1302
  }
1054
- #injectPe() {
1303
+ #injectPE() {
1055
1304
  const fd = (0, node_fs.openSync)(this.#options.executable, "r+");
1056
1305
  try {
1057
- const peOffset = this.#readU32(fd, 60);
1058
- const sig = this.#readU32(fd, peOffset);
1306
+ const peOffset = readU32(fd, 60);
1307
+ const sig = readU32(fd, peOffset);
1059
1308
  if (sig !== 17744) throw new SEAError("FORMAT", "Invalid PE signature", {
1060
1309
  executable: this.#options.executable,
1061
1310
  signature: sig
1062
1311
  });
1063
1312
  const coffOffset = peOffset + 4;
1064
- const numberOfSections = this.#readU16(fd, coffOffset + 2);
1065
- const optionalHeaderSize = this.#readU16(fd, coffOffset + 16);
1313
+ const numberOfSections = readU16(fd, coffOffset + 2);
1314
+ const optionalHeaderSize = readU16(fd, coffOffset + 16);
1066
1315
  const optionalOffset = coffOffset + 20;
1067
- const optMagic = this.#readU16(fd, optionalOffset);
1316
+ const optMagic = readU16(fd, optionalOffset);
1068
1317
  const is64 = optMagic === 523;
1069
1318
  if (optMagic !== 267 && optMagic !== 523) throw new SEAError("FORMAT", `Unsupported PE optional header magic: 0x${optMagic.toString(16)}`, {
1070
1319
  executable: this.#options.executable,
1071
1320
  optionalHeaderMagic: optMagic
1072
1321
  });
1073
- const sectionAlignment = this.#readU32(fd, optionalOffset + 32);
1074
- const fileAlignment = this.#readU32(fd, optionalOffset + 36);
1322
+ const sectionAlignment = readU32(fd, optionalOffset + 32);
1323
+ const fileAlignment = readU32(fd, optionalOffset + 36);
1075
1324
  this.#ensureValidPEAlignment(sectionAlignment, fileAlignment);
1076
1325
  const sizeOfImageOffset = optionalOffset + 56;
1077
1326
  const resourceDirRvaOffset = optionalOffset + (is64 ? 112 : 96) + 16;
1078
1327
  const resourceDirSizeOffset = resourceDirRvaOffset + 4;
1079
- const existingResourceRva = this.#readU32(fd, resourceDirRvaOffset);
1328
+ const existingResourceRVA = readU32(fd, resourceDirRvaOffset);
1080
1329
  const sectionTableOffset = optionalOffset + optionalHeaderSize;
1081
1330
  const sections = [];
1082
1331
  let rsrcSectionIndex = -1;
@@ -1084,12 +1333,12 @@ var Injector = class {
1084
1333
  const off = sectionTableOffset + i * 40;
1085
1334
  const nameBuf = Buffer.alloc(8);
1086
1335
  (0, node_fs.readSync)(fd, nameBuf, 0, 8, off);
1087
- const name = this.#stripTrailingNulls(nameBuf.toString("ascii"));
1088
- const virtualSize = this.#readU32(fd, off + 8);
1089
- const virtualAddress = this.#readU32(fd, off + 12);
1090
- const rawSize = this.#readU32(fd, off + 16);
1091
- const rawOffset = this.#readU32(fd, off + 20);
1092
- const characteristics = this.#readU32(fd, off + 36);
1336
+ const name = stripTrailingNulls(nameBuf.toString("ascii"));
1337
+ const virtualSize = readU32(fd, off + 8);
1338
+ const virtualAddress = readU32(fd, off + 12);
1339
+ const rawSize = readU32(fd, off + 16);
1340
+ const rawOffset = readU32(fd, off + 20);
1341
+ const characteristics = readU32(fd, off + 36);
1093
1342
  sections.push({
1094
1343
  name,
1095
1344
  virtualSize,
@@ -1099,19 +1348,19 @@ var Injector = class {
1099
1348
  characteristics,
1100
1349
  headerOffset: off
1101
1350
  });
1102
- if (existingResourceRva >= virtualAddress && existingResourceRva < virtualAddress + Math.max(virtualSize, rawSize)) rsrcSectionIndex = i;
1351
+ if (existingResourceRVA >= virtualAddress && existingResourceRVA < virtualAddress + Math.max(virtualSize, rawSize)) rsrcSectionIndex = i;
1103
1352
  }
1104
1353
  const sectionTableEnd = sectionTableOffset + numberOfSections * 40;
1105
1354
  const availableHeaderSpace = sections.reduce((min, s) => s.rawOffset > 0 && s.rawOffset < min ? s.rawOffset : min, Infinity) - sectionTableEnd;
1106
- if (availableHeaderSpace < 40) throw new SEAError("INJECT", `No room in PE header for a new section entry (${String(availableHeaderSpace)} bytes available, need ${String(40)})`, {
1355
+ if (availableHeaderSpace < 40) throw new SEAError("ROOM", `No room in PE header for a new section entry (${String(availableHeaderSpace)} bytes available, need ${String(40)})`, {
1107
1356
  executable: this.#options.executable,
1108
1357
  availableHeaderSpace,
1109
1358
  requiredHeaderSpace: 40
1110
1359
  });
1111
1360
  const existingLeaves = [];
1112
- if (rsrcSectionIndex !== -1 && existingResourceRva !== 0) {
1361
+ if (rsrcSectionIndex !== -1 && existingResourceRVA !== 0) {
1113
1362
  const rsrc = sections[rsrcSectionIndex];
1114
- if (rsrc !== void 0) this.#parseResourceDirectory(fd, rsrc.rawOffset, existingResourceRva, 0, existingLeaves, 0, 0, void 0, 0, void 0);
1363
+ if (rsrc !== void 0) this.#parseResourceDirectory(fd, rsrc.rawOffset, existingResourceRVA, 0, existingLeaves, 0, 0, void 0, 0, void 0);
1115
1364
  }
1116
1365
  const overwrite = this.#options.overwrite !== false;
1117
1366
  const upperName = this.#options.resource.toUpperCase();
@@ -1124,7 +1373,7 @@ var Injector = class {
1124
1373
  for (let i = 0; i < filteredLeaves.length; i++) {
1125
1374
  const leaf = filteredLeaves[i];
1126
1375
  if (leaf === void 0) continue;
1127
- const fileOffset = this.#rvaToFileOffset(leaf.dataRva, sections);
1376
+ const fileOffset = this.#rvaToFileOffset(leaf.dataRVA, sections);
1128
1377
  if (fileOffset >= 0) {
1129
1378
  const buf = Buffer.alloc(leaf.dataSize);
1130
1379
  (0, node_fs.readSync)(fd, buf, 0, leaf.dataSize, fileOffset);
@@ -1135,16 +1384,16 @@ var Injector = class {
1135
1384
  const tree = this.#buildResourceTree(filteredLeaves, upperName, blobSize);
1136
1385
  const { directoryBuffer, dataRegionSize } = this.#serializeResourceTree(tree, leafDataMap, blobSize);
1137
1386
  const totalRawSize = directoryBuffer.length + dataRegionSize;
1138
- const alignedRawSize = this.#align(totalRawSize, fileAlignment);
1387
+ const alignedRawSize = alignTo(totalRawSize, fileAlignment);
1139
1388
  let highestVaEnd = 0;
1140
1389
  for (const s of sections) {
1141
1390
  const end = s.virtualAddress + Math.max(s.virtualSize, s.rawSize);
1142
1391
  if (end > highestVaEnd) highestVaEnd = end;
1143
1392
  }
1144
- const newVa = this.#align(highestVaEnd, sectionAlignment);
1393
+ const newVa = alignTo(highestVaEnd, sectionAlignment);
1145
1394
  const newVirtualSize = totalRawSize;
1146
1395
  const fileSize = (0, node_fs.statSync)(this.#options.executable).size;
1147
- const newRawOffset = this.#align(fileSize, fileAlignment);
1396
+ const newRawOffset = alignTo(fileSize, fileAlignment);
1148
1397
  const newHeaderOffset = sectionTableEnd;
1149
1398
  const headerBuf = Buffer.alloc(40);
1150
1399
  headerBuf.write(".rsrc2", 0, 6, "ascii");
@@ -1158,28 +1407,27 @@ var Injector = class {
1158
1407
  headerBuf.writeUInt16LE(0, 34);
1159
1408
  headerBuf.writeUInt32LE(64 | PE_SCN_MEM_READ, 36);
1160
1409
  (0, node_fs.writeSync)(fd, headerBuf, 0, 40, newHeaderOffset);
1161
- this.#writeU16(fd, coffOffset + 2, numberOfSections + 1);
1162
- this.#writeU32(fd, resourceDirRvaOffset, newVa);
1163
- this.#writeU32(fd, resourceDirSizeOffset, directoryBuffer.length);
1164
- const newSizeOfImage = this.#align(newVa + Math.max(newVirtualSize, alignedRawSize), sectionAlignment);
1165
- this.#writeU32(fd, sizeOfImageOffset, newSizeOfImage);
1410
+ writeU16(fd, coffOffset + 2, numberOfSections + 1);
1411
+ writeU32(fd, resourceDirRvaOffset, newVa);
1412
+ writeU32(fd, resourceDirSizeOffset, directoryBuffer.length);
1413
+ writeU32(fd, sizeOfImageOffset, alignTo(newVa + Math.max(newVirtualSize, alignedRawSize), sectionAlignment));
1166
1414
  (0, node_fs.closeSync)(fd);
1167
1415
  const currentFileSize = (0, node_fs.statSync)(this.#options.executable).size;
1168
1416
  if (newRawOffset > currentFileSize) {
1169
1417
  const padding = Buffer.alloc(newRawOffset - currentFileSize);
1170
1418
  (0, node_fs.appendFileSync)(this.#options.executable, padding);
1171
1419
  }
1172
- this.#fixupDirectoryRvas(directoryBuffer, newVa);
1420
+ this.#fixupDataEntries(directoryBuffer, 0, newVa);
1173
1421
  (0, node_fs.appendFileSync)(this.#options.executable, directoryBuffer);
1174
1422
  for (let i = 0; i < filteredLeaves.length; i++) {
1175
1423
  const data = leafDataMap.get(i);
1176
1424
  if (data !== void 0) {
1177
1425
  (0, node_fs.appendFileSync)(this.#options.executable, data);
1178
- const padLen = this.#align(data.length, 4) - data.length;
1426
+ const padLen = alignTo(data.length, 4) - data.length;
1179
1427
  if (padLen > 0) (0, node_fs.appendFileSync)(this.#options.executable, Buffer.alloc(padLen));
1180
1428
  }
1181
1429
  }
1182
- this.#appendFile(this.#options.executable, this.#options.blob);
1430
+ appendFile(this.#options.executable, this.#options.blob);
1183
1431
  const writtenSize = (0, node_fs.statSync)(this.#options.executable).size - newRawOffset;
1184
1432
  if (writtenSize < alignedRawSize) (0, node_fs.appendFileSync)(this.#options.executable, Buffer.alloc(alignedRawSize - writtenSize));
1185
1433
  return optionalOffset;
@@ -1192,11 +1440,11 @@ var Injector = class {
1192
1440
  }
1193
1441
  #parseResourceDirectory(fd, sectionFileOffset, sectionRva, dirOffset, leaves, depth, currentTypeId, currentTypeName, currentNameId, currentNameName) {
1194
1442
  const absOffset = sectionFileOffset + dirOffset;
1195
- const totalEntries = this.#readU16(fd, absOffset + 12) + this.#readU16(fd, absOffset + 14);
1443
+ const totalEntries = readU16(fd, absOffset + 12) + readU16(fd, absOffset + 14);
1196
1444
  for (let i = 0; i < totalEntries; i++) {
1197
1445
  const entryOffset = absOffset + 16 + i * 8;
1198
- const nameOrId = this.#readU32(fd, entryOffset);
1199
- const offsetOrData = this.#readU32(fd, entryOffset + 4);
1446
+ const nameOrId = readU32(fd, entryOffset);
1447
+ const offsetOrData = readU32(fd, entryOffset + 4);
1200
1448
  let entryId = 0;
1201
1449
  let entryName;
1202
1450
  if ((nameOrId & 2147483648) !== 0) {
@@ -1219,9 +1467,9 @@ var Injector = class {
1219
1467
  this.#parseResourceDirectory(fd, sectionFileOffset, sectionRva, subDirOffset, leaves, depth + 1, typeId, typeName, nameId, nameName);
1220
1468
  } else {
1221
1469
  const dataEntryFileOffset = sectionFileOffset + offsetOrData;
1222
- const dataRva = this.#readU32(fd, dataEntryFileOffset);
1223
- const dataSize = this.#readU32(fd, dataEntryFileOffset + 4);
1224
- const codePage = this.#readU32(fd, dataEntryFileOffset + 8);
1470
+ const dataRVA = readU32(fd, dataEntryFileOffset);
1471
+ const dataSize = readU32(fd, dataEntryFileOffset + 4);
1472
+ const codePage = readU32(fd, dataEntryFileOffset + 8);
1225
1473
  const language = depth === 2 ? entryId : 0;
1226
1474
  leaves.push({
1227
1475
  typeId,
@@ -1230,7 +1478,7 @@ var Injector = class {
1230
1478
  nameName,
1231
1479
  language,
1232
1480
  codePage,
1233
- dataRva,
1481
+ dataRVA,
1234
1482
  dataSize
1235
1483
  });
1236
1484
  }
@@ -1307,7 +1555,7 @@ var Injector = class {
1307
1555
  value: str
1308
1556
  });
1309
1557
  stringPoolSize += 2 + str.length * 2;
1310
- stringPoolSize = this.#align(stringPoolSize, 2);
1558
+ stringPoolSize = alignTo(stringPoolSize, 2);
1311
1559
  }
1312
1560
  for (const [nameKey, langEntries] of nameMap) {
1313
1561
  dirTableSize += 16 + langEntries.length * 8;
@@ -1318,7 +1566,7 @@ var Injector = class {
1318
1566
  value: str
1319
1567
  });
1320
1568
  stringPoolSize += 2 + str.length * 2;
1321
- stringPoolSize = this.#align(stringPoolSize, 2);
1569
+ stringPoolSize = alignTo(stringPoolSize, 2);
1322
1570
  }
1323
1571
  for (const entry of langEntries) {
1324
1572
  allLeafEntries.push({
@@ -1341,7 +1589,7 @@ var Injector = class {
1341
1589
  const data = leafDataMap.get(entry.leafIndex);
1342
1590
  if (data !== void 0) {
1343
1591
  leafFileOffsets.set(entry.leafIndex, dataRegionOffset);
1344
- dataRegionOffset += this.#align(data.length, 4);
1592
+ dataRegionOffset += alignTo(data.length, 4);
1345
1593
  }
1346
1594
  }
1347
1595
  const blobDataOffset = dataRegionOffset;
@@ -1357,7 +1605,7 @@ var Injector = class {
1357
1605
  buf.writeUInt16LE(value.length, stringPos);
1358
1606
  buf.write(value, stringPos + 2, value.length * 2, "utf16le");
1359
1607
  stringPos += 2 + value.length * 2;
1360
- stringPos = this.#align(stringPos, 2);
1608
+ stringPos = alignTo(stringPos, 2);
1361
1609
  }
1362
1610
  const sortedTypeKeys = this.#sortResourceKeys([...tree.keys()]);
1363
1611
  const nextDirOffset = 16 + tree.size * 8;
@@ -1448,10 +1696,7 @@ var Injector = class {
1448
1696
  blobDataOffset
1449
1697
  };
1450
1698
  }
1451
- #fixupDirectoryRvas(directoryBuffer, sectionVa) {
1452
- this.#fixupDataEntries(directoryBuffer, 0, 0, sectionVa);
1453
- }
1454
- #fixupDataEntries(buf, dirOffset, depth, sectionVa) {
1699
+ #fixupDataEntries(buf, dirOffset, sectionVA) {
1455
1700
  if (dirOffset + 16 > buf.length) return;
1456
1701
  const totalEntries = buf.readUInt16LE(dirOffset + 12) + buf.readUInt16LE(dirOffset + 14);
1457
1702
  for (let i = 0; i < totalEntries; i++) {
@@ -1460,10 +1705,10 @@ var Injector = class {
1460
1705
  const offsetOrData = buf.readUInt32LE(entryOffset + 4);
1461
1706
  if ((offsetOrData & 2147483648) !== 0) {
1462
1707
  const subOffset = offsetOrData & ~PE_RESOURCE_SUBDIR_FLAG;
1463
- this.#fixupDataEntries(buf, subOffset, depth + 1, sectionVa);
1708
+ this.#fixupDataEntries(buf, subOffset, sectionVA);
1464
1709
  } else if (offsetOrData + 4 <= buf.length) {
1465
1710
  const currentRva = buf.readUInt32LE(offsetOrData);
1466
- buf.writeUInt32LE(currentRva + sectionVa >>> 0, offsetOrData);
1711
+ buf.writeUInt32LE(currentRva + sectionVA >>> 0, offsetOrData);
1467
1712
  }
1468
1713
  }
1469
1714
  }
@@ -1492,8 +1737,7 @@ var Injector = class {
1492
1737
  offset += bytesRead;
1493
1738
  }
1494
1739
  sum = (sum & 65535) + (sum >>> 16);
1495
- const checksum = sum + fileSize >>> 0;
1496
- this.#writeU32(fd, checksumOffset, checksum);
1740
+ writeU32(fd, checksumOffset, sum + fileSize >>> 0);
1497
1741
  } finally {
1498
1742
  (0, node_fs.closeSync)(fd);
1499
1743
  }
@@ -1505,14 +1749,10 @@ var Injector = class {
1505
1749
  });
1506
1750
  return [...named, ...ids];
1507
1751
  }
1508
- #injectElf() {
1752
+ #injectELF() {
1509
1753
  const exePath = this.#options.executable;
1510
1754
  const resource = this.#options.resource;
1511
1755
  const overwrite = this.#options.overwrite !== false;
1512
- const PT_LOAD = 1;
1513
- const PT_PHDR = 6;
1514
- const PF_R = 4;
1515
- const PAGE = 4096;
1516
1756
  let phdrOffset;
1517
1757
  let phdrEntrySize;
1518
1758
  let phdrCount;
@@ -1531,61 +1771,67 @@ var Injector = class {
1531
1771
  executable: exePath,
1532
1772
  elfData
1533
1773
  });
1534
- phdrOffset = Number(this.#readU64(fd, 32));
1535
- phdrEntrySize = this.#readU16(fd, 54);
1536
- phdrCount = this.#readU16(fd, 56);
1537
- headers = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1538
- for (const header of headers) {
1539
- if (header.type !== 4) continue;
1540
- const existingName = this.#readElfNoteName(fd, header.offset, header.filesz);
1774
+ phdrOffset = Number(readU64(fd, 32));
1775
+ phdrEntrySize = readU16(fd, 54);
1776
+ phdrCount = readU16(fd, 56);
1777
+ headers = this.#readELFProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1778
+ const stale = /* @__PURE__ */ new Set();
1779
+ for (let i = 0; i < headers.length; i++) {
1780
+ const header = headers[i];
1781
+ if (header === void 0 || header.type !== 4) continue;
1782
+ const existingName = this.#readELFNoteName(fd, header.offset, header.filesz);
1541
1783
  if (existingName === void 0 || !existingName.startsWith("NODE_SEA")) continue;
1542
1784
  if (!overwrite) throw new SEAError("INJECT", `Note with name "${resource}" already exists`, {
1543
1785
  executable: exePath,
1544
1786
  resource
1545
1787
  });
1546
- header.type = 0;
1788
+ stale.add(i);
1547
1789
  }
1790
+ headers = headers.map((header, index) => stale.has(index) ? {
1791
+ ...header,
1792
+ type: 0
1793
+ } : header);
1548
1794
  } finally {
1549
1795
  (0, node_fs.closeSync)(fd);
1550
1796
  }
1551
1797
  let maxVaddrEnd = 0;
1552
1798
  for (const header of headers) {
1553
- if (header.type !== PT_LOAD) continue;
1799
+ if (header.type !== 1) continue;
1554
1800
  const end = header.vaddr + header.memsz;
1555
1801
  if (end > maxVaddrEnd) maxVaddrEnd = end;
1556
1802
  }
1557
- const regionVaddr = this.#align(maxVaddrEnd, PAGE);
1803
+ const regionVaddr = alignTo(maxVaddrEnd, ELF_PAGE_SIZE);
1558
1804
  const blobSize = (0, node_fs.statSync)(this.#options.blob).size;
1559
- const { header: noteHeader, entryTotal: noteEntryTotal } = buildELFNoteHeader(resource, blobSize);
1560
- const noteAreaSize = this.#align(noteEntryTotal, 8);
1805
+ const { header: noteHeader, total: noteTotal } = buildELFNoteHeader(resource, blobSize);
1806
+ const noteAreaSize = alignTo(noteTotal, 8);
1561
1807
  const newEntryCount = headers.length + 2;
1562
1808
  const phtSize = newEntryCount * phdrEntrySize;
1563
1809
  const regionSize = noteAreaSize + phtSize;
1564
1810
  const fileSize = (0, node_fs.statSync)(exePath).size;
1565
- const regionStart = this.#align(fileSize, PAGE);
1811
+ const regionStart = alignTo(fileSize, ELF_PAGE_SIZE);
1566
1812
  const phtOff = regionStart + noteAreaSize;
1567
1813
  const newLoad = {
1568
- type: PT_LOAD,
1569
- flags: PF_R,
1814
+ type: 1,
1815
+ flags: 4,
1570
1816
  offset: regionStart,
1571
1817
  vaddr: regionVaddr,
1572
1818
  paddr: regionVaddr,
1573
1819
  filesz: regionSize,
1574
1820
  memsz: regionSize,
1575
- align: PAGE
1821
+ align: ELF_PAGE_SIZE
1576
1822
  };
1577
1823
  const newNote = {
1578
1824
  type: 4,
1579
- flags: PF_R,
1825
+ flags: 4,
1580
1826
  offset: regionStart,
1581
1827
  vaddr: regionVaddr,
1582
1828
  paddr: regionVaddr,
1583
- filesz: noteEntryTotal,
1584
- memsz: noteEntryTotal,
1829
+ filesz: noteTotal,
1830
+ memsz: noteTotal,
1585
1831
  align: 4
1586
1832
  };
1587
1833
  const finalHeaders = headers.map((header) => {
1588
- if (header.type !== PT_PHDR) return header;
1834
+ if (header.type !== 6) return header;
1589
1835
  const relVaddr = regionVaddr + (phtOff - regionStart);
1590
1836
  return {
1591
1837
  ...header,
@@ -1601,43 +1847,43 @@ var Injector = class {
1601
1847
  for (let i = 0; i < finalHeaders.length; i++) {
1602
1848
  const entry = finalHeaders[i];
1603
1849
  if (entry === void 0) continue;
1604
- this.#writeElfProgramHeaderEntry(phtBuffer, i * phdrEntrySize, entry);
1850
+ this.#writeELFProgramHeaderEntry(phtBuffer, i * phdrEntrySize, entry);
1605
1851
  }
1606
1852
  if (regionStart > fileSize) (0, node_fs.appendFileSync)(exePath, Buffer.alloc(regionStart - fileSize));
1607
1853
  (0, node_fs.appendFileSync)(exePath, noteHeader);
1608
- this.#appendFile(exePath, this.#options.blob);
1609
- const descPadding = this.#align(blobSize, 4) - blobSize;
1854
+ appendFile(exePath, this.#options.blob);
1855
+ const descPadding = alignTo(blobSize, 4) - blobSize;
1610
1856
  if (descPadding > 0) (0, node_fs.appendFileSync)(exePath, Buffer.alloc(descPadding));
1611
- const trailingPad = noteAreaSize - noteEntryTotal;
1857
+ const trailingPad = noteAreaSize - noteTotal;
1612
1858
  if (trailingPad > 0) (0, node_fs.appendFileSync)(exePath, Buffer.alloc(trailingPad));
1613
1859
  (0, node_fs.appendFileSync)(exePath, phtBuffer);
1614
1860
  const fd2 = (0, node_fs.openSync)(exePath, "r+");
1615
1861
  try {
1616
- this.#writeU64(fd2, 32, BigInt(phtOff));
1617
- this.#writeU16(fd2, 56, newEntryCount);
1618
- this.#verifyElfNoteMapping(fd2, phtOff, newEntryCount, phdrEntrySize);
1862
+ writeU64(fd2, 32, BigInt(phtOff));
1863
+ writeU16(fd2, 56, newEntryCount);
1864
+ this.#verifyELFNoteMapping(fd2, phtOff, newEntryCount, phdrEntrySize);
1619
1865
  } finally {
1620
1866
  (0, node_fs.closeSync)(fd2);
1621
1867
  }
1622
1868
  }
1623
- #readElfProgramHeaders(fd, phdrOffset, entrySize, count) {
1869
+ #readELFProgramHeaders(fd, phdrOffset, entrySize, count) {
1624
1870
  const headers = [];
1625
1871
  for (let i = 0; i < count; i++) {
1626
1872
  const off = phdrOffset + i * entrySize;
1627
1873
  headers.push({
1628
- type: this.#readU32(fd, off),
1629
- flags: this.#readU32(fd, off + 4),
1630
- offset: Number(this.#readU64(fd, off + 8)),
1631
- vaddr: Number(this.#readU64(fd, off + 16)),
1632
- paddr: Number(this.#readU64(fd, off + 24)),
1633
- filesz: Number(this.#readU64(fd, off + 32)),
1634
- memsz: Number(this.#readU64(fd, off + 40)),
1635
- align: Number(this.#readU64(fd, off + 48))
1874
+ type: readU32(fd, off),
1875
+ flags: readU32(fd, off + 4),
1876
+ offset: Number(readU64(fd, off + 8)),
1877
+ vaddr: Number(readU64(fd, off + 16)),
1878
+ paddr: Number(readU64(fd, off + 24)),
1879
+ filesz: Number(readU64(fd, off + 32)),
1880
+ memsz: Number(readU64(fd, off + 40)),
1881
+ align: Number(readU64(fd, off + 48))
1636
1882
  });
1637
1883
  }
1638
1884
  return headers;
1639
1885
  }
1640
- #writeElfProgramHeaderEntry(buf, pos, entry) {
1886
+ #writeELFProgramHeaderEntry(buf, pos, entry) {
1641
1887
  buf.writeUInt32LE(entry.type >>> 0, pos);
1642
1888
  buf.writeUInt32LE(entry.flags >>> 0, pos + 4);
1643
1889
  buf.writeBigUInt64LE(BigInt(entry.offset), pos + 8);
@@ -1647,22 +1893,22 @@ var Injector = class {
1647
1893
  buf.writeBigUInt64LE(BigInt(entry.memsz), pos + 40);
1648
1894
  buf.writeBigUInt64LE(BigInt(entry.align), pos + 48);
1649
1895
  }
1650
- #readElfNoteName(fd, offset, size) {
1896
+ #readELFNoteName(fd, offset, size) {
1651
1897
  if (size < 12) return void 0;
1652
- const namesz = this.#readU32(fd, offset);
1653
- const descsz = this.#readU32(fd, offset + 4);
1898
+ const namesz = readU32(fd, offset);
1899
+ const descsz = readU32(fd, offset + 4);
1654
1900
  if (namesz === 0 || namesz > 256) return void 0;
1655
- if (12 + this.#align(namesz, 4) + this.#align(descsz, 4) > size) return void 0;
1901
+ if (12 + alignTo(namesz, 4) + alignTo(descsz, 4) > size) return void 0;
1656
1902
  const nameBuf = Buffer.alloc(namesz);
1657
1903
  (0, node_fs.readSync)(fd, nameBuf, 0, namesz, offset + 12);
1658
- return this.#stripTrailingNulls(nameBuf.toString("utf-8"));
1904
+ return stripTrailingNulls(nameBuf.toString("utf-8"));
1659
1905
  }
1660
- #verifyElfNoteMapping(fd, phdrOffset, phdrCount, phdrEntrySize) {
1661
- const headers = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1906
+ #verifyELFNoteMapping(fd, phdrOffset, phdrCount, phdrEntrySize) {
1907
+ const headers = this.#readELFProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1662
1908
  const loads = headers.filter((h) => h.type === 1);
1663
1909
  const notes = headers.filter((h) => h.type === 4);
1664
1910
  for (const note of notes) {
1665
- const name = this.#readElfNoteName(fd, note.offset, note.filesz);
1911
+ const name = this.#readELFNoteName(fd, note.offset, note.filesz);
1666
1912
  if (name === void 0 || !name.startsWith("NODE_SEA")) continue;
1667
1913
  const covering = loads.find((load) => note.offset >= load.offset && note.offset < load.offset + load.filesz);
1668
1914
  if (covering === void 0) continue;
@@ -1673,7 +1919,7 @@ var Injector = class {
1673
1919
  resource: this.#options.resource
1674
1920
  });
1675
1921
  }
1676
- #injectMacho() {
1922
+ #injectMachO() {
1677
1923
  const exePath = this.#options.executable;
1678
1924
  const fileSize = (0, node_fs.statSync)(exePath).size;
1679
1925
  let srcFd = (0, node_fs.openSync)(exePath, "r");
@@ -1723,7 +1969,7 @@ var Injector = class {
1723
1969
  for (let i = 0; i < commands.length; i++) {
1724
1970
  const cmd = commands[i];
1725
1971
  if (cmd === void 0 || cmd.type !== 25) continue;
1726
- const segName = this.#stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii"));
1972
+ const segName = stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii"));
1727
1973
  if (segName === "__LINKEDIT") linkeditIndex = i;
1728
1974
  if (segName === segmentName) existingSegmentIndices.push(i);
1729
1975
  }
@@ -1732,13 +1978,12 @@ var Injector = class {
1732
1978
  segmentName
1733
1979
  });
1734
1980
  const linkeditCmd = linkeditIndex === -1 ? void 0 : commands[linkeditIndex];
1735
- if (linkeditCmd === void 0) throw new SEAError("INJECT", "Mach-O binary has no __LINKEDIT segment", { executable: exePath });
1736
- const Loff = Number(buf.readBigUInt64LE(linkeditCmd.offset + 40));
1737
- const Lsize = Number(buf.readBigUInt64LE(linkeditCmd.offset + 48));
1738
- const Lvm = buf.readBigUInt64LE(linkeditCmd.offset + 24);
1981
+ if (linkeditCmd === void 0) throw new SEAError("ROOM", "Mach-O binary has no __LINKEDIT segment", { executable: exePath });
1982
+ const linkeditOffset = Number(buf.readBigUInt64LE(linkeditCmd.offset + 40));
1983
+ const linkeditSize = Number(buf.readBigUInt64LE(linkeditCmd.offset + 48));
1984
+ const linkeditAddress = buf.readBigUInt64LE(linkeditCmd.offset + 24);
1739
1985
  const blobSize = (0, node_fs.statSync)(this.#options.blob).size;
1740
- const pageSize = cputype === 16777228 ? 16384 : 4096;
1741
- const shift = this.#align(blobSize, pageSize);
1986
+ const shift = alignTo(blobSize, cputype === 16777228 ? 16384 : 4096);
1742
1987
  let firstSectionOffset = fileSize;
1743
1988
  for (const cmd of commands) {
1744
1989
  if (cmd.type !== 25) continue;
@@ -1755,7 +2000,7 @@ var Injector = class {
1755
2000
  const removedSize = commands.filter((_c, i) => existingSegmentIndices.includes(i)).reduce((sum, c) => sum + c.size, 0);
1756
2001
  const newNcmds = commands.length - existingSegmentIndices.length + 1;
1757
2002
  const newSizeofcmds = sizeofcmds - removedSize + newCmdSize;
1758
- if (headerSize + newSizeofcmds + 16 > firstSectionOffset) throw new SEAError("INJECT", `Not enough header space for new Mach-O load command (need offset ${String(headerSize + newSizeofcmds + 16)}, first section at ${String(firstSectionOffset)})`, {
2003
+ if (headerSize + newSizeofcmds + 16 > firstSectionOffset) throw new SEAError("ROOM", `Not enough header space for new Mach-O load command (need offset ${String(headerSize + newSizeofcmds + 16)}, first section at ${String(firstSectionOffset)})`, {
1759
2004
  executable: exePath,
1760
2005
  firstSectionOffset,
1761
2006
  requiredOffset: headerSize + newSizeofcmds + 16
@@ -1764,14 +2009,14 @@ var Injector = class {
1764
2009
  const cmd = commands[i];
1765
2010
  if (cmd === void 0 || existingSegmentIndices.includes(i)) continue;
1766
2011
  if (cmd.type === 25) {
1767
- if (this.#stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii")) === "__LINKEDIT") {
1768
- if (buf.readUInt32LE(cmd.offset + 64) > 0) throw new SEAError("INJECT", "__LINKEDIT segment with sections is not supported", { executable: exePath });
1769
- buf.writeBigUInt64LE(Lvm + BigInt(shift), cmd.offset + 24);
1770
- buf.writeBigUInt64LE(BigInt(Loff + shift), cmd.offset + 40);
2012
+ if (stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii")) === "__LINKEDIT") {
2013
+ if (buf.readUInt32LE(cmd.offset + 64) > 0) throw new SEAError("ROOM", "__LINKEDIT segment with sections is not supported", { executable: exePath });
2014
+ buf.writeBigUInt64LE(linkeditAddress + BigInt(shift), cmd.offset + 24);
2015
+ buf.writeBigUInt64LE(BigInt(linkeditOffset + shift), cmd.offset + 40);
1771
2016
  }
1772
2017
  continue;
1773
2018
  }
1774
- this.#shiftMachoLinkeditOffsets(buf, cmd, Loff, shift);
2019
+ this.#shiftMachOLinkeditOffsets(buf, cmd, linkeditOffset, shift);
1775
2020
  }
1776
2021
  buf.writeUInt32LE(newNcmds, 16);
1777
2022
  buf.writeUInt32LE(newSizeofcmds, 20);
@@ -1779,9 +2024,9 @@ var Injector = class {
1779
2024
  cmd.writeUInt32LE(25, 0);
1780
2025
  cmd.writeUInt32LE(newCmdSize, 4);
1781
2026
  cmd.write(segmentName, 8, 16, "ascii");
1782
- cmd.writeBigUInt64LE(Lvm, 24);
2027
+ cmd.writeBigUInt64LE(linkeditAddress, 24);
1783
2028
  cmd.writeBigUInt64LE(BigInt(shift), 32);
1784
- cmd.writeBigUInt64LE(BigInt(Loff), 40);
2029
+ cmd.writeBigUInt64LE(BigInt(linkeditOffset), 40);
1785
2030
  cmd.writeBigUInt64LE(BigInt(shift), 48);
1786
2031
  cmd.writeUInt32LE(1, 56);
1787
2032
  cmd.writeUInt32LE(1, 60);
@@ -1789,9 +2034,9 @@ var Injector = class {
1789
2034
  cmd.writeUInt32LE(0, 68);
1790
2035
  cmd.write(sectionName, 72, 16, "ascii");
1791
2036
  cmd.write(segmentName, 88, 16, "ascii");
1792
- cmd.writeBigUInt64LE(Lvm, 104);
2037
+ cmd.writeBigUInt64LE(linkeditAddress, 104);
1793
2038
  cmd.writeBigUInt64LE(BigInt(blobSize), 112);
1794
- cmd.writeUInt32LE(Loff, 120);
2039
+ cmd.writeUInt32LE(linkeditOffset, 120);
1795
2040
  cmd.writeUInt32LE(0, 124);
1796
2041
  cmd.writeUInt32LE(0, 128);
1797
2042
  cmd.writeUInt32LE(0, 132);
@@ -1814,14 +2059,14 @@ var Injector = class {
1814
2059
  destFd = (0, node_fs.openSync)(injTemp, "w", mode);
1815
2060
  (0, node_fs.writeSync)(destFd, buf.subarray(0, headerSize));
1816
2061
  (0, node_fs.writeSync)(destFd, newLoadCmdsBuf);
1817
- copyRange(srcFd, destFd, headerSize + newSizeofcmds, Loff - (headerSize + newSizeofcmds));
2062
+ copyRange(srcFd, destFd, headerSize + newSizeofcmds, linkeditOffset - (headerSize + newSizeofcmds));
1818
2063
  blobFd = (0, node_fs.openSync)(this.#options.blob, "r");
1819
2064
  copyRange(blobFd, destFd, 0, blobSize);
1820
2065
  (0, node_fs.closeSync)(blobFd);
1821
2066
  blobFd = void 0;
1822
2067
  const blobPadding = shift - blobSize;
1823
2068
  if (blobPadding > 0) (0, node_fs.writeSync)(destFd, Buffer.alloc(blobPadding));
1824
- copyRange(srcFd, destFd, Loff, Lsize);
2069
+ copyRange(srcFd, destFd, linkeditOffset, linkeditSize);
1825
2070
  (0, node_fs.closeSync)(destFd);
1826
2071
  destFd = void 0;
1827
2072
  (0, node_fs.closeSync)(srcFd);
@@ -1829,7 +2074,7 @@ var Injector = class {
1829
2074
  (0, node_fs.chmodSync)(injTemp, mode & 4095);
1830
2075
  finalizeExecutable(injTemp, exePath);
1831
2076
  injTemp = void 0;
1832
- this.#verifyMachoSection(exePath, segmentName, sectionName, Loff, blobSize);
2077
+ this.#verifyMachOSection(exePath, segmentName, sectionName, linkeditOffset, blobSize);
1833
2078
  } finally {
1834
2079
  for (const fd of [
1835
2080
  blobFd,
@@ -1841,7 +2086,7 @@ var Injector = class {
1841
2086
  if (injTemp !== void 0) (0, node_fs.rmSync)(injTemp, { force: true });
1842
2087
  }
1843
2088
  }
1844
- #shiftMachoLinkeditOffsets(buf, cmd, threshold, shift) {
2089
+ #shiftMachOLinkeditOffsets(buf, cmd, threshold, shift) {
1845
2090
  let offsets;
1846
2091
  switch (cmd.type) {
1847
2092
  case 2:
@@ -1884,7 +2129,7 @@ var Injector = class {
1884
2129
  if (value >= threshold && value > 0) buf.writeUInt32LE(value + shift, fieldOffset);
1885
2130
  }
1886
2131
  }
1887
- #verifyMachoSection(exePath, segmentName, sectionName, expectedOffset, expectedSize) {
2132
+ #verifyMachOSection(exePath, segmentName, sectionName, expectedOffset, expectedSize) {
1888
2133
  const fd = (0, node_fs.openSync)(exePath, "r");
1889
2134
  try {
1890
2135
  const header = Buffer.alloc(32);
@@ -1899,12 +2144,12 @@ var Injector = class {
1899
2144
  if (cmdType === 25 && cmdSize >= 72) {
1900
2145
  const segBuf = Buffer.alloc(cmdSize);
1901
2146
  (0, node_fs.readSync)(fd, segBuf, 0, cmdSize, offset);
1902
- if (this.#stripTrailingNulls(segBuf.subarray(8, 24).toString("ascii")) === segmentName) {
2147
+ if (stripTrailingNulls(segBuf.subarray(8, 24).toString("ascii")) === segmentName) {
1903
2148
  const nsects = segBuf.readUInt32LE(64);
1904
2149
  for (let s = 0; s < nsects; s++) {
1905
2150
  const sectOff = 72 + s * 80;
1906
2151
  if (sectOff + 80 > segBuf.length) continue;
1907
- if (this.#stripTrailingNulls(segBuf.subarray(sectOff, sectOff + 16).toString("ascii")) !== sectionName) continue;
2152
+ if (stripTrailingNulls(segBuf.subarray(sectOff, sectOff + 16).toString("ascii")) !== sectionName) continue;
1908
2153
  const secSize = Number(segBuf.readBigUInt64LE(sectOff + 40));
1909
2154
  if (segBuf.readUInt32LE(sectOff + 48) === expectedOffset && secSize === expectedSize) return;
1910
2155
  }
@@ -1921,40 +2166,6 @@ var Injector = class {
1921
2166
  sectionName
1922
2167
  });
1923
2168
  }
1924
- #readU16(fd, offset) {
1925
- const b = Buffer.alloc(2);
1926
- (0, node_fs.readSync)(fd, b, 0, 2, offset);
1927
- return b.readUInt16LE(0);
1928
- }
1929
- #readU32(fd, offset) {
1930
- const b = Buffer.alloc(4);
1931
- (0, node_fs.readSync)(fd, b, 0, 4, offset);
1932
- return b.readUInt32LE(0);
1933
- }
1934
- #readU64(fd, offset) {
1935
- const b = Buffer.alloc(8);
1936
- (0, node_fs.readSync)(fd, b, 0, 8, offset);
1937
- return b.readBigUInt64LE(0);
1938
- }
1939
- #writeU16(fd, offset, value) {
1940
- const b = Buffer.alloc(2);
1941
- b.writeUInt16LE(value, 0);
1942
- (0, node_fs.writeSync)(fd, b, 0, 2, offset);
1943
- }
1944
- #writeU32(fd, offset, value) {
1945
- const b = Buffer.alloc(4);
1946
- b.writeUInt32LE(value >>> 0, 0);
1947
- (0, node_fs.writeSync)(fd, b, 0, 4, offset);
1948
- }
1949
- #writeU64(fd, offset, value) {
1950
- const b = Buffer.alloc(8);
1951
- b.writeBigUInt64LE(value, 0);
1952
- (0, node_fs.writeSync)(fd, b, 0, 8, offset);
1953
- }
1954
- #align(value, alignment) {
1955
- const remainder = value % alignment;
1956
- return remainder === 0 ? value : value + (alignment - remainder);
1957
- }
1958
2169
  #ensureValidPEAlignment(sectionAlignment, fileAlignment) {
1959
2170
  if (!isPowerOfTwo(sectionAlignment) || !isPowerOfTwo(fileAlignment)) throw new SEAError("FORMAT", "PE section/file alignment must be a nonzero power of two", {
1960
2171
  executable: this.#options.executable,
@@ -1967,35 +2178,35 @@ var Injector = class {
1967
2178
  fileAlignment
1968
2179
  });
1969
2180
  }
1970
- /** Append sourceFile to targetFile by streaming in 4 MB chunks */
1971
- #appendFile(targetPath, sourcePath) {
1972
- const chunkSize = 4194304;
1973
- const srcFd = (0, node_fs.openSync)(sourcePath, "r");
1974
- try {
1975
- const srcSize = (0, node_fs.statSync)(sourcePath).size;
1976
- const chunk = Buffer.alloc(Math.min(chunkSize, srcSize));
1977
- let offset = 0;
1978
- while (offset < srcSize) {
1979
- const toRead = Math.min(chunkSize, srcSize - offset);
1980
- const bytesRead = (0, node_fs.readSync)(srcFd, chunk, 0, toRead, offset);
1981
- if (bytesRead === 0) break;
1982
- (0, node_fs.appendFileSync)(targetPath, chunk.subarray(0, bytesRead));
1983
- offset += bytesRead;
1984
- }
1985
- } finally {
1986
- (0, node_fs.closeSync)(srcFd);
1987
- }
1988
- }
1989
- #stripTrailingNulls(value) {
1990
- const idx = value.indexOf(String.fromCharCode(0));
1991
- return idx === -1 ? value : value.slice(0, idx);
1992
- }
1993
2181
  };
1994
2182
  //#endregion
1995
- //#region src/server/seals/SEA.ts
2183
+ //#region src/server/seas/SEA.ts
2184
+ /**
2185
+ * Runs a Node.js single executable application build to completion.
2186
+ *
2187
+ * @remarks
2188
+ * `execute` compresses the configured directories, generates the SEA blob, copies
2189
+ * the host Node binary, injects the blob with an {@link Injector}, signs the
2190
+ * result where the platform supports it, and moves the finished executable into
2191
+ * place atomically. Each stage reports on `emitter`, and every failure throws a
2192
+ * coded `SEAError` after an `error` event carrying it.
2193
+ *
2194
+ * @param options - SEA build options: the output name, the entry point, the output
2195
+ * directory, and the optional assets, compression, Windows, and blob settings
2196
+ *
2197
+ * @example
2198
+ * ```ts
2199
+ * const sea = new SEA({
2200
+ * name: 'myapp',
2201
+ * entry: { path: 'dist/server/serve.cjs' },
2202
+ * output: 'dist/sea',
2203
+ * })
2204
+ * const result = await sea.execute()
2205
+ * sea.destroy()
2206
+ * ```
2207
+ */
1996
2208
  var SEA = class {
1997
2209
  #status = "idle";
1998
- #destroyed = false;
1999
2210
  #options;
2000
2211
  #emitter;
2001
2212
  constructor(options) {
@@ -2012,9 +2223,9 @@ var SEA = class {
2012
2223
  return this.#status;
2013
2224
  }
2014
2225
  async execute() {
2015
- if (this.#destroyed) throw new SEAError("STATE", "SEA is destroyed");
2226
+ if (this.#emitter.destroyed) throw new SEAError("STATE", "SEA is destroyed");
2016
2227
  if (this.#status === "active") throw new SEAError("STATE", "SEA build already in progress");
2017
- if (platformConfig() === void 0 || !isPlatformSupported()) {
2228
+ if (resolvePlatform() === void 0) {
2018
2229
  const error = new SEAError("PLATFORM", `Unsupported platform: ${process.platform}`, { platform: process.platform });
2019
2230
  this.#status = "error";
2020
2231
  this.#emitter.emit("error", error);
@@ -2029,7 +2240,7 @@ var SEA = class {
2029
2240
  this.#check();
2030
2241
  const compression = this.#compress(root);
2031
2242
  this.#check();
2032
- const blob = this.#blob(root, compression);
2243
+ const blob = this.#buildBlob(root, compression);
2033
2244
  this.#check();
2034
2245
  const assembled = this.#assemble(root, blob);
2035
2246
  const size = (0, node_fs.statSync)(assembled.executable).size;
@@ -2054,8 +2265,6 @@ var SEA = class {
2054
2265
  }
2055
2266
  }
2056
2267
  destroy() {
2057
- if (this.#destroyed) return;
2058
- this.#destroyed = true;
2059
2268
  this.#emitter.destroy();
2060
2269
  }
2061
2270
  #check() {
@@ -2066,16 +2275,12 @@ var SEA = class {
2066
2275
  ensureSafeName(this.#options.name);
2067
2276
  for (const [key, path] of Object.entries(this.#options.assets ?? {})) {
2068
2277
  ensureSafeKey(key);
2069
- ensureSafeKey(path);
2070
2278
  ensureContained(base, path);
2071
2279
  }
2072
- for (const path of this.#options.compression?.paths ?? []) {
2073
- ensureSafeKey(path);
2074
- if ((0, node_fs.existsSync)((0, node_path.resolve)(base, path))) ensureContained(base, path);
2075
- }
2280
+ for (const path of this.#options.compression?.paths ?? []) if ((0, node_fs.existsSync)((0, node_path.resolve)(base, path))) ensureContained(base, path);
2076
2281
  const sign = this.#options.windows?.sign;
2077
2282
  if (sign !== void 0) {
2078
- createSignCommand(sign, "placeholder");
2283
+ buildSignCommand(sign, "placeholder");
2079
2284
  if (sign.file !== void 0) ensureExists((0, node_path.resolve)(base, sign.file), "Certificate file not found", "SIGN");
2080
2285
  }
2081
2286
  }
@@ -2124,19 +2329,19 @@ var SEA = class {
2124
2329
  this.#emitter.emit("compress", manifest);
2125
2330
  return manifest;
2126
2331
  }
2127
- #blob(root, compression) {
2332
+ #buildBlob(root, compression) {
2128
2333
  const entry = (0, node_path.resolve)(root, this.#options.entry.path);
2129
2334
  ensureExists(entry, `Entry not found: ${this.#options.entry.path}`, "ENTRY");
2130
2335
  const output = (0, node_path.resolve)(root, this.#options.output);
2131
2336
  (0, node_fs.mkdirSync)(output, { recursive: true });
2132
2337
  const configPath = (0, node_path.join)(output, "sea-config.json");
2133
2338
  const blob = (0, node_path.join)(output, "sea-prep.blob");
2134
- const config = createBlobConfig({
2339
+ const config = buildBlobConfig({
2135
2340
  path: entry,
2136
2341
  ...this.#options.entry.format === void 0 ? {} : { format: this.#options.entry.format }
2137
- }, blob, this.#assets(root, compression), this.#options.blob);
2342
+ }, blob, this.#resolveAssets(root, compression), this.#options.blob);
2138
2343
  (0, node_fs.writeFileSync)(configPath, JSON.stringify(config, null, 2));
2139
- runShell([
2344
+ executeShell([
2140
2345
  process.execPath,
2141
2346
  "--experimental-sea-config",
2142
2347
  configPath
@@ -2150,7 +2355,7 @@ var SEA = class {
2150
2355
  return blob;
2151
2356
  }
2152
2357
  #assemble(root, blob) {
2153
- const platform = platformConfig();
2358
+ const platform = resolvePlatform();
2154
2359
  if (platform === void 0) throw new SEAError("PLATFORM", `Unsupported platform: ${process.platform}`, { platform: process.platform });
2155
2360
  const output = (0, node_path.resolve)(root, this.#options.output);
2156
2361
  const ext = process.platform === "win32" ? ".exe" : "";
@@ -2172,7 +2377,7 @@ var SEA = class {
2172
2377
  if (platform.remove !== void 0) {
2173
2378
  this.#check();
2174
2379
  try {
2175
- runShell([...platform.remove, temp], shell);
2380
+ executeShell([...platform.remove, temp], shell);
2176
2381
  } catch (thrown) {
2177
2382
  throw new SEAError("SIGN", "Failed to strip existing signature", { cause: thrown instanceof Error ? thrown.message : String(thrown) });
2178
2383
  }
@@ -2189,14 +2394,14 @@ var SEA = class {
2189
2394
  if (platform.sign !== void 0) {
2190
2395
  this.#check();
2191
2396
  try {
2192
- runShell([...platform.sign, temp], shell);
2397
+ executeShell([...platform.sign, temp], shell);
2193
2398
  } catch (thrown) {
2194
2399
  throw new SEAError("SIGN", "Failed to sign executable", { cause: thrown instanceof Error ? thrown.message : String(thrown) });
2195
2400
  }
2196
2401
  if (platform.verify !== void 0) {
2197
2402
  this.#check();
2198
2403
  try {
2199
- runShell([...platform.verify, temp], shell);
2404
+ executeShell([...platform.verify, temp], shell);
2200
2405
  } catch (thrown) {
2201
2406
  throw new SEAError("SIGN", "Signature verification failed", { cause: thrown instanceof Error ? thrown.message : String(thrown) });
2202
2407
  }
@@ -2222,12 +2427,12 @@ var SEA = class {
2222
2427
  const sign = this.#options.windows?.sign;
2223
2428
  if (sign !== void 0) {
2224
2429
  this.#check();
2225
- const signArgs = createSignCommand(sign.file !== void 0 ? {
2430
+ const signArgs = buildSignCommand(sign.file !== void 0 ? {
2226
2431
  ...sign,
2227
2432
  file: (0, node_path.resolve)(root, sign.file)
2228
2433
  } : sign, temp);
2229
2434
  try {
2230
- runShell(signArgs, shell);
2435
+ executeShell(signArgs, shell);
2231
2436
  } catch {
2232
2437
  throw new SEAError("SIGN", "Windows signing failed", { executable: temp });
2233
2438
  }
@@ -2235,7 +2440,7 @@ var SEA = class {
2235
2440
  if (platform.verify !== void 0) {
2236
2441
  this.#check();
2237
2442
  try {
2238
- runShell([...platform.verify, temp], shell);
2443
+ executeShell([...platform.verify, temp], shell);
2239
2444
  } catch {
2240
2445
  throw new SEAError("SIGN", "Signature verification failed", { executable: temp });
2241
2446
  }
@@ -2266,7 +2471,7 @@ var SEA = class {
2266
2471
  ...terminal === void 0 ? {} : { terminal }
2267
2472
  };
2268
2473
  }
2269
- #assets(root, compression) {
2474
+ #resolveAssets(root, compression) {
2270
2475
  const outputs = /* @__PURE__ */ new Map();
2271
2476
  for (const result of compression?.assets ?? []) outputs.set(result.input, result.output);
2272
2477
  const assets = {};
@@ -2279,6 +2484,23 @@ var SEA = class {
2279
2484
  };
2280
2485
  //#endregion
2281
2486
  //#region src/server/assets/Asset.ts
2487
+ /**
2488
+ * Holds one named asset's key, bytes, and compression state.
2489
+ *
2490
+ * @remarks
2491
+ * `compressed` is inferred from a `.br` suffix on the key whenever the input
2492
+ * leaves it unset, so a Brotli output registered under its own name reports itself
2493
+ * correctly without the caller restating it.
2494
+ *
2495
+ * @param input - The asset's key, content bytes, and optional compression flag
2496
+ *
2497
+ * @example
2498
+ * ```ts
2499
+ * const asset = new Asset({ key: 'client.html.br', content: compressedBuffer })
2500
+ * asset.key // 'client.html.br'
2501
+ * asset.compressed // true
2502
+ * ```
2503
+ */
2282
2504
  var Asset = class {
2283
2505
  key;
2284
2506
  content;
@@ -2292,24 +2514,41 @@ var Asset = class {
2292
2514
  //#endregion
2293
2515
  //#region src/server/assets/AssetManager.ts
2294
2516
  /**
2295
- * AssetManager
2517
+ * Collects named assets from a SEA blob or from disk and serves them by key.
2296
2518
  *
2297
- * Named asset collection with SEA and disk loading.
2298
- * In SEA mode, embedded assets are loaded automatically at construction.
2299
- * In development, `load()` reads client assets from disk.
2519
+ * @remarks
2520
+ * Construction registers every asset embedded in the running SEA blob, so an
2521
+ * executable built by this package reaches its assets without touching the
2522
+ * filesystem. Outside SEA mode that step registers nothing, and `load()` reads
2523
+ * the paths `options.assets` configures instead.
2524
+ *
2525
+ * @param options - Asset manager options: the project root, the key→path mapping
2526
+ * `load()` reads, and the event hooks
2527
+ *
2528
+ * @example
2529
+ * ```ts
2530
+ * const manager = new AssetManager({
2531
+ * root: process.cwd(),
2532
+ * assets: { 'client.html.br': 'dist/client/client.html.br' },
2533
+ * })
2534
+ * manager.load()
2535
+ * manager.asset('client.html.br')
2536
+ * manager.destroy()
2537
+ * ```
2300
2538
  */
2301
2539
  var AssetManager = class {
2302
2540
  #emitter;
2303
2541
  #assets = /* @__PURE__ */ new Map();
2304
- #keys = [];
2305
2542
  #root;
2543
+ #paths;
2306
2544
  constructor(options) {
2307
2545
  this.#root = options?.root ?? process.cwd();
2546
+ this.#paths = options?.assets ?? {};
2308
2547
  this.#emitter = new _orkestrel_emitter.Emitter({
2309
2548
  ...options?.on === void 0 ? {} : { on: options.on },
2310
2549
  ...options?.error === void 0 ? {} : { error: options.error }
2311
2550
  });
2312
- this.#loadSea();
2551
+ this.#loadSEA();
2313
2552
  }
2314
2553
  get emitter() {
2315
2554
  return this.#emitter;
@@ -2324,7 +2563,7 @@ var AssetManager = class {
2324
2563
  return [...this.#assets.values()];
2325
2564
  }
2326
2565
  keys() {
2327
- return [...this.#keys];
2566
+ return [...this.#assets.keys()];
2328
2567
  }
2329
2568
  register(input) {
2330
2569
  const items = Array.isArray(input) ? input : [input];
@@ -2336,46 +2575,31 @@ var AssetManager = class {
2336
2575
  }
2337
2576
  load() {
2338
2577
  if ((0, node_sea.isSea)()) return;
2339
- const devPath = (0, node_path.resolve)(this.#root, "client", CLIENT_ASSET_KEY_RAW);
2340
- const builtBrPath = (0, node_path.resolve)(this.#root, "dist", "client", CLIENT_ASSET_KEY_BR);
2341
- if ((0, node_fs.existsSync)(devPath)) {
2342
- try {
2343
- const raw = (0, node_fs.readFileSync)(devPath, "utf-8");
2344
- const content = new TextEncoder().encode(raw).buffer;
2345
- if (!(0, _orkestrel_contract.isArrayBuffer)(content)) throw new Error("Failed to encode client asset");
2346
- this.register({
2347
- key: CLIENT_ASSET_KEY_RAW,
2348
- content,
2349
- compressed: false
2350
- });
2351
- this.#emitter.emit("load", [CLIENT_ASSET_KEY_RAW]);
2352
- } catch (thrown) {
2353
- this.#emitter.emit("error", thrown);
2578
+ const registered = [];
2579
+ for (const [key, path] of Object.entries(this.#paths)) {
2580
+ const resolved = (0, node_path.resolve)(this.#root, path);
2581
+ if (!(0, node_fs.existsSync)(resolved)) {
2582
+ this.#emitter.emit("error", /* @__PURE__ */ new Error(`Asset not found: ${path}`));
2583
+ continue;
2354
2584
  }
2355
- return;
2356
- }
2357
- if ((0, node_fs.existsSync)(builtBrPath)) {
2358
2585
  try {
2359
- const buffer = (0, node_fs.readFileSync)(builtBrPath);
2586
+ const buffer = (0, node_fs.readFileSync)(resolved);
2360
2587
  const bufferData = buffer.buffer;
2361
- if (!(0, _orkestrel_contract.isArrayBuffer)(bufferData)) throw new Error("Failed to read client asset");
2588
+ if (!(0, _orkestrel_contract.isArrayBuffer)(bufferData)) throw new Error(`Failed to read asset: ${path}`);
2362
2589
  const content = bufferData.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
2363
2590
  this.register({
2364
- key: CLIENT_ASSET_KEY_BR,
2365
- content,
2366
- compressed: true
2591
+ key,
2592
+ content
2367
2593
  });
2368
- this.#emitter.emit("load", [CLIENT_ASSET_KEY_BR]);
2594
+ registered.push(key);
2369
2595
  } catch (thrown) {
2370
2596
  this.#emitter.emit("error", thrown);
2371
2597
  }
2372
- return;
2373
2598
  }
2374
- this.#emitter.emit("error", /* @__PURE__ */ new Error("Client assets not found"));
2599
+ if (registered.length > 0) this.#emitter.emit("load", registered);
2375
2600
  }
2376
2601
  clear() {
2377
2602
  this.#assets.clear();
2378
- this.#keys = [];
2379
2603
  this.#emitter.emit("clear");
2380
2604
  }
2381
2605
  destroy() {
@@ -2384,9 +2608,8 @@ var AssetManager = class {
2384
2608
  }
2385
2609
  #add(asset) {
2386
2610
  this.#assets.set(asset.key, asset);
2387
- if (!this.#keys.includes(asset.key)) this.#keys.push(asset.key);
2388
2611
  }
2389
- #loadSea() {
2612
+ #loadSEA() {
2390
2613
  if ((0, node_sea.isSea)()) {
2391
2614
  const assetKeys = (0, node_sea.getAssetKeys)();
2392
2615
  const registered = [];
@@ -2405,32 +2628,43 @@ var AssetManager = class {
2405
2628
  //#endregion
2406
2629
  //#region src/server/factories.ts
2407
2630
  /**
2408
- * Create a new SEA build orchestrator.
2631
+ * Creates a SEA build orchestrator over the given options and returns it as a
2632
+ * `SEAInterface`, the published contract a caller holds instead of the `SEA` class.
2409
2633
  *
2410
2634
  * @param options - SEA build options
2411
2635
  * @returns a new `SEAInterface`
2412
2636
  *
2413
- * @example
2637
+ * @example Build a single executable
2414
2638
  * ```ts
2415
- * const seal = createSEA({
2416
- * name: 'orkestrel',
2417
- * entry: { path: 'dist/bin/serve.cjs' },
2418
- * output: 'dist/sea',
2419
- * assets: { 'index.html.br': 'dist/client/index.html.br' },
2420
- * compression: { paths: ['dist/client'] },
2639
+ * import { createSEA, formatSize } from '@orkestrel/sea'
2640
+ *
2641
+ * const sea = createSEA({
2642
+ * name: 'myapp',
2643
+ * entry: { path: 'dist/server/serve.cjs' },
2644
+ * output: 'dist/sea',
2645
+ * assets: { 'model.gguf': 'models/model.gguf' },
2646
+ * compression: { paths: ['dist/app/browser'], mode: 'text' },
2647
+ * windows: { terminal: false },
2648
+ * timeout: 30_000,
2421
2649
  * })
2422
- * const result = await seal.execute()
2650
+ *
2651
+ * const result = await sea.execute()
2652
+ * process.stdout.write(
2653
+ * `${result.executable} ${formatSize(result.size)} ${String(result.duration)}ms\n`,
2654
+ * )
2423
2655
  * ```
2424
2656
  */
2425
2657
  function createSEA(options) {
2426
2658
  return new SEA(options);
2427
2659
  }
2428
2660
  /**
2429
- * Create a cross-platform binary resource injector.
2661
+ * Creates a resource injector bound to one target executable and returns it as an
2662
+ * `InjectorInterface`, with the executable's format already detected from its header.
2430
2663
  *
2431
- * Detects the executable format (PE, ELF, Mach-O) from the file header
2432
- * and injects the blob using pure TypeScript file I/O — no WASM, no
2433
- * external tools.
2664
+ * @remarks
2665
+ * The format detected at construction — PE, ELF, or Mach-O — selects the strategy
2666
+ * `inject` takes. Every write runs through pure TypeScript file I/O, so the injector
2667
+ * needs no WASM and no external tool.
2434
2668
  *
2435
2669
  * @param options - Injector options
2436
2670
  * @returns a new `InjectorInterface`
@@ -2450,7 +2684,9 @@ function createInjector(options) {
2450
2684
  return new Injector(options);
2451
2685
  }
2452
2686
  /**
2453
- * Create a single named asset.
2687
+ * Creates one named asset from a key and a content buffer and returns it as an
2688
+ * `AssetInterface`, with `compressed` inferred from the key where the input leaves
2689
+ * it unset.
2454
2690
  *
2455
2691
  * @param input - Asset key, content, and optional compression flag
2456
2692
  * @returns a new `AssetInterface`
@@ -2464,7 +2700,8 @@ function createAsset(input) {
2464
2700
  return new Asset(input);
2465
2701
  }
2466
2702
  /**
2467
- * Create an asset manager for SEA-embedded or disk-loaded assets.
2703
+ * Creates an asset collection and returns it as an `AssetManagerInterface`, already
2704
+ * carrying whatever assets the running SEA blob embeds.
2468
2705
  *
2469
2706
  * @param options - Asset manager options (root, event hooks)
2470
2707
  * @returns a new `AssetManagerInterface`
@@ -2482,14 +2719,16 @@ function createAssetManager(options) {
2482
2719
  exports.Asset = Asset;
2483
2720
  exports.AssetManager = AssetManager;
2484
2721
  exports.BROTLI_EXTENSION = BROTLI_EXTENSION;
2485
- exports.CLIENT_ASSET_KEY_BR = CLIENT_ASSET_KEY_BR;
2486
- exports.CLIENT_ASSET_KEY_RAW = CLIENT_ASSET_KEY_RAW;
2487
2722
  exports.DEFAULT_ENTRY_FORMAT = DEFAULT_ENTRY_FORMAT;
2488
2723
  exports.DEFAULT_SEA_COMPRESSION_QUALITY = DEFAULT_SEA_COMPRESSION_QUALITY;
2489
2724
  exports.ELF_CLASS_64 = ELF_CLASS_64;
2490
2725
  exports.ELF_DATA_LSB = ELF_DATA_LSB;
2491
2726
  exports.ELF_MAGIC = ELF_MAGIC;
2727
+ exports.ELF_PAGE_SIZE = ELF_PAGE_SIZE;
2728
+ exports.ELF_PF_R = ELF_PF_R;
2729
+ exports.ELF_PT_LOAD = ELF_PT_LOAD;
2492
2730
  exports.ELF_PT_NOTE = ELF_PT_NOTE;
2731
+ exports.ELF_PT_PHDR = ELF_PT_PHDR;
2493
2732
  exports.Injector = Injector;
2494
2733
  exports.MACHO_LC_SEGMENT_64 = MACHO_LC_SEGMENT_64;
2495
2734
  exports.MACHO_MAGIC_64 = MACHO_MAGIC_64;
@@ -2517,21 +2756,24 @@ exports.ShellError = ShellError;
2517
2756
  exports.WINDOWS_SUBSYSTEM_CONSOLE = WINDOWS_SUBSYSTEM_CONSOLE;
2518
2757
  exports.WINDOWS_SUBSYSTEM_GUI = WINDOWS_SUBSYSTEM_GUI;
2519
2758
  exports.alignELFNoteSize = alignELFNoteSize;
2759
+ exports.alignTo = alignTo;
2760
+ exports.appendFile = appendFile;
2761
+ exports.buildBlobConfig = buildBlobConfig;
2520
2762
  exports.buildELFNoteHeader = buildELFNoteHeader;
2763
+ exports.buildSignCommand = buildSignCommand;
2521
2764
  exports.compressDirectory = compressDirectory;
2522
2765
  exports.compressFile = compressFile;
2523
2766
  exports.computeSize = computeSize;
2524
2767
  exports.copyRange = copyRange;
2525
2768
  exports.createAsset = createAsset;
2526
2769
  exports.createAssetManager = createAssetManager;
2527
- exports.createBlobConfig = createBlobConfig;
2528
2770
  exports.createInjector = createInjector;
2529
2771
  exports.createSEA = createSEA;
2530
- exports.createSignCommand = createSignCommand;
2531
2772
  exports.ensureContained = ensureContained;
2532
2773
  exports.ensureExists = ensureExists;
2533
2774
  exports.ensureSafeKey = ensureSafeKey;
2534
2775
  exports.ensureSafeName = ensureSafeName;
2776
+ exports.executeShell = executeShell;
2535
2777
  exports.finalizeExecutable = finalizeExecutable;
2536
2778
  exports.formatSize = formatSize;
2537
2779
  exports.isCompressible = isCompressible;
@@ -2542,16 +2784,20 @@ exports.isPowerOfTwo = isPowerOfTwo;
2542
2784
  exports.isSEAError = isSEAError;
2543
2785
  exports.isShellError = isShellError;
2544
2786
  exports.openBrowser = openBrowser;
2545
- exports.parsePEOffset = parsePEOffset;
2546
2787
  exports.patchPESubsystem = patchPESubsystem;
2547
2788
  exports.patchSentinelFuse = patchSentinelFuse;
2548
- exports.platformConfig = platformConfig;
2789
+ exports.readPEOffset = readPEOffset;
2549
2790
  exports.readU16 = readU16;
2791
+ exports.readU32 = readU32;
2792
+ exports.readU64 = readU64;
2550
2793
  exports.redactCommand = redactCommand;
2551
- exports.runShell = runShell;
2794
+ exports.resolvePlatform = resolvePlatform;
2552
2795
  exports.stripPESignature = stripPESignature;
2796
+ exports.stripTrailingNulls = stripTrailingNulls;
2553
2797
  exports.syncDirectory = syncDirectory;
2554
2798
  exports.walkDirectory = walkDirectory;
2555
2799
  exports.writeU16 = writeU16;
2800
+ exports.writeU32 = writeU32;
2801
+ exports.writeU64 = writeU64;
2556
2802
 
2557
2803
  //# sourceMappingURL=index.cjs.map