-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathparse.test.ts
More file actions
580 lines (497 loc) · 19.6 KB
/
Copy pathparse.test.ts
File metadata and controls
580 lines (497 loc) · 19.6 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
572
573
574
575
576
577
578
579
580
import {expect, test, vi} from 'vitest'
import {ParseError} from '../src/errors.ts'
import {createParser} from '../src/parse.ts'
import {
getBasicFixtureStream,
getCarriageReturnFixtureStream,
getCarriageReturnLineFeedFixtureStream,
getCommentsFixtureStream,
getDataFieldParsingFixtureStream,
getEmptyEventsFixtureStream,
getEmptyRetryFixtureStream,
getHeartbeatsFixtureStream,
getHugeMessageFixtureStream,
getIdentifiedFixtureStream,
getInvalidBomFixtureStream,
getInvalidRetryFixtureStream,
getLeadingBomFixtureStream,
getLineFeedFixtureStream,
getMixedCommentsFixtureStream,
getMultiBomFixtureStream,
getMultibyteEmptyLineFixtureStream,
getMultibyteFixtureStream,
getMultilineFixtureStream,
getTimeFixtureStream,
getTimeFixtureStreamChunked,
getUnknownFieldsFixtureStream,
} from './fixtures.ts'
import {getParseResultMock} from './mock.ts'
import {expectedMultiByteEvents} from './multibyte.ts'
test('basic unnamed events stream', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getBasicFixtureStream(parser.feed)
mock.expectNumberOfMessagesToBe(6)
mock.expectNextMessage({data: '0', event: undefined, id: undefined})
mock.expectNextMessage({data: '1'})
mock.expectNextMessage({data: '2'})
mock.expectNextMessage({data: '3'})
mock.expectNextMessage({data: '4'})
mock.expectNextMessage({event: 'done', data: '✔'})
})
test('stream of `time` event name', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getTimeFixtureStream(parser.feed)
mock.expectNumberOfMessagesToBe(6)
mock.expectNextMessage({event: 'time', data: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/})
})
test('stream of `time` event names, unbalanced chunks', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getTimeFixtureStreamChunked(parser.feed)
while (mock.hasNextMessage()) {
mock.expectNextMessage({event: 'time', data: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/})
}
})
test('stream of identified messanges + retry interval', async () => {
const mock = getParseResultMock()
const parser = createParser(mock.callbacks)
await getIdentifiedFixtureStream(1337, parser.feed)
expect(mock.events[0]).toMatchObject({type: 'reconnect-interval', value: 50})
expect(mock.events[1]).toMatchObject({type: 'event', id: '1337', event: 'tick', data: '1337'})
expect(mock.events[2]).toMatchObject({type: 'reconnect-interval', value: 50})
expect(mock.events[3]).toMatchObject({type: 'event', id: '1338', event: 'tick', data: '1338'})
})
test('stream of "heartbeat" comments, unnamed events', async () => {
const onComment = vi.fn()
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse, onComment})
await getHeartbeatsFixtureStream(parser.feed)
for (let char = 65; char < 70; char++) {
mock.expectNextMessage({data: String.fromCharCode(char)})
}
mock.expectNextMessage({event: 'done', data: '✔'})
expect(onComment).toHaveBeenCalledTimes(5)
expect(onComment).toHaveBeenLastCalledWith(' ♥')
})
test('stream of multi-line data events', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getMultilineFixtureStream(parser.feed)
mock.expectNextMessage({
id: undefined,
event: 'stock',
data: 'YHOO\n+2\n10',
})
mock.expectNextMessage({
id: undefined,
event: 'stock',
data: 'GOOG\n-8\n1881',
})
})
test('stream of multi-byte events', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getMultibyteFixtureStream(parser.feed)
for (let i = 0; i < mock.events.length; i++) {
expect(mock.events[i]).toStrictEqual(expectedMultiByteEvents[i])
}
})
test('stream of multi-byte events with some empty lines thrown in', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getMultibyteEmptyLineFixtureStream(parser.feed)
mock.expectNextMessage({data: '我現在都看實況不玩遊戲'})
mock.expectNextMessage({event: 'done'})
})
test('stream of leading bom', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getLeadingBomFixtureStream(parser.feed)
mock.expectNextMessage({data: 'bomful 1'})
mock.expectNextMessage({data: 'bomless 2'})
mock.expectNextMessage({event: 'done'})
})
test('stream containing (invalid?) byte-order mark (multiple places)', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getInvalidBomFixtureStream(parser.feed)
mock.expectNextMessage({data: 'bomless 3'})
mock.expectNextMessage({event: 'done'})
})
test('stream containing byte-order mark (multiple places)', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getMultiBomFixtureStream(parser.feed)
mock.expectNextMessage({data: 'bomful 1'})
mock.expectNextMessage({data: 'bomless 3'})
mock.expectNextMessage({event: 'done'})
})
test('stream using carriage returns', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getCarriageReturnFixtureStream(parser.feed)
mock.expectNextMessage({data: 'dog\nbark'})
mock.expectNextMessage({data: 'cat\nmeow'})
mock.expectNextMessage({event: 'done'})
})
test('stream using line feeds', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getLineFeedFixtureStream(parser.feed)
mock.expectNextMessage({data: 'cow\nmoo'})
mock.expectNextMessage({data: 'horse\nneigh'})
mock.expectNextMessage({event: 'done'})
})
test('stream using carriage returns and line feeds', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getCarriageReturnLineFeedFixtureStream(parser.feed)
mock.expectNextMessage({data: 'sheep\nbleat'})
mock.expectNextMessage({data: 'pig\noink'})
mock.expectNextMessage({event: 'done'})
})
test('stream with varying odd uses of comments', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getCommentsFixtureStream(parser.feed)
mock.expectNextMessage({data: 'First'})
mock.expectNextMessage({data: 'Second'})
mock.expectNextMessage({data: 'Third'})
mock.expectNextMessage({data: 'Fourth'})
mock.expectNextMessage({data: 'Fifth'})
mock.expectNextMessage({data: '✔'})
})
test('stream with even more odd uses of comments', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getMixedCommentsFixtureStream(parser.feed)
mock.expectNextMessage({data: '1'})
mock.expectNextMessage({data: '2'})
mock.expectNextMessage({data: '3'})
mock.expectNextMessage({data: '4'})
// No newline after the last message, thus not emitted
})
test('stream with empty `event` field', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getEmptyEventsFixtureStream(parser.feed)
mock.expectNextMessage({data: 'Hello 1', event: undefined})
mock.expectNextMessage({data: '✔', event: 'done'})
})
test('stream with empty `retry` field', async () => {
const mock = getParseResultMock()
const parser = createParser(mock.callbacks)
await getEmptyRetryFixtureStream(0, parser.feed)
await getEmptyRetryFixtureStream(1, parser.feed)
await getEmptyRetryFixtureStream(2, parser.feed)
expect(mock.events[0]).toMatchObject({
type: 'reconnect-interval',
value: 500,
})
expect(mock.events[1]).toMatchObject({
data: '🥌',
event: undefined,
id: '1',
type: 'event',
})
expect(mock.events[2]).toMatchObject({
type: 'error',
error: expect.any(Error),
message: 'Invalid `retry` value: ""',
})
expect(mock.events[3]).toMatchObject({
data: '🧹',
event: undefined,
id: '2',
type: 'event',
})
expect(mock.events[4]).toMatchObject({
data: '✅',
event: undefined,
id: '3',
type: 'event',
})
})
test('stream with oddly shaped data field', async () => {
const mock = getParseResultMock()
const parser = createParser(mock.callbacks)
await getDataFieldParsingFixtureStream(parser.feed)
// `data:\n\n` - data field contains only a newline character, spec says:
// > If the data buffer is an empty string, set the data buffer and the event type
// > buffer to the empty string and return.
// As we have a newline character, the data buffer is _not_, in fact, empty.
// The spec continues:
// > If the data buffer's last character is a U+000A LINE FEED (LF) character,
// > then remove the last character from the data buffer.
// As the data buffer only contains a newline character, it is removed - leading to an empty
// data buffer. There is no mention of skipping this event _after_ this step, so the event is
// emitted with an empty data field.
mock.expectNextMessage({data: ''})
// `data\ndata\n\n` - two empty data lines without a colon, spec says to treat the whole line as field name, eg `data`,
// and append a newline to the data buffer. So data would be… `\n`, then two newlines terminates the event.
mock.expectNextMessage({data: '\n'})
// `data:test\n\n` - regular event with data
mock.expectNextMessage({data: 'test'})
})
test('stream with cr separating chunks of same event', async () => {
// CR at the end of a chunk might be part of a CRLF sequence that spans chunks,
// so we shouldn't treat it as a line terminator (yet). If we terminated it as a
// complete line, we would emit two events instead of one. For the below example:
// { id: undefined, event: undefined, data: 'A\nB' }
// { id: undefined, event: undefined, data: 'C' }
// -- instead of --
// { id: undefined, event: undefined, data: 'A\nB\nC' }
// See https://github.com/rexxars/eventsource-parser/issues/17 for more information.
const mock = getParseResultMock()
const parser = createParser(mock.callbacks)
parser.feed('data: A\r\n')
parser.feed('data: B\r')
parser.feed('\n')
parser.feed('data: C\r\n')
parser.feed('\n')
expect(mock.events).toHaveLength(1)
})
test('stream with partially incorrect retry fields', async () => {
const mock = getParseResultMock()
const parser = createParser(mock.callbacks)
await getInvalidRetryFixtureStream(parser.feed)
// `retry:1000\n`
expect(mock.events[0]).toMatchObject({type: 'reconnect-interval', value: 1000})
// `retry:2000x\n - invalid retry value, spec says:
// > If the field value consists of only ASCII digits, then interpret the field value as an
// > integer in base ten. Otherwise, ignore the field.
// Assert that we have emitted an error in this case (through the `onError` callback)
expect(mock.events[1]).toMatchObject({
type: 'error',
error: expect.any(Error),
message: 'Invalid `retry` value: "2000x"',
})
// `data:x\n\n` - regular event with data
expect(mock.events[2]).toMatchObject({type: 'event', data: 'x', event: undefined})
mock.expectNumberOfMessagesToBe(1)
})
test('stream with incorrect retry fields', async () => {
const mock = getParseResultMock()
const parser = createParser(mock.callbacks)
parser.feed(`
retry: 500
data: first
retry: 50x
data: second
`)
expect(mock.events[0]).toMatchObject({type: 'reconnect-interval', value: 500})
expect(mock.events[1]).toMatchObject({type: 'event', data: 'first', event: undefined})
expect(mock.events[2]).toSatisfy((event) => {
return (
// Event is of type `error`
typeof event === 'object' &&
'type' in event &&
event.type === 'error' &&
// Event has `message` property
'message' in event &&
event.message === 'Invalid `retry` value: "50x"' &&
// `error` property is an Error with `type`
'error' in event &&
event.error instanceof Error &&
event.error.message === 'Invalid `retry` value: "50x"' &&
'type' in event.error &&
event.error.type === 'invalid-retry'
)
})
expect(mock.events[3]).toMatchObject({type: 'event', data: 'second', event: undefined})
mock.expectNumberOfMessagesToBe(2)
})
test('stream with unknown fields in the stream', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getUnknownFieldsFixtureStream(parser.feed)
mock.expectNextMessage({event: undefined, data: 'abc\n\n123'})
})
test('stream with huge data chunks', async () => {
const mock = getParseResultMock()
const parser = createParser({onEvent: mock.onParse})
await getHugeMessageFixtureStream(parser.feed)
const hugeMsg = mock.events[0]
if (!hugeMsg || hugeMsg.type !== 'event') {
throw new Error('First message was not an event')
}
expect(hugeMsg.data.length).toBe(4808512)
const receivedHash = await sha256(hugeMsg.data)
const hashMsg = mock.events[1]
if (!hashMsg || hashMsg.type !== 'event') {
throw new Error('Second message was not an event')
}
expect(hashMsg.data).toBe(receivedHash)
}, 15000)
test('skips onError when the stream is invalid but not newline-terminated (through `reset()`)', async () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError})
parser.feed(
JSON.stringify({
error: 'Internal Server Error',
message: 'The server could not process your request',
}),
)
parser.reset({consume: false})
expect(onEvent).not.toHaveBeenCalled()
expect(onError).not.toHaveBeenCalled()
})
test('skips onError when the stream is invalid but not newline-terminated (through `reset()` with `consume: false`)', async () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError})
parser.feed(
JSON.stringify({
error: 'Internal Server Error',
message: 'The server could not process your request',
}),
)
parser.reset({consume: false})
expect(onEvent).not.toHaveBeenCalled()
expect(onError).not.toHaveBeenCalled()
})
test('calls onError when the stream is invalid but not newline-terminated (through `reset() with `consume: true`)', async () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError})
parser.feed(
JSON.stringify({
error: 'Internal Server Error',
message: 'The server could not process your request',
}),
)
parser.reset({consume: true})
expect(onEvent).not.toHaveBeenCalled()
expect(onError).toHaveBeenCalled()
const error = onError.mock.calls[0]?.[0]
expect(error).toBeInstanceOf(ParseError)
expect(error).toMatchObject({
type: 'unknown-field',
field: '{"error"',
value: `"Internal Server Error","message":"The server could not process your request"}`,
line: `{"error":"Internal Server Error","message":"The server could not process your request"}`,
})
})
test('calls onError when the stream is invalid (through newline)', async () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError})
parser.feed(
`${JSON.stringify({
error: 'Internal Server Error',
message: 'The server could not process your request',
})}\n`,
)
expect(onEvent).not.toHaveBeenCalled()
expect(onError).toHaveBeenCalled()
const error = onError.mock.calls[0]?.[0]
expect(error).toBeInstanceOf(ParseError)
expect(error).toMatchObject({
type: 'unknown-field',
field: '{"error"',
value: `"Internal Server Error","message":"The server could not process your request"}`,
line: `{"error":"Internal Server Error","message":"The server could not process your request"}`,
})
})
test('calls onError when the stream is invalid (no field separator)', async () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError})
parser.feed('Well, this is not what I expected\n')
expect(onEvent).not.toHaveBeenCalled()
expect(onError).toHaveBeenCalled()
const error = onError.mock.calls[0]?.[0]
expect(error).toBeInstanceOf(ParseError)
expect(error).toMatchObject({
type: 'unknown-field',
field: 'Well, this is not what I expected',
value: '',
line: 'Well, this is not what I expected',
})
})
test('maxBufferSize: triggers on pending fragment overflow (no terminator)', () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError, maxBufferSize: 16})
// Single feed under the limit — fine.
parser.feed('short start')
expect(onError).not.toHaveBeenCalled()
// Pushes the accumulated fragments past the limit.
parser.feed(' and now too long')
expect(onError).toHaveBeenCalledTimes(1)
const error = onError.mock.calls[0]?.[0]
expect(error).toBeInstanceOf(ParseError)
expect(error).toMatchObject({type: 'max-buffer-size-exceeded'})
})
test('maxBufferSize: triggers on data buffer overflow (no blank line)', () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError, maxBufferSize: 32})
// Each `data:` line appends its value to the event's data buffer. Without a
// blank line, data accumulates unboundedly.
for (let i = 0; i < 50; i++) {
parser.feed(`data: chunk-${i}\n`)
if (onError.mock.calls.length > 0) break
}
expect(onError).toHaveBeenCalledTimes(1)
expect(onEvent).not.toHaveBeenCalled()
const error = onError.mock.calls[0]?.[0]
expect(error).toBeInstanceOf(ParseError)
expect(error).toMatchObject({type: 'max-buffer-size-exceeded'})
})
test('maxBufferSize: feed throws after overflow, until reset', () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError, maxBufferSize: 8})
// The overflowing feed itself does not throw — it reports via onError.
parser.feed('this is too long for the buffer')
expect(onError).toHaveBeenCalledTimes(1)
// Subsequent feeds throw, signalling that the parser is unusable.
expect(() => parser.feed('data: hello\n\n')).toThrow(/max buffer size/)
expect(() => parser.feed('data: world\n\n')).toThrow(/max buffer size/)
expect(onEvent).not.toHaveBeenCalled()
expect(onError).toHaveBeenCalledTimes(1)
// After reset, the parser works again.
parser.reset()
parser.feed('data: hello\n\n')
expect(onEvent).toHaveBeenCalledTimes(1)
expect(onEvent).toHaveBeenLastCalledWith({id: undefined, event: undefined, data: 'hello'})
})
test('maxBufferSize: not triggered when events dispatch within the limit', () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError, maxBufferSize: 64})
// Lots of small events, each well under the limit and dispatched immediately.
for (let i = 0; i < 100; i++) {
parser.feed(`data: ${i}\n\n`)
}
expect(onError).not.toHaveBeenCalled()
expect(onEvent).toHaveBeenCalledTimes(100)
})
test('maxBufferSize: undefined option means unbounded (default behavior)', () => {
const onEvent = vi.fn()
const onError = vi.fn()
const parser = createParser({onEvent, onError})
parser.feed('x'.repeat(1_000_000))
expect(onError).not.toHaveBeenCalled()
})
test('passing a function to `createParser` will throw with helpful error', () => {
expect(() => {
// @ts-expect-error Should not allow a function, typing-wise
createParser(() => null)
}).toThrowError(
'`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?',
)
})
async function sha256(message: string): Promise<string> {
const encoder = new TextEncoder()
const data = encoder.encode(message)
const hash = await crypto.subtle.digest('SHA-256', data)
// Return hex
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}