@omnitron-dev/testing 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.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -0
  3. package/dist/async/deferred.d.ts +15 -0
  4. package/dist/async/deferred.js +35 -0
  5. package/dist/async/deferred.js.map +1 -0
  6. package/dist/async/events.d.ts +32 -0
  7. package/dist/async/events.js +176 -0
  8. package/dist/async/events.js.map +1 -0
  9. package/dist/async/index.d.ts +5 -0
  10. package/dist/async/index.js +6 -0
  11. package/dist/async/index.js.map +1 -0
  12. package/dist/async/mock-timer.d.ts +19 -0
  13. package/dist/async/mock-timer.js +87 -0
  14. package/dist/async/mock-timer.js.map +1 -0
  15. package/dist/async/retry.d.ts +8 -0
  16. package/dist/async/retry.js +36 -0
  17. package/dist/async/retry.js.map +1 -0
  18. package/dist/async/wait.d.ts +10 -0
  19. package/dist/async/wait.js +35 -0
  20. package/dist/async/wait.js.map +1 -0
  21. package/dist/docker/database-manager.d.ts +22 -0
  22. package/dist/docker/database-manager.js +97 -0
  23. package/dist/docker/database-manager.js.map +1 -0
  24. package/dist/docker/docker-test-manager.d.ts +44 -0
  25. package/dist/docker/docker-test-manager.js +812 -0
  26. package/dist/docker/docker-test-manager.js.map +1 -0
  27. package/dist/docker/index.d.ts +4 -0
  28. package/dist/docker/index.js +4 -0
  29. package/dist/docker/index.js.map +1 -0
  30. package/dist/docker/redis-manager.d.ts +12 -0
  31. package/dist/docker/redis-manager.js +452 -0
  32. package/dist/docker/redis-manager.js.map +1 -0
  33. package/dist/docker/types.d.ts +103 -0
  34. package/dist/docker/types.js +2 -0
  35. package/dist/docker/types.js.map +1 -0
  36. package/dist/errors.d.ts +15 -0
  37. package/dist/errors.js +28 -0
  38. package/dist/errors.js.map +1 -0
  39. package/dist/helpers/assertions.d.ts +6 -0
  40. package/dist/helpers/assertions.js +37 -0
  41. package/dist/helpers/assertions.js.map +1 -0
  42. package/dist/helpers/console.d.ts +1 -0
  43. package/dist/helpers/console.js +23 -0
  44. package/dist/helpers/console.js.map +1 -0
  45. package/dist/helpers/index.d.ts +3 -0
  46. package/dist/helpers/index.js +4 -0
  47. package/dist/helpers/index.js.map +1 -0
  48. package/dist/helpers/temp-dir.d.ts +2 -0
  49. package/dist/helpers/temp-dir.js +13 -0
  50. package/dist/helpers/temp-dir.js.map +1 -0
  51. package/dist/index.d.ts +18 -0
  52. package/dist/index.js +22 -0
  53. package/dist/index.js.map +1 -0
  54. package/dist/performance/index.d.ts +2 -0
  55. package/dist/performance/index.js +3 -0
  56. package/dist/performance/index.js.map +1 -0
  57. package/dist/performance/memory-detector.d.ts +9 -0
  58. package/dist/performance/memory-detector.js +61 -0
  59. package/dist/performance/memory-detector.js.map +1 -0
  60. package/dist/performance/perf-timer.d.ts +9 -0
  61. package/dist/performance/perf-timer.js +49 -0
  62. package/dist/performance/perf-timer.js.map +1 -0
  63. package/dist/runtime/bun-adapter.d.ts +1 -0
  64. package/dist/runtime/bun-adapter.js +100 -0
  65. package/dist/runtime/bun-adapter.js.map +1 -0
  66. package/dist/runtime/deno-adapter.d.ts +27 -0
  67. package/dist/runtime/deno-adapter.js +221 -0
  68. package/dist/runtime/deno-adapter.js.map +1 -0
  69. package/dist/runtime/node-adapter.d.ts +16 -0
  70. package/dist/runtime/node-adapter.js +30 -0
  71. package/dist/runtime/node-adapter.js.map +1 -0
  72. package/dist/runtime/test-adapter.d.ts +22 -0
  73. package/dist/runtime/test-adapter.js +93 -0
  74. package/dist/runtime/test-adapter.js.map +1 -0
  75. package/dist/titan/container-utils.d.ts +20 -0
  76. package/dist/titan/container-utils.js +78 -0
  77. package/dist/titan/container-utils.js.map +1 -0
  78. package/dist/titan/database/database-testing.module.d.ts +82 -0
  79. package/dist/titan/database/database-testing.module.js +433 -0
  80. package/dist/titan/database/database-testing.module.js.map +1 -0
  81. package/dist/titan/database/index.d.ts +3 -0
  82. package/dist/titan/database/index.js +4 -0
  83. package/dist/titan/database/index.js.map +1 -0
  84. package/dist/titan/database/test-utilities.d.ts +31 -0
  85. package/dist/titan/database/test-utilities.js +146 -0
  86. package/dist/titan/database/test-utilities.js.map +1 -0
  87. package/dist/titan/index.d.ts +14 -0
  88. package/dist/titan/index.js +10 -0
  89. package/dist/titan/index.js.map +1 -0
  90. package/dist/titan/nexus/index.d.ts +3 -0
  91. package/dist/titan/nexus/index.js +4 -0
  92. package/dist/titan/nexus/index.js.map +1 -0
  93. package/dist/titan/nexus/mock-provider.d.ts +41 -0
  94. package/dist/titan/nexus/mock-provider.js +127 -0
  95. package/dist/titan/nexus/mock-provider.js.map +1 -0
  96. package/dist/titan/nexus/test-container.d.ts +120 -0
  97. package/dist/titan/nexus/test-container.js +559 -0
  98. package/dist/titan/nexus/test-container.js.map +1 -0
  99. package/dist/titan/nexus/test-utilities.d.ts +135 -0
  100. package/dist/titan/nexus/test-utilities.js +484 -0
  101. package/dist/titan/nexus/test-utilities.js.map +1 -0
  102. package/dist/titan/pm/index.d.ts +4 -0
  103. package/dist/titan/pm/index.js +4 -0
  104. package/dist/titan/pm/index.js.map +1 -0
  105. package/dist/titan/pm/mock-process-spawner.d.ts +61 -0
  106. package/dist/titan/pm/mock-process-spawner.js +343 -0
  107. package/dist/titan/pm/mock-process-spawner.js.map +1 -0
  108. package/dist/titan/pm/mock-spawner.d.ts +28 -0
  109. package/dist/titan/pm/mock-spawner.js +101 -0
  110. package/dist/titan/pm/mock-spawner.js.map +1 -0
  111. package/dist/titan/pm/test-process-manager.d.ts +49 -0
  112. package/dist/titan/pm/test-process-manager.js +192 -0
  113. package/dist/titan/pm/test-process-manager.js.map +1 -0
  114. package/dist/titan/redis-test-utils.d.ts +33 -0
  115. package/dist/titan/redis-test-utils.js +415 -0
  116. package/dist/titan/redis-test-utils.js.map +1 -0
  117. package/dist/titan/test-application.d.ts +21 -0
  118. package/dist/titan/test-application.js +90 -0
  119. package/dist/titan/test-application.js.map +1 -0
  120. package/dist/titan/test-fixtures.d.ts +97 -0
  121. package/dist/titan/test-fixtures.js +223 -0
  122. package/dist/titan/test-fixtures.js.map +1 -0
  123. package/dist/titan/test-mocks.d.ts +30 -0
  124. package/dist/titan/test-mocks.js +262 -0
  125. package/dist/titan/test-mocks.js.map +1 -0
  126. package/dist/titan/test-module.d.ts +47 -0
  127. package/dist/titan/test-module.js +120 -0
  128. package/dist/titan/test-module.js.map +1 -0
  129. package/package.json +146 -0
  130. package/runtime/bun.d.ts +2 -0
  131. package/runtime/bun.js +5 -0
  132. package/runtime/bun.ts +7 -0
  133. package/runtime/deno.d.ts +2 -0
  134. package/runtime/deno.js +4 -0
  135. package/runtime/vitest.d.ts +2 -0
  136. package/runtime/vitest.js +16 -0
  137. package/runtime/vitest.ts +7 -0
  138. package/src/async/README.md +336 -0
  139. package/src/async/deferred.ts +98 -0
  140. package/src/async/events.ts +386 -0
  141. package/src/async/index.ts +23 -0
  142. package/src/async/mock-timer.ts +220 -0
  143. package/src/async/retry.ts +115 -0
  144. package/src/async/wait.ts +148 -0
  145. package/src/docker/database-manager.ts +242 -0
  146. package/src/docker/docker-test-manager.ts +1198 -0
  147. package/src/docker/index.ts +48 -0
  148. package/src/docker/redis-manager.ts +741 -0
  149. package/src/docker/types.ts +216 -0
  150. package/src/errors.ts +38 -0
  151. package/src/globals.d.ts +24 -0
  152. package/src/helpers/assertions.ts +168 -0
  153. package/src/helpers/console.ts +74 -0
  154. package/src/helpers/index.ts +15 -0
  155. package/src/helpers/temp-dir.ts +50 -0
  156. package/src/index.ts +43 -0
  157. package/src/performance/index.ts +11 -0
  158. package/src/performance/memory-detector.ts +166 -0
  159. package/src/performance/perf-timer.ts +146 -0
  160. package/src/runtime/bun-adapter.ts +127 -0
  161. package/src/runtime/deno-adapter.ts +286 -0
  162. package/src/runtime/node-adapter.ts +40 -0
  163. package/src/runtime/test-adapter.test.ts +98 -0
  164. package/src/runtime/test-adapter.ts +122 -0
  165. package/src/titan/container-utils.ts +128 -0
  166. package/src/titan/database/database-testing.module.ts +851 -0
  167. package/src/titan/database/index.ts +30 -0
  168. package/src/titan/database/test-utilities.ts +340 -0
  169. package/src/titan/index.ts +128 -0
  170. package/src/titan/nexus/index.ts +3 -0
  171. package/src/titan/nexus/mock-provider.ts +189 -0
  172. package/src/titan/nexus/test-container.ts +895 -0
  173. package/src/titan/nexus/test-utilities.ts +797 -0
  174. package/src/titan/pm/index.ts +22 -0
  175. package/src/titan/pm/mock-process-spawner.ts +534 -0
  176. package/src/titan/pm/mock-spawner.ts +162 -0
  177. package/src/titan/pm/test-process-manager.ts +352 -0
  178. package/src/titan/redis-test-utils.ts +567 -0
  179. package/src/titan/test-application.ts +154 -0
  180. package/src/titan/test-fixtures.ts +304 -0
  181. package/src/titan/test-mocks.ts +336 -0
  182. package/src/titan/test-module.ts +233 -0
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Process Manager Testing Utilities
3
+ *
4
+ * Testing utilities for Titan Process Manager including mock spawners
5
+ * and test process manager with simulation capabilities.
6
+ */
7
+
8
+ // Export test process manager
9
+ export { TestProcessManager, createTestProcessManager } from './test-process-manager.js';
10
+ export type { ITestProcessManagerConfig, IOperationRecord } from './test-process-manager.js';
11
+
12
+ // Export mock spawner (simpler version)
13
+ export { MockProcessSpawner } from './mock-spawner.js';
14
+
15
+ // Export advanced mock process spawner
16
+ export {
17
+ MockWorker,
18
+ MockNetronClient,
19
+ MockWorkerHandle,
20
+ MockProcessSpawner as AdvancedMockProcessSpawner,
21
+ SimpleMockProcessSpawner,
22
+ } from './mock-process-spawner.js';
@@ -0,0 +1,534 @@
1
+ /**
2
+ * Mock Process Spawner for Testing
3
+ *
4
+ * Optimized mock spawner that runs processes in the same thread for fast testing.
5
+ * Implements the same interface as the real spawner for seamless switching.
6
+ */
7
+
8
+ import { EventEmitter } from 'events';
9
+ import path from 'path';
10
+ import { generateUuidV7 } from '@omnitron-dev/titan/utils';
11
+ import { Errors } from '@omnitron-dev/titan/errors';
12
+ import type { ProcessMethod } from '@omnitron-dev/titan-pm';
13
+ import type { ILogger } from '@omnitron-dev/titan/module/logger';
14
+ import type {
15
+ IProcessSpawner,
16
+ ISpawnOptions,
17
+ IWorkerHandle,
18
+ IProcessManagerConfig,
19
+ IProcessMetrics,
20
+ IHealthStatus,
21
+ } from '@omnitron-dev/titan-pm';
22
+ import { ProcessStatus } from '@omnitron-dev/titan-pm';
23
+ import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan-pm';
24
+
25
+ /**
26
+ * Mock worker that runs in the same thread
27
+ */
28
+ export class MockWorker extends EventEmitter {
29
+ public readonly threadId = Math.floor(Math.random() * 10000);
30
+ public readonly pid = process.pid;
31
+ private instance: any;
32
+ private publicMethods = new Map<string, ProcessMethod>();
33
+ private _status: ProcessStatus = ProcessStatus.STARTING;
34
+ private metrics: IProcessMetrics = {
35
+ cpu: 0,
36
+ memory: 0,
37
+ requests: 0,
38
+ errors: 0,
39
+ };
40
+
41
+ constructor(
42
+ public readonly id: string,
43
+ ProcessClass: new (...args: any[]) => any,
44
+ private readonly options: ISpawnOptions = {}
45
+ ) {
46
+ super();
47
+
48
+ // Create instance with options
49
+ try {
50
+ this.instance = new ProcessClass(options.config || {});
51
+ } catch (_error) {
52
+ // If instantiation fails, create a simple object
53
+ this.instance = {};
54
+ }
55
+
56
+ // Extract and bind public methods
57
+ if (ProcessClass && ProcessClass.prototype) {
58
+ this.extractPublicMethods(ProcessClass);
59
+ }
60
+
61
+ // Setup internal methods
62
+ this.setupInternalMethods();
63
+
64
+ // Don't emit ready here - let the spawner call notifyReady() after setup
65
+ this._status = ProcessStatus.STARTING;
66
+ }
67
+
68
+ /**
69
+ * Notify that the worker is ready (called by spawner after listener is attached)
70
+ */
71
+ notifyReady(): void {
72
+ setImmediate(() => {
73
+ this._status = ProcessStatus.RUNNING;
74
+ this.emit('message', { type: 'ready' });
75
+ });
76
+ }
77
+
78
+ get status(): ProcessStatus {
79
+ return this._status;
80
+ }
81
+
82
+ /**
83
+ * Extract public methods from the process class
84
+ */
85
+ private extractPublicMethods(ProcessClass: new (...args: any[]) => any): void {
86
+ if (!ProcessClass || !ProcessClass.prototype) {
87
+ return;
88
+ }
89
+
90
+ const prototype = ProcessClass.prototype;
91
+ const propertyNames = Object.getOwnPropertyNames(prototype);
92
+
93
+ for (const propertyName of propertyNames) {
94
+ if (propertyName === 'constructor') continue;
95
+
96
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, propertyName);
97
+ if (!descriptor || typeof descriptor.value !== 'function') continue;
98
+
99
+ // Check if method is marked as public (supports both PM decorators and core @Method decorator)
100
+ const pmMetadata = Reflect.getMetadata(PROCESS_METHOD_METADATA_KEY, prototype, propertyName);
101
+ const corePublic = Reflect.getMetadata('public', prototype, propertyName);
102
+
103
+ if (pmMetadata?.public || corePublic) {
104
+ this.publicMethods.set(propertyName, descriptor.value.bind(this.instance));
105
+ }
106
+ }
107
+
108
+ // Add special methods if they exist
109
+ const specialMethods = ['checkHealth', 'onShutdown', 'getMetrics'];
110
+ for (const method of specialMethods) {
111
+ if (typeof this.instance[method] === 'function') {
112
+ this.publicMethods.set(method, this.instance[method]!.bind(this.instance));
113
+ }
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Setup internal process management methods
119
+ */
120
+ private setupInternalMethods(): void {
121
+ this.publicMethods.set('__getProcessMetrics', async (): Promise<IProcessMetrics> => {
122
+ if (this.metrics) this.metrics.requests = (this.metrics.requests || 0) + 1;
123
+ return {
124
+ ...(this.metrics || { cpu: 0, memory: 0, requests: 0, errors: 0 }),
125
+ cpu: Math.random() * 100,
126
+ memory: process.memoryUsage().heapUsed,
127
+ };
128
+ });
129
+
130
+ this.publicMethods.set('__getProcessHealth', async (): Promise<IHealthStatus> => {
131
+ if (this.publicMethods.has('checkHealth')) {
132
+ const result = await this.publicMethods.get('checkHealth')!();
133
+ // Normalize the result to IHealthStatus format
134
+ if (result && typeof result === 'object') {
135
+ const healthResult = result as any;
136
+ // If it already has the correct format, return as-is
137
+ if ('status' in healthResult && 'checks' in healthResult && 'timestamp' in healthResult) {
138
+ return healthResult as IHealthStatus;
139
+ }
140
+ // Convert from test format to IHealthStatus
141
+ const status = healthResult.status || (this._status === ProcessStatus.RUNNING ? 'healthy' : 'unhealthy');
142
+ return {
143
+ status: status as 'healthy' | 'degraded' | 'unhealthy',
144
+ checks: healthResult.checks || [
145
+ {
146
+ name: 'checkHealth',
147
+ status: status === 'healthy' ? 'pass' : 'fail',
148
+ message: healthResult.message,
149
+ details: healthResult.details,
150
+ },
151
+ ],
152
+ timestamp: healthResult.timestamp || Date.now(),
153
+ };
154
+ }
155
+ }
156
+
157
+ return {
158
+ status: this._status === ProcessStatus.RUNNING ? 'healthy' : 'unhealthy',
159
+ checks: [
160
+ {
161
+ name: 'mock',
162
+ status: 'pass',
163
+ },
164
+ ],
165
+ timestamp: Date.now(),
166
+ };
167
+ });
168
+
169
+ this.publicMethods.set('__destroy', async (): Promise<void> => {
170
+ await this.terminate();
171
+ });
172
+ }
173
+
174
+ /**
175
+ * Call a method on the mock worker
176
+ * Note: This method returns Promise<unknown> but for async generators,
177
+ * it returns the generator directly (not wrapped in a promise)
178
+ */
179
+ callMethod(methodName: string, args: unknown[]): unknown {
180
+ const method = this.publicMethods.get(methodName);
181
+ if (!method) {
182
+ if (this.metrics) this.metrics.errors = (this.metrics.errors || 0) + 1;
183
+ throw Errors.notFound('Method', methodName);
184
+ }
185
+
186
+ try {
187
+ if (this.metrics) this.metrics.requests = (this.metrics.requests || 0) + 1;
188
+ const result = method(...args);
189
+
190
+ // Check for async generator FIRST - it has Symbol.asyncIterator
191
+ // AsyncGenerators are thenable but we should NOT await them
192
+ if (result && typeof result === 'object' && typeof (result as any)[Symbol.asyncIterator] === 'function') {
193
+ return result;
194
+ }
195
+
196
+ // If the method returns a promise (but NOT an async generator), await it
197
+ if (
198
+ result &&
199
+ typeof result === 'object' &&
200
+ 'then' in result &&
201
+ typeof (result as Promise<unknown>).then === 'function'
202
+ ) {
203
+ return result as Promise<unknown>;
204
+ }
205
+
206
+ // Return as-is for sync values
207
+ return result;
208
+ } catch (error) {
209
+ if (this.metrics) this.metrics.errors = (this.metrics.errors || 0) + 1;
210
+ throw error;
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Send message to the mock worker
216
+ */
217
+ postMessage(message: any): void {
218
+ setImmediate(() => {
219
+ if (message.type === 'shutdown') {
220
+ this.terminate();
221
+ } else {
222
+ this.emit('message', { type: 'response', data: message });
223
+ }
224
+ });
225
+ }
226
+
227
+ /**
228
+ * Terminate the mock worker
229
+ */
230
+ async terminate(): Promise<void> {
231
+ this._status = ProcessStatus.STOPPING;
232
+
233
+ // Call onShutdown if available
234
+ if (this.publicMethods.has('onShutdown')) {
235
+ try {
236
+ await this.publicMethods.get('onShutdown')!();
237
+ } catch (_error) {
238
+ // Ignore shutdown errors
239
+ }
240
+ }
241
+
242
+ this._status = ProcessStatus.STOPPED;
243
+ this.emit('exit', 0);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Mock Netron client for testing
249
+ */
250
+ export class MockNetronClient {
251
+ private connected = false;
252
+ private worker: MockWorker;
253
+
254
+ constructor(
255
+ public readonly processId: string,
256
+ public readonly logger: ILogger,
257
+ worker: MockWorker
258
+ ) {
259
+ this.worker = worker;
260
+ }
261
+
262
+ async start(): Promise<void> {
263
+ // Mock start
264
+ }
265
+
266
+ async connect(url: string): Promise<void> {
267
+ this.connected = true;
268
+ }
269
+
270
+ async disconnect(): Promise<void> {
271
+ this.connected = false;
272
+ }
273
+
274
+ async stop(): Promise<void> {
275
+ await this.disconnect();
276
+ }
277
+
278
+ isConnected(): boolean {
279
+ return this.connected;
280
+ }
281
+
282
+ async call(service: string, method: string, args: any[]): Promise<any> {
283
+ return this.worker.callMethod(method, args);
284
+ }
285
+
286
+ // Add mockCall for compatibility
287
+ async mockCall(method: string, args: any[]): Promise<any> {
288
+ return this.worker.callMethod(method, args);
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Mock worker handle implementation
294
+ */
295
+ export class MockWorkerHandle implements IWorkerHandle {
296
+ public readonly proxy: any;
297
+ public readonly netronClient: MockNetronClient;
298
+ public readonly worker: MockWorker;
299
+
300
+ constructor(
301
+ public readonly id: string,
302
+ worker: MockWorker,
303
+ public readonly transportUrl: string,
304
+ public readonly serviceName: string,
305
+ public readonly serviceVersion: string,
306
+ private readonly logger: ILogger
307
+ ) {
308
+ this.worker = worker;
309
+ // Create mock Netron client
310
+ this.netronClient = new MockNetronClient(id, logger, worker);
311
+
312
+ // Create proxy for method calls
313
+ this.proxy = new Proxy(
314
+ {},
315
+ {
316
+ get: (target, property: string | symbol) => {
317
+ // Handle control methods
318
+ if (property === '__processId') {
319
+ return this.id;
320
+ }
321
+
322
+ if (property === '__destroy') {
323
+ return () => this.terminate();
324
+ }
325
+
326
+ if (property === '__getMetrics') {
327
+ return () => this.worker.callMethod('__getProcessMetrics', []);
328
+ }
329
+
330
+ if (property === '__getHealth') {
331
+ return () => this.worker.callMethod('__getProcessHealth', []);
332
+ }
333
+
334
+ // Handle Promise-like properties
335
+ if (property === 'then' || property === 'catch' || property === 'finally') {
336
+ return undefined;
337
+ }
338
+
339
+ // Handle symbols
340
+ if (typeof property === 'symbol') {
341
+ return undefined;
342
+ }
343
+
344
+ // Convert property to string
345
+ const methodName = String(property);
346
+
347
+ // Check if this should be a streaming method
348
+ // Methods that include 'Stream' or start with 'stream' may return AsyncIterables
349
+ const isStreamMethod = methodName.startsWith('stream') || methodName.toLowerCase().includes('stream');
350
+
351
+ if (isStreamMethod) {
352
+ const workerInstance = this.worker;
353
+ // For streaming methods, we need to detect if the result is actually an async generator
354
+ // Some methods like "processStream" contain "stream" but return Promise<T>, not AsyncGenerator
355
+
356
+ return (...args: any[]): any => {
357
+ // Call the method
358
+ const result = workerInstance.callMethod(methodName, args);
359
+
360
+ const anyResult = result as any;
361
+
362
+ // If result is already an async iterable (AsyncGenerator), return it directly
363
+ if (anyResult && typeof anyResult[Symbol.asyncIterator] === 'function') {
364
+ return anyResult;
365
+ }
366
+
367
+ // If result is a sync iterable (but NOT a Promise), convert to async generator
368
+ if (
369
+ anyResult &&
370
+ typeof anyResult[Symbol.iterator] === 'function' &&
371
+ typeof anyResult.then !== 'function'
372
+ ) {
373
+ // eslint-disable-next-line func-names
374
+ return (async function* () {
375
+ yield* anyResult;
376
+ })();
377
+ }
378
+
379
+ // If it's a Promise, we need to check what it resolves to
380
+ if (anyResult && typeof anyResult.then === 'function') {
381
+ // Return a Promise that resolves to the actual value
382
+ // If the resolved value is an async iterable, wrap it properly
383
+ return (async () => {
384
+ const resolved = await anyResult;
385
+ // If resolved is an async iterable, we can't return it directly from an async function
386
+ // because the caller expects to iterate over the result of the original call
387
+ // For methods that return Promise<AsyncIterable>, this is a limitation
388
+ // But for methods that return Promise<T> (like processStream -> Promise<number[]>),
389
+ // we just return the resolved value
390
+ if (resolved && typeof resolved[Symbol.asyncIterator] === 'function') {
391
+ // Can't properly handle Promise<AsyncIterable> in mock - return as-is
392
+ return resolved;
393
+ }
394
+ return resolved;
395
+ })();
396
+ }
397
+
398
+ // Otherwise return as-is
399
+ return result;
400
+ };
401
+ }
402
+
403
+ // Return async method wrapper
404
+ return async (...args: any[]) => this.worker.callMethod(methodName, args);
405
+ },
406
+
407
+ has: (target, property) => {
408
+ // Report that we have the special control methods
409
+ const controlMethods = ['__processId', '__destroy', '__getMetrics', '__getHealth'];
410
+ if (typeof property === 'string' && controlMethods.includes(property)) {
411
+ return true;
412
+ }
413
+ // All other methods are assumed to be available
414
+ return typeof property === 'string';
415
+ },
416
+ }
417
+ );
418
+ }
419
+
420
+ get status(): ProcessStatus {
421
+ return this.worker.status;
422
+ }
423
+
424
+ async terminate(): Promise<void> {
425
+ await this.worker.terminate();
426
+ }
427
+
428
+ isAlive(): boolean {
429
+ return this.worker.status === ProcessStatus.RUNNING;
430
+ }
431
+
432
+ async send(message: any): Promise<void> {
433
+ this.worker.postMessage(message);
434
+ }
435
+
436
+ onMessage(handler: (data: any) => void): void {
437
+ this.worker.on('message', handler);
438
+ }
439
+ }
440
+
441
+ /**
442
+ * Mock process spawner for testing
443
+ */
444
+ export class MockProcessSpawner implements IProcessSpawner {
445
+ private workers = new Map<string, MockWorker>();
446
+
447
+ constructor(
448
+ private readonly logger: ILogger,
449
+ private readonly config: IProcessManagerConfig = {}
450
+ ) {}
451
+
452
+ /**
453
+ * Spawn a mock process
454
+ */
455
+ async spawn<T>(
456
+ processPathOrClass: string | (new (...args: any[]) => T),
457
+ options: ISpawnOptions = {}
458
+ ): Promise<IWorkerHandle> {
459
+ const processId = options.processId || generateUuidV7();
460
+
461
+ let ProcessClass: new (...args: any[]) => T;
462
+ let serviceName: string;
463
+
464
+ if (typeof processPathOrClass === 'string') {
465
+ // For file paths, we need to load the module
466
+ // In mock spawner, we'll try to import it dynamically
467
+ try {
468
+ const module = await import(processPathOrClass);
469
+ if (module.default) {
470
+ ProcessClass = module.default;
471
+ } else {
472
+ const keys = Object.keys(module);
473
+ const firstKey = keys[0];
474
+ if (firstKey && module[firstKey]) {
475
+ ProcessClass = module[firstKey];
476
+ } else {
477
+ throw Errors.notFound('Default export', 'process file');
478
+ }
479
+ }
480
+ serviceName = options.name || path.basename(processPathOrClass, '.js');
481
+ } catch (_error) {
482
+ // If import fails in test, create a simple mock class
483
+ ProcessClass = class MockProcess {
484
+ constructor() {}
485
+ } as any;
486
+ serviceName = options.name || 'MockProcess';
487
+ }
488
+ } else {
489
+ ProcessClass = processPathOrClass;
490
+ serviceName = options.name || ProcessClass.name;
491
+ }
492
+
493
+ const serviceVersion = options.version || '1.0.0';
494
+ const transportUrl = `mock://${processId}`;
495
+
496
+ // Create mock worker
497
+ const worker = new MockWorker(processId, ProcessClass, options);
498
+ this.workers.set(processId, worker);
499
+
500
+ // Create handle
501
+ const handle = new MockWorkerHandle(processId, worker, transportUrl, serviceName, serviceVersion, this.logger);
502
+
503
+ // Wait for ready - set up listener FIRST, then trigger ready
504
+ const readyPromise = new Promise<void>((resolve) => {
505
+ worker.once('message', (data) => {
506
+ if (data.type === 'ready') {
507
+ resolve();
508
+ }
509
+ });
510
+ });
511
+
512
+ // Now trigger the ready event (after listener is attached)
513
+ worker.notifyReady();
514
+
515
+ await readyPromise;
516
+ return handle;
517
+ }
518
+
519
+ /**
520
+ * Cleanup spawner resources
521
+ */
522
+ async cleanup(): Promise<void> {
523
+ // Terminate all workers
524
+ for (const [_id, worker] of this.workers) {
525
+ await worker.terminate();
526
+ }
527
+ this.workers.clear();
528
+ }
529
+ }
530
+
531
+ /**
532
+ * Export the old name for backward compatibility
533
+ */
534
+ export { MockProcessSpawner as SimpleMockProcessSpawner };