-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathReactFlightReplyServer.js
More file actions
1937 lines (1825 loc) · 56.7 KB
/
ReactFlightReplyServer.js
File metadata and controls
1937 lines (1825 loc) · 56.7 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 {Thenable} from 'shared/ReactTypes';
// The server acts as a Client of itself when resolving Server References.
// That's why we import the Client configuration from the Server.
// Everything is aliased as their Server equivalence for clarity.
import type {
ServerReferenceId,
ServerManifest,
ClientReference as ServerReference,
} from 'react-client/src/ReactFlightClientConfig';
import type {TemporaryReferenceSet} from './ReactFlightServerTemporaryReferences';
import {
resolveServerReference,
preloadModule,
requireModule,
} from 'react-client/src/ReactFlightClientConfig';
import {
createTemporaryReference,
registerTemporaryReference,
} from './ReactFlightServerTemporaryReferences';
import {ASYNC_ITERATOR} from 'shared/ReactSymbols';
import hasOwnProperty from 'shared/hasOwnProperty';
import getPrototypeOf from 'shared/getPrototypeOf';
import isArray from 'shared/isArray';
interface FlightStreamController {
enqueueModel(json: string): void;
close(json: string): void;
error(error: Error): void;
}
export type JSONValue =
| number
| null
| boolean
| string
| {+[key: string]: JSONValue}
| $ReadOnlyArray<JSONValue>;
const PENDING = 'pending';
const BLOCKED = 'blocked';
const RESOLVED_MODEL = 'resolved_model';
const INITIALIZED = 'fulfilled';
const ERRORED = 'rejected';
const __PROTO__ = '__proto__';
type RESPONSE_SYMBOL_TYPE = 'RESPONSE_SYMBOL'; // Fake symbol type.
const RESPONSE_SYMBOL: RESPONSE_SYMBOL_TYPE = (Symbol(): any);
type PendingChunk<T> = {
status: 'pending',
value: null | Array<InitializationReference | (T => mixed)>,
reason: null | Array<InitializationReference | (mixed => mixed)>,
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)>,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type ResolvedModelChunk<T> = {
status: 'resolved_model',
value: string,
reason: {id: number, [RESPONSE_SYMBOL_TYPE]: Response},
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type InitializedChunk<T> = {
status: 'fulfilled',
value: T,
reason: null | NestedArrayContext,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type InitializedStreamChunk<
T: ReadableStream | $AsyncIterable<any, any, void>,
> = {
status: 'fulfilled',
value: T,
reason: FlightStreamController,
then(resolve: (ReadableStream) => mixed, reject?: (mixed) => mixed): void,
};
type ErroredChunk<T> = {
status: 'rejected',
value: null,
reason: mixed,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type SomeChunk<T> =
| PendingChunk<T>
| BlockedChunk<T>
| ResolvedModelChunk<T>
| InitializedChunk<T>
| ErroredChunk<T>;
// $FlowFixMe[missing-this-annot]
function ReactPromise(status: any, value: any, reason: any) {
this.status = status;
this.value = value;
this.reason = reason;
}
// 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;
}
// The status might have changed after initialization.
switch (chunk.status) {
case INITIALIZED:
if (typeof resolve === 'function') {
let inspectedValue = chunk.value;
// Recursively check if the value is itself a ReactPromise and if so if it points
// back to itself. This helps catch recursive thenables early error.
let cycleProtection = 0;
const visited = new Set<typeof ReactPromise>();
while (inspectedValue instanceof ReactPromise) {
cycleProtection++;
if (
inspectedValue === chunk ||
visited.has(inspectedValue) ||
cycleProtection > 1000
) {
if (typeof reject === 'function') {
reject(new Error('Cannot have cyclic thenables.'));
}
return;
}
visited.add(inspectedValue);
if (inspectedValue.status === INITIALIZED) {
inspectedValue = inspectedValue.value;
} else {
// If this is lazily resolved, pending or blocked, it'll eventually become
// initialized and break the loop. Rejected also breaks it.
break;
}
}
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;
default:
if (typeof reject === 'function') {
reject(chunk.reason);
}
break;
}
};
const ObjectPrototype = Object.prototype;
const ArrayPrototype = Array.prototype;
export type Response = {
_bundlerConfig: ServerManifest,
_prefix: string,
_formData: FormData,
_chunks: Map<number, SomeChunk<any>>,
_closed: boolean,
_closedReason: mixed,
_temporaryReferences: void | TemporaryReferenceSet,
_rootArrayContexts: WeakMap<$ReadOnlyArray<mixed>, NestedArrayContext>,
_arraySizeLimit: number,
};
export function getRoot<T>(response: Response): Thenable<T> {
const chunk = getChunk(response, 0);
return (chunk: any);
}
function createPendingChunk<T>(response: Response): PendingChunk<T> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(PENDING, null, null);
}
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.reason);
}
}
}
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 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:
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;
}
const listeners = chunk.reason;
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: string,
id: number,
): ResolvedModelChunk<T> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(RESOLVED_MODEL, value, {
id,
[RESPONSE_SYMBOL]: response,
});
}
function createErroredChunk<T>(
response: Response,
reason: mixed,
): ErroredChunk<T> {
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
return new ReactPromise(ERRORED, null, reason);
}
function resolveModelChunk<T>(
response: Response,
chunk: SomeChunk<T>,
value: string,
id: number,
): 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;
if (value[0] === 'C') {
controller.close(value === 'C' ? '"$undefined"' : value.slice(1));
} else {
controller.enqueueModel(value);
}
return;
}
const resolveListeners = chunk.value;
const rejectListeners = chunk.reason;
const resolvedChunk: ResolvedModelChunk<T> = (chunk: any);
resolvedChunk.status = RESOLVED_MODEL;
resolvedChunk.value = value;
resolvedChunk.reason = {id, [RESPONSE_SYMBOL]: 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 createInitializedStreamChunk<
T: ReadableStream | $AsyncIterable<any, any, void>,
>(
response: Response,
value: T,
controller: FlightStreamController,
): InitializedChunk<T> {
// 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: string,
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, {
id: -1,
[RESPONSE_SYMBOL]: response,
});
}
function resolveIteratorResultChunk<T>(
response: Response,
chunk: SomeChunk<IteratorResult<T, T>>,
value: string,
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, -1);
}
function loadServerReference<A: Iterable<any>, T>(
response: Response,
metaData: {
id: any,
bound: null | Thenable<Array<any>>,
},
parentObject: Object,
key: string,
): (...A) => Promise<T> {
const id: ServerReferenceId = metaData.id;
if (typeof id !== 'string') {
return (null: any);
}
if (key === 'then') {
// This should never happen because we always serialize objects with then-functions
// as "thenable" which reduces to ReactPromise with no other fields.
return (null: any);
}
// Check for a cached promise from a previous call with the same metadata.
// This handles deduplication when the same server reference appears multiple
// times in the payload.
const cachedPromise: SomeChunk<T> | void = (metaData: any).$$promise;
if (cachedPromise !== undefined) {
if (cachedPromise.status === INITIALIZED) {
// The value was already resolved by a previous call.
const resolvedValue: T = cachedPromise.value;
if (key === __PROTO__) {
return (null: any);
}
parentObject[key] = resolvedValue;
return (resolvedValue: any);
}
// The promise is still blocked. Increment the handler dependency count ...
let handler: InitializationHandler;
if (initializingHandler) {
handler = initializingHandler;
handler.deps++;
} else {
handler = initializingHandler = {
chunk: null,
value: null,
reason: null,
deps: 1,
errored: false,
};
}
// ... and register resolve and reject listeners on the promise.
cachedPromise.then(
resolveReference.bind(null, response, handler, parentObject, key),
rejectReference.bind(null, response, handler),
);
// Return a place holder value for now.
return (null: any);
}
// This is the first call for this server reference metadata. Create a cached
// promise to be used for subsequent calls.
// $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
const blockedPromise: BlockedChunk<T> = new ReactPromise(BLOCKED, null, null);
(metaData: any).$$promise = blockedPromise;
const serverReference: ServerReference<T> =
resolveServerReference<$FlowFixMe>(response._bundlerConfig, id);
// We expect most servers to not really need this because you'd just have all
// the relevant modules already loaded but it allows for lazy loading of code
// if needed.
const bound = metaData.bound;
let serverReferencePromise: null | Thenable<any> =
preloadModule(serverReference);
if (!serverReferencePromise) {
if (bound instanceof ReactPromise) {
serverReferencePromise = Promise.resolve(bound);
} else {
const resolvedValue = (requireModule(serverReference): any);
// Resolve the cached promise synchronously.
const initializedPromise: InitializedChunk<T> = (blockedPromise: any);
initializedPromise.status = INITIALIZED;
initializedPromise.value = resolvedValue;
initializedPromise.reason = null;
return resolvedValue;
}
} else if (bound instanceof ReactPromise) {
serverReferencePromise = Promise.all([serverReferencePromise, bound]);
}
let handler: InitializationHandler;
if (initializingHandler) {
handler = initializingHandler;
handler.deps++;
} else {
handler = initializingHandler = {
chunk: null,
value: null,
reason: null,
deps: 1,
errored: false,
};
}
function fulfill(): void {
let resolvedValue = (requireModule(serverReference): any);
if (metaData.bound) {
// This promise is coming from us and should have initialized by now.
const promiseValue = (metaData.bound: any).value;
const boundArgs: Array<any> = isArray(promiseValue)
? promiseValue.slice(0)
: [];
if (boundArgs.length > MAX_BOUND_ARGS) {
reject(
new Error(
'Server Function has too many bound arguments. Received ' +
boundArgs.length +
' but the limit is ' +
MAX_BOUND_ARGS +
'.',
),
);
return;
}
boundArgs.unshift(null); // this
resolvedValue = resolvedValue.bind.apply(resolvedValue, boundArgs);
}
// Resolve the cached promise so subsequent references can use the value.
const resolveListeners = blockedPromise.value;
const initializedPromise: InitializedChunk<T> = (blockedPromise: any);
initializedPromise.status = INITIALIZED;
initializedPromise.value = resolvedValue;
initializedPromise.reason = null;
if (resolveListeners !== null) {
// Notify any resolve listeners that were added via .then() from
// subsequent loadServerReference calls for the same reference.
wakeChunk(response, resolveListeners, resolvedValue, initializedPromise);
}
resolveReference(response, handler, parentObject, key, resolvedValue);
}
function reject(error: mixed): void {
// Mark the cached promise as errored so subsequent references fail too.
const rejectListeners = blockedPromise.reason;
const erroredPromise: ErroredChunk<T> = (blockedPromise: any);
erroredPromise.status = ERRORED;
erroredPromise.value = null;
erroredPromise.reason = error;
if (rejectListeners !== null) {
// Notify any reject listeners that were added via .then() from subsequent
// loadServerReference calls for the same reference.
rejectChunk(response, rejectListeners, error);
}
rejectReference(response, handler, error);
}
serverReferencePromise.then(fulfill, reject);
// Return a place holder value for now.
return (null: any);
}
function reviveModel(
response: Response,
parentObj: any,
parentKey: string,
value: JSONValue,
reference: void | string,
arrayRoot: null | NestedArrayContext,
): any {
if (typeof value === 'string') {
// We can't use .bind here because we need the "this" value.
return parseModelString(
response,
parentObj,
parentKey,
value,
reference,
arrayRoot,
);
}
if (typeof value === 'object' && value !== null) {
if (
reference !== undefined &&
response._temporaryReferences !== undefined
) {
// Store this object's reference in case it's returned later.
registerTemporaryReference(
response._temporaryReferences,
value,
reference,
);
}
if (isArray(value)) {
let childContext: NestedArrayContext;
if (arrayRoot === null) {
childContext = ({
count: 0,
fork: false,
}: NestedArrayContext);
response._rootArrayContexts.set(value, childContext);
} else {
childContext = arrayRoot;
}
if (value.length > 1) {
childContext.fork = true;
}
bumpArrayCount(childContext, value.length + 1, response);
for (let i = 0; i < value.length; i++) {
const childRef =
reference !== undefined ? reference + ':' + i : undefined;
// $FlowFixMe[cannot-write]
value[i] = reviveModel(
response,
value,
'' + i,
value[i],
childRef,
childContext,
);
}
} else {
for (const key in value) {
if (hasOwnProperty.call(value, key)) {
if (key === __PROTO__) {
// $FlowFixMe[cannot-write]
delete value[key];
continue;
}
const childRef =
reference !== undefined && key.indexOf(':') === -1
? reference + ':' + key
: undefined;
const newValue = reviveModel(
response,
value,
key,
value[key],
childRef,
null, // The array context resets when we're entering a non-array
);
if (newValue !== undefined) {
// $FlowFixMe[cannot-write]
value[key] = newValue;
} else {
// $FlowFixMe[cannot-write]
delete value[key];
}
}
}
}
}
return value;
}
type NestedArrayContext = {
// Keeps track of how many slots, bytes or characters are in nested arrays/strings/typed arrays.
count: number,
// A single child is itself not harmful. There needs to be at least one parent array with more
// than one child.
fork: boolean,
};
function bumpArrayCount(
arrayContext: NestedArrayContext,
slots: number,
response: Response,
): void {
const newCount = (arrayContext.count += slots);
if (newCount > response._arraySizeLimit && arrayContext.fork) {
throw new Error(
'Maximum array nesting exceeded. Large nested arrays can be dangerous. Try adding intermediate objects.',
);
}
}
type InitializationReference = {
handler: InitializationHandler,
parentObject: Object,
key: string,
map: (
response: Response,
model: any,
parentObject: Object,
key: string,
) => any,
path: Array<string>,
arrayRoot: null | NestedArrayContext,
};
type InitializationHandler = {
chunk: null | BlockedChunk<any>,
value: any,
reason: any,
deps: number,
errored: boolean,
};
let initializingHandler: null | InitializationHandler = null;
function initializeModelChunk<T>(chunk: ResolvedModelChunk<T>): void {
const prevHandler = initializingHandler;
initializingHandler = null;
const {[RESPONSE_SYMBOL]: response, id} = chunk.reason;
const rootReference = id === -1 ? undefined : id.toString(16);
const resolvedModel = chunk.value;
// We go to the BLOCKED state until we've fully resolved this.
// We do this before parsing in case we try to initialize the same chunk
// while parsing the model. Such as in a cyclic reference.
const cyclicChunk: BlockedChunk<T> = (chunk: any);
cyclicChunk.status = BLOCKED;
cyclicChunk.value = null;
cyclicChunk.reason = null;
try {
const rawModel = JSON.parse(resolvedModel);
// The root might not be an array but if it is we want to track the count of entries.
const arrayRoot: NestedArrayContext = {
count: 0,
fork: false,
};
const value: T = reviveModel(
response,
{'': rawModel},
'',
rawModel,
rootReference,
arrayRoot,
);
// Invoke any listeners added while resolving this model. I.e. cyclic
// references. This may or may not fully resolve the model depending on
// if they were blocked.
const resolveListeners = cyclicChunk.value;
if (resolveListeners !== null) {
cyclicChunk.value = null;
cyclicChunk.reason = null;
for (let i = 0; i < resolveListeners.length; i++) {
const listener = resolveListeners[i];
if (typeof listener === 'function') {
listener(value);
} else {
fulfillReference(response, listener, value, arrayRoot);
}
}
}
if (initializingHandler !== null) {
if (initializingHandler.errored) {
throw initializingHandler.reason;
}
if (initializingHandler.deps > 0) {
// We discovered new dependencies on modules that are not yet resolved.
// We have to keep the BLOCKED state until they're resolved.
initializingHandler.value = value;
initializingHandler.reason = arrayRoot;
initializingHandler.chunk = cyclicChunk;
return;
}
}
const initializedChunk: InitializedChunk<T> = (chunk: any);
initializedChunk.status = INITIALIZED;
initializedChunk.value = value;
initializedChunk.reason = arrayRoot;
} catch (error) {
const erroredChunk: ErroredChunk<T> = (chunk: any);
erroredChunk.status = ERRORED;
erroredChunk.reason = error;
} finally {
initializingHandler = prevHandler;
}
}
// Report that any missing chunks in the model is now going to throw this
// error upon read. Also notify any pending promises.
export function reportGlobalError(response: Response, error: Error): void {
response._closed = true;
response._closedReason = error;
response._chunks.forEach(chunk => {
// If this chunk was already resolved or errored, it won't
// trigger an error but if it wasn't then we need to
// because we won't be getting any new data to resolve it.
if (chunk.status === PENDING) {
triggerErrorOnChunk(response, chunk, error);
} else if (chunk.status === INITIALIZED && chunk.reason !== null) {
const maybeController = chunk.reason;
// $FlowFixMe
if (typeof maybeController.error === 'function') {
maybeController.error(error);
}
}
});
}
function getChunk(response: Response, id: number): SomeChunk<any> {
const chunks = response._chunks;
let chunk = chunks.get(id);
if (!chunk) {
const prefix = response._prefix;
const key = prefix + id;
// Check if we have this field in the backing store already.
const backingEntry = response._formData.get(key);
if (typeof backingEntry === 'string') {
chunk = createResolvedModelChunk(response, backingEntry, id);
} else if (response._closed) {
// We have already errored the response and we're not going to get
// anything more streaming in so this will immediately error.
chunk = createErroredChunk(response, response._closedReason);
} else {
// We're still waiting on this entry to stream in.
chunk = createPendingChunk(response);
}
chunks.set(id, chunk);
}
return chunk;
}
function fulfillReference(
response: Response,
reference: InitializationReference,
value: any,
arrayRoot: null | NestedArrayContext,
): void {
const {handler, parentObject, key, map, path} = reference;
let resolvedValue;
try {
let localLength: number = 0;
const rootArrayContexts = response._rootArrayContexts;
for (let i = 1; i < path.length; i++) {
// The server doesn't have any lazy references so we don't expect to go through a Promise.
const name = path[i];
if (
typeof value === 'object' &&
value !== null &&
(getPrototypeOf(value) === ObjectPrototype ||
getPrototypeOf(value) === ArrayPrototype) &&
hasOwnProperty.call(value, name)
) {
value = value[name];
if (isArray(value)) {
localLength = 0;
arrayRoot = rootArrayContexts.get(value) || arrayRoot;
} else {
arrayRoot = null;
if (typeof value === 'string') {
localLength = value.length;
} else if (typeof value === 'bigint') {
// Estimate the length to avoid expensive toString() calls on large
// BigInt values. If the value is too large, we get Infinity, which
// will trigger the array size limit error.
// eslint-disable-next-line react-internal/no-primitive-constructors
const n = Math.abs(Number(value));
if (n === 0) {
localLength = 1;
} else {
localLength = Math.floor(Math.log10(n)) + 1;
}
} else if (ArrayBuffer.isView(value)) {
localLength = value.byteLength;
} else {
localLength = 0;
}
}
} else {
throw new Error('Invalid reference.');
}
}
resolvedValue = map(response, value, parentObject, key);
// Add any array counts to the reference's array root. The value that we're
// resolving might have deep nesting that we need to resolve.
const referenceArrayRoot = reference.arrayRoot;
if (referenceArrayRoot !== null) {
if (arrayRoot !== null) {
if (arrayRoot.fork) {
referenceArrayRoot.fork = true;
}
bumpArrayCount(referenceArrayRoot, arrayRoot.count, response);
} else if (localLength > 0) {
bumpArrayCount(referenceArrayRoot, localLength, response);
}
}
} catch (error) {
rejectReference(response, handler, error);
return;
}
// There are no Elements or Debug Info to transfer here.
resolveReference(response, handler, parentObject, key, resolvedValue);
}
function resolveReference(
response: Response,
handler: InitializationHandler,
parentObject: Object,
key: string,
resolvedValue: mixed,
): void {
if (key !== __PROTO__) {
parentObject[key] = resolvedValue;
}
// If this is the root object for a model reference, where `handler.value`
// is a stale `null`, the resolved value can be used directly.
if (key === '' && handler.value === null) {
handler.value = resolvedValue;
}
handler.deps--;
if (handler.deps === 0) {
const chunk = handler.chunk;
if (chunk === null || chunk.status !== BLOCKED) {
return;
}
const resolveListeners = chunk.value;
const initializedChunk: InitializedChunk<any> = (chunk: any);
initializedChunk.status = INITIALIZED;
initializedChunk.value = handler.value;
initializedChunk.reason = handler.reason; // Used by streaming chunks
if (resolveListeners !== null) {
wakeChunk(response, resolveListeners, handler.value, initializedChunk);
}
}
}
function rejectReference(
response: Response,
handler: InitializationHandler,
error: mixed,
): void {
if (handler.errored) {
// We've already errored. We could instead build up an AggregateError
// but if there are multiple errors we just take the first one like
// Promise.all.
return;
}
handler.errored = true;
handler.value = null;
handler.reason = error;
const chunk = handler.chunk;
if (chunk === null || chunk.status !== BLOCKED) {
return;
}
// There's no debug info to forward in this direction.
triggerErrorOnChunk(response, chunk, error);
}
function waitForReference<T>(
response: Response,
referencedChunk: BlockedChunk<T>,
parentObject: Object,
key: string,
arrayRoot: null | NestedArrayContext,
map: (response: Response, model: any, parentObject: Object, key: string) => T,
path: Array<string>,
): T {
let handler: InitializationHandler;
if (initializingHandler) {
handler = initializingHandler;
handler.deps++;
} else {
handler = initializingHandler = {
chunk: null,
value: null,
reason: null,
deps: 1,
errored: false,
};
}
const reference: InitializationReference = {
handler,
parentObject,
key,
map,
path,
arrayRoot,
};
// Add "listener".
if (referencedChunk.value === null) {
referencedChunk.value = [reference];
} else {
referencedChunk.value.push(reference);
}
if (referencedChunk.reason === null) {
referencedChunk.reason = [reference];
} else {
referencedChunk.reason.push(reference);
}
// Return a place holder value for now.