@workflow/world-local 5.0.0-beta.10 → 5.0.0-beta.3

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 (74) hide show
  1. package/dist/config.d.ts +17 -5
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +18 -13
  4. package/dist/config.js.map +1 -1
  5. package/dist/fs.d.ts +102 -2
  6. package/dist/fs.d.ts.map +1 -1
  7. package/dist/fs.js +291 -24
  8. package/dist/fs.js.map +1 -1
  9. package/dist/index.d.ts +15 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +82 -5
  12. package/dist/index.js.map +1 -1
  13. package/dist/init.d.ts +91 -0
  14. package/dist/init.d.ts.map +1 -0
  15. package/dist/init.js +268 -0
  16. package/dist/init.js.map +1 -0
  17. package/dist/instrumentObject.d.ts +8 -0
  18. package/dist/instrumentObject.d.ts.map +1 -0
  19. package/dist/instrumentObject.js +66 -0
  20. package/dist/instrumentObject.js.map +1 -0
  21. package/dist/queue.d.ts +8 -1
  22. package/dist/queue.d.ts.map +1 -1
  23. package/dist/queue.js +164 -53
  24. package/dist/queue.js.map +1 -1
  25. package/dist/storage/events-storage.d.ts +7 -0
  26. package/dist/storage/events-storage.d.ts.map +1 -0
  27. package/dist/storage/events-storage.js +760 -0
  28. package/dist/storage/events-storage.js.map +1 -0
  29. package/dist/storage/filters.d.ts +22 -0
  30. package/dist/storage/filters.d.ts.map +1 -0
  31. package/dist/storage/filters.js +33 -0
  32. package/dist/storage/filters.js.map +1 -0
  33. package/dist/storage/helpers.d.ts +18 -0
  34. package/dist/storage/helpers.d.ts.map +1 -0
  35. package/dist/storage/helpers.js +44 -0
  36. package/dist/storage/helpers.js.map +1 -0
  37. package/dist/storage/hooks-storage.d.ts +12 -0
  38. package/dist/storage/hooks-storage.d.ts.map +1 -0
  39. package/dist/storage/hooks-storage.js +93 -0
  40. package/dist/storage/hooks-storage.js.map +1 -0
  41. package/dist/storage/index.d.ts +12 -0
  42. package/dist/storage/index.d.ts.map +1 -0
  43. package/dist/storage/index.js +32 -0
  44. package/dist/storage/index.js.map +1 -0
  45. package/dist/storage/legacy.d.ts +13 -0
  46. package/dist/storage/legacy.d.ts.map +1 -0
  47. package/dist/storage/legacy.js +77 -0
  48. package/dist/storage/legacy.js.map +1 -0
  49. package/dist/storage/runs-storage.d.ts +7 -0
  50. package/dist/storage/runs-storage.d.ts.map +1 -0
  51. package/dist/storage/runs-storage.js +59 -0
  52. package/dist/storage/runs-storage.js.map +1 -0
  53. package/dist/storage/steps-storage.d.ts +7 -0
  54. package/dist/storage/steps-storage.d.ts.map +1 -0
  55. package/dist/storage/steps-storage.js +52 -0
  56. package/dist/storage/steps-storage.js.map +1 -0
  57. package/dist/storage.d.ts +9 -2
  58. package/dist/storage.d.ts.map +1 -1
  59. package/dist/storage.js +8 -455
  60. package/dist/storage.js.map +1 -1
  61. package/dist/streamer.d.ts +4 -2
  62. package/dist/streamer.d.ts.map +1 -1
  63. package/dist/streamer.js +456 -104
  64. package/dist/streamer.js.map +1 -1
  65. package/dist/telemetry.d.ts +28 -0
  66. package/dist/telemetry.d.ts.map +1 -0
  67. package/dist/telemetry.js +71 -0
  68. package/dist/telemetry.js.map +1 -0
  69. package/dist/test-helpers.d.ts +54 -0
  70. package/dist/test-helpers.d.ts.map +1 -0
  71. package/dist/test-helpers.js +118 -0
  72. package/dist/test-helpers.js.map +1 -0
  73. package/dist/util.js.map +1 -1
  74. package/package.json +12 -11
