@jxrstudios/jxr 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +6 -2
  2. package/bin/jxr.js +60 -0
  3. package/dist/deployer.d.ts +8 -12
  4. package/dist/deployer.d.ts.map +1 -1
  5. package/dist/deployer.js +69 -106
  6. package/dist/deployer.js.map +1 -1
  7. package/dist/enhanced-transpiler.d.ts +36 -0
  8. package/dist/enhanced-transpiler.d.ts.map +1 -0
  9. package/dist/enhanced-transpiler.js +272 -0
  10. package/dist/enhanced-transpiler.js.map +1 -0
  11. package/dist/entry-point-detection.d.ts +22 -0
  12. package/dist/entry-point-detection.d.ts.map +1 -0
  13. package/dist/entry-point-detection.js +415 -0
  14. package/dist/entry-point-detection.js.map +1 -0
  15. package/dist/index.d.ts +19 -12
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +2119 -16
  18. package/dist/index.js.map +1 -1
  19. package/dist/jxr-server-manager.d.ts +32 -0
  20. package/dist/jxr-server-manager.d.ts.map +1 -0
  21. package/dist/jxr-server-manager.js +353 -0
  22. package/dist/jxr-server-manager.js.map +1 -0
  23. package/dist/runtime.d.ts +9 -9
  24. package/dist/runtime.d.ts.map +1 -1
  25. package/dist/runtime.js +3 -3
  26. package/package.json +15 -4
  27. package/src/deployer.ts +231 -0
  28. package/src/enhanced-transpiler.ts +331 -0
  29. package/src/entry-point-detection.ts +470 -0
  30. package/src/index.ts +63 -0
  31. package/src/jxr-server-manager.ts +410 -0
  32. package/src/module-resolver.ts +520 -0
  33. package/src/moq-transport.ts +267 -0
  34. package/src/runtime.ts +188 -0
  35. package/src/web-crypto.ts +279 -0
  36. package/src/worker-pool.ts +321 -0
  37. package/zzz_react_template/App.tsx +160 -0
  38. package/zzz_react_template/index.css +16 -0
  39. package/zzz_react_template/index.html +12 -0
  40. package/zzz_react_template/main.tsx +10 -0
  41. package/zzz_react_template/package.json +25 -0
