-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStdinWrappers.test.ts
More file actions
571 lines (474 loc) · 14.8 KB
/
Copy pathStdinWrappers.test.ts
File metadata and controls
571 lines (474 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import assert from 'node:assert/strict';
import type { Buffer } from 'node:buffer';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PassThrough } from 'node:stream';
import { test } from 'node:test';
import { InputRecording } from './InputRecording.ts';
import { RecordableStdin, type Session } from './RecordableStdin.ts';
import { ReplayableStdin } from './ReplayableStdin.ts';
async function waitFor(
predicate: () => boolean,
timeoutMs = 250,
): Promise<void>
{
const deadline = Date.now() + timeoutMs;
while (!predicate())
{
if (Date.now() > deadline)
{
throw new Error('Timed out waiting for condition');
}
await new Promise<void>((resolve) => setTimeout(resolve, 5));
}
}
function collectReadableChunks(
stream: RecordableStdin | ReplayableStdin,
sink: string[],
): void
{
stream.on('readable', () =>
{
let chunk = stream.read();
while (chunk !== null)
{
sink.push(chunk.toString());
chunk = stream.read();
}
});
}
test('RecordableStdin supports both data and readable consumers and detaches listeners', () =>
{
const source = new PassThrough();
const first = new RecordableStdin(source);
const second = new RecordableStdin(source);
const dataChunks: string[] = [];
const readableChunks: string[] = [];
first.on('data', (chunk: Buffer | string) =>
{
dataChunks.push(chunk.toString());
});
collectReadableChunks(first, readableChunks);
assert.strictEqual(source.listenerCount('data'), 2);
source.write('hello');
assert.deepStrictEqual(dataChunks, ['hello']);
assert.deepStrictEqual(readableChunks, ['hello']);
const recording = first.getRecording();
assert.strictEqual(recording.length, 1);
assert.strictEqual(typeof recording[0]!.timestamp, 'number');
assert.strictEqual(recording[0]!.data, 'hello');
first.destroy();
assert.strictEqual(source.listenerCount('data'), 1);
second.destroy();
assert.strictEqual(source.listenerCount('data'), 0);
});
test('RecordableStdin.saveSession returns the persisted session payload', async () =>
{
const tempDir = await mkdtemp(join(tmpdir(), 'recordable-stdin-'));
const sessionPath = join(tempDir, 'session.json');
const source = new PassThrough();
const stdin = new RecordableStdin(source);
try
{
source.write('hello');
const session = await stdin.saveSession(sessionPath);
const savedSession = JSON.parse(await readFile(sessionPath, 'utf8')) as Session;
assert.deepStrictEqual(session, savedSession);
assert.strictEqual(session.events.length, 1);
assert.strictEqual(typeof session.events[0]!.timestamp, 'number');
assert.strictEqual(session.events[0]!.data, 'hello');
}
finally
{
stdin.destroy();
await rm(tempDir, { recursive: true, force: true });
}
});
test('RecordableStdin skips persisted chunks while InputRecording is disabled', () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
const dataChunks: string[] = [];
stdin.on('data', (chunk: Buffer | string) =>
{
dataChunks.push(chunk.toString());
});
try
{
source.write('public-1');
InputRecording.prohibit();
source.write('secret');
InputRecording.removeProhibition();
source.write('public-2');
assert.deepStrictEqual(dataChunks, ['public-1', 'secret', 'public-2']);
const recording = stdin.getRecording();
// 3 events: public-1, placeholder (for the prohibited input), public-2
assert.strictEqual(recording.length, 3);
assert.strictEqual(recording[0]!.data, 'public-1');
assert.ok(recording[1]!.data.includes('FIXME'), 'prohibited input should be replaced with a FIXME placeholder');
assert.strictEqual(recording[2]!.data, 'public-2');
}
finally
{
while (InputRecording.disabled)
{
InputRecording.removeProhibition();
}
stdin.destroy();
}
});
test('ReplayableStdin.setRawMode during replay is buffered and applied on switch to interactive', async () =>
{
const tempDir = await mkdtemp(join(tmpdir(), 'replayable-stdin-rawmode-'));
const sessionPath = join(tempDir, 'session.json');
let rawModeValue: boolean | undefined;
const source = Object.assign(new PassThrough(), {
isTTY: true,
setRawMode(mode: boolean)
{
rawModeValue = mode;
},
});
const session: Session = {
version: '1.0',
timestamp: new Date().toISOString(),
events: [{ timestamp: 0, data: 'x' }],
};
try
{
await writeFile(sessionPath, JSON.stringify(session), 'utf-8');
const stdin = await ReplayableStdin.create(sessionPath, source);
// During replay, setRawMode should be buffered, not applied
stdin.setRawMode(true);
assert.strictEqual(rawModeValue, undefined);
stdin.startReplay(0);
await waitFor(() => !stdin.isReplayActive());
// After replay, the buffered raw mode should be applied
assert.strictEqual(rawModeValue, true);
stdin.destroy();
}
finally
{
await rm(tempDir, { recursive: true, force: true });
}
});
test('ReplayableStdin does not force raw mode if setRawMode was never called during replay', async () =>
{
const tempDir = await mkdtemp(join(tmpdir(), 'replayable-stdin-noraw-'));
const sessionPath = join(tempDir, 'session.json');
let rawModeSet = false;
const source = Object.assign(new PassThrough(), {
isTTY: true,
setRawMode(_mode: boolean)
{
rawModeSet = true;
},
});
const session: Session = {
version: '1.0',
timestamp: new Date().toISOString(),
events: [{ timestamp: 0, data: 'x' }],
};
try
{
await writeFile(sessionPath, JSON.stringify(session), 'utf-8');
const stdin = await ReplayableStdin.create(sessionPath, source);
// Never call setRawMode during replay
stdin.startReplay(0);
await waitFor(() => !stdin.isReplayActive());
// Raw mode should NOT have been set
assert.strictEqual(rawModeSet, false);
stdin.destroy();
}
finally
{
await rm(tempDir, { recursive: true, force: true });
}
});
test('ReplayableStdin emits replayed data to both data and readable consumers and detaches listeners', async () =>
{
const tempDir = await mkdtemp(join(tmpdir(), 'replayable-stdin-'));
const sessionPath = join(tempDir, 'session.json');
const source = new PassThrough();
const dataChunks: string[] = [];
const readableChunks: string[] = [];
const session: Session = {
version: '1.0',
timestamp: new Date().toISOString(),
events: [
{ timestamp: 0, data: 'replay' },
],
};
try
{
await writeFile(sessionPath, JSON.stringify(session), 'utf-8');
const stdin = await ReplayableStdin.create(sessionPath, source);
stdin.on('data', (chunk: Buffer | string) =>
{
dataChunks.push(chunk.toString());
});
collectReadableChunks(stdin, readableChunks);
assert.strictEqual(source.listenerCount('data'), 0);
stdin.startReplay(0);
await waitFor(() => !stdin.isReplayActive());
assert.deepStrictEqual(dataChunks, ['replay']);
assert.deepStrictEqual(readableChunks, ['replay']);
assert.strictEqual(source.listenerCount('data'), 1);
source.write('interactive');
assert.deepStrictEqual(dataChunks, ['replay', 'interactive']);
assert.deepStrictEqual(readableChunks, ['replay', 'interactive']);
stdin.destroy();
assert.strictEqual(source.listenerCount('data'), 0);
}
finally
{
await rm(tempDir, { recursive: true, force: true });
}
});
// =============================================================================
// BufferedStdin edge cases
// =============================================================================
test('BufferedStdin.read returns null when buffer is empty', () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
try
{
assert.strictEqual(stdin.read(), null);
}
finally
{
stdin.destroy();
}
});
test('BufferedStdin.read with size returns partial data', () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
try
{
source.write('hello world');
// Read only 5 bytes
const chunk = stdin.read(5);
assert.notStrictEqual(chunk, undefined);
assert.strictEqual(chunk!.toString(), 'hello');
// Remaining data should still be available
const rest = stdin.read();
assert.notStrictEqual(rest, undefined);
assert.strictEqual(rest!.toString(), ' world');
}
finally
{
stdin.destroy();
}
});
test('BufferedStdin.unshift puts data back at front of buffer', () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
try
{
source.write('world');
// Read it
const chunk = stdin.read();
assert.strictEqual(chunk!.toString(), 'world');
// Push it back
stdin.unshift('hello ');
stdin.unshift(chunk!);
// Read both — unshifted items come first
const first = stdin.read();
const second = stdin.read();
assert.strictEqual(first!.toString(), 'world');
assert.strictEqual(second!.toString(), 'hello ');
}
finally
{
stdin.destroy();
}
});
test('BufferedStdin.setEncoding causes read to return strings', () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
try
{
stdin.setEncoding('utf8');
source.write('hello');
const chunk = stdin.read();
assert.strictEqual(typeof chunk, 'string');
assert.strictEqual(chunk, 'hello');
}
finally
{
stdin.destroy();
}
});
test('BufferedStdin.destroy is idempotent', () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
let closeCount = 0;
stdin.on('close', () => closeCount++);
stdin.destroy();
stdin.destroy(); // second destroy should be a no-op
assert.strictEqual(closeCount, 1);
});
test('BufferedStdin.isTTY delegates to source', () =>
{
const source = new PassThrough();
const nonTTY = new RecordableStdin(source);
assert.strictEqual(nonTTY.isTTY, false);
nonTTY.destroy();
const ttySource = Object.assign(new PassThrough(), { isTTY: true });
const ttyStdin = new RecordableStdin(ttySource);
assert.strictEqual(ttyStdin.isTTY, true);
ttyStdin.destroy();
});
// =============================================================================
// RecordableStdin edge cases
// =============================================================================
test('RecordableStdin records multiple events with increasing timestamps', async () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
try
{
source.write('a');
await new Promise<void>((resolve) => setTimeout(resolve, 10));
source.write('b');
const recording = stdin.getRecording();
assert.strictEqual(recording.length, 2);
assert.strictEqual(recording[0]!.data, 'a');
assert.strictEqual(recording[1]!.data, 'b');
assert.ok(recording[1]!.timestamp >= recording[0]!.timestamp);
}
finally
{
stdin.destroy();
}
});
test('RecordableStdin ignores data after destroy', () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
source.write('before');
stdin.destroy();
source.write('after');
assert.strictEqual(stdin.getRecording().length, 1);
assert.strictEqual(stdin.getRecording()[0]!.data, 'before');
});
test('RecordableStdin.getEventCount matches recording length', () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
try
{
assert.strictEqual(stdin.getEventCount(), 0);
source.write('a');
assert.strictEqual(stdin.getEventCount(), 1);
source.write('b');
assert.strictEqual(stdin.getEventCount(), 2);
}
finally
{
stdin.destroy();
}
});
test('RecordableStdin.setRawMode on non-TTY source is a no-op', () =>
{
const source = new PassThrough();
const stdin = new RecordableStdin(source);
try
{
// Should not throw
const result = stdin.setRawMode(true);
assert.strictEqual(result, stdin); // returns this
}
finally
{
stdin.destroy();
}
});
// =============================================================================
// ReplayableStdin edge cases
// =============================================================================
test('ReplayableStdin with empty session immediately switches to interactive', async () =>
{
const tempDir = await mkdtemp(join(tmpdir(), 'replayable-stdin-empty-'));
const sessionPath = join(tempDir, 'session.json');
const source = new PassThrough();
const session: Session = {
version: '1.0',
timestamp: new Date().toISOString(),
events: [],
};
try
{
await writeFile(sessionPath, JSON.stringify(session), 'utf-8');
const stdin = await ReplayableStdin.create(sessionPath, source);
stdin.startReplay(0);
await waitFor(() => !stdin.isReplayActive());
// Should have switched to interactive — source data should flow through
const chunks: string[] = [];
stdin.on('data', (chunk: Buffer | string) => chunks.push(chunk.toString()));
source.write('live');
assert.deepStrictEqual(chunks, ['live']);
stdin.destroy();
}
finally
{
await rm(tempDir, { recursive: true, force: true });
}
});
test('ReplayableStdin.startReplay when destroyed is a no-op', async () =>
{
const tempDir = await mkdtemp(join(tmpdir(), 'replayable-stdin-destroyed-'));
const sessionPath = join(tempDir, 'session.json');
const source = new PassThrough();
const session: Session = {
version: '1.0',
timestamp: new Date().toISOString(),
events: [{ timestamp: 0, data: 'x' }],
};
try
{
await writeFile(sessionPath, JSON.stringify(session), 'utf-8');
const stdin = await ReplayableStdin.create(sessionPath, source);
stdin.destroy();
// Should not throw or emit data
stdin.startReplay(0);
await new Promise<void>((resolve) => setTimeout(resolve, 50));
// If we get here without error, the no-op behavior is correct
assert.strictEqual(stdin.isReplayActive(), true); // still flagged as replaying since switchToInteractive never ran
}
finally
{
await rm(tempDir, { recursive: true, force: true });
}
});
test('ReplayableStdin.isReplayActive returns false after replay completes', async () =>
{
const tempDir = await mkdtemp(join(tmpdir(), 'replayable-stdin-active-'));
const sessionPath = join(tempDir, 'session.json');
const source = new PassThrough();
const session: Session = {
version: '1.0',
timestamp: new Date().toISOString(),
events: [{ timestamp: 0, data: 'x' }],
};
try
{
await writeFile(sessionPath, JSON.stringify(session), 'utf-8');
const stdin = await ReplayableStdin.create(sessionPath, source);
assert.strictEqual(stdin.isReplayActive(), true);
stdin.startReplay(0);
await waitFor(() => !stdin.isReplayActive());
assert.strictEqual(stdin.isReplayActive(), false);
stdin.destroy();
}
finally
{
await rm(tempDir, { recursive: true, force: true });
}
});