package/dist/streamer.js CHANGED
@@ -1,130 +1,482 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import path from 'node:path';
3
3
  import { monotonicFactory } from 'ulid';
4
- import { listJSONFiles, readBuffer, write } from './fs.js';
4
+ import { z } from 'zod';
5
+ import { assertSafeEntityId, listFilesByExtension, readBuffer, readJSONWithFallback, taggedPath, write, writeJSON, } from './fs.js';
5
6
  // Create a monotonic ULID factory that ensures ULIDs are always increasing
6
7
  // even when generated within the same millisecond
7
8
  const monotonicUlid = monotonicFactory(() => Math.random());
9
+ // Schema for the run-to-streams mapping file
10
+ const RunStreamsSchema = z.object({
11
+ streams: z.array(z.string()),
12
+ });
8
13
  export function serializeChunk(chunk) {
9
14
  const eofByte = Buffer.from([chunk.eof ? 1 : 0]);
10
15
  return Buffer.concat([eofByte, chunk.chunk]);
11
16
  }
17
+ /** Check only the EOF flag byte without copying chunk payload. */
18
+ export function isEofChunk(serialized) {
19
+ return serialized[0] === 1;
20
+ }
12
21
  export function deserializeChunk(serialized) {
13
22
  const eof = serialized[0] === 1;
14
- const chunk = serialized.subarray(1);
23
+ // Create a copy instead of a view to prevent ArrayBuffer detachment
24
+ const chunk = Buffer.from(serialized.subarray(1));
15
25
  return { eof, chunk };
16
26
  }
