-
Notifications
You must be signed in to change notification settings - Fork 0
/
readable-stream.js
1945 lines (1493 loc) · 57.9 KB
/
readable-stream.js
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const { ArrayBufferCopy, CreateIterResultObject, IsFiniteNonNegativeNumber, InvokeOrNoop, PromiseInvokeOrNoop,
TransferArrayBuffer, ValidateAndNormalizeQueuingStrategy, ValidateAndNormalizeHighWaterMark } =
require('./helpers.js');
const { createArrayFromList, createDataProperty, typeIsObject } = require('./helpers.js');
const { assert, rethrowAssertionErrorRejection } = require('./utils.js');
const { DequeueValue, EnqueueValueWithSize, ResetQueue } = require('./queue-with-sizes.js');
const { AcquireWritableStreamDefaultWriter, IsWritableStream, IsWritableStreamLocked,
WritableStreamAbort, WritableStreamDefaultWriterCloseWithErrorPropagation,
WritableStreamDefaultWriterRelease, WritableStreamDefaultWriterWrite, WritableStreamCloseQueuedOrInFlight } =
require('./writable-stream.js');
class ReadableStream {
constructor(underlyingSource = {}, { size, highWaterMark } = {}) {
// Exposed to controllers.
this._state = 'readable';
this._reader = undefined;
this._storedError = undefined;
this._disturbed = false;
// Initialize to undefined first because the constructor of the controller checks this
// variable to validate the caller.
this._readableStreamController = undefined;
const type = underlyingSource.type;
const typeString = String(type);
if (typeString === 'bytes') {
if (highWaterMark === undefined) {
highWaterMark = 0;
}
this._readableStreamController = new ReadableByteStreamController(this, underlyingSource, highWaterMark);
} else if (type === undefined) {
if (highWaterMark === undefined) {
highWaterMark = 1;
}
this._readableStreamController = new ReadableStreamDefaultController(this, underlyingSource, size, highWaterMark);
} else {
throw new RangeError('Invalid type is specified');
}
}
get locked() {
if (IsReadableStream(this) === false) {
throw streamBrandCheckException('locked');
}
return IsReadableStreamLocked(this);
}
cancel(reason) {
if (IsReadableStream(this) === false) {
return Promise.reject(streamBrandCheckException('cancel'));
}
if (IsReadableStreamLocked(this) === true) {
return Promise.reject(new TypeError('Cannot cancel a stream that already has a reader'));
}
return ReadableStreamCancel(this, reason);
}
getReader({ mode } = {}) {
if (IsReadableStream(this) === false) {
throw streamBrandCheckException('getReader');
}
if (mode === undefined) {
return AcquireReadableStreamDefaultReader(this);
}
mode = String(mode);
if (mode === 'byob') {
return AcquireReadableStreamBYOBReader(this);
}
throw new RangeError('Invalid mode is specified');
}
pipeThrough({ writable, readable }, options) {
const promise = this.pipeTo(writable, options);
ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);
return readable;
}
pipeTo(dest, { preventClose, preventAbort, preventCancel } = {}) {
if (IsReadableStream(this) === false) {
return Promise.reject(streamBrandCheckException('pipeTo'));
}
if (IsWritableStream(dest) === false) {
return Promise.reject(
new TypeError('ReadableStream.prototype.pipeTo\'s first argument must be a WritableStream'));
}
preventClose = Boolean(preventClose);
preventAbort = Boolean(preventAbort);
preventCancel = Boolean(preventCancel);
if (IsReadableStreamLocked(this) === true) {
return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
}
if (IsWritableStreamLocked(dest) === true) {
return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
}
const reader = AcquireReadableStreamDefaultReader(this);
const writer = AcquireWritableStreamDefaultWriter(dest);
let shuttingDown = false;
// This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
let currentWrite = Promise.resolve();
return new Promise((resolve, reject) => {
// Using reader and writer, read all chunks from this and write them to dest
// - Backpressure must be enforced
// - Shutdown must stop all activity
function pipeLoop() {
currentWrite = Promise.resolve();
if (shuttingDown === true) {
return Promise.resolve();
}
return writer._readyPromise.then(() => {
return ReadableStreamDefaultReaderRead(reader).then(({ value, done }) => {
if (done === true) {
return;
}
currentWrite = WritableStreamDefaultWriterWrite(writer, value).catch(() => {});
});
})
.then(pipeLoop);
}
// Errors must be propagated forward
isOrBecomesErrored(this, reader._closedPromise, storedError => {
if (preventAbort === false) {
shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
} else {
shutdown(true, storedError);
}
});
// Errors must be propagated backward
isOrBecomesErrored(dest, writer._closedPromise, storedError => {
if (preventCancel === false) {
shutdownWithAction(() => ReadableStreamCancel(this, storedError), true, storedError);
} else {
shutdown(true, storedError);
}
});
// Closing must be propagated forward
isOrBecomesClosed(this, reader._closedPromise, () => {
if (preventClose === false) {
shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
} else {
shutdown();
}
});
// Closing must be propagated backward
if (WritableStreamCloseQueuedOrInFlight(dest) === true || dest._state === 'closed') {
const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
if (preventCancel === false) {
shutdownWithAction(() => ReadableStreamCancel(this, destClosed), true, destClosed);
} else {
shutdown(true, destClosed);
}
}
pipeLoop().catch(err => {
currentWrite = Promise.resolve();
rethrowAssertionErrorRejection(err);
});
function waitForWritesToFinish() {
// Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
// for that too.
const oldCurrentWrite = currentWrite;
return currentWrite.then(() => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
}
function isOrBecomesErrored(stream, promise, action) {
if (stream._state === 'errored') {
action(stream._storedError);
} else {
promise.catch(action).catch(rethrowAssertionErrorRejection);
}
}
function isOrBecomesClosed(stream, promise, action) {
if (stream._state === 'closed') {
action();
} else {
promise.then(action).catch(rethrowAssertionErrorRejection);
}
}
function shutdownWithAction(action, originalIsError, originalError) {
if (shuttingDown === true) {
return;
}
shuttingDown = true;
if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {
waitForWritesToFinish().then(doTheRest);
} else {
doTheRest();
}
function doTheRest() {
action().then(
() => finalize(originalIsError, originalError),
newError => finalize(true, newError)
)
.catch(rethrowAssertionErrorRejection);
}
}
function shutdown(isError, error) {
if (shuttingDown === true) {
return;
}
shuttingDown = true;
if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {
waitForWritesToFinish().then(() => finalize(isError, error)).catch(rethrowAssertionErrorRejection);
} else {
finalize(isError, error);
}
}
function finalize(isError, error) {
WritableStreamDefaultWriterRelease(writer);
ReadableStreamReaderGenericRelease(reader);
if (isError) {
reject(error);
} else {
resolve(undefined);
}
}
});
}
tee() {
if (IsReadableStream(this) === false) {
throw streamBrandCheckException('tee');
}
const branches = ReadableStreamTee(this, false);
return createArrayFromList(branches);
}
}
module.exports = {
ReadableStream,
IsReadableStreamDisturbed,
ReadableStreamDefaultControllerClose,
ReadableStreamDefaultControllerEnqueue,
ReadableStreamDefaultControllerError,
ReadableStreamDefaultControllerGetDesiredSize
};
// Abstract operations for the ReadableStream.
function AcquireReadableStreamBYOBReader(stream) {
return new ReadableStreamBYOBReader(stream);
}
function AcquireReadableStreamDefaultReader(stream) {
return new ReadableStreamDefaultReader(stream);
}
function IsReadableStream(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
return false;
}
return true;
}
function IsReadableStreamDisturbed(stream) {
assert(IsReadableStream(stream) === true, 'IsReadableStreamDisturbed should only be used on known readable streams');
return stream._disturbed;
}
function IsReadableStreamLocked(stream) {
assert(IsReadableStream(stream) === true, 'IsReadableStreamLocked should only be used on known readable streams');
if (stream._reader === undefined) {
return false;
}
return true;
}
function ReadableStreamTee(stream, cloneForBranch2) {
assert(IsReadableStream(stream) === true);
assert(typeof cloneForBranch2 === 'boolean');
const reader = AcquireReadableStreamDefaultReader(stream);
const teeState = {
closedOrErrored: false,
canceled1: false,
canceled2: false,
reason1: undefined,
reason2: undefined
};
teeState.promise = new Promise(resolve => {
teeState._resolve = resolve;
});
const pull = create_ReadableStreamTeePullFunction();
pull._reader = reader;
pull._teeState = teeState;
pull._cloneForBranch2 = cloneForBranch2;
const cancel1 = create_ReadableStreamTeeBranch1CancelFunction();
cancel1._stream = stream;
cancel1._teeState = teeState;
const cancel2 = create_ReadableStreamTeeBranch2CancelFunction();
cancel2._stream = stream;
cancel2._teeState = teeState;
const underlyingSource1 = Object.create(Object.prototype);
createDataProperty(underlyingSource1, 'pull', pull);
createDataProperty(underlyingSource1, 'cancel', cancel1);
const branch1Stream = new ReadableStream(underlyingSource1);
const underlyingSource2 = Object.create(Object.prototype);
createDataProperty(underlyingSource2, 'pull', pull);
createDataProperty(underlyingSource2, 'cancel', cancel2);
const branch2Stream = new ReadableStream(underlyingSource2);
pull._branch1 = branch1Stream._readableStreamController;
pull._branch2 = branch2Stream._readableStreamController;
reader._closedPromise.catch(r => {
if (teeState.closedOrErrored === true) {
return;
}
ReadableStreamDefaultControllerError(pull._branch1, r);
ReadableStreamDefaultControllerError(pull._branch2, r);
teeState.closedOrErrored = true;
});
return [branch1Stream, branch2Stream];
}
function create_ReadableStreamTeePullFunction() {
function f() {
const { _reader: reader, _branch1: branch1, _branch2: branch2, _teeState: teeState/* ,
_cloneForBranch2: cloneForBranch2*/ } = f;
return ReadableStreamDefaultReaderRead(reader).then(result => {
assert(typeIsObject(result));
const value = result.value;
const done = result.done;
assert(typeof done === 'boolean');
if (done === true && teeState.closedOrErrored === false) {
if (teeState.canceled1 === false) {
ReadableStreamDefaultControllerClose(branch1);
}
if (teeState.canceled2 === false) {
ReadableStreamDefaultControllerClose(branch2);
}
teeState.closedOrErrored = true;
}
if (teeState.closedOrErrored === true) {
return;
}
const value1 = value;
const value2 = value;
// There is no way to access the cloning code right now in the reference implementation.
// If we add one then we'll need an implementation for serializable objects.
// if (teeState.canceled2 === false && cloneForBranch2 === true) {
// value2 = StructuredDeserialize(StructuredSerialize(value2));
// }
if (teeState.canceled1 === false) {
ReadableStreamDefaultControllerEnqueue(branch1, value1);
}
if (teeState.canceled2 === false) {
ReadableStreamDefaultControllerEnqueue(branch2, value2);
}
});
}
return f;
}
function create_ReadableStreamTeeBranch1CancelFunction() {
function f(reason) {
const { _stream: stream, _teeState: teeState } = f;
teeState.canceled1 = true;
teeState.reason1 = reason;
if (teeState.canceled2 === true) {
const compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]);
const cancelResult = ReadableStreamCancel(stream, compositeReason);
teeState._resolve(cancelResult);
}
return teeState.promise;
}
return f;
}
function create_ReadableStreamTeeBranch2CancelFunction() {
function f(reason) {
const { _stream: stream, _teeState: teeState } = f;
teeState.canceled2 = true;
teeState.reason2 = reason;
if (teeState.canceled1 === true) {
const compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]);
const cancelResult = ReadableStreamCancel(stream, compositeReason);
teeState._resolve(cancelResult);
}
return teeState.promise;
}
return f;
}
// ReadableStream API exposed for controllers.
function ReadableStreamAddReadIntoRequest(stream) {
assert(IsReadableStreamBYOBReader(stream._reader) === true);
assert(stream._state === 'readable' || stream._state === 'closed');
const promise = new Promise((resolve, reject) => {
const readIntoRequest = {
_resolve: resolve,
_reject: reject
};
stream._reader._readIntoRequests.push(readIntoRequest);
});
return promise;
}
function ReadableStreamAddReadRequest(stream) {
assert(IsReadableStreamDefaultReader(stream._reader) === true);
assert(stream._state === 'readable');
const promise = new Promise((resolve, reject) => {
const readRequest = {
_resolve: resolve,
_reject: reject
};
stream._reader._readRequests.push(readRequest);
});
return promise;
}
function ReadableStreamCancel(stream, reason) {
stream._disturbed = true;
if (stream._state === 'closed') {
return Promise.resolve(undefined);
}
if (stream._state === 'errored') {
return Promise.reject(stream._storedError);
}
ReadableStreamClose(stream);
const sourceCancelPromise = stream._readableStreamController.__cancelSteps(reason);
return sourceCancelPromise.then(() => undefined);
}
function ReadableStreamClose(stream) {
assert(stream._state === 'readable');
stream._state = 'closed';
const reader = stream._reader;
if (reader === undefined) {
return undefined;
}
if (IsReadableStreamDefaultReader(reader) === true) {
for (let i = 0; i < reader._readRequests.length; i++) {
const _resolve = reader._readRequests[i];
_resolve(CreateIterResultObject(undefined, true));
}
reader._readRequests = [];
}
defaultReaderClosedPromiseResolve(reader);
return undefined;
}
function ReadableStreamError(stream, e) {
assert(IsReadableStream(stream) === true, 'stream must be ReadableStream');
assert(stream._state === 'readable', 'state must be readable');
stream._state = 'errored';
stream._storedError = e;
const reader = stream._reader;
if (reader === undefined) {
return undefined;
}
if (IsReadableStreamDefaultReader(reader) === true) {
for (let i = 0; i < reader._readRequests.length; i++) {
const readRequest = reader._readRequests[i];
readRequest._reject(e);
}
reader._readRequests = [];
} else {
assert(IsReadableStreamBYOBReader(reader), 'reader must be ReadableStreamBYOBReader');
for (let i = 0; i < reader._readIntoRequests.length; i++) {
const readIntoRequest = reader._readIntoRequests[i];
readIntoRequest._reject(e);
}
reader._readIntoRequests = [];
}
defaultReaderClosedPromiseReject(reader, e);
reader._closedPromise.catch(() => {});
}
function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
const reader = stream._reader;
assert(reader._readIntoRequests.length > 0);
const readIntoRequest = reader._readIntoRequests.shift();
readIntoRequest._resolve(CreateIterResultObject(chunk, done));
}
function ReadableStreamFulfillReadRequest(stream, chunk, done) {
const reader = stream._reader;
assert(reader._readRequests.length > 0);
const readRequest = reader._readRequests.shift();
readRequest._resolve(CreateIterResultObject(chunk, done));
}
function ReadableStreamGetNumReadIntoRequests(stream) {
return stream._reader._readIntoRequests.length;
}
function ReadableStreamGetNumReadRequests(stream) {
return stream._reader._readRequests.length;
}
function ReadableStreamHasBYOBReader(stream) {
const reader = stream._reader;
if (reader === undefined) {
return false;
}
if (IsReadableStreamBYOBReader(reader) === false) {
return false;
}
return true;
}
function ReadableStreamHasDefaultReader(stream) {
const reader = stream._reader;
if (reader === undefined) {
return false;
}
if (IsReadableStreamDefaultReader(reader) === false) {
return false;
}
return true;
}
// Readers
class ReadableStreamDefaultReader {
constructor(stream) {
if (IsReadableStream(stream) === false) {
throw new TypeError('ReadableStreamDefaultReader can only be constructed with a ReadableStream instance');
}
if (IsReadableStreamLocked(stream) === true) {
throw new TypeError('This stream has already been locked for exclusive reading by another reader');
}
ReadableStreamReaderGenericInitialize(this, stream);
this._readRequests = [];
}
get closed() {
if (IsReadableStreamDefaultReader(this) === false) {
return Promise.reject(defaultReaderBrandCheckException('closed'));
}
return this._closedPromise;
}
cancel(reason) {
if (IsReadableStreamDefaultReader(this) === false) {
return Promise.reject(defaultReaderBrandCheckException('cancel'));
}
if (this._ownerReadableStream === undefined) {
return Promise.reject(readerLockException('cancel'));
}
return ReadableStreamReaderGenericCancel(this, reason);
}
read() {
if (IsReadableStreamDefaultReader(this) === false) {
return Promise.reject(defaultReaderBrandCheckException('read'));
}
if (this._ownerReadableStream === undefined) {
return Promise.reject(readerLockException('read from'));
}
return ReadableStreamDefaultReaderRead(this);
}
releaseLock() {
if (IsReadableStreamDefaultReader(this) === false) {
throw defaultReaderBrandCheckException('releaseLock');
}
if (this._ownerReadableStream === undefined) {
return;
}
if (this._readRequests.length > 0) {
throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
}
ReadableStreamReaderGenericRelease(this);
}
}
class ReadableStreamBYOBReader {
constructor(stream) {
if (!IsReadableStream(stream)) {
throw new TypeError('ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a ' +
'byte source');
}
if (IsReadableByteStreamController(stream._readableStreamController) === false) {
throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
'source');
}
if (IsReadableStreamLocked(stream)) {
throw new TypeError('This stream has already been locked for exclusive reading by another reader');
}
ReadableStreamReaderGenericInitialize(this, stream);
this._readIntoRequests = [];
}
get closed() {
if (!IsReadableStreamBYOBReader(this)) {
return Promise.reject(byobReaderBrandCheckException('closed'));
}
return this._closedPromise;
}
cancel(reason) {
if (!IsReadableStreamBYOBReader(this)) {
return Promise.reject(byobReaderBrandCheckException('cancel'));
}
if (this._ownerReadableStream === undefined) {
return Promise.reject(readerLockException('cancel'));
}
return ReadableStreamReaderGenericCancel(this, reason);
}
read(view) {
if (!IsReadableStreamBYOBReader(this)) {
return Promise.reject(byobReaderBrandCheckException('read'));
}
if (this._ownerReadableStream === undefined) {
return Promise.reject(readerLockException('read from'));
}
if (!ArrayBuffer.isView(view)) {
return Promise.reject(new TypeError('view must be an array buffer view'));
}
if (view.byteLength === 0) {
return Promise.reject(new TypeError('view must have non-zero byteLength'));
}
return ReadableStreamBYOBReaderRead(this, view);
}
releaseLock() {
if (!IsReadableStreamBYOBReader(this)) {
throw byobReaderBrandCheckException('releaseLock');
}
if (this._ownerReadableStream === undefined) {
return;
}
if (this._readIntoRequests.length > 0) {
throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
}
ReadableStreamReaderGenericRelease(this);
}
}
// Abstract operations for the readers.
function IsReadableStreamBYOBReader(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
return false;
}
return true;
}
function IsReadableStreamDefaultReader(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
return false;
}
return true;
}
function ReadableStreamReaderGenericInitialize(reader, stream) {
reader._ownerReadableStream = stream;
stream._reader = reader;
if (stream._state === 'readable') {
defaultReaderClosedPromiseInitialize(reader);
} else if (stream._state === 'closed') {
defaultReaderClosedPromiseInitializeAsResolved(reader);
} else {
assert(stream._state === 'errored', 'state must be errored');
defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
reader._closedPromise.catch(() => {});
}
}
// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
// check.
function ReadableStreamReaderGenericCancel(reader, reason) {
const stream = reader._ownerReadableStream;
assert(stream !== undefined);
return ReadableStreamCancel(stream, reason);
}
function ReadableStreamReaderGenericRelease(reader) {
assert(reader._ownerReadableStream !== undefined);
assert(reader._ownerReadableStream._reader === reader);
if (reader._ownerReadableStream._state === 'readable') {
defaultReaderClosedPromiseReject(
reader,
new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));
} else {
defaultReaderClosedPromiseResetToRejected(
reader,
new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));
}
reader._closedPromise.catch(() => {});
reader._ownerReadableStream._reader = undefined;
reader._ownerReadableStream = undefined;
}
function ReadableStreamBYOBReaderRead(reader, view) {
const stream = reader._ownerReadableStream;
assert(stream !== undefined);
stream._disturbed = true;
if (stream._state === 'errored') {
return Promise.reject(stream._storedError);
}
// Controllers must implement this.
return ReadableByteStreamControllerPullInto(stream._readableStreamController, view);
}
function ReadableStreamDefaultReaderRead(reader) {
const stream = reader._ownerReadableStream;
assert(stream !== undefined);
stream._disturbed = true;
if (stream._state === 'closed') {
return Promise.resolve(CreateIterResultObject(undefined, true));
}
if (stream._state === 'errored') {
return Promise.reject(stream._storedError);
}
assert(stream._state === 'readable');
return stream._readableStreamController.__pullSteps();
}
// Controllers
class ReadableStreamDefaultController {
constructor(stream, underlyingSource, size, highWaterMark) {
if (IsReadableStream(stream) === false) {
throw new TypeError('ReadableStreamDefaultController can only be constructed with a ReadableStream instance');
}
if (stream._readableStreamController !== undefined) {
throw new TypeError(
'ReadableStreamDefaultController instances can only be created by the ReadableStream constructor');
}
this._controlledReadableStream = stream;
this._underlyingSource = underlyingSource;
// Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
this._queue = undefined;
this._queueTotalSize = undefined;
ResetQueue(this);
this._started = false;
this._closeRequested = false;
this._pullAgain = false;
this._pulling = false;
const normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark);
this._strategySize = normalizedStrategy.size;
this._strategyHWM = normalizedStrategy.highWaterMark;
const controller = this;
const startResult = InvokeOrNoop(underlyingSource, 'start', [this]);
Promise.resolve(startResult).then(
() => {
controller._started = true;
assert(controller._pulling === false);
assert(controller._pullAgain === false);
ReadableStreamDefaultControllerCallPullIfNeeded(controller);
},
r => {
ReadableStreamDefaultControllerErrorIfNeeded(controller, r);
}
)
.catch(rethrowAssertionErrorRejection);
}
get desiredSize() {
if (IsReadableStreamDefaultController(this) === false) {
throw defaultControllerBrandCheckException('desiredSize');
}
return ReadableStreamDefaultControllerGetDesiredSize(this);
}
close() {
if (IsReadableStreamDefaultController(this) === false) {
throw defaultControllerBrandCheckException('close');
}
if (this._closeRequested === true) {
throw new TypeError('The stream has already been closed; do not close it again!');
}
const state = this._controlledReadableStream._state;
if (state !== 'readable') {
throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
}
ReadableStreamDefaultControllerClose(this);
}
enqueue(chunk) {
if (IsReadableStreamDefaultController(this) === false) {
throw defaultControllerBrandCheckException('enqueue');
}
if (this._closeRequested === true) {
throw new TypeError('stream is closed or draining');
}
const state = this._controlledReadableStream._state;
if (state !== 'readable') {
throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
}
return ReadableStreamDefaultControllerEnqueue(this, chunk);
}
error(e) {
if (IsReadableStreamDefaultController(this) === false) {
throw defaultControllerBrandCheckException('error');
}
const stream = this._controlledReadableStream;
if (stream._state !== 'readable') {
throw new TypeError(`The stream is ${stream._state} and so cannot be errored`);
}
ReadableStreamDefaultControllerError(this, e);
}
__cancelSteps(reason) {
ResetQueue(this);
return PromiseInvokeOrNoop(this._underlyingSource, 'cancel', [reason]);
}
__pullSteps() {
const stream = this._controlledReadableStream;
if (this._queue.length > 0) {
const chunk = DequeueValue(this);
if (this._closeRequested === true && this._queue.length === 0) {
ReadableStreamClose(stream);
} else {
ReadableStreamDefaultControllerCallPullIfNeeded(this);
}
return Promise.resolve(CreateIterResultObject(chunk, false));
}
const pendingPromise = ReadableStreamAddReadRequest(stream);
ReadableStreamDefaultControllerCallPullIfNeeded(this);
return pendingPromise;
}
}
// Abstract operations for the ReadableStreamDefaultController.
function IsReadableStreamDefaultController(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSource')) {
return false;
}
return true;
}
function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
if (shouldPull === false) {