All files / player-terminal/src/node sea-worker.ts

81.81% Statements 9/11
100% Branches 6/6
66.66% Functions 2/3
81.81% Lines 9/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45              16x     16x   16x         35x 35x             11x 3x   8x 8x                              
import { getAsset, isSea } from 'node:sea';
import { Worker } from 'node:worker_threads';
 
/**
 * Marker field injected into `workerData` when a worker is spawned from the SEA bundle asset. The SEA entry
 * (`src/sea-main.ts`) reads it before the CLI entry runs to decide which worker module to execute.
 */
export const SEA_WORKER_ROLE_FIELD = '__beMusicSeaWorkerRole';
 
/** Asset name under which the SEA build embeds a copy of the bundle itself (see `scripts/build-sea.ts`). */
export const SEA_BUNDLE_ASSET_NAME = 'sea-entry.cjs';
 
export const SEA_WORKER_ROLES = ['node-gameplay-worker', 'node-ui-worker', 'bga-video-worker'] as const;
 
export type SEAWorkerRole = (typeof SEA_WORKER_ROLES)[number];
 
export function isSEARuntime(): boolean {
  try {
    return isSea();
  } catch {
    return false;
  }
}
 
export function resolveSEAWorkerRole(workerData: unknown): SEAWorkerRole | undefined {
  if (typeof workerData !== 'object' || workerData === null) {
    return undefined;
  }
  const role = (workerData as Record<string, unknown>)[SEA_WORKER_ROLE_FIELD];
  return (SEA_WORKER_ROLES as readonly unknown[]).includes(role) ? (role as SEAWorkerRole) : undefined;
}
 
/**
 * SEA binaries cannot load worker scripts from disk: the worker `.js` files are not shipped next to the
 * executable and the SEA-injected `require` only resolves builtins. Instead, spawn an eval worker that
 * re-runs the embedded bundle; the role marker makes `sea-main.ts` execute the matching worker module
 * instead of the CLI entry.
 */
export function createSEAWorker(role: SEAWorkerRole, workerData: object): Worker {
  return new Worker(getAsset(SEA_BUNDLE_ASSET_NAME, 'utf8'), {
    eval: true,
    workerData: { [SEA_WORKER_ROLE_FIELD]: role, ...workerData },
  });
}