1
+/**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ */
9
+
10
+import {TextEncoder} from 'util';
11
+import {createHash} from 'crypto';
12
+
13
+export type Destination = ReadableStreamController;
14
+
15
+export type PrecomputedChunk = Uint8Array;
16
+export opaque type Chunk = Uint8Array;
17
+export type BinaryChunk = Uint8Array;
18
+
19
+export function scheduleWork(callback: () => void) {
20
+ setImmediate(callback);
21
+}
22
+
23
+export const scheduleMicrotask = queueMicrotask;
24
+
25
+export function flushBuffered(destination: Destination) {
26
+ // WHATWG Streams do not yet have a way to flush the underlying
27
+ // transform streams. https://github.com/whatwg/streams/issues/960
28
+}
29
+
30
+const VIEW_SIZE = 2048;
31
+let currentView = null;
32
+let writtenBytes = 0;
33
+
34
+export function beginWriting(destination: Destination) {
35
+ currentView = new Uint8Array(VIEW_SIZE);
36
+ writtenBytes = 0;
37
+}
38
+
39
+export function writeChunk(
40
+ destination: Destination,
41
+ chunk: PrecomputedChunk | Chunk | BinaryChunk,
42
+): void {
43
+ if (chunk.byteLength === 0) {
44
+ return;
45
+ }
46
+
47
+ if (chunk.byteLength > VIEW_SIZE) {
48
+ // this chunk may overflow a single view which implies it was not
49
+ // one that is cached by the streaming renderer. We will enqueu
50
+ // it directly and expect it is not re-used
51
+ if (writtenBytes > 0) {
52
+ destination.enqueue(
53
+ new Uint8Array(
54
+ ((currentView: any): Uint8Array).buffer,
55
+ 0,
56
+ writtenBytes,
57
+ ),
58
+ );
59
+ currentView = new Uint8Array(VIEW_SIZE);
60
+ writtenBytes = 0;
61
+ }
62
+ destination.enqueue(chunk);
63
+ return;
64
+ }
65
+
66
+ let bytesToWrite = chunk;
67
+ const allowableBytes = ((currentView: any): Uint8Array).length - writtenBytes;
68
+ if (allowableBytes < bytesToWrite.byteLength) {
69
+ // this chunk would overflow the current view. We enqueue a full view
70
+ // and start a new view with the remaining chunk
71
+ if (allowableBytes === 0) {
72
+ // the current view is already full, send it
73
+ destination.enqueue(currentView);
74
+ } else {
75
+ // fill up the current view and apply the remaining chunk bytes
76
+ // to a new view.
77
+ ((currentView: any): Uint8Array).set(
78
+ bytesToWrite.subarray(0, allowableBytes),
79
+ writtenBytes,
80
+ );
81
+ // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view
82
+ destination.enqueue(currentView);
83
+ bytesToWrite = bytesToWrite.subarray(allowableBytes);
84
+ }
85
+ currentView = new Uint8Array(VIEW_SIZE);
86
+ writtenBytes = 0;
87
+ }
88
+ ((currentView: any): Uint8Array).set(bytesToWrite, writtenBytes);
89
+ writtenBytes += bytesToWrite.byteLength;
90
+}
91
+
92
+export function writeChunkAndReturn(
93
+ destination: Destination,
94
+ chunk: PrecomputedChunk | Chunk | BinaryChunk,
95
+): boolean {
96
+ writeChunk(destination, chunk);
97
+ // in web streams there is no backpressure so we can alwas write more
98
+ return true;
99
+}
100
+
101
+export function completeWriting(destination: Destination) {
102
+ if (currentView && writtenBytes > 0) {
103
+ destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
104
+ currentView = null;
105
+ writtenBytes = 0;
106
+ }
107
+}
108
+
109
+export function close(destination: Destination) {
110
+ destination.close();
111
+}
112
+
113
+const textEncoder = new TextEncoder();
114
+
115
+export function stringToChunk(content: string): Chunk {
116
+ return textEncoder.encode(content);
117
+}
118
+
119
+export function stringToPrecomputedChunk(content: string): PrecomputedChunk {
120
+ const precomputedChunk = textEncoder.encode(content);
121
+
122
+ if (__DEV__) {
123
+ if (precomputedChunk.byteLength > VIEW_SIZE) {
124
+ console.error(
125
+ 'precomputed chunks must be smaller than the view size configured for this host. This is a bug in React.',
126
+ );
127
+ }
128
+ }
129
+
130
+ return precomputedChunk;
131
+}
132
+
133
+export function typedArrayToBinaryChunk(
134
+ content: $ArrayBufferView,
135
+): BinaryChunk {
136
+ // Convert any non-Uint8Array array to Uint8Array. We could avoid this for Uint8Arrays.
137
+ // If we passed through this straight to enqueue we wouldn't have to convert it but since
138
+ // we need to copy the buffer in that case, we need to convert it to copy it.
139
+ // When we copy it into another array using set() it needs to be a Uint8Array.
140
+ const buffer = new Uint8Array(
141
+ content.buffer,
142
+ content.byteOffset,
143
+ content.byteLength,
144
+ );
145
+ // We clone large chunks so that we can transfer them when we write them.
146
+ // Others get copied into the target buffer.
147
+ return content.byteLength > VIEW_SIZE ? buffer.slice() : buffer;
148
+}
149
+
150
+export function byteLengthOfChunk(chunk: Chunk | PrecomputedChunk): number {
151
+ return chunk.byteLength;
152
+}
153
+
154
+export function byteLengthOfBinaryChunk(chunk: BinaryChunk): number {
155
+ return chunk.byteLength;
156
+}
157
+
158
+export function closeWithError(destination: Destination, error: mixed): void {
159
+ // $FlowFixMe[method-unbinding]
160
+ if (typeof destination.error === 'function') {
161
+ // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types.
162
+ destination.error(error);
163
+ } else {
164
+ // Earlier implementations doesn't support this method. In that environment you're
165
+ // supposed to throw from a promise returned but we don't return a promise in our
166
+ // approach. We could fork this implementation but this is environment is an edge
167
+ // case to begin with. It's even less common to run this in an older environment.
168
+ // Even then, this is not where errors are supposed to happen and they get reported
169
+ // to a global callback in addition to this anyway. So it's fine just to close this.
170
+ destination.close();
171
+ }
172
+}
173
+
174
+export function createFastHash(input: string): string | number {
175
+ const hash = createHash('md5');
176
+ hash.update(input);
177
+ return hash.digest('hex');
178
+}
179
+
180
+export function readAsDataURL(blob: Blob): Promise<string> {
181
+ return blob.arrayBuffer().then(arrayBuffer => {
182
+ const encoded = Buffer.from(arrayBuffer).toString('base64');
183
+ const mimeType = blob.type || 'application/octet-stream';
184
+ return 'data:' + mimeType + ';base64,' + encoded;
185
+ });
186
+}