-
Notifications
You must be signed in to change notification settings - Fork 50.7k
Expand file tree
/
Copy pathReactFlightClient.js
More file actions
5379 lines (5133 loc) · 170 KB
/
ReactFlightClient.js
File metadata and controls
5379 lines (5133 loc) · 170 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
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {
JSONValue,
Thenable,
ReactDebugInfo,
ReactDebugInfoEntry,
ReactComponentInfo,
ReactAsyncInfo,
ReactIOInfo,
ReactStackTrace,
ReactFunctionLocation,
ReactErrorInfoDev,
} from 'shared/ReactTypes';
import type {LazyComponent} from 'react/src/ReactLazy';
import type {
ClientReference,
ClientReferenceMetadata,
ServerConsumerModuleMap,
ServerManifest,
StringDecoder,
ModuleLoading,
} from './ReactFlightClientConfig';
import type {
HintCode,
HintModel,
} from 'react-server/src/ReactFlightServerConfig';
import type {
CallServerCallback,
EncodeFormActionCallback,
} from './ReactFlightReplyClient';
import type {TemporaryReferenceSet} from './ReactFlightTemporaryReferences';
import {
enableProfilerTimer,
enableComponentPerformanceTrack,
enableAsyncDebugInfo,
} from 'shared/ReactFeatureFlags';
import {
resolveClientReference,
resolveServerReference,
preloadModule,
requireModule,
getModuleDebugInfo,
dispatchHint,
readPartialStringChunk,
readFinalStringChunk,
createStringDecoder,
prepareDestinationForModule,
bindToConsole,
rendererVersion,
rendererPackageName,
checkEvalAvailabilityOnceDev,
} from './ReactFlightClientConfig';
import {
createBoundServerReference,
registerBoundServerReference,
} from './ReactFlightReplyClient';
import {readTemporaryReference} from './ReactFlightTemporaryReferences';
import {
markAllTracksInOrder,
logComponentRender,
logDedupedComponentRender,
logComponentAborted,
logComponentErrored,
logIOInfo,
logIOInfoErrored,
logComponentAwait,
logComponentAwaitAborted,
logComponentAwaitErrored,
} from './ReactFlightPerformanceTrack';
import {
REACT_LAZY_TYPE,
REACT_ELEMENT_TYPE,
ASYNC_ITERATOR,
REACT_FRAGMENT_TYPE,
} from 'shared/ReactSymbols';
import getComponentNameFromType from 'shared/getComponentNameFromType';
import {getOwnerStackByComponentInfoInDev} from 'shared/ReactComponentInfoStack';
import hasOwnProperty from 'shared/hasOwnProperty';
import {injectInternals} from './ReactFlightClientDevToolsHook';
import {OMITTED_PROP_ERROR} from 'shared/ReactFlightPropertyAccess';
import ReactVersion from 'shared/ReactVersion';
import isArray from 'shared/isArray';
import * as React from 'react';
import type {SharedStateServer} from 'react/src/ReactSharedInternalsServer';
import type {SharedStateClient} from 'react/src/ReactSharedInternalsClient';
// TODO: This is an unfortunate hack. We shouldn't feature detect the internals
// like this. It's just that for now we support the same build of the Flight
// client both in the RSC environment, in the SSR environments as well as the
// browser client. We should probably have a separate RSC build. This is DEV
// only though.
const ReactSharedInteralsServer: void | SharedStateServer = (React: any)
.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const ReactSharedInternals: SharedStateServer | SharedStateClient =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE ||
ReactSharedInteralsServer;
export type {CallServerCallback, EncodeFormActionCallback};
interface FlightStreamController {
enqueueValue(value: any): void;
enqueueModel(json: UninitializedModel): void;
close(json: UninitializedModel): void;
error(error: Error): void;
}
type UninitializedModel = string;
type ProfilingResult = {
track: number,
endTime: number,
component: null | ReactComponentInfo,
};
const ROW_ID = 0;
const ROW_TAG = 1;
const ROW_LENGTH = 2;
const ROW_CHUNK_BY_NEWLINE = 3;
const ROW_CHUNK_BY_LENGTH = 4;
type RowParserState = 0 | 1 | 2 | 3 | 4;
const PENDING = 'pending';
const BLOCKED = 'blocked';
const RESOLVED_MODEL = 'resolved_model';
const RESOLVED_MODULE = 'resolved_module';
const INITIALIZED = 'fulfilled';
const ERRORED = 'rejected';
const HALTED = 'halted'; // DEV-only. Means it never resolves even if connection closes.
const __PROTO__ = '__proto__';
type PendingChunk<T> = {
status: 'pending',
value: null | Array<InitializationReference | (T => mixed)>,
reason: null | Array<InitializationReference | (mixed => mixed)>,
_children: Array<SomeChunk<any>> | ProfilingResult, // Profiling-only
_debugChunk: null | SomeChunk<ReactDebugInfoEntry>, // DEV-only
_debugInfo: ReactDebugInfo, // DEV-only
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type BlockedChunk<T> = {
status: 'blocked',
value: null | Array<InitializationReference | (T => mixed)>,
reason: null | Array<InitializationReference | (mixed => mixed)>,
_children: Array<SomeChunk<any>> | ProfilingResult, // Profiling-only
_debugChunk: null, // DEV-only
_debugInfo: ReactDebugInfo, // DEV-only
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type ResolvedModelChunk<T> = {
status: 'resolved_model',
value: UninitializedModel,
reason: Response,
_children: Array<SomeChunk<any>> | ProfilingResult, // Profiling-only
_debugChunk: null | SomeChunk<ReactDebugInfoEntry>, // DEV-only
_debugInfo: ReactDebugInfo, // DEV-only
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type ResolvedModuleChunk<T> = {
status: 'resolved_module',
value: ClientReference<T>,
reason: null,
_children: Array<SomeChunk<any>> | ProfilingResult, // Profiling-only
_debugChunk: null, // DEV-only
_debugInfo: ReactDebugInfo, // DEV-only
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type InitializedChunk<T> = {
status: 'fulfilled',
value: T,
reason: null | FlightStreamController,
_children: Array<SomeChunk<any>> | ProfilingResult, // Profiling-only
_debugChunk: null, // DEV-only
_debugInfo: ReactDebugInfo, // DEV-only
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type InitializedStreamChunk<
T: ReadableStream | $AsyncIterable<any, any, void>,
> = {
status: 'fulfilled',
value: T,
reason: FlightStreamController,
_children: Array<SomeChunk<any>> | ProfilingResult, // Profiling-only
_debugChunk: null, // DEV-only
_debugInfo: ReactDebugInfo, // DEV-only
then(resolve: (ReadableStream) => mixed, reject?: (mixed) => mixed): void,
};
type ErroredChunk<T> = {
status: 'rejected',
value: null,
reason: mixed,
_children: Array<SomeChunk<any>> | ProfilingResult, // Profiling-only
_debugChunk: null, // DEV-only
_debugInfo: ReactDebugInfo, // DEV-only
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type HaltedChunk<T> = {
status: 'halted',
value: null,
reason: null,
_children: Array<SomeChunk<any>> | ProfilingResult, // Profiling-only
_debugChunk: null, // DEV-only
_debugInfo: ReactDebugInfo, // DEV-only
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type SomeChunk<T> =
| PendingChunk<T>
| BlockedChunk<T>
| ResolvedModelChunk<T>
| ResolvedModuleChunk<T>
| InitializedChunk<T>
| ErroredChunk<T>
| HaltedChunk<T>;
// $FlowFixMe[missing-this-annot]
function ReactPromise(status: any, value: any, reason: any) {
this.status = status;
this.value = value;
this.reason = reason;
if (enableProfilerTimer && enableComponentPerformanceTrack) {
this._children = [];
}
if (__DEV__) {
this._debugChunk = null;
this._debugInfo = [];
}
}
// We subclass Promise.prototype so that we get other methods like .catch
ReactPromise.prototype = (Object.create(Promise.prototype): any);
// TODO: This doesn't return a new Promise chain unlike the real .then
ReactPromise.prototype.then = function <T>(
this: SomeChunk<T>,
resolve: (value: T) => mixed,
reject?: (reason: mixed) => mixed,
) {
const chunk: SomeChunk<T> = this;
// If we have resolved content, we try to initialize it first which
// might put us back into one of the other states.
switch (chunk.status) {
case RESOLVED_MODEL:
initializeModelChunk(chunk);
break;
case RESOLVED_MODULE:
initializeModuleChunk(chunk);
break;
}
if (__DEV__ && enableAsyncDebugInfo) {
// Because only native Promises get picked up when we're awaiting we need to wrap
// this in a native Promise in DEV. This means that these callbacks are no longer sync
// but the lazy initialization is still sync and the .value can be inspected after,
// allowing it to be read synchronously anyway.
const resolveCallback = resolve;
const rejectCallback = reject;
const wrapperPromise: Promise<T> = new Promise((res, rej) => {
resolve = value => {
// $FlowFixMe
wrapperPromise._debugInfo = this._debugInfo;
res(value);
};
reject = reason => {
// $FlowFixMe
wrapperPromise._debugInfo = this._debugInfo;
rej(reason);
};
});
wrapperPromise.then(resolveCallback, rejectCallback);
}
// The status might have changed after initialization.
switch (chunk.status) {
case INITIALIZED:
if (typeof resolve === 'function') {
resolve(chunk.value);
}
break;
case PENDING:
case BLOCKED:
if (typeof resolve === 'function') {
if (chunk.value === null) {
chunk.value = ([]: Array<InitializationReference | (T => mixed)>);
}
chunk.value.push(resolve);
}
if (typeof reject === 'function') {
if (chunk.reason === null) {
chunk.reason = ([]: Array<
InitializationReference | (mixed => mixed),
>);
}
chunk.reason.push(reject);
}
break;
case HALTED: {
break;
}
default:
if (typeof reject === 'function') {
reject(chunk.reason);
}
break;
}
};
export type FindSourceMapURLCallback = (
fileName: string,
environmentName: string,
) => null | string;
export type DebugChannelCallback = (message: string) => void;
export type DebugChannel = {
hasReadable: boolean,
callback: DebugChannelCallback | null,
};
type Response = {
_bundlerConfig: ServerConsumerModuleMap,
_serverReferenceConfig: null | ServerManifest,
_moduleLoading: ModuleLoading,
_callServer: CallServerCallback,
_encodeFormAction: void | EncodeFormActionCallback,
_nonce: ?string,
_chunks: Map<number, SomeChunk<any>>,
_stringDecoder: StringDecoder,
_closed: boolean,
_closedReason: mixed,
_allowPartialStream: boolean,
_tempRefs: void | TemporaryReferenceSet, // the set temporary references can be resolved from
_timeOrigin: number, // Profiling-only
_pendingInitialRender: null | TimeoutID, // Profiling-only,
_pendingChunks: number, // DEV-only
_weakResponse: WeakResponse, // DEV-only
_debugRootOwner?: null | ReactComponentInfo, // DEV-only
_debugRootStack?: null | Error, // DEV-only
_debugRootTask?: null | ConsoleTask, // DEV-only
_debugStartTime: number, // DEV-only
_debugEndTime?: number, // DEV-only
_debugIOStarted: boolean, // DEV-only
_debugFindSourceMapURL?: void | FindSourceMapURLCallback, // DEV-only
_debugChannel?: void | DebugChannel, // DEV-only
_blockedConsole?: null | SomeChunk<ConsoleEntry>, // DEV-only
_replayConsole: boolean, // DEV-only
_rootEnvironmentName: string, // DEV-only, the requested environment name.
};
// This indirection exists only to clean up DebugChannel when all Lazy References are GC:ed.
// Therefore we only use the indirection in DEV.
type WeakResponse = {
weak: WeakRef<Response>,
response: null | Response, // This is null when there are no pending chunks.
};
export type {WeakResponse as Response};
function hasGCedResponse(weakResponse: WeakResponse): boolean {
return __DEV__ && weakResponse.weak.deref() === undefined;
}
function unwrapWeakResponse(weakResponse: WeakResponse): Response {
if (__DEV__) {
const response = weakResponse.weak.deref();
if (response === undefined) {
// eslint-disable-next-line react-internal/prod-error-codes
throw new Error(
'We did not expect to receive new data after GC:ing the response.',
);
}
return response;
} else {
return (weakResponse: any); // In prod we just use the real Response directly.
}
}
function getWeakResponse(response: Response): WeakResponse {
if (__DEV__) {
return response._weakResponse;
} else {
return (response: any); // In prod we just use the real Response directly.
}
}
function closeDebugChannel(debugChannel: DebugChannel): void {
if (debugChannel.callback) {
debugChannel.callback('');
}
}
// If FinalizationRegistry doesn't exist, we cannot use the debugChannel.
const debugChannelRegistry =
__DEV__ && typeof FinalizationRegistry === 'function'
? new FinalizationRegistry(closeDebugChannel)
: null;
function readChunk<T>(chunk: SomeChunk<T>): T {
// If we have resolved content, we try to initialize it first which
// might put us back into one of the other states.
switch (chunk.status) {
case RESOLVED_MODEL:
initializeModelChunk(chunk);
break;
case RESOLVED_MODULE:
initializeModuleChunk(chunk);
break;
}
// The status might have changed after initialization.
switch (chunk.status) {
case INITIALIZED:
return chunk.value;
case PENDING:
case BLOCKED:
case HALTED:
// eslint-disable-next-line no-throw-literal
throw ((chunk: any): Thenable<T>);
default:
throw chunk.reason;
}
}
export function getRoot<T>(weakResponse: WeakResponse): Thenable<T> {
const response = unwrapWeakResponse(weakResponse);
const chunk = getChunk(response, 0);
return (chunk: any);
}
function createPendingChunk<T>(response: Response): PendingChunk<T> {
if (__DEV__) {
// Retain a strong reference to the Response while we wait for the result.
if (response._pendingChunks++ === 0) {
response._weakResponse.response = response;
if (response._pendingInitialRender !== null) {
clearTimeout(response._pendingInitialRender);
response._pendingInitialRender = null;
}
}
}
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(PENDING, null, null);
}
function releasePendingChunk(response: Response, chunk: SomeChunk<any>): void {
if (__DEV__ && chunk.status === PENDING) {
if (--response._pendingChunks === 0) {
// We're no longer waiting for any more chunks. We can release the strong reference
// to the response. We'll regain it if we ask for any more data later on.
response._weakResponse.response = null;
// Wait a short period to see if any more chunks get asked for. E.g. by a React render.
// These chunks might discover more pending chunks.
// If we don't ask for more then we assume that those chunks weren't blocking initial
// render and are excluded from the performance track.
response._pendingInitialRender = setTimeout(
flushInitialRenderPerformance.bind(null, response),
100,
);
}
}
}
function createBlockedChunk<T>(response: Response): BlockedChunk<T> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(BLOCKED, null, null);
}
function createErrorChunk<T>(
response: Response,
error: mixed,
): ErroredChunk<T> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(ERRORED, null, error);
}
function filterDebugInfo(
response: Response,
value: {_debugInfo: ReactDebugInfo, ...},
) {
if (response._debugEndTime === null) {
// No end time was defined, so we keep all debug info entries.
return;
}
// Remove any debug info entries after the defined end time. For async info
// that means we're including anything that was awaited before the end time,
// but it doesn't need to be resolved before the end time.
const relativeEndTime =
response._debugEndTime -
// $FlowFixMe[prop-missing]
performance.timeOrigin;
const debugInfo = [];
for (let i = 0; i < value._debugInfo.length; i++) {
const info = value._debugInfo[i];
if (typeof info.time === 'number' && info.time > relativeEndTime) {
break;
}
debugInfo.push(info);
}
value._debugInfo = debugInfo;
}
function moveDebugInfoFromChunkToInnerValue<T>(
chunk: InitializedChunk<T> | InitializedStreamChunk<any>,
value: T,
): void {
// Remove the debug info from the initialized chunk, and add it to the inner
// value instead. This can be a React element, an array, or an uninitialized
// Lazy.
const resolvedValue = resolveLazy(value);
if (
typeof resolvedValue === 'object' &&
resolvedValue !== null &&
(isArray(resolvedValue) ||
typeof resolvedValue[ASYNC_ITERATOR] === 'function' ||
resolvedValue.$$typeof === REACT_ELEMENT_TYPE ||
resolvedValue.$$typeof === REACT_LAZY_TYPE)
) {
const debugInfo = chunk._debugInfo.splice(0);
if (isArray(resolvedValue._debugInfo)) {
// $FlowFixMe[method-unbinding]
resolvedValue._debugInfo.unshift.apply(
resolvedValue._debugInfo,
debugInfo,
);
} else if (!Object.isFrozen(resolvedValue)) {
Object.defineProperty((resolvedValue: any), '_debugInfo', {
configurable: false,
enumerable: false,
writable: true,
value: debugInfo,
});
}
// TODO: If the resolved value is a frozen element (e.g. a client-created
// element from a temporary reference, or a JSX element exported as a client
// reference), server debug info is currently dropped because the element
// can't be mutated. We should probably clone the element so each rendering
// context gets its own mutable copy with the correct debug info.
}
}
function processChunkDebugInfo<T>(
response: Response,
chunk: InitializedChunk<T> | InitializedStreamChunk<any>,
value: T,
): void {
filterDebugInfo(response, chunk);
moveDebugInfoFromChunkToInnerValue(chunk, value);
}
function wakeChunk<T>(
response: Response,
listeners: Array<InitializationReference | (T => mixed)>,
value: T,
chunk: InitializedChunk<T>,
): void {
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i];
if (typeof listener === 'function') {
listener(value);
} else {
fulfillReference(response, listener, value, chunk);
}
}
if (__DEV__) {
processChunkDebugInfo(response, chunk, value);
}
}
function rejectChunk(
response: Response,
listeners: Array<InitializationReference | (mixed => mixed)>,
error: mixed,
): void {
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i];
if (typeof listener === 'function') {
listener(error);
} else {
rejectReference(response, listener.handler, error);
}
}
}
function resolveBlockedCycle<T>(
resolvedChunk: SomeChunk<T>,
reference: InitializationReference,
): null | InitializationHandler {
const referencedChunk = reference.handler.chunk;
if (referencedChunk === null) {
return null;
}
if (referencedChunk === resolvedChunk) {
// We found the cycle. We can resolve the blocked cycle now.
return reference.handler;
}
const resolveListeners = referencedChunk.value;
if (resolveListeners !== null) {
for (let i = 0; i < resolveListeners.length; i++) {
const listener = resolveListeners[i];
if (typeof listener !== 'function') {
const foundHandler = resolveBlockedCycle(resolvedChunk, listener);
if (foundHandler !== null) {
return foundHandler;
}
}
}
}
return null;
}
function wakeChunkIfInitialized<T>(
response: Response,
chunk: SomeChunk<T>,
resolveListeners: Array<InitializationReference | (T => mixed)>,
rejectListeners: null | Array<InitializationReference | (mixed => mixed)>,
): void {
switch (chunk.status) {
case INITIALIZED:
wakeChunk(response, resolveListeners, chunk.value, chunk);
break;
case BLOCKED:
// It is possible that we're blocked on our own chunk if it's a cycle.
// Before adding back the listeners to the chunk, let's check if it would
// result in a cycle.
for (let i = 0; i < resolveListeners.length; i++) {
const listener = resolveListeners[i];
if (typeof listener !== 'function') {
const reference: InitializationReference = listener;
const cyclicHandler = resolveBlockedCycle(chunk, reference);
if (cyclicHandler !== null) {
// This reference points back to this chunk. We can resolve the cycle by
// using the value from that handler.
fulfillReference(response, reference, cyclicHandler.value, chunk);
resolveListeners.splice(i, 1);
i--;
if (rejectListeners !== null) {
const rejectionIdx = rejectListeners.indexOf(reference);
if (rejectionIdx !== -1) {
rejectListeners.splice(rejectionIdx, 1);
}
}
// The status might have changed after fulfilling the reference.
switch ((chunk: SomeChunk<T>).status) {
case INITIALIZED:
const initializedChunk: InitializedChunk<T> = (chunk: any);
wakeChunk(
response,
resolveListeners,
initializedChunk.value,
initializedChunk,
);
return;
case ERRORED:
if (rejectListeners !== null) {
rejectChunk(response, rejectListeners, chunk.reason);
}
return;
}
}
}
}
// Fallthrough
case PENDING:
if (chunk.value) {
for (let i = 0; i < resolveListeners.length; i++) {
chunk.value.push(resolveListeners[i]);
}
} else {
chunk.value = resolveListeners;
}
if (chunk.reason) {
if (rejectListeners) {
for (let i = 0; i < rejectListeners.length; i++) {
chunk.reason.push(rejectListeners[i]);
}
}
} else {
chunk.reason = rejectListeners;
}
break;
case ERRORED:
if (rejectListeners) {
rejectChunk(response, rejectListeners, chunk.reason);
}
break;
}
}
function triggerErrorOnChunk<T>(
response: Response,
chunk: SomeChunk<T>,
error: mixed,
): void {
if (chunk.status !== PENDING && chunk.status !== BLOCKED) {
// If we get more data to an already resolved ID, we assume that it's
// a stream chunk since any other row shouldn't have more than one entry.
const streamChunk: InitializedStreamChunk<any> = (chunk: any);
const controller = streamChunk.reason;
// $FlowFixMe[incompatible-call]: The error method should accept mixed.
controller.error(error);
return;
}
releasePendingChunk(response, chunk);
const listeners = chunk.reason;
if (__DEV__ && chunk.status === PENDING) {
// Lazily initialize any debug info and block the initializing chunk on any unresolved entries.
if (chunk._debugChunk != null) {
const prevHandler = initializingHandler;
const prevChunk = initializingChunk;
initializingHandler = null;
const cyclicChunk: BlockedChunk<T> = (chunk: any);
cyclicChunk.status = BLOCKED;
cyclicChunk.value = null;
cyclicChunk.reason = null;
if ((enableProfilerTimer && enableComponentPerformanceTrack) || __DEV__) {
initializingChunk = cyclicChunk;
}
try {
initializeDebugChunk(response, chunk);
if (initializingHandler !== null) {
if (initializingHandler.errored) {
// Ignore error parsing debug info, we'll report the original error instead.
} else if (initializingHandler.deps > 0) {
// TODO: Block the resolution of the error until all the debug info has loaded.
// We currently don't have a way to throw an error after all dependencies have
// loaded because we currently treat errors as immediately cancelling the handler.
}
}
} finally {
initializingHandler = prevHandler;
initializingChunk = prevChunk;
}
}
}
const erroredChunk: ErroredChunk<T> = (chunk: any);
erroredChunk.status = ERRORED;
erroredChunk.reason = error;
if (listeners !== null) {
rejectChunk(response, listeners, error);
}
}
function createResolvedModelChunk<T>(
response: Response,
value: UninitializedModel,
): ResolvedModelChunk<T> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(RESOLVED_MODEL, value, response);
}
function createResolvedModuleChunk<T>(
response: Response,
value: ClientReference<T>,
): ResolvedModuleChunk<T> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(RESOLVED_MODULE, value, null);
}
function createInitializedTextChunk(
response: Response,
value: string,
): InitializedChunk<string> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(INITIALIZED, value, null);
}
function createInitializedBufferChunk(
response: Response,
value: $ArrayBufferView | ArrayBuffer,
): InitializedChunk<Uint8Array> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(INITIALIZED, value, null);
}
function createInitializedIteratorResultChunk<T>(
response: Response,
value: T,
done: boolean,
): InitializedChunk<IteratorResult<T, T>> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(INITIALIZED, {done: done, value: value}, null);
}
function createInitializedStreamChunk<
T: ReadableStream | $AsyncIterable<any, any, void>,
>(
response: Response,
value: T,
controller: FlightStreamController,
): InitializedChunk<T> {
if (__DEV__) {
// Retain a strong reference to the Response while we wait for chunks.
if (response._pendingChunks++ === 0) {
response._weakResponse.response = response;
}
}
// We use the reason field to stash the controller since we already have that
// field. It's a bit of a hack but efficient.
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(INITIALIZED, value, controller);
}
function createResolvedIteratorResultChunk<T>(
response: Response,
value: UninitializedModel,
done: boolean,
): ResolvedModelChunk<IteratorResult<T, T>> {
// To reuse code as much code as possible we add the wrapper element as part of the JSON.
const iteratorResultJSON =
(done ? '{"done":true,"value":' : '{"done":false,"value":') + value + '}';
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(RESOLVED_MODEL, iteratorResultJSON, response);
}
function resolveIteratorResultChunk<T>(
response: Response,
chunk: SomeChunk<IteratorResult<T, T>>,
value: UninitializedModel,
done: boolean,
): void {
// To reuse code as much code as possible we add the wrapper element as part of the JSON.
const iteratorResultJSON =
(done ? '{"done":true,"value":' : '{"done":false,"value":') + value + '}';
resolveModelChunk(response, chunk, iteratorResultJSON);
}
function resolveModelChunk<T>(
response: Response,
chunk: SomeChunk<T>,
value: UninitializedModel,
): void {
if (chunk.status !== PENDING) {
// If we get more data to an already resolved ID, we assume that it's
// a stream chunk since any other row shouldn't have more than one entry.
const streamChunk: InitializedStreamChunk<any> = (chunk: any);
const controller = streamChunk.reason;
controller.enqueueModel(value);
return;
}
releasePendingChunk(response, chunk);
const resolveListeners = chunk.value;
const rejectListeners = chunk.reason;
const resolvedChunk: ResolvedModelChunk<T> = (chunk: any);
resolvedChunk.status = RESOLVED_MODEL;
resolvedChunk.value = value;
resolvedChunk.reason = response;
if (resolveListeners !== null) {
// This is unfortunate that we're reading this eagerly if
// we already have listeners attached since they might no
// longer be rendered or might not be the highest pri.
initializeModelChunk(resolvedChunk);
// The status might have changed after initialization.
wakeChunkIfInitialized(response, chunk, resolveListeners, rejectListeners);
}
}
function resolveModuleChunk<T>(
response: Response,
chunk: SomeChunk<T>,
value: ClientReference<T>,
): void {
if (chunk.status !== PENDING && chunk.status !== BLOCKED) {
// We already resolved. We didn't expect to see this.
return;
}
releasePendingChunk(response, chunk);
const resolveListeners = chunk.value;
const rejectListeners = chunk.reason;
const resolvedChunk: ResolvedModuleChunk<T> = (chunk: any);
resolvedChunk.status = RESOLVED_MODULE;
resolvedChunk.value = value;
resolvedChunk.reason = null;
if (__DEV__) {
const debugInfo = getModuleDebugInfo(value);
if (debugInfo !== null) {
// Add to the live set if it was already initialized.
// $FlowFixMe[method-unbinding]
resolvedChunk._debugInfo.push.apply(resolvedChunk._debugInfo, debugInfo);
}
}
if (resolveListeners !== null) {
initializeModuleChunk(resolvedChunk);
wakeChunkIfInitialized(response, chunk, resolveListeners, rejectListeners);
}
}
type InitializationReference = {
handler: InitializationHandler,
parentObject: Object,
key: string,
map: (
response: Response,
model: any,
parentObject: Object,
key: string,
) => any,
path: Array<string>,
isDebug?: boolean, // DEV-only
};
type InitializationHandler = {
parent: null | InitializationHandler,
chunk: null | BlockedChunk<any>,
value: any,
reason: any,
deps: number,
errored: boolean,
};
let initializingHandler: null | InitializationHandler = null;
let initializingChunk: null | BlockedChunk<any> = null;
let isInitializingDebugInfo: boolean = false;
function initializeDebugChunk(
response: Response,
chunk: ResolvedModelChunk<any> | PendingChunk<any>,
): void {
const debugChunk = chunk._debugChunk;
if (debugChunk !== null) {
const debugInfo = chunk._debugInfo;
const prevIsInitializingDebugInfo = isInitializingDebugInfo;
isInitializingDebugInfo = true;
try {
if (debugChunk.status === RESOLVED_MODEL) {
// Find the index of this debug info by walking the linked list.
let idx = debugInfo.length;
let c = debugChunk._debugChunk;
while (c !== null) {
if (c.status !== INITIALIZED) {
idx++;
}
c = c._debugChunk;
}
// Initializing the model for the first time.
initializeModelChunk(debugChunk);
const initializedChunk = ((debugChunk: any): SomeChunk<any>);
switch (initializedChunk.status) {
case INITIALIZED: {
debugInfo[idx] = initializeDebugInfo(
response,
initializedChunk.value,
);
break;
}
case BLOCKED:
case PENDING: {
waitForReference(
initializedChunk,
debugInfo,
'' + idx,
response,
initializeDebugInfo,
[''], // path
true,
);
break;
}
default:
throw initializedChunk.reason;
}
} else {
switch (debugChunk.status) {
case INITIALIZED: {
// Already done.
break;
}
case BLOCKED:
case PENDING: {
// Signal to the caller that we need to wait.
waitForReference(
debugChunk,
{}, // noop, since we'll have already added an entry to debug info
'debug', // noop, but we need it to not be empty string since that indicates the root object
response,