@adatechnology/game-workers 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/coordinator.ts","../src/define.ts","../src/plan.ts","../src/protocol.ts","../src/host.ts","../src/in-thread.ts","../src/check.ts","../src/spawn.ts","../src/shared.ts","../src/sim-thread.ts","../src/index.ts"],"sourcesContent":["import { WORKER_INPUT_LOST, WORKER_LANES } from '@adatechnology/game-contracts'\nimport type {\n AnyWorkerKind,\n ResidentHandle,\n ResidentInstance,\n ResidentKind,\n TaskHandle,\n TaskKind,\n WorkerCoordinator,\n WorkerCoordinatorStats,\n WorkerKindSchedule,\n WorkerKindStats,\n WorkerLane,\n WorkerLateRule,\n WorkerResultSource,\n} from '@adatechnology/game-contracts'\nimport { checkSchedule } from './define'\nimport { planWorkers } from './plan'\nimport type { WorkerPlan, WorkerPlanOptions } from './plan'\nimport { isFromWorker } from './protocol'\nimport type { Spawn, ToWorker, WorkerLike } from './protocol'\n\n/** Jobs a worker holds at once unless `CoordinatorOptions.inFlightPerWorker` says otherwise (room measurement, spec 009 T7). */\nexport const IN_FLIGHT_PER_WORKER = 16\n\nexport interface CoordinatorOptions extends WorkerPlanOptions {\n /** Makes one worker (`browserSpawn`, `sourceSpawn`, `nodeSpawn`, `inThreadSpawn`). Without it every job runs on the main thread. */\n readonly spawn?: Spawn\n /** The game's overrides of a kind's schedule, by kind id. */\n readonly kinds?: Readonly<Record<string, Partial<WorkerKindSchedule>>>\n /**\n * Jobs a worker holds at once (default `IN_FLIGHT_PER_WORKER`, 16): the rest wait in the coordinator's queue, where a more urgent one can pass them. A job only leaves that\n * queue when the main thread reads a worker's answer, which on a busy frame is once per frame: a burst (a blast asks for dozens of ground tiles at once) with a small cap\n * needs several frames of round trips and misses its due frame. Measured in the room (crater, 4 threads): 2 left 139 of 163 tiles late, 16 none.\n */\n readonly inFlightPerWorker?: number\n /** The machine's cores for the automatic count (default `navigator.hardwareConcurrency`). */\n readonly cores?: number\n /** Clock in milliseconds (default `performance.now`). */\n readonly now?: () => number\n}\n\n/** The promise of a job given up by `late: 'drop'` rejects with it. */\nexport class WorkerTaskDropped extends Error {\n constructor(kind: string) {\n super(`worker job of ${kind} dropped: no worker took it`)\n this.name = 'WorkerTaskDropped'\n }\n}\n\n/** The promise of a cancelled job rejects with it. */\nexport class WorkerTaskCancelled extends Error {\n constructor(kind: string) {\n super(`worker job of ${kind} cancelled`)\n this.name = 'WorkerTaskCancelled'\n }\n}\n\n/**\n * The promise of an awaited job whose input was transferred (`transferAwaitedInput`) rejects with it when its worker died holding it: the input went with the worker, so the\n * coordinator cannot run it here; the caller makes it from its own copy (`isWorkerInputLost`). A worker that answers with an error rejects with that error instead.\n */\nexport class WorkerTaskInputLost extends Error {\n constructor(kind: string) {\n super(`worker job of ${kind}: its worker died holding its transferred input`)\n this.name = WORKER_INPUT_LOST\n }\n}\n\ntype JobState = 'queued' | 'running' | 'done' | 'settled' | 'cancelled'\n\ntype KindCounters = { -readonly [K in keyof WorkerKindStats]: WorkerKindStats[K] }\n\ninterface Resident {\n readonly rid: number\n readonly kind: ResidentKind<unknown, unknown, unknown>\n readonly schedule: WorkerKindSchedule\n readonly init: unknown\n slot: Slot | null\n local: ResidentInstance<unknown, unknown> | null\n disposed: boolean\n}\n\ninterface Job {\n readonly id: number\n readonly seq: number\n readonly kindId: string\n readonly counters: KindCounters\n readonly lane: WorkerLane\n readonly priority: number\n readonly late: WorkerLateRule\n readonly dueFrame: number\n readonly message: ToWorker\n readonly transfer: readonly ArrayBuffer[]\n /** A `sync` job whose input is transferred (`transferAwaitedInput`): once sent, it cannot run here nor be sent again. */\n readonly moved: boolean\n readonly runHere: () => unknown\n readonly resident: Resident | null\n readonly queuedAt: number\n state: JobState\n /** Workers that died holding it: a job that keeps killing its worker runs here (or fails) instead of killing the next one. */\n crashes: number\n output: unknown\n error: Error | null\n source: WorkerResultSource | null\n slot: Slot | null\n readonly settle: { resolve: (value: unknown) => void; reject: (error: Error) => void }\n readonly promise: Promise<unknown>\n}\n\ninterface Slot {\n readonly index: number\n readonly home: WorkerLane\n readonly serves: readonly WorkerLane[]\n worker: WorkerLike\n readonly running: Map<number, Job>\n /** Steps of the residents pinned here, in order. */\n readonly own: Job[]\n readonly residents: Set<Resident>\n readonly hello: Map<number, (kinds: readonly string[]) => void>\n alive: boolean\n}\n\nconst MAX_CRASHES = 2\nconst MAX_RESPAWNS = 5\n\nconst defaultNow = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now())\n\n/** Higher priority first, then the nearest due frame, then the order of submission. */\nconst before = (a: Job, b: Job): boolean => a.priority > b.priority || (a.priority === b.priority && (a.dueFrame < b.dueFrame || (a.dueFrame === b.dueFrame && a.seq < b.seq)))\n\nconst insertSorted = (queue: Job[], job: Job): void => {\n let i = queue.length\n while (i > 0 && before(job, queue[i - 1]!)) i--\n queue.splice(i, 0, job)\n}\n\n/**\n * The coordinator of every worker of a game (see the `game-workers` README). `sim` jobs are applied in a fixed frame: `collect(dueFrame)`\n * gives the worker's answer when it is back and runs the same kernel here when it is not, so the result never depends on timing. The main\n * thread never waits for a worker.\n */\nexport function createWorkerCoordinator(options: CoordinatorOptions = {}): WorkerCoordinator & { readonly plan: WorkerPlan } {\n const now = options.now ?? defaultNow\n const perWorker = Math.max(1, Math.floor(options.inFlightPerWorker ?? IN_FLIGHT_PER_WORKER))\n const overrides = options.kinds ?? {}\n const plan: WorkerPlan = options.spawn ? planWorkers(options, options.cores) : { total: 0, lanes: { sim: 0, build: 0, background: 0 }, homes: [], serves: [] }\n const queues: Record<WorkerLane, Job[]> = { sim: [], build: [], background: [] }\n const mainQueue: Job[] = []\n const counters = new Map<string, KindCounters>()\n const residents = new Set<Resident>()\n const slots: Slot[] = []\n let frame = 0\n let nextId = 1\n let nextRid = 1\n let respawned = 0\n const deathsAt = new Map<number, number>()\n let disposed = false\n let mainTimer: ReturnType<typeof setTimeout> | null = null\n\n const countersOf = (kind: AnyWorkerKind, lane: WorkerLane): KindCounters => {\n let c = counters.get(kind.id)\n if (!c) counters.set(kind.id, (c = { id: kind.id, lane, submitted: 0, answered: 0, onTime: 0, fallback: 0, dropped: 0, cancelled: 0, failed: 0, workerMs: 0, mainMs: 0, queueMs: 0 }))\n return c\n }\n\n const scheduleOf = (kind: AnyWorkerKind): WorkerKindSchedule => {\n const own = overrides[kind.id]\n if (!own) return kind\n const merged: WorkerKindSchedule = { lane: own.lane ?? kind.lane, priority: own.priority ?? kind.priority, latencyFrames: own.latencyFrames ?? kind.latencyFrames, late: own.late ?? kind.late }\n checkSchedule(kind.id, merged)\n return merged\n }\n\n // ── workers ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n const makeSlot = (index: number, home: WorkerLane, serves: readonly WorkerLane[]): Slot | null => {\n let worker: WorkerLike\n try {\n worker = (options.spawn as Spawn)()\n } catch {\n return null\n }\n const slot: Slot = { index, home, serves, worker, running: new Map(), own: [], residents: new Set(), hello: new Map(), alive: true }\n worker.onmessage = (event) => onReply(slot, event.data)\n worker.onerror = () => onCrash(slot)\n return slot\n }\n\n for (let i = 0; i < plan.serves.length; i++) {\n const slot = makeSlot(i, plan.homes[i]!, plan.serves[i]!)\n if (slot) slots.push(slot)\n }\n const served = (lane: WorkerLane): boolean => slots.some((slot) => slot.serves.includes(lane))\n const homeOf = (lane: WorkerLane): Slot | null => {\n let best: Slot | null = null\n for (const slot of slots) {\n if (!slot.alive || !slot.serves.includes(lane)) continue\n const own = slot.home === lane ? 0 : 1\n const bestOwn = best && best.home === lane ? 0 : 1\n if (!best || own < bestOwn || (own === bestOwn && slot.residents.size < best.residents.size)) best = slot\n }\n return best\n }\n\n const send = (slot: Slot, job: Job): void => {\n job.state = 'running'\n job.slot = slot\n job.counters.queueMs += now() - job.queuedAt\n slot.running.set(job.id, job)\n try {\n slot.worker.postMessage(job.message, job.transfer)\n } catch (error) {\n // a message that cannot be posted (an input that does not clone) is not the caller's synchronous throw: a sync job runs here (nothing was transferred), any other fails\n slot.running.delete(job.id)\n job.slot = null\n job.counters.failed++\n if (job.late === 'sync') runOnMain(job)\n else fail(job, error instanceof Error ? error : new Error(String(error)))\n }\n }\n\n const dispatch = (): void => {\n if (disposed) return\n for (const slot of slots) {\n while (slot.alive && slot.running.size < perWorker) {\n let job = slot.own.shift()\n if (!job) for (const lane of slot.serves) if ((job = queues[lane].shift())) break\n if (!job) break\n send(slot, job)\n }\n }\n }\n\n const onReply = (slot: Slot, data: unknown): void => {\n if (!isFromWorker(data)) return\n if (data.t === 'hello') {\n slot.hello.get(data.id)?.(data.kinds)\n slot.hello.delete(data.id)\n return\n }\n const job = slot.running.get(data.id)\n if (!job) return\n slot.running.delete(data.id)\n job.counters.workerMs += data.ms\n job.counters.answered++\n if (job.state === 'running') {\n if (data.ok) {\n job.state = 'done'\n job.output = data.output\n job.source = 'worker'\n // a job with no frame to wait for is on time as soon as it is back\n if (job.lane !== 'sim' && !job.resident) finish(job)\n else job.settle.resolve(job.output)\n } else {\n job.counters.failed++\n // a transferred input cannot run here: the worker's own error (the kernel threw, or the worker does not host the kind)\n if (job.late === 'sync' && !job.moved) runOnMain(job)\n else fail(job, new Error(data.error))\n }\n }\n dispatch()\n }\n\n const onCrash = (slot: Slot): void => {\n if (!slot.alive) return\n slot.alive = false\n slot.worker.terminate()\n const deaths = (deathsAt.get(slot.index) ?? 0) + 1\n deathsAt.set(slot.index, deaths)\n // a worker that keeps dying (a script that does not load) is not replaced forever: its lanes fall back to the others, or the main thread\n const replacement = disposed || deaths > MAX_RESPAWNS ? null : makeSlot(slot.index, slot.home, slot.serves)\n if (replacement) {\n respawned++\n slots[slots.indexOf(slot)] = replacement\n } else slots.splice(slots.indexOf(slot), 1)\n for (const resident of slot.residents) {\n resident.slot = replacement\n if (replacement) {\n replacement.residents.add(resident)\n replacement.worker.postMessage({ t: 'create', rid: resident.rid, kind: resident.kind.id, init: resident.init } satisfies ToWorker)\n }\n }\n // what the dead worker held goes back in line, steps of a resident first and in their order\n const waiting = [...slot.own]\n const back = [...slot.running.values()].filter((job) => job.state === 'running').sort((a, b) => a.seq - b.seq)\n slot.own.length = 0\n for (const job of back) job.crashes++\n for (const job of [...back, ...waiting]) {\n job.state = 'queued'\n job.slot = null\n if (job.crashes >= MAX_CRASHES || job.moved) {\n job.counters.failed++\n if (job.moved) fail(job, new WorkerTaskInputLost(job.kindId))\n else if (job.late === 'sync') runOnMain(job)\n else fail(job, new Error(`${job.kindId}: its worker died ${job.crashes} times running it`))\n } else if (job.resident) {\n if (replacement) replacement.own.push(job)\n // no worker for it any more: it is run here when it is collected\n } else if (served(job.lane)) insertSorted(queues[job.lane], job)\n else toMain(job)\n }\n dispatch()\n }\n\n // ── results ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n const finish = (job: Job): void => {\n if (job.source === 'worker') job.counters.onTime++\n job.state = 'settled'\n job.settle.resolve(job.output)\n }\n const fail = (job: Job, error: Error): void => {\n job.state = 'settled'\n job.error = error\n job.settle.reject(error)\n }\n const unqueue = (job: Job): void => {\n for (const queue of [queues[job.lane], mainQueue, job.resident?.slot?.own ?? []]) {\n const at = queue.indexOf(job)\n if (at >= 0) queue.splice(at, 1)\n }\n }\n /** The kernel here, now: a late worker, a crash, or no worker. A running job's answer is thrown away when it comes. */\n const runOnMain = (job: Job): void => {\n unqueue(job)\n const started = now()\n try {\n job.output = job.runHere()\n job.source = 'main'\n job.counters.fallback++\n job.counters.mainMs += now() - started\n finish(job)\n } catch (error) {\n job.counters.mainMs += now() - started\n fail(job, error instanceof Error ? error : new Error(String(error)))\n }\n }\n\n const drainMain = (): void => {\n mainTimer = null\n const job = mainQueue.shift()\n if (job && job.state === 'queued') runOnMain(job)\n if (mainQueue.length && !disposed) mainTimer = setTimeout(drainMain, 0)\n }\n /** A `build` or `background` job no worker can take: dropped, or run here one per macrotask, by priority. */\n const toMain = (job: Job): void => {\n if (job.late === 'drop') {\n job.counters.dropped++\n fail(job, new WorkerTaskDropped(job.kindId))\n return\n }\n insertSorted(mainQueue, job)\n if (!mainTimer) mainTimer = setTimeout(drainMain, 0)\n }\n\n // ── jobs ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n interface JobSpec {\n readonly kind: AnyWorkerKind\n readonly schedule: WorkerKindSchedule\n readonly dueFrame: number\n readonly message: (id: number) => ToWorker\n readonly transfer: readonly ArrayBuffer[]\n readonly moved?: boolean\n readonly runHere: () => unknown\n readonly resident: Resident | null\n }\n const makeJob = (spec: JobSpec): Job => {\n let settle: Job['settle'] = { resolve: () => undefined, reject: () => undefined }\n const promise = new Promise<unknown>((resolve, reject) => (settle = { resolve, reject }))\n // a job read only through `collect` must not leave an unhandled rejection behind\n promise.catch(() => undefined)\n const id = nextId++\n const job: Job = {\n id,\n seq: id,\n kindId: spec.kind.id,\n counters: countersOf(spec.kind, spec.schedule.lane),\n lane: spec.schedule.lane,\n priority: spec.schedule.priority,\n late: spec.schedule.late,\n dueFrame: spec.dueFrame,\n message: spec.message(id),\n transfer: spec.transfer,\n moved: spec.moved ?? false,\n runHere: spec.runHere,\n resident: spec.resident,\n queuedAt: now(),\n state: 'queued',\n crashes: 0,\n output: undefined,\n error: null,\n source: null,\n slot: null,\n settle,\n promise,\n }\n job.counters.submitted++\n return job\n }\n\n const handleOf = <Out>(job: Job): TaskHandle<Out> => ({\n dueFrame: job.dueFrame,\n promise: job.promise as Promise<Out>,\n get source() {\n return job.source\n },\n collect(at: number): Out {\n if (at < job.dueFrame) throw new Error(`${job.kindId}: collected in frame ${at}, before its due frame ${job.dueFrame}`)\n if (job.state === 'cancelled') throw new WorkerTaskCancelled(job.kindId)\n if (job.state === 'done') finish(job)\n else if (job.state === 'queued' || job.state === 'running') runOnMain(job)\n if (job.error) throw job.error\n return job.output as Out\n },\n cancel(): void {\n if (job.state !== 'queued' && job.state !== 'running') return\n unqueue(job)\n job.state = 'cancelled'\n job.counters.cancelled++\n job.settle.reject(new WorkerTaskCancelled(job.kindId))\n },\n })\n\n const enqueue = (job: Job): void => {\n if (disposed) throw new Error('worker coordinator: disposed')\n if (job.resident) {\n if (job.resident.slot) job.resident.slot.own.push(job)\n // a resident with no worker runs here, at its collect\n } else if (served(job.lane)) insertSorted(queues[job.lane], job)\n else if (job.lane !== 'sim') toMain(job)\n // a sim job no worker serves waits for its collect, where it runs here\n dispatch()\n }\n\n const latencyOf = (schedule: WorkerKindSchedule, at?: { readonly latencyFrames?: number }): number => Math.max(1, Math.floor(at?.latencyFrames ?? schedule.latencyFrames ?? 1))\n\n const taskJob = <In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }, awaited = false): Job => {\n const schedule = scheduleOf(kind as TaskKind<unknown, unknown>)\n const submitted = at?.frame ?? frame\n const moved = schedule.late === 'sync' && awaited && kind.transferAwaitedInput === true && kind.transferInput !== undefined\n const job = makeJob({\n kind: kind as TaskKind<unknown, unknown>,\n schedule,\n dueFrame: schedule.lane === 'sim' ? submitted + latencyOf(schedule, at) : Number.POSITIVE_INFINITY,\n message: (id) => ({ t: 'task', id, kind: kind.id, input }),\n transfer: schedule.late === 'sync' && !moved ? [] : [...(kind.transferInput?.(input) ?? [])],\n moved,\n runHere: () => kind.run(input),\n resident: null,\n })\n return job\n }\n\n const coordinator: WorkerCoordinator & { readonly plan: WorkerPlan } = {\n plan,\n submit<In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Out> {\n const job = taskJob(kind, input, at)\n enqueue(job)\n return handleOf<Out>(job)\n },\n\n run<In, Out>(kind: TaskKind<In, Out>, input: In, signal?: AbortSignal): Promise<Out> {\n const job = taskJob(kind, input, undefined, true)\n enqueue(job)\n // nobody collects an awaited job: a `sim` kind with no worker to serve it runs here, as the other lanes do (the simulation thread awaits its jobs)\n if (job.lane === 'sim' && job.state === 'queued' && !served('sim')) toMain(job)\n const handle = handleOf<Out>(job)\n if (signal) {\n if (signal.aborted) handle.cancel()\n else signal.addEventListener('abort', () => handle.cancel(), { once: true })\n }\n return handle.promise\n },\n\n resident<Init, Step, Result>(kind: ResidentKind<Init, Step, Result>, init: Init): ResidentHandle<Step, Result> {\n const any = kind as unknown as ResidentKind<unknown, unknown, unknown>\n const schedule = scheduleOf(any)\n const resident: Resident = { rid: nextRid++, kind: any, schedule, init, slot: homeOf(schedule.lane), local: null, disposed: false }\n residents.add(resident)\n resident.slot?.residents.add(resident)\n resident.slot?.worker.postMessage({ t: 'create', rid: resident.rid, kind: kind.id, init } satisfies ToWorker)\n const local = (): ResidentInstance<unknown, unknown> => (resident.local ??= any.create(init))\n return {\n id: kind.id,\n step(input: Step, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Result> {\n if (resident.disposed) throw new Error(`${kind.id}: resident disposed`)\n const submitted = at?.frame ?? frame\n const job = makeJob({\n kind: any,\n schedule,\n dueFrame: submitted + latencyOf(schedule, at),\n message: (id) => ({ t: 'step', id, rid: resident.rid, input }),\n transfer: schedule.late === 'sync' ? [] : [...(kind.transferInput?.(input) ?? [])],\n runHere: () => local().step(input),\n resident,\n })\n enqueue(job)\n return handleOf<Result>(job)\n },\n dispose(): void {\n if (resident.disposed) return\n resident.disposed = true\n residents.delete(resident)\n resident.slot?.residents.delete(resident)\n if (resident.slot?.alive) resident.slot.worker.postMessage({ t: 'dispose', rid: resident.rid } satisfies ToWorker)\n resident.local?.dispose?.()\n },\n }\n },\n\n tick(at: number): void {\n frame = at\n dispatch()\n },\n\n async warm(kinds: readonly AnyWorkerKind[]): Promise<void> {\n for (const kind of kinds) scheduleOf(kind)\n await Promise.all(\n slots.map(async (slot) => {\n const id = nextId++\n const known = await new Promise<readonly string[]>((resolve) => {\n slot.hello.set(id, resolve)\n slot.worker.postMessage({ t: 'hello', id } satisfies ToWorker)\n })\n const missing = kinds.filter((kind) => !known.includes(kind.id)).map((kind) => kind.id)\n if (missing.length) throw new Error(`worker ${slot.index} does not know ${missing.join(', ')}: add them to its installWorkerHost`)\n }),\n )\n // each worker runs each warm-up once, straight to it (the queue would give them all to the first free worker)\n const warmups: Promise<unknown>[] = []\n for (const kind of kinds) {\n if (kind.kind !== 'task' || kind.warmup === undefined) continue\n for (const slot of slots) {\n const job = makeJob({ kind, schedule: scheduleOf(kind), dueFrame: Number.NEGATIVE_INFINITY, message: (id) => ({ t: 'task', id, kind: kind.id, input: kind.warmup }), transfer: [], runHere: () => kind.run(kind.warmup), resident: null })\n job.counters.submitted--\n send(slot, job)\n warmups.push(job.promise.catch(() => undefined))\n }\n }\n await Promise.all(warmups)\n },\n\n scheduleOf,\n\n stats(): WorkerCoordinatorStats {\n let running = 0\n for (const slot of slots) running += slot.running.size\n const lanes = { sim: 0, build: 0, background: 0 }\n for (const slot of slots) lanes[slot.home]++\n return {\n workers: slots.length,\n lanes,\n queued: WORKER_LANES.reduce((n, lane) => n + queues[lane].length, 0) + mainQueue.length + slots.reduce((n, slot) => n + slot.own.length, 0),\n running,\n respawned,\n kinds: [...counters.values()].map((c) => ({ ...c })),\n }\n },\n\n dispose(): void {\n if (disposed) return\n disposed = true\n if (mainTimer) clearTimeout(mainTimer)\n const pending = [...WORKER_LANES.flatMap((lane) => queues[lane]), ...mainQueue, ...slots.flatMap((slot) => [...slot.own, ...slot.running.values()])]\n for (const job of pending) if (job.state === 'queued' || job.state === 'running') fail(job, new Error('worker coordinator: disposed'))\n for (const slot of slots) {\n slot.alive = false\n slot.worker.terminate()\n }\n for (const resident of residents) resident.local?.dispose?.()\n residents.clear()\n slots.length = 0\n },\n }\n return coordinator\n}\n","import { WORKER_KIND_DEFAULTS, WORKER_LANES, WORKER_LATE_RULES } from '@adatechnology/game-contracts'\nimport type { ResidentKind, TaskKind, WorkerKindSchedule } from '@adatechnology/game-contracts'\n\nconst ID = /^[a-z0-9-]+(\\.[a-z0-9-]+)+$/\n\n/** Checks a schedule: a known lane and rule, `sync` on the `sim` lane (its result is read in a fixed frame), a whole latency >= 1. */\nexport function checkSchedule(id: string, schedule: WorkerKindSchedule): void {\n if (!WORKER_LANES.includes(schedule.lane)) throw new Error(`worker kind ${id}: unknown lane \"${schedule.lane}\"`)\n if (!WORKER_LATE_RULES.includes(schedule.late)) throw new Error(`worker kind ${id}: unknown late rule \"${schedule.late}\"`)\n if (schedule.lane === 'sim' && schedule.late !== 'sync') throw new Error(`worker kind ${id}: the sim lane needs late \"sync\" (its result is applied in a fixed frame)`)\n if (!Number.isFinite(schedule.priority)) throw new Error(`worker kind ${id}: priority must be a number`)\n const latency = schedule.latencyFrames ?? 1\n if (!Number.isInteger(latency) || latency < 1) throw new Error(`worker kind ${id}: latencyFrames must be a whole number >= 1`)\n}\n\nconst checkId = (id: string): void => {\n if (!ID.test(id)) throw new Error(`worker kind \"${id}\": the id is \"package.thing\" in lowercase (destruction.ground-tiles)`)\n}\n\n/** The schedule a kit kind declares by default, by id (`WORKER_KIND_DEFAULTS`); `undefined` for a game's own kind. */\nexport const kitScheduleOf = (id: string): WorkerKindSchedule | undefined => (WORKER_KIND_DEFAULTS as Readonly<Record<string, WorkerKindSchedule>>)[id]\n\n/**\n * A task kind, checked: the id, the lane and the late rule. The kit's kinds take their schedule from `WORKER_KIND_DEFAULTS`.\n *\n * ```ts\n * export const pathfinding = defineTaskKind<PathInput, PathOutput>({ id: 'mygame.pathfinding', lane: 'sim', priority: 180, latencyFrames: 2, late: 'sync', run: aStar })\n * ```\n */\nexport function defineTaskKind<In, Out>(kind: Omit<TaskKind<In, Out>, 'kind'>): TaskKind<In, Out> {\n checkId(kind.id)\n checkSchedule(kind.id, kind)\n if (kind.transferAwaitedInput && !kind.transferInput) throw new Error(`worker kind ${kind.id}: transferAwaitedInput needs transferInput (the buffers to transfer)`)\n return Object.freeze({ ...kind, kind: 'task' as const })\n}\n\n/** A resident kind, checked as `defineTaskKind`. */\nexport function defineResidentKind<Init, Step, Result>(kind: Omit<ResidentKind<Init, Step, Result>, 'kind'>): ResidentKind<Init, Step, Result> {\n checkId(kind.id)\n checkSchedule(kind.id, kind)\n return Object.freeze({ ...kind, kind: 'resident' as const })\n}\n","import type { WorkerLane } from '@adatechnology/game-contracts'\n\nexport interface LaneOptions {\n /** Workers of this lane (default: the automatic split). */\n readonly workers?: number\n /** `build` only: its idle workers take `sim` jobs (default true). */\n readonly borrow?: boolean\n}\n\nexport interface WorkerPlanOptions {\n /** `'auto'` (default): `cores - 1 - reserveCores`, at most `maxWorkers`. A number: exactly that many. 0: everything on the main thread. */\n readonly workers?: 'auto' | number\n /** Ceiling of the automatic count (default 8). */\n readonly maxWorkers?: number\n /** Cores others use (Jolt's job threads, an audio worklet): the automatic count leaves them free. */\n readonly reserveCores?: number\n readonly lanes?: Partial<Readonly<Record<WorkerLane, LaneOptions>>>\n}\n\nexport interface WorkerPlan {\n readonly total: number\n readonly lanes: Readonly<Record<WorkerLane, number>>\n /** For each worker, by index, the lane it belongs to. */\n readonly homes: readonly WorkerLane[]\n /** For each worker, by index, the lanes it takes jobs from, in order (a `build` worker takes `sim` jobs first: they have a deadline). */\n readonly serves: readonly (readonly WorkerLane[])[]\n}\n\nexport const DEFAULT_MAX_WORKERS = 8\n\n/** The cores of this machine, or 1 where the runtime does not say. */\nexport function hardwareCores(): number {\n const n = (globalThis as { navigator?: { hardwareConcurrency?: number } }).navigator?.hardwareConcurrency\n return typeof n === 'number' && n > 0 ? n : 1\n}\n\nconst whole = (n: number): number => Math.max(0, Math.floor(n))\n\n/**\n * How many workers and which lanes each one serves. Automatic: `cores - 1 - reserveCores` workers (the main thread keeps a core), at most\n * `maxWorkers`; the `sim` lane takes a third rounded up (1 to 3), `background` gets its own worker from 6 on, `build` the rest. One worker\n * serves every lane. A `build` worker takes `sim` jobs first (they have a deadline), then its own, then `background` when that lane has\n * none of its own; a `background` worker never takes `sim` jobs, so the far world never delays a frame.\n */\nexport function planWorkers(options: WorkerPlanOptions = {}, cores = hardwareCores()): WorkerPlan {\n const max = whole(options.maxWorkers ?? DEFAULT_MAX_WORKERS)\n const asked = options.workers ?? 'auto'\n const total = asked === 'auto' ? Math.min(max, whole(cores - 1 - (options.reserveCores ?? 0))) : whole(asked)\n const fixed = options.lanes ?? {}\n let sim: number\n let background: number\n if (total <= 1) {\n sim = total\n background = 0\n } else {\n sim = Math.min(3, Math.max(1, Math.ceil(total / 3)))\n background = total >= 6 ? 1 : 0\n }\n if (fixed.sim?.workers !== undefined) sim = whole(fixed.sim.workers)\n if (fixed.background?.workers !== undefined) background = whole(fixed.background.workers)\n let build = fixed.build?.workers !== undefined ? whole(fixed.build.workers) : Math.max(0, total - sim - background)\n // lanes given by hand win over the total; the automatic split never goes over it\n if (fixed.sim?.workers === undefined && fixed.build?.workers === undefined && fixed.background?.workers === undefined) build = total - sim - background\n const count = sim + build + background\n const borrow = fixed.build?.borrow !== false\n const serves: WorkerLane[][] = []\n for (let i = 0; i < sim; i++) serves.push(['sim', ...(build === 0 ? (['build'] as const) : []), ...(build === 0 && background === 0 ? (['background'] as const) : [])])\n for (let i = 0; i < build; i++) serves.push([...(borrow ? (['sim'] as const) : []), 'build', ...(background === 0 ? (['background'] as const) : [])])\n for (let i = 0; i < background; i++) serves.push(['background'])\n const homes: WorkerLane[] = [...Array<WorkerLane>(sim).fill('sim'), ...Array<WorkerLane>(build).fill('build'), ...Array<WorkerLane>(background).fill('background')]\n return { total: count, lanes: { sim, build, background }, homes, serves }\n}\n","/** Messages between the coordinator and a worker host. One protocol for browser workers, `worker_threads` and the in-thread host. */\n\nexport type ToWorker =\n | { readonly t: 'hello'; readonly id: number }\n | { readonly t: 'task'; readonly id: number; readonly kind: string; readonly input: unknown }\n | { readonly t: 'create'; readonly rid: number; readonly kind: string; readonly init: unknown }\n | { readonly t: 'step'; readonly id: number; readonly rid: number; readonly input: unknown }\n | { readonly t: 'dispose'; readonly rid: number }\n\nexport type FromWorker =\n | { readonly t: 'hello'; readonly id: number; readonly kinds: readonly string[] }\n | { readonly t: 'done'; readonly id: number; readonly ok: true; readonly output: unknown; readonly ms: number }\n | { readonly t: 'done'; readonly id: number; readonly ok: false; readonly error: string; readonly ms: number }\n\n/** Anything with `postMessage` / `onmessage` / `terminate`: a browser `Worker`, a `worker_threads` wrapper, the in-thread host. */\nexport interface WorkerLike {\n onmessage: ((event: { data: unknown }) => void) | null\n onerror: ((event: unknown) => void) | null\n postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void\n terminate(): void\n}\n\n/** The worker side: `self` in a browser worker, `parentPort` in Node (through `nodeWorkerScope`), or the in-thread host. */\nexport interface WorkerScopeLike {\n onmessage: ((event: { data: unknown }) => void) | null\n postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void\n}\n\n/** Makes one worker that runs `installWorkerHost` with the kinds the coordinator is asked for. */\nexport type Spawn = () => WorkerLike\n\nexport const isFromWorker = (data: unknown): data is FromWorker => typeof data === 'object' && data !== null && typeof (data as { t?: unknown }).t === 'string'\nexport const isToWorker = (data: unknown): data is ToWorker => typeof data === 'object' && data !== null && typeof (data as { t?: unknown }).t === 'string'\n","import type { AnyResidentKind, AnyWorkerKind, ResidentInstance } from '@adatechnology/game-contracts'\nimport { isToWorker } from './protocol'\nimport type { FromWorker, WorkerScopeLike } from './protocol'\n\nconst now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now())\n\n/**\n * The worker side of the coordinator: answers each job with the kind's own `run` (or the resident instance's `step`) and transfers the\n * output's buffers back. Call it in the file the worker loads, with every kind the game registers, the kit's and its own:\n *\n * ```ts\n * // game-worker.ts\n * import { installWorkerHost } from '@adatechnology/game-workers'\n * installWorkerHost(self, [...KIT_WORKER_KINDS, pathfinding])\n * ```\n */\nexport function installWorkerHost(scope: WorkerScopeLike, kinds: readonly AnyWorkerKind[]): void {\n const byId = new Map<string, AnyWorkerKind>()\n for (const kind of kinds) {\n if (byId.has(kind.id) && byId.get(kind.id) !== kind) throw new Error(`installWorkerHost: two kinds with the id ${kind.id}`)\n byId.set(kind.id, kind)\n }\n const residents = new Map<number, { kind: AnyResidentKind; instance: ResidentInstance<unknown, unknown> }>()\n const reply = (message: FromWorker, transfer: readonly ArrayBuffer[] = []): void => scope.postMessage(message, transfer)\n const fail = (id: number, error: unknown, started: number): void => reply({ t: 'done', id, ok: false, error: error instanceof Error ? error.message : String(error), ms: now() - started })\n\n scope.onmessage = (event) => {\n const message = event.data\n if (!isToWorker(message)) return\n switch (message.t) {\n case 'hello':\n reply({ t: 'hello', id: message.id, kinds: [...byId.keys()] })\n return\n case 'task': {\n const started = now()\n const kind = byId.get(message.kind)\n if (!kind || kind.kind !== 'task') return fail(message.id, new Error(`this worker has no task kind ${message.kind}`), started)\n try {\n const output = kind.run(message.input)\n reply({ t: 'done', id: message.id, ok: true, output, ms: now() - started }, kind.transferOutput?.(output) ?? [])\n } catch (error) {\n fail(message.id, error, started)\n }\n return\n }\n case 'create': {\n const kind = byId.get(message.kind)\n // an unknown kind answers at its first step, where there is a job id to fail\n if (kind?.kind === 'resident') residents.set(message.rid, { kind, instance: kind.create(message.init) })\n return\n }\n case 'step': {\n const started = now()\n const resident = residents.get(message.rid)\n if (!resident) return fail(message.id, new Error(`this worker has no resident ${message.rid}`), started)\n try {\n const output = resident.instance.step(message.input)\n reply({ t: 'done', id: message.id, ok: true, output, ms: now() - started }, resident.kind.transferOutput?.(output) ?? [])\n } catch (error) {\n fail(message.id, error, started)\n }\n return\n }\n case 'dispose':\n residents.get(message.rid)?.instance.dispose?.()\n residents.delete(message.rid)\n return\n }\n }\n}\n","import type { AnyWorkerKind } from '@adatechnology/game-contracts'\nimport { installWorkerHost } from './host'\nimport type { Spawn, WorkerLike, WorkerScopeLike } from './protocol'\n\nexport interface InThreadOptions {\n /** Milliseconds before each answer reaches the coordinator (default 0: the next macrotask), to play a slow worker in tests. */\n readonly delayMs?: number\n}\n\n/**\n * A worker that runs `installWorkerHost` in this thread and answers on a later macrotask, as a real one does: the same protocol, the same\n * copy of the input (`structuredClone`) and the same transfer of the output. For tests, and the reference of `checkTaskKind`.\n */\nexport function inThreadSpawn(kinds: readonly AnyWorkerKind[], options: InThreadOptions = {}): Spawn {\n return () => {\n let alive = true\n const worker: WorkerLike = {\n onmessage: null,\n onerror: null,\n postMessage(message, transfer = []) {\n const copy: unknown = structuredClone(message, { transfer: [...transfer] })\n setTimeout(() => alive && scope.onmessage?.({ data: copy }), 0)\n },\n terminate() {\n alive = false\n },\n }\n const scope: WorkerScopeLike = {\n onmessage: null,\n postMessage(message, transfer = []) {\n const copy: unknown = structuredClone(message, { transfer: [...transfer] })\n setTimeout(() => alive && worker.onmessage?.({ data: copy }), options.delayMs ?? 0)\n },\n }\n installWorkerHost(scope, kinds)\n return worker\n }\n}\n","import type { AnyWorkerKind, TaskKind } from '@adatechnology/game-contracts'\nimport { createWorkerCoordinator } from './coordinator'\nimport { inThreadSpawn } from './in-thread'\nimport type { Spawn } from './protocol'\n\nexport interface KindReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nconst bytesOf = (view: ArrayBufferView): Uint8Array => new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n\n/** Where two values differ, byte for byte in typed arrays (`-0`, `NaN` payloads included); `null` when they are the same. */\nexport function firstDifference(a: unknown, b: unknown, path = 'output'): string | null {\n if (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {\n if (!ArrayBuffer.isView(a) || !ArrayBuffer.isView(b) || a.constructor !== b.constructor) return `${path}: not the same kind of array`\n const x = bytesOf(a)\n const y = bytesOf(b)\n if (x.length !== y.length) return `${path}: ${x.length} bytes against ${y.length}`\n for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return `${path}: byte ${i} differs`\n return null\n }\n if (a instanceof ArrayBuffer || b instanceof ArrayBuffer) {\n if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) return `${path}: not both ArrayBuffers`\n return firstDifference(new Uint8Array(a), new Uint8Array(b), path)\n }\n if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return Object.is(a, b) ? null : `${path}: ${String(a)} against ${String(b)}`\n if (Array.isArray(a) !== Array.isArray(b)) return `${path}: an array against an object`\n const keys = new Set([...Object.keys(a), ...Object.keys(b)])\n for (const key of keys) {\n const difference = firstDifference((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], `${path}.${key}`)\n if (difference) return difference\n }\n return null\n}\n\n/**\n * The equivalence test every kind passes (CLAUDE.md §14): each sample run on the main thread, through the in-thread worker (the protocol,\n * the copy and the transfer) and through each `spawn` given (a real `worker_threads` worker in CI), and the outputs compared byte for byte.\n * `extraKinds`: the other kinds the given workers host.\n */\nexport async function checkTaskKind<In, Out>(kind: TaskKind<In, Out>, samples: readonly In[], spawns: readonly Spawn[] = [], extraKinds: readonly AnyWorkerKind[] = []): Promise<KindReport> {\n const problems: string[] = []\n const any = kind as TaskKind<unknown, unknown>\n const paths: { name: string; spawn: Spawn }[] = [{ name: 'in-thread worker', spawn: inThreadSpawn([any, ...extraKinds]) }, ...spawns.map((spawn, i) => ({ name: `worker ${i + 1}`, spawn }))]\n for (const path of paths) {\n const coordinator = createWorkerCoordinator({ spawn: path.spawn, workers: 1 })\n try {\n await coordinator.warm([any])\n for (let i = 0; i < samples.length; i++) {\n const reference = kind.run(structuredClone(samples[i]) as In)\n const handle = coordinator.submit(kind, structuredClone(samples[i]) as In, { frame: 0 })\n const out = await handle.promise\n if (handle.source !== 'worker') problems.push(`${kind.id} sample ${i}: ${path.name} did not answer (${handle.source ?? 'no result'})`)\n const difference = firstDifference(reference, out)\n if (difference) problems.push(`${kind.id} sample ${i}, ${path.name}: ${difference}`)\n // an awaited job of a kind that transfers its input goes another way: checked too\n if (kind.transferAwaitedInput) {\n const awaited = firstDifference(reference, await coordinator.run(kind, structuredClone(samples[i]) as In))\n if (awaited) problems.push(`${kind.id} sample ${i}, ${path.name}, awaited: ${awaited}`)\n }\n }\n } catch (error) {\n problems.push(`${kind.id}, ${path.name}: ${error instanceof Error ? error.message : String(error)}`)\n } finally {\n coordinator.dispose()\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","import type { Spawn, WorkerLike } from './protocol'\n\ninterface BrowserWorker {\n onmessage: ((event: { data: unknown }) => void) | null\n onerror: ((event: unknown) => void) | null\n postMessage(message: unknown, transfer: Transferable[]): void\n terminate(): void\n}\ntype WorkerConstructor = new (url: string | URL, options?: { type?: 'module' | 'classic'; name?: string }) => BrowserWorker\n\nconst workerConstructor = (): WorkerConstructor | null => (globalThis as { Worker?: WorkerConstructor }).Worker ?? null\n\n/** Whether this runtime has browser workers. */\nexport const canSpawnBrowserWorkers = (): boolean => workerConstructor() !== null\n\nconst wrap = (worker: BrowserWorker): WorkerLike => {\n const like: WorkerLike = {\n onmessage: null,\n onerror: null,\n postMessage: (message, transfer = []) => worker.postMessage(message, [...transfer]),\n terminate: () => worker.terminate(),\n }\n worker.onmessage = (event) => like.onmessage?.(event)\n worker.onerror = (event) => like.onerror?.(event)\n return like\n}\n\n/**\n * Module workers that load `url`, the file that calls `installWorkerHost` (a bundler resolves `new URL('./game-worker.js', import.meta.url)`).\n * Throws where there is no `Worker`; the coordinator then runs every job on the main thread.\n */\nexport function browserSpawn(url: string | URL, options: { readonly type?: 'module' | 'classic'; readonly name?: string } = {}): Spawn {\n return () => {\n const Ctor = workerConstructor()\n if (!Ctor) throw new Error('browserSpawn: no Worker in this runtime')\n return wrap(new Ctor(url, { type: options.type ?? 'module', ...(options.name ? { name: options.name } : {}) }))\n }\n}\n\n/**\n * Workers made from the worker's own source text, for a page that is one file (no worker file beside it to load): the build embeds the\n * bundle of the worker as a string and this makes a Blob URL of it once.\n */\nexport function sourceSpawn(source: string, options: { readonly type?: 'module' | 'classic'; readonly name?: string } = {}): Spawn {\n let url: string | null = null\n return () => {\n if (!url) {\n if (typeof Blob === 'undefined' || typeof URL.createObjectURL !== 'function') throw new Error('sourceSpawn: no Blob URLs in this runtime')\n url = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }))\n }\n return browserSpawn(url, options)()\n }\n}\n","/**\n * Memory the main thread and the simulation thread share, with no lock and no wait on the main thread (it may not wait in a browser or in\n * the Electron renderer): a triple buffer of snapshots (the simulation writes, the page reads the newest whole one) and a ring of commands\n * (the page writes input, the simulation drains it at the start of a step). One writer and one reader each.\n */\n\nconst HEADER_BYTES = 32\nconst SLOTS = 3\n// header Int32 words of the snapshot buffer\nconst PUBLISHED = 0 // slot + 1 of the newest whole snapshot, 0 before the first\nconst CLAIMED = 1 // slot + 1 the reader is reading, 0 none\nconst FRAME = 2 // frame of each slot (3 words)\n\nconst align8 = (n: number): number => Math.ceil(n / 8) * 8\n\n/** Whether this runtime shares memory between threads: `SharedArrayBuffer` and, in a page, cross-origin isolation (COOP/COEP; always in Electron). */\nexport function canShareMemory(): boolean {\n if (typeof SharedArrayBuffer === 'undefined' || typeof Atomics === 'undefined') return false\n const isolated = (globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated\n return isolated !== false\n}\n\n/** A buffer of three snapshots of `bytes` each. */\nexport function createSnapshotBuffer(bytes: number): SharedArrayBuffer {\n return new SharedArrayBuffer(HEADER_BYTES + SLOTS * align8(bytes))\n}\n\nconst slotBytes = (buffer: SharedArrayBuffer): number => (buffer.byteLength - HEADER_BYTES) / SLOTS\n\n/** One snapshot as the reader sees it: valid until its next `latest()`, which may hand the slot back to the writer. */\nexport interface Snapshot {\n readonly frame: number\n readonly buffer: SharedArrayBuffer\n readonly byteOffset: number\n readonly byteLength: number\n readonly bytes: Uint8Array\n}\n\n/** The writer's side (the simulation thread): `begin` a free slot, fill it, `commit` it with its frame. Never waits. */\nexport class SnapshotWriter {\n private readonly header: Int32Array\n private readonly views: Uint8Array[]\n private slot = -1\n constructor(readonly buffer: SharedArrayBuffer) {\n this.header = new Int32Array(buffer, 0, HEADER_BYTES / 4)\n const size = slotBytes(buffer)\n this.views = Array.from({ length: SLOTS }, (_, k) => new Uint8Array(buffer, HEADER_BYTES + k * size, size))\n }\n /** A slot neither published nor being read: there is always one of the three. */\n begin(): Uint8Array {\n const published = Atomics.load(this.header, PUBLISHED) - 1\n const claimed = Atomics.load(this.header, CLAIMED) - 1\n let slot = 0\n while (slot === published || slot === claimed) slot++\n this.slot = slot\n return this.views[slot]!\n }\n commit(frame: number): void {\n if (this.slot < 0) throw new Error('SnapshotWriter.commit: no begin')\n Atomics.store(this.header, FRAME + this.slot, frame)\n Atomics.store(this.header, PUBLISHED, this.slot + 1)\n this.slot = -1\n }\n}\n\n/** The reader's side (the page): the newest whole snapshot, or `null` before the first. Never waits; retries only when a commit lands mid-claim. */\nexport class SnapshotReader {\n private readonly header: Int32Array\n private readonly size: number\n private readonly views: Uint8Array[]\n constructor(readonly buffer: SharedArrayBuffer) {\n this.header = new Int32Array(buffer, 0, HEADER_BYTES / 4)\n this.size = slotBytes(buffer)\n this.views = Array.from({ length: SLOTS }, (_, k) => new Uint8Array(buffer, HEADER_BYTES + k * this.size, this.size))\n }\n latest(): Snapshot | null {\n for (;;) {\n const published = Atomics.load(this.header, PUBLISHED)\n if (published === 0) return null\n Atomics.store(this.header, CLAIMED, published)\n // the writer only skips the claimed slot from its next begin on: the claim holds when the slot is still the newest after it\n if (Atomics.load(this.header, PUBLISHED) !== published) continue\n const slot = published - 1\n return {\n frame: Atomics.load(this.header, FRAME + slot),\n buffer: this.buffer,\n byteOffset: HEADER_BYTES + slot * this.size,\n byteLength: this.size,\n bytes: this.views[slot]!,\n }\n }\n }\n /** Lets the writer take the slot of the last snapshot (the reader is done with it). */\n release(): void {\n Atomics.store(this.header, CLAIMED, 0)\n }\n}\n\nconst RING_HEADER_BYTES = 8 // Int32: written, read\n\n/** A ring of `capacity` commands of `width` numbers each. */\nexport function createCommandBuffer(width: number, capacity: number): SharedArrayBuffer {\n if (!Number.isInteger(width) || width < 1 || !Number.isInteger(capacity) || capacity < 1) throw new Error('createCommandBuffer: width and capacity are integers >= 1')\n const buffer = new SharedArrayBuffer(RING_HEADER_BYTES + 8 + width * capacity * 8)\n // the layout is read back from the buffer: width in the slot after the header\n new Float64Array(buffer, RING_HEADER_BYTES, 1)[0] = width\n return buffer\n}\n\n/** Both ends of the ring: the page `push`es, the simulation `drain`s; a full ring refuses the command (`false`) rather than waiting. */\nexport class CommandRing {\n private readonly header: Int32Array\n private readonly data: Float64Array\n readonly width: number\n readonly capacity: number\n constructor(readonly buffer: SharedArrayBuffer) {\n this.header = new Int32Array(buffer, 0, 2)\n this.width = new Float64Array(buffer, RING_HEADER_BYTES, 1)[0]!\n this.data = new Float64Array(buffer, RING_HEADER_BYTES + 8)\n this.capacity = this.data.length / this.width\n }\n push(command: ArrayLike<number>): boolean {\n if (command.length > this.width) throw new Error(`CommandRing.push: ${command.length} numbers, the ring holds ${this.width}`)\n const written = Atomics.load(this.header, 0)\n if (written - Atomics.load(this.header, 1) >= this.capacity) return false\n const at = (written % this.capacity) * this.width\n this.data.fill(0, at, at + this.width)\n for (let k = 0; k < command.length; k++) this.data[at + k] = command[k]!\n Atomics.store(this.header, 0, written + 1)\n return true\n }\n /** Every command pushed so far, oldest first, each a copy. */\n drain(): Float64Array[] {\n const written = Atomics.load(this.header, 0)\n const read = Atomics.load(this.header, 1)\n const out: Float64Array[] = []\n for (let k = read; k < written; k++) {\n const at = (k % this.capacity) * this.width\n out.push(this.data.slice(at, at + this.width))\n }\n Atomics.store(this.header, 1, written)\n return out\n }\n}\n","import { CommandRing, SnapshotReader, SnapshotWriter, canShareMemory, createCommandBuffer, createSnapshotBuffer } from './shared'\nimport type { Snapshot } from './shared'\nimport type { AnySimModule, SimInstance, SimModule } from '@adatechnology/game-contracts'\nimport type { Spawn, WorkerScopeLike } from './protocol'\n\n/**\n * The simulation thread (spec 009, T22): the whole fixed step of a game runs in one dedicated worker, which **may wait** (for the jobs it\n * hands to other workers, for its next step), as the main thread of a native engine's simulation does. The page only pushes input into a\n * command ring and draws the newest whole snapshot, so it never waits, in a browser or in the Electron renderer.\n *\n * The same module also runs on the calling thread (`runSimInline`): the snapshot bytes are the same after the same steps and commands, which\n * is what the equivalence test checks.\n */\n\nexport interface SimLoopOptions {\n /** Seconds of one fixed step (default 1/60). */\n readonly stepSeconds?: number\n /** Stop after this many steps (tests, a replay); default: run until `stop`. */\n readonly steps?: number\n /** Steps on the clock (default) or as fast as they compute (`false`: tests, a server). */\n readonly paced?: boolean\n /** Steps the loop catches up after a stall before it drops the time instead (default 4). */\n readonly maxCatchUp?: number\n}\n\nexport interface SimThreadOptions<Init> extends SimLoopOptions {\n readonly module: string\n readonly init: Init\n /** Bytes of one snapshot. */\n readonly snapshotBytes: number\n /** Numbers in one command (default 8) and commands the ring holds (default 256). */\n readonly commandWidth?: number\n readonly commandCapacity?: number\n}\n\nexport interface SimThreadStats {\n /** Steps done. */\n readonly steps: number\n readonly lastStepMs: number\n readonly meanStepMs: number\n readonly maxStepMs: number\n /** Stalls the loop gave up catching up on. */\n readonly dropped: number\n}\n\n/** The page's side of a running simulation thread. */\nexport interface SimThread {\n /** Resolves when the module is built and the first step is about to run; rejects when the thread could not build it. */\n readonly ready: Promise<void>\n /** Resolves with the steps done when the loop ends (`steps` reached or `stop`). */\n readonly done: Promise<number>\n /** The newest whole snapshot (never waits), `null` before the first. Valid until the next `latest`. */\n latest(): Snapshot | null\n /** Queues a command for the start of the next step; `false` when the ring is full. */\n send(command: ArrayLike<number>): boolean\n stats(): SimThreadStats\n /** Ends the loop after the step it is in. */\n stop(): void\n /** Stops and terminates the worker. */\n dispose(): void\n}\n\n// control buffer: Int32 words, then Float64 numbers from byte 32\nconst STOP = 0\nconst STEPS = 1\nconst WAKE = 2\nconst DROPPED = 3\nconst LAST_MS = 0\nconst SUM_MS = 1\nconst MAX_MS = 2\nconst CONTROL_BYTES = 64\n\ntype ToSim = {\n readonly t: 'sim-start'\n readonly module: string\n readonly init: unknown\n readonly snapshot: SharedArrayBuffer\n readonly commands: SharedArrayBuffer\n readonly control: SharedArrayBuffer\n readonly loop: SimLoopOptions\n}\ntype FromSim = { readonly t: 'sim-ready' } | { readonly t: 'sim-done'; readonly steps: number } | { readonly t: 'sim-error'; readonly error: string }\n\nconst now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now())\nconst message = (error: unknown): string => (error instanceof Error ? error.message : String(error))\nconst isThenable = (value: unknown): value is PromiseLike<void> => typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function'\n\ninterface LoopIo {\n readonly ring: CommandRing\n readonly writer: SnapshotWriter\n readonly control: SharedArrayBuffer\n /** A real sleep: `Atomics.wait` in a worker; never called with `paced: false`. */\n readonly sleep: (ms: number) => void\n /** Called before each step's drain (the inline runner pushes that frame's commands). */\n readonly beforeStep?: (frame: number) => void\n}\n\n/** The fixed-step loop, the same in the simulation thread and inline: drain commands, step (awaited), write the snapshot, sleep to the next step. */\nasync function simLoop(instance: SimInstance, options: SimLoopOptions, io: LoopIo): Promise<number> {\n const stepSeconds = options.stepSeconds ?? 1 / 60\n const stepMs = stepSeconds * 1000\n const paced = options.paced ?? true\n const maxCatchUp = options.maxCatchUp ?? 4\n const words = new Int32Array(io.control, 0, 8)\n const numbers = new Float64Array(io.control, 32, 4)\n let frame = 0\n let next = now()\n while (Atomics.load(words, STOP) === 0 && (options.steps === undefined || frame < options.steps)) {\n if (paced) {\n const wait = next - now()\n if (wait > 0.25) {\n io.sleep(wait)\n continue\n }\n if (-wait > maxCatchUp * stepMs) {\n next = now()\n Atomics.add(words, DROPPED, 1)\n }\n }\n io.beforeStep?.(frame)\n const commands = io.ring.drain()\n const started = now()\n const stepped = instance.step(frame, stepSeconds, commands)\n if (isThenable(stepped)) await stepped\n instance.write(io.writer.begin(), frame)\n io.writer.commit(frame)\n const ms = now() - started\n numbers[LAST_MS] = ms\n numbers[SUM_MS] = numbers[SUM_MS]! + ms\n if (ms > numbers[MAX_MS]!) numbers[MAX_MS] = ms\n frame++\n Atomics.store(words, STEPS, frame)\n next += stepMs\n }\n return frame\n}\n\nconst statsOf = (control: SharedArrayBuffer): SimThreadStats => {\n const words = new Int32Array(control, 0, 8)\n const numbers = new Float64Array(control, 32, 4)\n const steps = Atomics.load(words, STEPS)\n return { steps, lastStepMs: numbers[LAST_MS]!, meanStepMs: steps ? numbers[SUM_MS]! / steps : 0, maxStepMs: numbers[MAX_MS]!, dropped: Atomics.load(words, DROPPED) }\n}\n\nconst isToSim = (data: unknown): data is ToSim => typeof data === 'object' && data !== null && (data as { t?: unknown }).t === 'sim-start'\nconst isFromSim = (data: unknown): data is FromSim => typeof data === 'object' && data !== null && typeof (data as { t?: unknown }).t === 'string'\n\n/**\n * The simulation thread's side: call it in the file of the simulation worker with every module the game may start.\n *\n * ```ts\n * // sim-worker.ts\n * import { installSimThread } from '@adatechnology/game-workers'\n * installSimThread(self, [hordeSim])\n * ```\n */\nexport function installSimThread(scope: WorkerScopeLike, modules: readonly AnySimModule[]): void {\n const byId = new Map(modules.map((m) => [m.id, m]))\n scope.onmessage = (event) => {\n const start = event.data\n if (!isToSim(start)) return\n const reply = (m: FromSim): void => scope.postMessage(m)\n const module = byId.get(start.module)\n if (!module) {\n reply({ t: 'sim-error', error: `installSimThread: no module ${start.module} (this thread has ${[...byId.keys()].join(', ') || 'none'})` })\n return\n }\n const words = new Int32Array(start.control, 0, 8)\n const io: LoopIo = {\n ring: new CommandRing(start.commands),\n writer: new SnapshotWriter(start.snapshot),\n control: start.control,\n // a worker may wait: this is the native engine's sleep, woken early by `stop`\n sleep: (ms) => void Atomics.wait(words, WAKE, 0, ms),\n }\n void (async () => {\n let instance: SimInstance | null = null\n try {\n instance = await module.create(start.init)\n reply({ t: 'sim-ready' })\n reply({ t: 'sim-done', steps: await simLoop(instance, start.loop, io) })\n } catch (error) {\n reply({ t: 'sim-error', error: message(error) })\n } finally {\n instance?.dispose?.()\n }\n })()\n }\n}\n\n/** Whether a simulation thread can run here: shared memory (`canShareMemory`) and workers to spawn. */\nexport const canRunSimThread = (): boolean => canShareMemory()\n\n/** Starts `options.module` in a new worker from `spawn` (a worker that calls `installSimThread`). Throws where memory cannot be shared. */\nexport function startSimThread<Init>(spawn: Spawn, options: SimThreadOptions<Init>): SimThread {\n if (!canShareMemory()) throw new Error('startSimThread: no shared memory here (SharedArrayBuffer and cross-origin isolation: COOP/COEP, always on in Electron)')\n const snapshot = createSnapshotBuffer(options.snapshotBytes)\n const commands = createCommandBuffer(options.commandWidth ?? 8, options.commandCapacity ?? 256)\n const control = new SharedArrayBuffer(CONTROL_BYTES)\n const words = new Int32Array(control, 0, 8)\n const reader = new SnapshotReader(snapshot)\n const ring = new CommandRing(commands)\n const worker = spawn()\n let readyResolve!: () => void\n let readyReject!: (error: Error) => void\n let doneResolve!: (steps: number) => void\n let doneReject!: (error: Error) => void\n const ready = new Promise<void>((resolve, reject) => ((readyResolve = resolve), (readyReject = reject)))\n const done = new Promise<number>((resolve, reject) => ((doneResolve = resolve), (doneReject = reject)))\n // a caller that awaits only `ready` sees the failure there: `done`'s copy of it is not an unhandled rejection\n done.catch(() => {})\n const fail = (error: Error): void => {\n readyReject(error)\n doneReject(error)\n }\n worker.onmessage = (event) => {\n const data = event.data\n if (!isFromSim(data)) return\n if (data.t === 'sim-ready') readyResolve()\n else if (data.t === 'sim-done') doneResolve(data.steps)\n else fail(new Error(data.error))\n }\n worker.onerror = (event) => fail(event instanceof Error ? event : new Error(`simulation thread failed: ${message((event as { message?: unknown }).message ?? event)}`))\n const loop: SimLoopOptions = {\n ...(options.stepSeconds !== undefined ? { stepSeconds: options.stepSeconds } : {}),\n ...(options.steps !== undefined ? { steps: options.steps } : {}),\n ...(options.paced !== undefined ? { paced: options.paced } : {}),\n ...(options.maxCatchUp !== undefined ? { maxCatchUp: options.maxCatchUp } : {}),\n }\n const start: ToSim = { t: 'sim-start', module: options.module, init: options.init, snapshot, commands, control, loop }\n worker.postMessage(start)\n const stop = (): void => {\n Atomics.store(words, STOP, 1)\n Atomics.notify(words, WAKE)\n }\n return {\n ready,\n done,\n latest: () => reader.latest(),\n send: (command) => ring.push(command),\n stats: () => statsOf(control),\n stop,\n dispose: () => {\n stop()\n worker.terminate()\n },\n }\n}\n\n/**\n * The same module and loop on this thread, unpaced: the snapshot after `steps` steps, with `commands[frame]` pushed before that step. The\n * reference the simulation thread must match byte for byte, and the fallback where memory cannot be shared.\n */\nexport async function runSimInline<Init>(\n module: SimModule<Init>,\n init: Init,\n options: { readonly steps: number; readonly snapshotBytes: number; readonly stepSeconds?: number; readonly commands?: readonly (readonly ArrayLike<number>[])[]; readonly commandWidth?: number },\n): Promise<Uint8Array> {\n const snapshot = createSnapshotBuffer(options.snapshotBytes)\n const control = new SharedArrayBuffer(CONTROL_BYTES)\n const ring = new CommandRing(createCommandBuffer(options.commandWidth ?? 8, 4096))\n const instance = await module.create(init)\n try {\n await simLoop(instance, { steps: options.steps, paced: false, ...(options.stepSeconds !== undefined ? { stepSeconds: options.stepSeconds } : {}) }, {\n ring,\n writer: new SnapshotWriter(snapshot),\n control,\n sleep: () => {},\n beforeStep: (frame) => {\n for (const command of options.commands?.[frame] ?? []) if (!ring.push(command)) throw new Error('runSimInline: more commands in one frame than the ring holds')\n },\n })\n } finally {\n instance.dispose?.()\n }\n return new SnapshotReader(snapshot).latest()!.bytes.slice()\n}\n","export { checkTaskKind, firstDifference } from './check'\nexport type { KindReport } from './check'\nexport { createWorkerCoordinator, IN_FLIGHT_PER_WORKER, WorkerTaskCancelled, WorkerTaskDropped, WorkerTaskInputLost } from './coordinator'\nexport type { CoordinatorOptions } from './coordinator'\nexport { checkSchedule, defineResidentKind, defineTaskKind, kitScheduleOf } from './define'\nexport { installWorkerHost } from './host'\nexport { inThreadSpawn } from './in-thread'\nexport type { InThreadOptions } from './in-thread'\nexport { DEFAULT_MAX_WORKERS, hardwareCores, planWorkers } from './plan'\nexport type { LaneOptions, WorkerPlan, WorkerPlanOptions } from './plan'\nexport type { FromWorker, Spawn, ToWorker, WorkerLike, WorkerScopeLike } from './protocol'\nexport { browserSpawn, canSpawnBrowserWorkers, sourceSpawn } from './spawn'\nexport { CommandRing, SnapshotReader, SnapshotWriter, canShareMemory, createCommandBuffer, createSnapshotBuffer } from './shared'\nexport type { Snapshot } from './shared'\nexport { canRunSimThread, installSimThread, runSimInline, startSimThread } from './sim-thread'\nexport type { SimLoopOptions, SimThread, SimThreadOptions, SimThreadStats } from './sim-thread'\nexport type {\n AnyResidentKind,\n AnySimModule,\n AnyTaskKind,\n AnyWorkerKind,\n ResidentHandle,\n ResidentInstance,\n ResidentKind,\n SimInstance,\n SimModule,\n TaskHandle,\n TaskKind,\n WorkerCoordinator,\n WorkerCoordinatorStats,\n WorkerKindSchedule,\n WorkerKindStats,\n WorkerLane,\n WorkerLateRule,\n WorkerResultSource,\n} from '@adatechnology/game-contracts'\nexport { WORKER_KIND_DEFAULTS, WORKER_KIND_ID, WORKER_LANES } from '@adatechnology/game-contracts'\n"],"mappings":";;;;;AAAA,SAAS,mBAAmB,gBAAAA,qBAAoB;;;ACAhD,SAAS,sBAAsB,cAAc,yBAAyB;AAGtE,IAAM,KAAK;AAGJ,SAAS,cAAc,IAAY,UAAoC;AAC5E,MAAI,CAAC,aAAa,SAAS,SAAS,IAAI,EAAG,OAAM,IAAI,MAAM,eAAe,EAAE,mBAAmB,SAAS,IAAI,GAAG;AAC/G,MAAI,CAAC,kBAAkB,SAAS,SAAS,IAAI,EAAG,OAAM,IAAI,MAAM,eAAe,EAAE,wBAAwB,SAAS,IAAI,GAAG;AACzH,MAAI,SAAS,SAAS,SAAS,SAAS,SAAS,OAAQ,OAAM,IAAI,MAAM,eAAe,EAAE,2EAA2E;AACrK,MAAI,CAAC,OAAO,SAAS,SAAS,QAAQ,EAAG,OAAM,IAAI,MAAM,eAAe,EAAE,6BAA6B;AACvG,QAAM,UAAU,SAAS,iBAAiB;AAC1C,MAAI,CAAC,OAAO,UAAU,OAAO,KAAK,UAAU,EAAG,OAAM,IAAI,MAAM,eAAe,EAAE,6CAA6C;AAC/H;AAEA,IAAM,UAAU,CAAC,OAAqB;AACpC,MAAI,CAAC,GAAG,KAAK,EAAE,EAAG,OAAM,IAAI,MAAM,gBAAgB,EAAE,sEAAsE;AAC5H;AAGO,IAAM,gBAAgB,CAAC,OAAgD,qBAAsE,EAAE;AAS/I,SAAS,eAAwB,MAA0D;AAChG,UAAQ,KAAK,EAAE;AAC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;AAAA,IACA,SAAS,MAAM;AACb,WAAK;AACL,aAAO,UAAU;AAAA,IACnB;AAAA,EACF;AACF;AAMA,eAAsB,aACpB,QACA,MACA,SACqB;AACrB,QAAM,WAAW,qBAAqB,QAAQ,aAAa;AAC3D,QAAM,UAAU,IAAI,kBAAkB,aAAa;AACnD,QAAM,OAAO,IAAI,YAAY,oBAAoB,QAAQ,gBAAgB,GAAG,IAAI,CAAC;AACjF,QAAM,WAAW,MAAM,OAAO,OAAO,IAAI;AACzC,MAAI;AACF,UAAM,QAAQ,UAAU,EAAE,OAAO,QAAQ,OAAO,OAAO,OAAO,GAAI,QAAQ,gBAAgB,SAAY,EAAE,aAAa,QAAQ,YAAY,IAAI,CAAC,EAAG,GAAG;AAAA,MAClJ;AAAA,MACA,QAAQ,IAAI,eAAe,QAAQ;AAAA,MACnC;AAAA,MACA,OAAO,MAAM;AAAA,MAAC;AAAA,MACd,YAAY,CAAC,UAAU;AACrB,mBAAW,WAAW,QAAQ,WAAW,KAAK,KAAK,CAAC,EAAG,KAAI,CAAC,KAAK,KAAK,OAAO,EAAG,OAAM,IAAI,MAAM,8DAA8D;AAAA,MAChK;AAAA,IACF,CAAC;AAAA,EACH,UAAE;AACA,aAAS,UAAU;AAAA,EACrB;AACA,SAAO,IAAI,eAAe,QAAQ,EAAE,OAAO,EAAG,MAAM,MAAM;AAC5D;;;AChPA,SAAS,wBAAAC,uBAAsB,gBAAgB,gBAAAC,qBAAoB;","names":["WORKER_LANES","now","WORKER_LANES","message","message","message","now","WORKER_KIND_DEFAULTS","WORKER_LANES"]}
package/dist/node.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /** Anything with `postMessage` / `onmessage` / `terminate`: a browser `Worker`, a `worker_threads` wrapper, the in-thread host. */
2
+ interface WorkerLike {
3
+ onmessage: ((event: {
4
+ data: unknown;
5
+ }) => void) | null;
6
+ onerror: ((event: unknown) => void) | null;
7
+ postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void;
8
+ terminate(): void;
9
+ }
10
+ /** The worker side: `self` in a browser worker, `parentPort` in Node (through `nodeWorkerScope`), or the in-thread host. */
11
+ interface WorkerScopeLike {
12
+ onmessage: ((event: {
13
+ data: unknown;
14
+ }) => void) | null;
15
+ postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void;
16
+ }
17
+ /** Makes one worker that runs `installWorkerHost` with the kinds the coordinator is asked for. */
18
+ type Spawn = () => WorkerLike;
19
+
20
+ /**
21
+ * Node `worker_threads` workers that load `url` (an ES module that calls `installWorkerHost(nodeWorkerScope(), kinds)`), with the same
22
+ * protocol as a browser worker. Node only: import it from `@adatechnology/game-workers/node`.
23
+ */
24
+ declare function nodeSpawn(url: string | URL, options?: {
25
+ readonly execArgv?: readonly string[];
26
+ }): Spawn;
27
+ /** The worker side in Node: `parentPort` as the scope `installWorkerHost` takes. */
28
+ declare function nodeWorkerScope(): WorkerScopeLike;
29
+
30
+ export { nodeSpawn, nodeWorkerScope };
package/dist/node.js ADDED
@@ -0,0 +1,33 @@
1
+ // src/node.ts
2
+ import { parentPort, Worker } from "worker_threads";
3
+ function nodeSpawn(url, options = {}) {
4
+ return () => {
5
+ const worker = new Worker(url, options.execArgv ? { execArgv: [...options.execArgv] } : {});
6
+ const like = {
7
+ onmessage: null,
8
+ onerror: null,
9
+ postMessage: (message, transfer = []) => worker.postMessage(message, [...transfer]),
10
+ terminate: () => void worker.terminate()
11
+ };
12
+ worker.on("message", (data) => like.onmessage?.({ data }));
13
+ worker.on("error", (error) => like.onerror?.(error));
14
+ worker.on("exit", (code) => code !== 0 && like.onerror?.(new Error(`worker exited with ${code}`)));
15
+ worker.unref();
16
+ return like;
17
+ };
18
+ }
19
+ function nodeWorkerScope() {
20
+ const port = parentPort;
21
+ if (!port) throw new Error("nodeWorkerScope: not inside a worker_threads worker");
22
+ const scope = {
23
+ onmessage: null,
24
+ postMessage: (message, transfer = []) => port.postMessage(message, [...transfer])
25
+ };
26
+ port.on("message", (data) => scope.onmessage?.({ data }));
27
+ return scope;
28
+ }
29
+ export {
30
+ nodeSpawn,
31
+ nodeWorkerScope
32
+ };
33
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/node.ts"],"sourcesContent":["import { parentPort, Worker } from 'node:worker_threads'\nimport type { Spawn, WorkerLike, WorkerScopeLike } from './protocol'\n\n/**\n * Node `worker_threads` workers that load `url` (an ES module that calls `installWorkerHost(nodeWorkerScope(), kinds)`), with the same\n * protocol as a browser worker. Node only: import it from `@adatechnology/game-workers/node`.\n */\nexport function nodeSpawn(url: string | URL, options: { readonly execArgv?: readonly string[] } = {}): Spawn {\n return () => {\n const worker = new Worker(url, options.execArgv ? { execArgv: [...options.execArgv] } : {})\n const like: WorkerLike = {\n onmessage: null,\n onerror: null,\n postMessage: (message, transfer = []) => worker.postMessage(message, [...transfer]),\n terminate: () => void worker.terminate(),\n }\n worker.on('message', (data: unknown) => like.onmessage?.({ data }))\n worker.on('error', (error: unknown) => like.onerror?.(error))\n // a worker that exits on its own took its jobs with it\n worker.on('exit', (code: number) => code !== 0 && like.onerror?.(new Error(`worker exited with ${code}`)))\n worker.unref()\n return like\n }\n}\n\n/** The worker side in Node: `parentPort` as the scope `installWorkerHost` takes. */\nexport function nodeWorkerScope(): WorkerScopeLike {\n const port = parentPort\n if (!port) throw new Error('nodeWorkerScope: not inside a worker_threads worker')\n const scope: WorkerScopeLike = {\n onmessage: null,\n postMessage: (message, transfer = []) => port.postMessage(message, [...transfer]),\n }\n port.on('message', (data: unknown) => scope.onmessage?.({ data }))\n return scope\n}\n"],"mappings":";AAAA,SAAS,YAAY,cAAc;AAO5B,SAAS,UAAU,KAAmB,UAAqD,CAAC,GAAU;AAC3G,SAAO,MAAM;AACX,UAAM,SAAS,IAAI,OAAO,KAAK,QAAQ,WAAW,EAAE,UAAU,CAAC,GAAG,QAAQ,QAAQ,EAAE,IAAI,CAAC,CAAC;AAC1F,UAAM,OAAmB;AAAA,MACvB,WAAW;AAAA,MACX,SAAS;AAAA,MACT,aAAa,CAAC,SAAS,WAAW,CAAC,MAAM,OAAO,YAAY,SAAS,CAAC,GAAG,QAAQ,CAAC;AAAA,MAClF,WAAW,MAAM,KAAK,OAAO,UAAU;AAAA,IACzC;AACA,WAAO,GAAG,WAAW,CAAC,SAAkB,KAAK,YAAY,EAAE,KAAK,CAAC,CAAC;AAClE,WAAO,GAAG,SAAS,CAAC,UAAmB,KAAK,UAAU,KAAK,CAAC;AAE5D,WAAO,GAAG,QAAQ,CAAC,SAAiB,SAAS,KAAK,KAAK,UAAU,IAAI,MAAM,sBAAsB,IAAI,EAAE,CAAC,CAAC;AACzG,WAAO,MAAM;AACb,WAAO;AAAA,EACT;AACF;AAGO,SAAS,kBAAmC;AACjD,QAAM,OAAO;AACb,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,qDAAqD;AAChF,QAAM,QAAyB;AAAA,IAC7B,WAAW;AAAA,IACX,aAAa,CAAC,SAAS,WAAW,CAAC,MAAM,KAAK,YAAY,SAAS,CAAC,GAAG,QAAQ,CAAC;AAAA,EAClF;AACA,OAAK,GAAG,WAAW,CAAC,SAAkB,MAAM,YAAY,EAAE,KAAK,CAAC,CAAC;AACjE,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@adatechnology/game-workers",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "license": "MIT",
5
+ "description": "The coordinator of every worker of a game: how many workers (by cores or by hand), which lane each kind of job runs in, priority and deadline in frames, the same kernel on the main thread when a worker is late. Browser module workers, Node worker_threads, or none.",
6
+ "keywords": [
7
+ "game",
8
+ "web-worker",
9
+ "worker_threads",
10
+ "job-system",
11
+ "thread-pool",
12
+ "deterministic"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/Andersonfrfilho/adatechnology-game-kit.git",
17
+ "directory": "packages/game-workers"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "type": "module",
23
+ "main": "dist/index.js",
24
+ "module": "dist/index.js",
25
+ "types": "dist/index.d.ts",
26
+ "unpkg": "dist/index.global.js",
27
+ "jsdelivr": "dist/index.global.js",
28
+ "sideEffects": false,
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ },
34
+ "./node": {
35
+ "types": "./dist/node.d.ts",
36
+ "import": "./dist/node.js"
37
+ },
38
+ "./global": "./dist/index.global.js"
39
+ },
40
+ "files": [
41
+ "dist"
42
+ ],
43
+ "dependencies": {
44
+ "@adatechnology/game-contracts": "^0.37.0"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^22.10.7",
48
+ "tsup": "^8.5.1",
49
+ "typescript": "^5.7.3",
50
+ "vitest": "^3.2.4"
51
+ },
52
+ "scripts": {
53
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
54
+ "typecheck": "tsc -p tsconfig.json --noEmit",
55
+ "test": "vitest run"
56
+ }
6
57
  }