17
- export function createStreamer(basedir) {
27
+ /**
28
+ * List chunk files for a stream, sorted chronologically (ULID order).
29
+ * Returns both the sorted file names and a map of file → extension for
30
+ * resolving the full path. Handles tagged and legacy (.json) formats.
31
+ */
32
+ async function listChunkFilesForStream(chunksDir, name, tag) {
33
+ // Name is used as a filename prefix below; validate it can't escape chunksDir.
34
+ assertSafeEntityId('streamName', name);
35
+ const listPromises = [
36
+ listFilesByExtension(chunksDir, '.bin'),
37
+ listFilesByExtension(chunksDir, '.json'),
38
+ ];
39
+ if (tag) {
40
+ listPromises.push(listFilesByExtension(chunksDir, `.${tag}.bin`));
41
+ }
42
+ const [binFiles, jsonFiles, ...taggedResults] = await Promise.all(listPromises);
43
+ const taggedBinFiles = taggedResults[0] ?? [];
44
+ const extMap = new Map();
45
+ for (const f of jsonFiles)
46
+ extMap.set(f, '.json');
47
+ const tagSfx = tag ? `.${tag}` : '';
48
+ for (const f of binFiles) {
49
+ if (tag && f.endsWith(tagSfx))
50
+ continue;
51
+ extMap.set(f, '.bin');
52
+ }
53
+ for (const f of taggedBinFiles)
54
+ extMap.set(f, `.${tag}.bin`);
55
+ const files = [...extMap.keys()]
56
+ .filter((file) => file.startsWith(`${name}-`))
57
+ .sort();
58
+ return { files, extMap };
59
+ }
60
+ export function createStreamer(basedir, tag) {
61
+ const tagSuffix = tag ? `.${tag}` : '';
18
62
  const streamEmitter = new EventEmitter();
63
+ // Track which streams have already been registered for a run (in-memory cache)
64
+ const registeredStreams = new Set();
65
+ // Helper to record the runId <> streamId association
66
+ async function registerStreamForRun(runId, streamName) {
67
+ assertSafeEntityId('runId', runId);
68
+ assertSafeEntityId('streamName', streamName);
69
+ const cacheKey = `${runId}:${streamName}`;
70
+ if (registeredStreams.has(cacheKey)) {
71
+ return; // Already registered in this session
72
+ }
73
+ const runStreamsPath = taggedPath(basedir, 'streams/runs', runId, tag);
74
+ // Read existing streams for this run (try tagged first, fall back to untagged)
75
+ const existing = await readJSONWithFallback(basedir, 'streams/runs', runId, RunStreamsSchema, tag);
76
+ const streams = existing?.streams ?? [];
77
+ // Add stream if not already present
78
+ if (!streams.includes(streamName)) {
79
+ streams.push(streamName);
80
+ await writeJSON(runStreamsPath, { streams }, { overwrite: true });
81
+ }
82
+ registeredStreams.add(cacheKey);
83
+ }
84
+ // Helper to convert a chunk to a Buffer
85
+ function toBuffer(chunk) {
86
+ if (typeof chunk === 'string') {
87
+ return Buffer.from(new TextEncoder().encode(chunk));
88
+ }
89
+ else if (chunk instanceof Buffer) {
90
+ return chunk;
91
+ }
92
+ else {
93
+ return Buffer.from(chunk);
94
+ }
95
+ }
19
96
  return {
20
- async writeToStream(name, _runId, chunk) {
21
- // Await runId if it's a promise to ensure proper flushing
22
- await _runId;
23
- const chunkId = `strm_${monotonicUlid()}`;
24
- if (typeof chunk === 'string') {
25
- chunk = new TextEncoder().encode(chunk);
26
- }
27
- const serialized = serializeChunk({
28
- chunk: Buffer.from(chunk),
29
- eof: false,
30
- });
31
- const chunkPath = path.join(basedir, 'streams', 'chunks', `${name}-${chunkId}.json`);
32
- await write(chunkPath, serialized);
33
- // Emit real-time event
34
- const chunkData = typeof chunk === 'string'
35
- ? new TextEncoder().encode(chunk)
36
- : chunk instanceof Buffer
37
- ? new Uint8Array(chunk)
38
- : chunk;
39
- streamEmitter.emit(`chunk:${name}`, {
40
- streamName: name,
41
- chunkData,
42
- chunkId,
43
- });
44
- },
45
- async closeStream(name, _runId) {
46
- // Await runId if it's a promise to ensure proper flushing
47
- await _runId;
48
- const chunkId = `strm_${monotonicUlid()}`;
49
- const chunkPath = path.join(basedir, 'streams', 'chunks', `${name}-${chunkId}.json`);
50
- await write(chunkPath, serializeChunk({ chunk: Buffer.from([]), eof: true }));
51
- streamEmitter.emit(`close:${name}`, { streamName: name });
52
- },
53
- async readFromStream(name, startIndex = 0) {
54
- const chunksDir = path.join(basedir, 'streams', 'chunks');
55
- let removeListeners = () => { };
56
- return new ReadableStream({
57
- async start(controller) {
58
- // Track chunks delivered via events to prevent duplicates and maintain order.
59
- const deliveredChunkIds = new Set();
60
- // Buffer for chunks that arrive via events during disk reading
61
- const bufferedEventChunks = [];
62
- let isReadingFromDisk = true;
63
- const chunkListener = (event) => {
64
- deliveredChunkIds.add(event.chunkId);
65
- if (isReadingFromDisk) {
66
- // Buffer chunks that arrive during disk reading to maintain order
67
- bufferedEventChunks.push({
68
- chunkId: event.chunkId,
69
- chunkData: event.chunkData,
70
- });
71
- }
72
- else {
73
- // After disk reading is complete, deliver chunks immediately
74
- controller.enqueue(event.chunkData);
75
- }
76
- };
77
- const closeListener = () => {
78
- // Remove listeners before closing
79
- streamEmitter.off(`chunk:${name}`, chunkListener);
80
- streamEmitter.off(`close:${name}`, closeListener);
81
- controller.close();
97
+ streams: {
98
+ async write(_runId, name, chunk) {
99
+ // Generate ULID synchronously BEFORE any await to preserve call order.
100
+ // This ensures that chunks written in sequence maintain their order even
101
+ // when runId is a promise that multiple writes are waiting on.
102
+ const chunkId = `chnk_${monotonicUlid()}`;
103
+ // Await runId if it's a promise to ensure proper flushing
104
+ const runId = await _runId;
105
+ // Register this stream for the run
106
+ await registerStreamForRun(runId, name);
107
+ // Convert chunk to buffer for serialization
108
+ const chunkBuffer = toBuffer(chunk);
109
+ const serialized = serializeChunk({
110
+ chunk: chunkBuffer,
111
+ eof: false,
112
+ });
113
+ const chunkPath = path.join(basedir, 'streams', 'chunks', `${name}-${chunkId}${tagSuffix}.bin`);
114
+ await write(chunkPath, serialized);
115
+ // Emit real-time event with Uint8Array (create copy to prevent ArrayBuffer detachment)
116
+ const chunkData = Uint8Array.from(chunkBuffer);
117
+ streamEmitter.emit(`chunk:${name}`, {
118
+ streamName: name,
119
+ chunkData,
120
+ chunkId,
121
+ });
122
+ },
123
+ async writeMulti(_runId, name, chunks) {
124
+ if (chunks.length === 0)
125
+ return;
126
+ // Generate all ULIDs synchronously BEFORE any await to preserve call order.
127
+ // This ensures that chunks maintain their order even when runId is a promise.
128
+ const chunkIds = chunks.map(() => `chnk_${monotonicUlid()}`);
129
+ // Await runId if it's a promise
130
+ const runId = await _runId;
131
+ // Register this stream for the run
132
+ await registerStreamForRun(runId, name);
133
+ // Prepare chunk data for parallel writes
134
+ const chunkBuffers = chunks.map((chunk) => toBuffer(chunk));
135
+ // Write all chunks in parallel for efficiency, but track individual completion
136
+ const writePromises = chunkBuffers.map(async (chunkBuffer, i) => {
137
+ const chunkId = chunkIds[i];
138
+ const serialized = serializeChunk({
139
+ chunk: chunkBuffer,
140
+ eof: false,
141
+ });
142
+ const chunkPath = path.join(basedir, 'streams', 'chunks', `${name}-${chunkId}${tagSuffix}.bin`);
143
+ await write(chunkPath, serialized);
144
+ // Return data needed for event emission
145
+ return {
146
+ chunkId,
147
+ chunkData: Uint8Array.from(chunkBuffer),
82
148
  };
83
- removeListeners = closeListener;
84
- // Set up listeners FIRST to avoid missing events
85
- streamEmitter.on(`chunk:${name}`, chunkListener);
86
- streamEmitter.on(`close:${name}`, closeListener);
87
- // Now load existing chunks from disk
88
- const files = await listJSONFiles(chunksDir);
89
- const chunkFiles = files
90
- .filter((file) => file.startsWith(`${name}-`))
91
- .sort(); // ULID lexicographic sort = chronological order
92
- // Process existing chunks, skipping any already delivered via events
93
- let isComplete = false;
94
- for (let i = startIndex; i < chunkFiles.length; i++) {
95
- const file = chunkFiles[i];
96
- // Extract chunk ID from filename: "streamName-chunkId"
97
- const chunkId = file.substring(name.length + 1);
98
- // Skip if already delivered via event
99
- if (deliveredChunkIds.has(chunkId)) {
100
- continue;
101
- }
102
- const chunk = deserializeChunk(await readBuffer(path.join(chunksDir, `${file}.json`)));
103
- if (chunk?.eof === true) {
104
- isComplete = true;
149
+ });
150
+ // Emit events in order, waiting for each chunk's write to complete
151
+ // This ensures events are emitted in order while writes happen in parallel
152
+ for (const writePromise of writePromises) {
153
+ const { chunkId, chunkData } = await writePromise;
154
+ streamEmitter.emit(`chunk:${name}`, {
155
+ streamName: name,
156
+ chunkData,
157
+ chunkId,
158
+ });
159
+ }
160
+ },
161
+ async close(_runId, name) {
162
+ // Generate ULID synchronously BEFORE any await to preserve call order.
163
+ const chunkId = `chnk_${monotonicUlid()}`;
164
+ // Await runId if it's a promise to ensure proper flushing
165
+ const runId = await _runId;
166
+ // Register this stream for the run (in case write wasn't called)
167
+ await registerStreamForRun(runId, name);
168
+ const chunkPath = path.join(basedir, 'streams', 'chunks', `${name}-${chunkId}${tagSuffix}.bin`);
169
+ await write(chunkPath, serializeChunk({ chunk: Buffer.from([]), eof: true }));
170
+ streamEmitter.emit(`close:${name}`, { streamName: name });
171
+ },
172
+ async list(runId) {
173
+ assertSafeEntityId('runId', runId);
174
+ const data = await readJSONWithFallback(basedir, 'streams/runs', runId, RunStreamsSchema, tag);
175
+ return data?.streams ?? [];
176
+ },
177
+ async getChunks(_runId, name, options) {
178
+ const limit = options?.limit ?? 100;
179
+ const chunksDir = path.join(basedir, 'streams', 'chunks');
180
+ const { files: chunkFiles, extMap: fileExtMap } = await listChunkFilesForStream(chunksDir, name, tag);
181
+ // Decode cursor
182
+ let startIndex = 0;
183
+ if (options?.cursor) {
184
+ try {
185
+ const decoded = JSON.parse(Buffer.from(options.cursor, 'base64').toString('utf-8'));
186
+ startIndex = decoded.i;
187
+ }
188
+ catch {
189
+ startIndex = 0;
190
+ }
191
+ }
192
+ // Walk from startIndex, reading only the files we need.
193
+ // Files before the cursor are skipped entirely.
194
+ let streamDone = false;
195
+ const resultChunks = [];
196
+ let dataIndex = 0; // running count of data (non-EOF) files seen
197
+ for (const file of chunkFiles) {
198
+ const ext = fileExtMap.get(file) ?? '.bin';
199
+ const filePath = path.join(chunksDir, `${file}${ext}`);
200
+ // Before the cursor: only need to check EOF (1 byte), skip content
201
+ if (dataIndex < startIndex) {
202
+ if (isEofChunk(await readBuffer(filePath))) {
203
+ streamDone = true;
105
204
  break;
106
205
  }
107
- if (chunk.chunk.byteLength) {
108
- controller.enqueue(chunk.chunk);
206
+ dataIndex++;
207
+ continue;
208
+ }
209
+ // Collected enough data chunks — peek at the next file for EOF/hasMore
210
+ if (resultChunks.length >= limit) {
211
+ if (isEofChunk(await readBuffer(filePath))) {
212
+ streamDone = true;
109
213
  }
214
+ else {
215
+ // More data files exist beyond this page
216
+ dataIndex++;
217
+ }
218
+ break;
110
219
  }
111
- // Finished reading from disk - now deliver buffered event chunks in chronological order
112
- isReadingFromDisk = false;
113
- // Sort buffered chunks by ULID (chronological order)
114
- bufferedEventChunks.sort((a, b) => a.chunkId.localeCompare(b.chunkId));
115
- for (const buffered of bufferedEventChunks) {
116
- controller.enqueue(buffered.chunkData);
220
+ // In the page window: deserialize fully
221
+ const chunk = deserializeChunk(await readBuffer(filePath));
222
+ if (chunk.eof) {
223
+ streamDone = true;
224
+ break;
117
225
  }
118
- if (isComplete) {
119
- removeListeners();
120
- controller.close();
121
- return;
226
+ resultChunks.push({
227
+ index: dataIndex,
228
+ data: Uint8Array.from(chunk.chunk),
229
+ });
230
+ dataIndex++;
231
+ }
232
+ // hasMore = we know there are data files beyond this page
233
+ const hasMore = !streamDone && dataIndex > startIndex + resultChunks.length;
234
+ const nextIndex = startIndex + resultChunks.length;
235
+ const nextCursor = hasMore
236
+ ? Buffer.from(JSON.stringify({ i: nextIndex })).toString('base64')
237
+ : null;
238
+ return {
239
+ data: resultChunks,
240
+ cursor: nextCursor,
241
+ hasMore,
242
+ done: streamDone,
243
+ };
244
+ },
245
+ async getInfo(_runId, name) {
246
+ const chunksDir = path.join(basedir, 'streams', 'chunks');
247
+ const { files: chunkFiles, extMap: fileExtMap } = await listChunkFilesForStream(chunksDir, name, tag);
248
+ // Only read the first byte of each file to check EOF — no full
249
+ // deserialization needed since we just need a count.
250
+ let streamDone = false;
251
+ let dataCount = 0;
252
+ for (const file of chunkFiles) {
253
+ const ext = fileExtMap.get(file) ?? '.bin';
254
+ if (isEofChunk(await readBuffer(path.join(chunksDir, `${file}${ext}`)))) {
255
+ streamDone = true;
256
+ break;
122
257
  }
123
- },
124
- cancel() {
125
- removeListeners();
126
- },
127
- });
258
+ dataCount++;
259
+ }
260
+ return { tailIndex: dataCount - 1, done: streamDone };
261
+ },
262
+ async get(_runId, name, startIndex = 0) {
263
+ const chunksDir = path.join(basedir, 'streams', 'chunks');
264
+ let removeListeners = () => { };
265
+ let pollInterval = null;
266
+ return new ReadableStream({
267
+ async start(controller) {
268
+ // Track chunks delivered via events to prevent duplicates and maintain order.
269
+ const deliveredChunkIds = new Set();
270
+ // Buffer for chunks that arrive via events during disk reading
271
+ const bufferedEventChunks = [];
272
+ let isReadingFromDisk = true;
273
+ // Buffer close event if it arrives during disk reading
274
+ let pendingClose = false;
275
+ // Set when the controller is closed; guards against enqueue-after-close
276
+ // in the polling callback when closeListener fires mid-iteration.
277
+ let streamClosed = false;
278
+ const chunkListener = (event) => {
279
+ // Skip empty chunks to maintain consistency with disk reading behavior
280
+ if (event.chunkData.byteLength === 0) {
281
+ deliveredChunkIds.add(event.chunkId);
282
+ return;
283
+ }
284
+ if (isReadingFromDisk) {
285
+ deliveredChunkIds.add(event.chunkId);
286
+ // Buffer chunks that arrive during disk reading to maintain order
287
+ // Create a copy to prevent ArrayBuffer detachment when enqueued later
288
+ bufferedEventChunks.push({
289
+ chunkId: event.chunkId,
290
+ chunkData: Uint8Array.from(event.chunkData),
291
+ });
292
+ }
293
+ else if (!deliveredChunkIds.has(event.chunkId)) {
294
+ // Guard against duplicates: polling may have already claimed this
295
+ // chunk between its has() check and readBuffer() yield.
296
+ deliveredChunkIds.add(event.chunkId);
297
+ // After disk reading is complete, deliver chunks immediately
298
+ // Create a copy to prevent ArrayBuffer detachment
299
+ controller.enqueue(Uint8Array.from(event.chunkData));
300
+ }
301
+ };
302
+ const closeListener = () => {
303
+ // Buffer close event if disk reading is still in progress
304
+ if (isReadingFromDisk) {
305
+ pendingClose = true;
306
+ return;
307
+ }
308
+ // Remove listeners before closing
309
+ streamClosed = true;
310
+ streamEmitter.off(`chunk:${name}`, chunkListener);
311
+ streamEmitter.off(`close:${name}`, closeListener);
312
+ if (pollInterval) {
313
+ clearInterval(pollInterval);
314
+ pollInterval = null;
315
+ }
316
+ try {
317
+ controller.close();
318
+ }
319
+ catch {
320
+ // Ignore if controller is already closed (e.g., from cancel() or EOF)
321
+ }
322
+ };
323
+ removeListeners = closeListener;
324
+ // Set up listeners FIRST to avoid missing events
325
+ streamEmitter.on(`chunk:${name}`, chunkListener);
326
+ streamEmitter.on(`close:${name}`, closeListener);
327
+ // Now load existing chunks from disk.
328
+ const { files: chunkFiles, extMap: fileExtMap } = await listChunkFilesForStream(chunksDir, name, tag);
329
+ // Resolve negative startIndex relative to the number of data chunks
330
+ // (excluding the trailing EOF marker chunk, if present).
331
+ let dataChunkCount = chunkFiles.length;
332
+ if (typeof startIndex === 'number' &&
333
+ startIndex < 0 &&
334
+ chunkFiles.length > 0) {
335
+ const lastFile = chunkFiles[chunkFiles.length - 1];
336
+ const lastExt = fileExtMap.get(lastFile) ?? '.bin';
337
+ // Note: this incurs an extra disk read to check the EOF marker.
338
+ // Acceptable since negative startIndex is not a hot path.
339
+ const lastChunk = deserializeChunk(await readBuffer(path.join(chunksDir, `${lastFile}${lastExt}`)));
340
+ if (lastChunk?.eof === true) {
341
+ dataChunkCount--;
342
+ }
343
+ }
344
+ const resolvedStartIndex = typeof startIndex === 'number' && startIndex < 0
345
+ ? Math.max(0, dataChunkCount + startIndex)
346
+ : startIndex;
347
+ // Process existing chunks, skipping any already delivered via events
348
+ let isComplete = false;
349
+ for (let i = resolvedStartIndex; i < chunkFiles.length; i++) {
350
+ const file = chunkFiles[i];
351
+ // Extract chunk ID from filename: "streamName-chunkId" or "streamName-chunkId.tag"
352
+ const rawChunkId = file.substring(name.length + 1);
353
+ // Strip tag suffix (e.g., "chnk_ULID.vitest-0" → "chnk_ULID")
354
+ const chunkId = tag
355
+ ? rawChunkId.replace(`.${tag}`, '')
356
+ : rawChunkId;
357
+ // Skip if already delivered via event
358
+ if (deliveredChunkIds.has(chunkId)) {
359
+ continue;
360
+ }
361
+ const ext = fileExtMap.get(file) ?? '.bin';
362
+ const chunk = deserializeChunk(await readBuffer(path.join(chunksDir, `${file}${ext}`)));
363
+ if (chunk?.eof === true) {
364
+ isComplete = true;
365
+ break;
366
+ }
367
+ // Track as handled so polling doesn't re-deliver
368
+ deliveredChunkIds.add(chunkId);
369
+ if (chunk.chunk.byteLength) {
370
+ // Create a copy to prevent ArrayBuffer detachment
371
+ controller.enqueue(Uint8Array.from(chunk.chunk));
372
+ }
373
+ }
374
+ // Finished reading from disk - now deliver buffered event chunks in chronological order
375
+ isReadingFromDisk = false;
376
+ // Sort buffered chunks by ULID (chronological order)
377
+ bufferedEventChunks.sort((a, b) => a.chunkId.localeCompare(b.chunkId));
378
+ for (const buffered of bufferedEventChunks) {
379
+ // Create a copy for defense in depth (already copied at storage, but be extra safe)
380
+ controller.enqueue(Uint8Array.from(buffered.chunkData));
381
+ }
382
+ if (isComplete) {
383
+ removeListeners();
384
+ try {
385
+ controller.close();
386
+ }
387
+ catch {
388
+ // Ignore if controller is already closed (e.g., from closeListener event)
389
+ }
390
+ return;
391
+ }
392
+ // Process any pending close event that arrived during disk reading
393
+ if (pendingClose) {
394
+ streamEmitter.off(`chunk:${name}`, chunkListener);
395
+ streamEmitter.off(`close:${name}`, closeListener);
396
+ try {
397
+ controller.close();
398
+ }
399
+ catch {
400
+ // Ignore if controller is already closed
401
+ }
402
+ return;
403
+ }
404
+ // Track pre-startIndex chunks so polling doesn't re-deliver them
405
+ for (let i = 0; i < resolvedStartIndex && i < chunkFiles.length; i++) {
406
+ const file = chunkFiles[i];
407
+ const rawChunkId = file.substring(name.length + 1);
408
+ const chunkId = tag
409
+ ? rawChunkId.replace(`.${tag}`, '')
410
+ : rawChunkId;
411
+ deliveredChunkIds.add(chunkId);
412
+ }
413
+ // Start filesystem polling for cross-process streaming support.
414
+ // The EventEmitter only works in-process; when the writer is in a
415
+ // separate process (e.g. e2e test runner ↔ workbench app), polling
416
+ // the shared filesystem is the fallback delivery mechanism.
417
+ let isPolling = false;
418
+ pollInterval = setInterval(async () => {
419
+ if (isPolling)
420
+ return;
421
+ isPolling = true;
422
+ try {
423
+ const { files: currentFiles, extMap: currentExtMap } = await listChunkFilesForStream(chunksDir, name, tag);
424
+ for (const file of currentFiles) {
425
+ const rawChunkId = file.substring(name.length + 1);
426
+ const chunkId = tag
427
+ ? rawChunkId.replace(`.${tag}`, '')
428
+ : rawChunkId;
429
+ if (deliveredChunkIds.has(chunkId))
430
+ continue;
431
+ deliveredChunkIds.add(chunkId);
432
+ const ext = currentExtMap.get(file) ?? '.bin';
433
+ const chunk = deserializeChunk(await readBuffer(path.join(chunksDir, `${file}${ext}`)));
434
+ if (chunk?.eof === true) {
435
+ streamClosed = true;
436
+ if (pollInterval) {
437
+ clearInterval(pollInterval);
438
+ pollInterval = null;
439
+ }
440
+ streamEmitter.off(`chunk:${name}`, chunkListener);
441
+ streamEmitter.off(`close:${name}`, closeListener);
442
+ try {
443
+ controller.close();
444
+ }
445
+ catch {
446
+ // Ignore if controller is already closed
447
+ }
448
+ return;
449
+ }
450
+ // Guard against enqueue-after-close: closeListener may have
451
+ // fired between our readBuffer() yield and this point.
452
+ if (streamClosed)
453
+ return;
454
+ if (chunk.chunk.byteLength) {
455
+ controller.enqueue(Uint8Array.from(chunk.chunk));
456
+ }
457
+ }
458
+ }
459
+ catch (err) {
460
+ // Silently ignore transient filesystem errors (ENOENT, EACCES, etc.)
461
+ // Surface unexpected errors so bugs aren't hidden
462
+ if (!(err instanceof Error && 'code' in err)) {
463
+ console.error('[world-local] Unexpected polling error:', err);
464
+ }
465
+ }
466
+ finally {
467
+ isPolling = false;
468
+ }
469
+ }, 100);
470
+ },
471
+ cancel() {
472
+ removeListeners();
473
+ if (pollInterval) {
474
+ clearInterval(pollInterval);
475
+ pollInterval = null;
476
+ }
477
+ },
478
+ });
479
+ },
128
480
  },
129
481
  };
130
482
  }