[79a0317] | 1 | 'use strict';
|
---|
| 2 |
|
---|
| 3 | const parseChunked = require('./parse-chunked.cjs');
|
---|
| 4 | const stringifyChunked = require('./stringify-chunked.cjs');
|
---|
| 5 | const utils = require('./utils.cjs');
|
---|
| 6 |
|
---|
| 7 | /* eslint-env browser */
|
---|
| 8 |
|
---|
| 9 | function parseFromWebStream(stream) {
|
---|
| 10 | // 2024/6/17: currently, an @@asyncIterator on a ReadableStream is not widely supported,
|
---|
| 11 | // therefore use a fallback using a reader
|
---|
| 12 | // https://caniuse.com/mdn-api_readablestream_--asynciterator
|
---|
| 13 | return parseChunked.parseChunked(utils.isIterable(stream) ? stream : async function*() {
|
---|
| 14 | const reader = stream.getReader();
|
---|
| 15 |
|
---|
| 16 | try {
|
---|
| 17 | while (true) {
|
---|
| 18 | const { value, done } = await reader.read();
|
---|
| 19 |
|
---|
| 20 | if (done) {
|
---|
| 21 | break;
|
---|
| 22 | }
|
---|
| 23 |
|
---|
| 24 | yield value;
|
---|
| 25 | }
|
---|
| 26 | } finally {
|
---|
| 27 | reader.releaseLock();
|
---|
| 28 | }
|
---|
| 29 | });
|
---|
| 30 | }
|
---|
| 31 |
|
---|
| 32 | function createStringifyWebStream(value, replacer, space) {
|
---|
| 33 | // 2024/6/17: the ReadableStream.from() static method is supported
|
---|
| 34 | // in Node.js 20.6+ and Firefox only
|
---|
| 35 | if (typeof ReadableStream.from === 'function') {
|
---|
| 36 | return ReadableStream.from(stringifyChunked.stringifyChunked(value, replacer, space));
|
---|
| 37 | }
|
---|
| 38 |
|
---|
| 39 | // emulate ReadableStream.from()
|
---|
| 40 | return new ReadableStream({
|
---|
| 41 | start() {
|
---|
| 42 | this.generator = stringifyChunked.stringifyChunked(value, replacer, space);
|
---|
| 43 | },
|
---|
| 44 | pull(controller) {
|
---|
| 45 | const { value, done } = this.generator.next();
|
---|
| 46 |
|
---|
| 47 | if (done) {
|
---|
| 48 | controller.close();
|
---|
| 49 | } else {
|
---|
| 50 | controller.enqueue(value);
|
---|
| 51 | }
|
---|
| 52 | },
|
---|
| 53 | cancel() {
|
---|
| 54 | this.generator = null;
|
---|
| 55 | }
|
---|
| 56 | });
|
---|
| 57 | }
|
---|
| 58 |
|
---|
| 59 | exports.createStringifyWebStream = createStringifyWebStream;
|
---|
| 60 | exports.parseFromWebStream = parseFromWebStream;
|
---|