@@ -0,0 +1,279 @@
1
+ /**
2
+ * JXR.js — Web Crypto Engine
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * Design: LavaFlow OS — Thermal Precision + Edge Command
5
+ * Layer: Core Runtime / Security
6
+ *
7
+ * Architecture:
8
+ * Universal Web Crypto API wrapper providing:
9
+ * - Module integrity verification (SHA-256/SHA-384 hashing)
10
+ * - Signed module manifests (ECDSA P-256)
11
+ * - Encrypted module caching (AES-GCM 256)
12
+ * - Key derivation for per-project isolation (HKDF)
13
+ * - Random nonce generation for replay protection
14
+ *
15
+ * All operations use the native SubtleCrypto API — no dependencies,
16
+ * runs in any modern browser, Cloudflare Worker, or Deno runtime.
17
+ * ─────────────────────────────────────────────────────────────────────────────
18
+ */
19
+
20
+ const subtle = globalThis.crypto.subtle;
21
+
22
+ export interface ModuleHash {
23
+ algorithm: 'SHA-256' | 'SHA-384' | 'SHA-512';
24
+ digest: string; // hex-encoded
25
+ size: number;
26
+ timestamp: number;
27
+ }
28
+
29
+ export interface SignedManifest {
30
+ modules: Record<string, ModuleHash>;
31
+ projectId: string;
32
+ version: string;
33
+ signedAt: number;
34
+ signature: string; // base64url-encoded ECDSA signature
35
+ publicKey: string; // base64url-encoded SPKI public key
36
+ }
37
+
38
+ export interface EncryptedModule {
39
+ ciphertext: string; // base64url
40
+ iv: string; // base64url, 12 bytes for AES-GCM
41
+ tag: string; // base64url, 16 bytes auth tag
42
+ keyId: string;
43
+ }
44
+
45
+ export interface CryptoKeyPair {
46
+ publicKey: CryptoKey;
47
+ privateKey: CryptoKey;
48
+ publicKeyExported: string; // base64url SPKI
49
+ }
50
+
51
+ /**
52
+ * JXRCrypto — Universal Web Crypto API abstraction
53
+ */
54
+ export class JXRCrypto {
55
+ private signingKeyPair: CryptoKeyPair | null = null;
56
+ private encryptionKeys: Map<string, CryptoKey> = new Map();
57
+ private hashCache: Map<string, ModuleHash> = new Map();
58
+
59
+ /** Generate an ECDSA P-256 signing key pair for module manifests */
60
+ async generateSigningKeyPair(): Promise<CryptoKeyPair> {
61
+ const keyPair = await subtle.generateKey(
62
+ { name: 'ECDSA', namedCurve: 'P-256' },
63
+ true,
64
+ ['sign', 'verify']
65
+ );
66
+
67
+ const spki = await subtle.exportKey('spki', keyPair.publicKey);
68
+ const publicKeyExported = this.toBase64Url(spki);
69
+
70
+ this.signingKeyPair = {
71
+ publicKey: keyPair.publicKey,
72
+ privateKey: keyPair.privateKey,
73
+ publicKeyExported,
74
+ };
75
+
76
+ return this.signingKeyPair;
77
+ }
78
+
79
+ /** Hash a module's source code for integrity verification */
80
+ async hashModule(
81
+ source: string,
82
+ algorithm: 'SHA-256' | 'SHA-384' | 'SHA-512' = 'SHA-256'
83
+ ): Promise<ModuleHash> {
84
+ const cacheKey = `${algorithm}:${source.length}:${source.slice(0, 64)}`;
85
+ const cached = this.hashCache.get(cacheKey);
86
+ if (cached) return cached;
87
+
88
+ const encoded = new TextEncoder().encode(source);
89
+ const hashBuffer = await subtle.digest(algorithm, encoded);
90
+ const digest = this.toHex(hashBuffer);
91
+
92
+ const result: ModuleHash = {
93
+ algorithm,
94
+ digest,
95
+ size: encoded.byteLength,
96
+ timestamp: Date.now(),
97
+ };
98
+
99
+ this.hashCache.set(cacheKey, result);
100
+ return result;
101
+ }
102
+
103
+ /** Verify a module's integrity against a known hash */
104
+ async verifyModule(source: string, expected: ModuleHash): Promise<boolean> {
105
+ const actual = await this.hashModule(source, expected.algorithm);
106
+ return actual.digest === expected.digest;
107
+ }
108
+
109
+ /** Sign a module manifest with ECDSA P-256 */
110
+ async signManifest(
111
+ modules: Record<string, ModuleHash>,
112
+ projectId: string,
113
+ version: string
114
+ ): Promise<SignedManifest> {
115
+ if (!this.signingKeyPair) {
116
+ await this.generateSigningKeyPair();
117
+ }
118
+
119
+ const manifest = {
120
+ modules,
121
+ projectId,
122
+ version,
123
+ signedAt: Date.now(),
124
+ };
125
+
126
+ const data = new TextEncoder().encode(JSON.stringify(manifest));
127
+ const signatureBuffer = await subtle.sign(
128
+ { name: 'ECDSA', hash: 'SHA-256' },
129
+ this.signingKeyPair!.privateKey,
130
+ data
131
+ );
132
+
133
+ return {
134
+ ...manifest,
135
+ signature: this.toBase64Url(signatureBuffer),
136
+ publicKey: this.signingKeyPair!.publicKeyExported,
137
+ };
138
+ }
139
+
140
+ /** Verify a signed manifest */
141
+ async verifyManifest(manifest: SignedManifest): Promise<boolean> {
142
+ try {
143
+ const spki = this.fromBase64Url(manifest.publicKey);
144
+ const publicKey = await subtle.importKey(
145
+ 'spki',
146
+ spki,
147
+ { name: 'ECDSA', namedCurve: 'P-256' },
148
+ false,
149
+ ['verify']
150
+ );
151
+
152
+ const { signature, publicKey: _pk, ...rest } = manifest;
153
+ const data = new TextEncoder().encode(JSON.stringify(rest));
154
+ const sigBuffer = this.fromBase64Url(signature);
155
+
156
+ return await subtle.verify(
157
+ { name: 'ECDSA', hash: 'SHA-256' },
158
+ publicKey,
159
+ sigBuffer,
160
+ data
161
+ );
162
+ } catch {
163
+ return false;
164
+ }
165
+ }
166
+
167
+ /** Generate or retrieve an AES-GCM-256 encryption key for a project */
168
+ async getEncryptionKey(keyId: string, projectSeed?: string): Promise<CryptoKey> {
169
+ const existing = this.encryptionKeys.get(keyId);
170
+ if (existing) return existing;
171
+
172
+ let key: CryptoKey;
173
+
174
+ if (projectSeed) {
175
+ // Derive key from project seed using HKDF
176
+ const seedBytes = new TextEncoder().encode(projectSeed);
177
+ const baseKey = await subtle.importKey('raw', seedBytes, 'HKDF', false, ['deriveKey']);
178
+ const salt = new TextEncoder().encode(`jxr-project-${keyId}`);
179
+ const info = new TextEncoder().encode('JXR.js Module Cache v1');
180
+
181
+ key = await subtle.deriveKey(
182
+ { name: 'HKDF', hash: 'SHA-256', salt, info },
183
+ baseKey,
184
+ { name: 'AES-GCM', length: 256 },
185
+ false,
186
+ ['encrypt', 'decrypt']
187
+ );
188
+ } else {
189
+ key = await subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, [
190
+ 'encrypt',
191
+ 'decrypt',
192
+ ]);
193
+ }
194
+
195
+ this.encryptionKeys.set(keyId, key);
196
+ return key;
197
+ }
198
+
199
+ /** Encrypt a module for secure caching */
200
+ async encryptModule(source: string, keyId: string): Promise<EncryptedModule> {
201
+ const key = await this.getEncryptionKey(keyId);
202
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
203
+ const encoded = new TextEncoder().encode(source);
204
+
205
+ const cipherBuffer = await subtle.encrypt({ name: 'AES-GCM', iv }, key, encoded);
206
+
207
+ // AES-GCM appends 16-byte auth tag to ciphertext
208
+ const ciphertext = cipherBuffer.slice(0, cipherBuffer.byteLength - 16);
209
+ const tag = cipherBuffer.slice(cipherBuffer.byteLength - 16);
210
+
211
+ return {
212
+ ciphertext: this.toBase64Url(ciphertext),
213
+ iv: this.toBase64Url(iv.buffer),
214
+ tag: this.toBase64Url(tag),
215
+ keyId,
216
+ };
217
+ }
218
+
219
+ /** Decrypt a cached module */
220
+ async decryptModule(encrypted: EncryptedModule): Promise<string> {
221
+ const key = await this.getEncryptionKey(encrypted.keyId);
222
+ const iv = this.fromBase64Url(encrypted.iv);
223
+ const ciphertext = this.fromBase64Url(encrypted.ciphertext);
224
+ const tag = this.fromBase64Url(encrypted.tag);
225
+
226
+ // Reassemble ciphertext + tag for AES-GCM
227
+ const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength);
228
+ combined.set(new Uint8Array(ciphertext));
229
+ combined.set(new Uint8Array(tag), ciphertext.byteLength);
230
+
231
+ const plainBuffer = await subtle.decrypt({ name: 'AES-GCM', iv }, key, combined);
232
+ return new TextDecoder().decode(plainBuffer);
233
+ }
234
+
235
+ /** Generate a cryptographically secure random nonce */
236
+ generateNonce(bytes = 16): string {
237
+ const nonce = globalThis.crypto.getRandomValues(new Uint8Array(bytes));
238
+ return this.toBase64Url(nonce.buffer);
239
+ }
240
+
241
+ /** Generate a project-unique ID using Web Crypto */
242
+ async generateProjectId(name: string, timestamp: number): Promise<string> {
243
+ const data = new TextEncoder().encode(`${name}:${timestamp}`);
244
+ const hash = await subtle.digest('SHA-256', data);
245
+ return this.toHex(hash).slice(0, 16);
246
+ }
247
+
248
+ // ─── Encoding utilities ───────────────────────────────────────────────────
249
+
250
+ private toHex(buffer: ArrayBuffer): string {
251
+ return Array.from(new Uint8Array(buffer))
252
+ .map((b) => b.toString(16).padStart(2, '0'))
253
+ .join('');
254
+ }
255
+
256
+ private toBase64Url(buffer: ArrayBuffer): string {
257
+ const bytes = new Uint8Array(buffer);
258
+ let binary = '';
259
+ for (let i = 0; i < bytes.byteLength; i++) {
260
+ binary += String.fromCharCode(bytes[i]);
261
+ }
262
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
263
+ }
264
+
265
+ private fromBase64Url(str: string): ArrayBuffer {
266
+ const padded = str.replace(/-/g, '+').replace(/_/g, '/');
267
+ const padLength = (4 - (padded.length % 4)) % 4;
268
+ const base64 = padded + '='.repeat(padLength);
269
+ const binary = atob(base64);
270
+ const bytes = new Uint8Array(binary.length);
271
+ for (let i = 0; i < binary.length; i++) {
272
+ bytes[i] = binary.charCodeAt(i);
273
+ }
274
+ return bytes.buffer;
275
+ }
276
+ }
277
+
278
+ /** Singleton instance */
279
+ export const jxrCrypto = new JXRCrypto();
@@ -0,0 +1,321 @@
1
+ /**
2
+ * JXR.js — Worker Pool Engine
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * Design: LavaFlow OS — Thermal Precision + Edge Command
5
+ * Layer: Core Runtime / Worker Orchestration
6
+ *
7
+ * Architecture:
8
+ * WorkerPool manages a fleet of Web Workers for parallel task execution.
9
+ * Tasks are dispatched via a priority queue and results streamed back
10
+ * through a structured message protocol. Each worker is isolated with
11
+ * its own module scope, enabling true parallelism without shared state.
12
+ *
13
+ * Performance targets:
14
+ * - Task dispatch latency: <1ms
15
+ * - Worker spawn time: <5ms (pre-warmed pool)
16
+ * - Throughput: saturate all available CPU cores
17
+ * ─────────────────────────────────────────────────────────────────────────────
18
+ */
19
+
20
+ export type WorkerStatus = 'idle' | 'busy' | 'error' | 'terminated';
21
+ export type TaskPriority = 'critical' | 'high' | 'normal' | 'low';
22
+
23
+ export interface WorkerTask<T = unknown, R = unknown> {
24
+ id: string;
25
+ type: string;
26
+ payload: T;
27
+ priority: TaskPriority;
28
+ timestamp: number;
29
+ resolve: (result: R) => void;
30
+ reject: (error: Error) => void;
31
+ timeoutMs?: number;
32
+ }
33
+
34
+ export interface WorkerMetrics {
35
+ workerId: string;
36
+ status: WorkerStatus;
37
+ tasksCompleted: number;
38
+ tasksFailed: number;
39
+ avgLatencyMs: number;
40
+ lastActiveAt: number;
41
+ cpuLoad: number;
42
+ }
43
+
44
+ export interface PoolMetrics {
45
+ totalWorkers: number;
46
+ idleWorkers: number;
47
+ busyWorkers: number;
48
+ queueDepth: number;
49
+ throughputPerSec: number;
50
+ avgLatencyMs: number;
51
+ totalTasksCompleted: number;
52
+ }
53
+
54
+ interface WorkerEntry {
55
+ worker: Worker;
56
+ status: WorkerStatus;
57
+ currentTaskId: string | null;
58
+ metrics: WorkerMetrics;
59
+ latencyHistory: number[];
60
+ }
61
+
62
+ const PRIORITY_WEIGHTS: Record<TaskPriority, number> = {
63
+ critical: 4,
64
+ high: 3,
65
+ normal: 2,
66
+ low: 1,
67
+ };
68
+
69
+ /**
70
+ * WorkerPool — Pre-warmed, priority-aware Web Worker fleet
71
+ */
72
+ export class WorkerPool {
73
+ private workers: Map<string, WorkerEntry> = new Map();
74
+ private taskQueue: WorkerTask[] = [];
75
+ private pendingTasks: Map<string, WorkerTask> = new Map();
76
+ private metricsHistory: number[] = [];
77
+ private throughputWindow: number[] = [];
78
+ private readonly maxWorkers: number;
79
+ private readonly workerScript: string;
80
+ private taskCounter = 0;
81
+ private listeners: Map<string, Set<(metrics: PoolMetrics) => void>> = new Map();
82
+
83
+ constructor(workerScript: string, maxWorkers?: number) {
84
+ this.workerScript = workerScript;
85
+ this.maxWorkers = maxWorkers ?? Math.max(2, (navigator.hardwareConcurrency ?? 4) - 1);
86
+ this.prewarm();
87
+ }
88
+
89
+ /** Pre-warm the pool to eliminate cold-start latency */
90
+ private prewarm(): void {
91
+ const initialCount = Math.min(2, this.maxWorkers);
92
+ for (let i = 0; i < initialCount; i++) {
93
+ this.spawnWorker();
94
+ }
95
+ }
96
+
97
+ private spawnWorker(): string {
98
+ const workerId = `worker-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
99
+ const worker = new Worker(this.workerScript, { type: 'module' });
100
+
101
+ const entry: WorkerEntry = {
102
+ worker,
103
+ status: 'idle',
104
+ currentTaskId: null,
105
+ latencyHistory: [],
106
+ metrics: {
107
+ workerId,
108
+ status: 'idle',
109
+ tasksCompleted: 0,
110
+ tasksFailed: 0,
111
+ avgLatencyMs: 0,
112
+ lastActiveAt: Date.now(),
113
+ cpuLoad: 0,
114
+ },
115
+ };
116
+
117
+ worker.onmessage = (event) => this.handleWorkerMessage(workerId, event);
118
+ worker.onerror = (error) => this.handleWorkerError(workerId, error);
119
+
120
+ this.workers.set(workerId, entry);
121
+ return workerId;
122
+ }
123
+
124
+ private handleWorkerMessage(workerId: string, event: MessageEvent): void {
125
+ const { taskId, result, error, type } = event.data;
126
+ const entry = this.workers.get(workerId);
127
+ if (!entry) return;
128
+
129
+ if (type === 'metrics') {
130
+ entry.metrics.cpuLoad = event.data.cpuLoad ?? 0;
131
+ return;
132
+ }
133
+
134
+ const task = this.pendingTasks.get(taskId);
135
+ if (!task) return;
136
+
137
+ const latency = Date.now() - task.timestamp;
138
+ entry.latencyHistory.push(latency);
139
+ if (entry.latencyHistory.length > 50) entry.latencyHistory.shift();
140
+
141
+ entry.metrics.avgLatencyMs =
142
+ entry.latencyHistory.reduce((a, b) => a + b, 0) / entry.latencyHistory.length;
143
+ entry.metrics.lastActiveAt = Date.now();
144
+
145
+ if (error) {
146
+ entry.metrics.tasksFailed++;
147
+ task.reject(new Error(error));
148
+ } else {
149
+ entry.metrics.tasksCompleted++;
150
+ this.throughputWindow.push(Date.now());
151
+ task.resolve(result);
152
+ }
153
+
154
+ this.pendingTasks.delete(taskId);
155
+ entry.status = 'idle';
156
+ entry.metrics.status = 'idle';
157
+ entry.currentTaskId = null;
158
+
159
+ this.emitMetrics();
160
+ this.drainQueue();
161
+ }
162
+
163
+ private handleWorkerError(workerId: string, error: ErrorEvent): void {
164
+ const entry = this.workers.get(workerId);
165
+ if (!entry) return;
166
+
167
+ entry.status = 'error';
168
+ entry.metrics.status = 'error';
169
+
170
+ if (entry.currentTaskId) {
171
+ const task = this.pendingTasks.get(entry.currentTaskId);
172
+ if (task) {
173
+ task.reject(new Error(error.message));
174
+ this.pendingTasks.delete(entry.currentTaskId);
175
+ }
176
+ }
177
+
178
+ // Respawn worker
179
+ entry.worker.terminate();
180
+ this.workers.delete(workerId);
181
+ this.spawnWorker();
182
+ this.drainQueue();
183
+ }
184
+
185
+ private getIdleWorker(): WorkerEntry | null {
186
+ for (const [, entry] of Array.from(this.workers.entries())) {
187
+ if (entry.status === 'idle') return entry;
188
+ }
189
+ return null;
190
+ }
191
+
192
+ private drainQueue(): void {
193
+ if (this.taskQueue.length === 0) return;
194
+
195
+ // Sort by priority weight descending
196
+ this.taskQueue.sort(
197
+ (a, b) => PRIORITY_WEIGHTS[b.priority] - PRIORITY_WEIGHTS[a.priority]
198
+ );
199
+
200
+ let idleWorker = this.getIdleWorker();
201
+
202
+ // Scale up if needed and under cap
203
+ if (!idleWorker && this.workers.size < this.maxWorkers) {
204
+ const newId = this.spawnWorker();
205
+ idleWorker = this.workers.get(newId) ?? null;
206
+ }
207
+
208
+ if (!idleWorker) return;
209
+
210
+ const task = this.taskQueue.shift()!;
211
+ this.dispatchToWorker(idleWorker, task);
212
+ }
213
+
214
+ private dispatchToWorker(entry: WorkerEntry, task: WorkerTask): void {
215
+ entry.status = 'busy';
216
+ entry.metrics.status = 'busy';
217
+ entry.currentTaskId = task.id;
218
+ this.pendingTasks.set(task.id, task);
219
+
220
+ entry.worker.postMessage({
221
+ taskId: task.id,
222
+ type: task.type,
223
+ payload: task.payload,
224
+ });
225
+
226
+ if (task.timeoutMs) {
227
+ setTimeout(() => {
228
+ if (this.pendingTasks.has(task.id)) {
229
+ task.reject(new Error(`Task ${task.id} timed out after ${task.timeoutMs}ms`));
230
+ this.pendingTasks.delete(task.id);
231
+ }
232
+ }, task.timeoutMs);
233
+ }
234
+ }
235
+
236
+ /** Submit a task to the pool, returns a Promise */
237
+ submit<T = unknown, R = unknown>(
238
+ type: string,
239
+ payload: T,
240
+ options: { priority?: TaskPriority; timeoutMs?: number } = {}
241
+ ): Promise<R> {
242
+ return new Promise<R>((resolve, reject) => {
243
+ const task: WorkerTask<T, R> = {
244
+ id: `task-${++this.taskCounter}-${Date.now()}`,
245
+ type,
246
+ payload,
247
+ priority: options.priority ?? 'normal',
248
+ timestamp: Date.now(),
249
+ timeoutMs: options.timeoutMs,
250
+ resolve,
251
+ reject,
252
+ };
253
+
254
+ const idleWorker = this.getIdleWorker();
255
+ if (idleWorker) {
256
+ this.dispatchToWorker(idleWorker, task as WorkerTask);
257
+ } else {
258
+ this.taskQueue.push(task as WorkerTask);
259
+ // Scale up if under cap
260
+ if (this.workers.size < this.maxWorkers) {
261
+ this.spawnWorker();
262
+ this.drainQueue();
263
+ }
264
+ }
265
+ });
266
+ }
267
+
268
+ /** Get current pool metrics */
269
+ getMetrics(): PoolMetrics {
270
+ const now = Date.now();
271
+ // Clean throughput window to last 1 second
272
+ this.throughputWindow = this.throughputWindow.filter((t) => now - t < 1000);
273
+
274
+ const allLatencies = Array.from(this.workers.values() as Iterable<WorkerEntry>).flatMap(
275
+ (e) => e.latencyHistory
276
+ );
277
+ const avgLatency =
278
+ allLatencies.length > 0
279
+ ? allLatencies.reduce((a, b) => a + b, 0) / allLatencies.length
280
+ : 0;
281
+
282
+ const totalCompleted = Array.from(this.workers.values() as Iterable<WorkerEntry>).reduce(
283
+ (sum, e) => sum + e.metrics.tasksCompleted,
284
+ 0
285
+ );
286
+
287
+ return {
288
+ totalWorkers: this.workers.size,
289
+ idleWorkers: Array.from(this.workers.values() as Iterable<WorkerEntry>).filter((e) => e.status === 'idle').length,
290
+ busyWorkers: Array.from(this.workers.values() as Iterable<WorkerEntry>).filter((e) => e.status === 'busy').length,
291
+ queueDepth: this.taskQueue.length,
292
+ throughputPerSec: this.throughputWindow.length,
293
+ avgLatencyMs: Math.round(avgLatency * 10) / 10,
294
+ totalTasksCompleted: totalCompleted,
295
+ };
296
+ }
297
+
298
+ getWorkerMetrics(): WorkerMetrics[] {
299
+ return Array.from(this.workers.values() as Iterable<WorkerEntry>).map((e) => ({ ...e.metrics }));
300
+ }
301
+
302
+ onMetrics(event: string, cb: (metrics: PoolMetrics) => void): () => void {
303
+ if (!this.listeners.has(event)) this.listeners.set(event, new Set());
304
+ this.listeners.get(event)!.add(cb);
305
+ return () => this.listeners.get(event)?.delete(cb);
306
+ }
307
+
308
+ private emitMetrics(): void {
309
+ const metrics = this.getMetrics();
310
+ this.listeners.get('metrics')?.forEach((cb) => cb(metrics));
311
+ }
312
+
313
+ terminate(): void {
314
+ for (const [, entry] of Array.from(this.workers.entries())) {
315
+ entry.worker.terminate();
316
+ }
317
+ this.workers.clear();
318
+ this.taskQueue.length = 0;
319
+ this.pendingTasks.clear();
320
+ }
321
+ }