react-server-dom-webpack 18.3.0-next-fa4314841-20230502 → 19.0.0-canary-05797cceb-20240328

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/cjs/react-server-dom-webpack-client.browser.development.js +1768 -1188
  2. package/cjs/react-server-dom-webpack-client.browser.production.js +1739 -0
  3. package/cjs/react-server-dom-webpack-client.browser.production.min.js +40 -34
  4. package/cjs/react-server-dom-webpack-client.browser.production.min.js.map +1 -0
  5. package/cjs/react-server-dom-webpack-client.edge.development.js +1755 -221
  6. package/cjs/react-server-dom-webpack-client.edge.production.js +1986 -0
  7. package/cjs/react-server-dom-webpack-client.edge.production.min.js +45 -28
  8. package/cjs/react-server-dom-webpack-client.edge.production.min.js.map +1 -0
  9. package/cjs/react-server-dom-webpack-client.node.development.js +1743 -239
  10. package/cjs/react-server-dom-webpack-client.node.production.js +1942 -0
  11. package/cjs/react-server-dom-webpack-client.node.production.min.js +44 -28
  12. package/cjs/react-server-dom-webpack-client.node.production.min.js.map +1 -0
  13. package/cjs/react-server-dom-webpack-client.node.unbundled.development.js +1702 -194
  14. package/cjs/react-server-dom-webpack-client.node.unbundled.production.js +1895 -0
  15. package/cjs/react-server-dom-webpack-client.node.unbundled.production.min.js +43 -26
  16. package/cjs/react-server-dom-webpack-client.node.unbundled.production.min.js.map +1 -0
  17. package/cjs/react-server-dom-webpack-node-register.js +12 -18
  18. package/cjs/react-server-dom-webpack-node-register.js.map +1 -0
  19. package/cjs/react-server-dom-webpack-plugin.js +22 -19
  20. package/cjs/react-server-dom-webpack-plugin.js.map +1 -0
  21. package/cjs/react-server-dom-webpack-server.browser.development.js +1588 -808
  22. package/cjs/react-server-dom-webpack-server.browser.production.js +3257 -0
  23. package/cjs/react-server-dom-webpack-server.browser.production.min.js +80 -62
  24. package/cjs/react-server-dom-webpack-server.browser.production.min.js.map +1 -0
  25. package/cjs/react-server-dom-webpack-server.edge.development.js +1583 -811
  26. package/cjs/react-server-dom-webpack-server.edge.production.js +3261 -0
  27. package/cjs/react-server-dom-webpack-server.edge.production.min.js +82 -62
  28. package/cjs/react-server-dom-webpack-server.edge.production.min.js.map +1 -0
  29. package/cjs/react-server-dom-webpack-server.node.development.js +1575 -805
  30. package/cjs/react-server-dom-webpack-server.node.production.js +3464 -0
  31. package/cjs/react-server-dom-webpack-server.node.production.min.js +85 -67
  32. package/cjs/react-server-dom-webpack-server.node.production.min.js.map +1 -0
  33. package/cjs/react-server-dom-webpack-server.node.unbundled.development.js +1526 -761
  34. package/cjs/react-server-dom-webpack-server.node.unbundled.production.js +3391 -0
  35. package/cjs/react-server-dom-webpack-server.node.unbundled.production.min.js +82 -65
  36. package/cjs/react-server-dom-webpack-server.node.unbundled.production.min.js.map +1 -0
  37. package/esm/react-server-dom-webpack-node-loader.production.min.js +19 -12
  38. package/package.json +7 -13
  39. package/umd/react-server-dom-webpack-client.browser.development.js +1770 -1189
  40. package/umd/react-server-dom-webpack-client.browser.production.min.js +26 -20
  41. package/umd/react-server-dom-webpack-server.browser.development.js +1589 -808
  42. package/umd/react-server-dom-webpack-server.browser.production.min.js +55 -42
@@ -0,0 +1,3391 @@
1
+ /**
2
+ * @license React
3
+ * react-server-dom-webpack-server.node.unbundled.production.min.js
4
+ *
5
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ var util = require('util');
14
+ require('crypto');
15
+ var async_hooks = require('async_hooks');
16
+ var ReactDOM = require('react-dom');
17
+ var React = require('react');
18
+
19
+ // -----------------------------------------------------------------------------
20
+ const enablePostpone = false;
21
+
22
+ function scheduleWork(callback) {
23
+ setImmediate(callback);
24
+ }
25
+ function flushBuffered(destination) {
26
+ // If we don't have any more data to send right now.
27
+ // Flush whatever is in the buffer to the wire.
28
+ if (typeof destination.flush === 'function') {
29
+ // By convention the Zlib streams provide a flush function for this purpose.
30
+ // For Express, compression middleware adds this method.
31
+ destination.flush();
32
+ }
33
+ }
34
+ const VIEW_SIZE = 2048;
35
+ let currentView = null;
36
+ let writtenBytes = 0;
37
+ let destinationHasCapacity = true;
38
+ function beginWriting(destination) {
39
+ currentView = new Uint8Array(VIEW_SIZE);
40
+ writtenBytes = 0;
41
+ destinationHasCapacity = true;
42
+ }
43
+
44
+ function writeStringChunk(destination, stringChunk) {
45
+ if (stringChunk.length === 0) {
46
+ return;
47
+ } // maximum possible view needed to encode entire string
48
+
49
+
50
+ if (stringChunk.length * 3 > VIEW_SIZE) {
51
+ if (writtenBytes > 0) {
52
+ writeToDestination(destination, currentView.subarray(0, writtenBytes));
53
+ currentView = new Uint8Array(VIEW_SIZE);
54
+ writtenBytes = 0;
55
+ }
56
+
57
+ writeToDestination(destination, textEncoder.encode(stringChunk));
58
+ return;
59
+ }
60
+
61
+ let target = currentView;
62
+
63
+ if (writtenBytes > 0) {
64
+ target = currentView.subarray(writtenBytes);
65
+ }
66
+
67
+ const _textEncoder$encodeIn = textEncoder.encodeInto(stringChunk, target),
68
+ read = _textEncoder$encodeIn.read,
69
+ written = _textEncoder$encodeIn.written;
70
+
71
+ writtenBytes += written;
72
+
73
+ if (read < stringChunk.length) {
74
+ writeToDestination(destination, currentView.subarray(0, writtenBytes));
75
+ currentView = new Uint8Array(VIEW_SIZE);
76
+ writtenBytes = textEncoder.encodeInto(stringChunk.slice(read), currentView).written;
77
+ }
78
+
79
+ if (writtenBytes === VIEW_SIZE) {
80
+ writeToDestination(destination, currentView);
81
+ currentView = new Uint8Array(VIEW_SIZE);
82
+ writtenBytes = 0;
83
+ }
84
+ }
85
+
86
+ function writeViewChunk(destination, chunk) {
87
+ if (chunk.byteLength === 0) {
88
+ return;
89
+ }
90
+
91
+ if (chunk.byteLength > VIEW_SIZE) {
92
+ // this chunk may overflow a single view which implies it was not
93
+ // one that is cached by the streaming renderer. We will enqueu
94
+ // it directly and expect it is not re-used
95
+ if (writtenBytes > 0) {
96
+ writeToDestination(destination, currentView.subarray(0, writtenBytes));
97
+ currentView = new Uint8Array(VIEW_SIZE);
98
+ writtenBytes = 0;
99
+ }
100
+
101
+ writeToDestination(destination, chunk);
102
+ return;
103
+ }
104
+
105
+ let bytesToWrite = chunk;
106
+ const allowableBytes = currentView.length - writtenBytes;
107
+
108
+ if (allowableBytes < bytesToWrite.byteLength) {
109
+ // this chunk would overflow the current view. We enqueue a full view
110
+ // and start a new view with the remaining chunk
111
+ if (allowableBytes === 0) {
112
+ // the current view is already full, send it
113
+ writeToDestination(destination, currentView);
114
+ } else {
115
+ // fill up the current view and apply the remaining chunk bytes
116
+ // to a new view.
117
+ currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes);
118
+ writtenBytes += allowableBytes;
119
+ writeToDestination(destination, currentView);
120
+ bytesToWrite = bytesToWrite.subarray(allowableBytes);
121
+ }
122
+
123
+ currentView = new Uint8Array(VIEW_SIZE);
124
+ writtenBytes = 0;
125
+ }
126
+
127
+ currentView.set(bytesToWrite, writtenBytes);
128
+ writtenBytes += bytesToWrite.byteLength;
129
+
130
+ if (writtenBytes === VIEW_SIZE) {
131
+ writeToDestination(destination, currentView);
132
+ currentView = new Uint8Array(VIEW_SIZE);
133
+ writtenBytes = 0;
134
+ }
135
+ }
136
+
137
+ function writeChunk(destination, chunk) {
138
+ if (typeof chunk === 'string') {
139
+ writeStringChunk(destination, chunk);
140
+ } else {
141
+ writeViewChunk(destination, chunk);
142
+ }
143
+ }
144
+
145
+ function writeToDestination(destination, view) {
146
+ const currentHasCapacity = destination.write(view);
147
+ destinationHasCapacity = destinationHasCapacity && currentHasCapacity;
148
+ }
149
+
150
+ function writeChunkAndReturn(destination, chunk) {
151
+ writeChunk(destination, chunk);
152
+ return destinationHasCapacity;
153
+ }
154
+ function completeWriting(destination) {
155
+ if (currentView && writtenBytes > 0) {
156
+ destination.write(currentView.subarray(0, writtenBytes));
157
+ }
158
+
159
+ currentView = null;
160
+ writtenBytes = 0;
161
+ destinationHasCapacity = true;
162
+ }
163
+ function close$1(destination) {
164
+ destination.end();
165
+ }
166
+ const textEncoder = new util.TextEncoder();
167
+ function stringToChunk(content) {
168
+ return content;
169
+ }
170
+ function byteLengthOfChunk(chunk) {
171
+ return typeof chunk === 'string' ? Buffer.byteLength(chunk, 'utf8') : chunk.byteLength;
172
+ }
173
+ function closeWithError(destination, error) {
174
+ // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types.
175
+ destination.destroy(error);
176
+ }
177
+
178
+ // eslint-disable-next-line no-unused-vars
179
+ const CLIENT_REFERENCE_TAG$1 = Symbol.for('react.client.reference');
180
+ const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
181
+ function isClientReference(reference) {
182
+ return reference.$$typeof === CLIENT_REFERENCE_TAG$1;
183
+ }
184
+ function isServerReference(reference) {
185
+ return reference.$$typeof === SERVER_REFERENCE_TAG;
186
+ }
187
+ function registerClientReference(proxyImplementation, id, exportName) {
188
+ return registerClientReferenceImpl(proxyImplementation, id + '#' + exportName, false);
189
+ }
190
+
191
+ function registerClientReferenceImpl(proxyImplementation, id, async) {
192
+ return Object.defineProperties(proxyImplementation, {
193
+ $$typeof: {
194
+ value: CLIENT_REFERENCE_TAG$1
195
+ },
196
+ $$id: {
197
+ value: id
198
+ },
199
+ $$async: {
200
+ value: async
201
+ }
202
+ });
203
+ } // $FlowFixMe[method-unbinding]
204
+
205
+
206
+ const FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding]
207
+
208
+ const ArraySlice = Array.prototype.slice;
209
+
210
+ function bind() {
211
+ // $FlowFixMe[unsupported-syntax]
212
+ const newFn = FunctionBind.apply(this, arguments);
213
+
214
+ if (this.$$typeof === SERVER_REFERENCE_TAG) {
215
+
216
+ const args = ArraySlice.call(arguments, 1);
217
+ return Object.defineProperties(newFn, {
218
+ $$typeof: {
219
+ value: SERVER_REFERENCE_TAG
220
+ },
221
+ $$id: {
222
+ value: this.$$id
223
+ },
224
+ $$bound: {
225
+ value: this.$$bound ? this.$$bound.concat(args) : args
226
+ },
227
+ bind: {
228
+ value: bind
229
+ }
230
+ });
231
+ }
232
+
233
+ return newFn;
234
+ }
235
+
236
+ function registerServerReference(reference, id, exportName) {
237
+ return Object.defineProperties(reference, {
238
+ $$typeof: {
239
+ value: SERVER_REFERENCE_TAG
240
+ },
241
+ $$id: {
242
+ value: exportName === null ? id : id + '#' + exportName,
243
+ configurable: true
244
+ },
245
+ $$bound: {
246
+ value: null,
247
+ configurable: true
248
+ },
249
+ bind: {
250
+ value: bind,
251
+ configurable: true
252
+ }
253
+ });
254
+ }
255
+ const PROMISE_PROTOTYPE = Promise.prototype;
256
+ const deepProxyHandlers = {
257
+ get: function (target, name, receiver) {
258
+ switch (name) {
259
+ // These names are read by the Flight runtime if you end up using the exports object.
260
+ case '$$typeof':
261
+ // These names are a little too common. We should probably have a way to
262
+ // have the Flight runtime extract the inner target instead.
263
+ return target.$$typeof;
264
+
265
+ case '$$id':
266
+ return target.$$id;
267
+
268
+ case '$$async':
269
+ return target.$$async;
270
+
271
+ case 'name':
272
+ return target.name;
273
+
274
+ case 'displayName':
275
+ return undefined;
276
+ // We need to special case this because createElement reads it if we pass this
277
+ // reference.
278
+
279
+ case 'defaultProps':
280
+ return undefined;
281
+ // Avoid this attempting to be serialized.
282
+
283
+ case 'toJSON':
284
+ return undefined;
285
+
286
+ case Symbol.toPrimitive:
287
+ // $FlowFixMe[prop-missing]
288
+ return Object.prototype[Symbol.toPrimitive];
289
+
290
+ case Symbol.toStringTag:
291
+ // $FlowFixMe[prop-missing]
292
+ return Object.prototype[Symbol.toStringTag];
293
+
294
+ case 'Provider':
295
+ throw new Error("Cannot render a Client Context Provider on the Server. " + "Instead, you can export a Client Component wrapper " + "that itself renders a Client Context Provider.");
296
+ } // eslint-disable-next-line react-internal/safe-string-coercion
297
+
298
+
299
+ const expression = String(target.name) + '.' + String(name);
300
+ throw new Error("Cannot access " + expression + " on the server. " + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.');
301
+ },
302
+ set: function () {
303
+ throw new Error('Cannot assign to a client module from a server module.');
304
+ }
305
+ };
306
+
307
+ function getReference(target, name) {
308
+ switch (name) {
309
+ // These names are read by the Flight runtime if you end up using the exports object.
310
+ case '$$typeof':
311
+ return target.$$typeof;
312
+
313
+ case '$$id':
314
+ return target.$$id;
315
+
316
+ case '$$async':
317
+ return target.$$async;
318
+
319
+ case 'name':
320
+ return target.name;
321
+ // We need to special case this because createElement reads it if we pass this
322
+ // reference.
323
+
324
+ case 'defaultProps':
325
+ return undefined;
326
+ // Avoid this attempting to be serialized.
327
+
328
+ case 'toJSON':
329
+ return undefined;
330
+
331
+ case Symbol.toPrimitive:
332
+ // $FlowFixMe[prop-missing]
333
+ return Object.prototype[Symbol.toPrimitive];
334
+
335
+ case Symbol.toStringTag:
336
+ // $FlowFixMe[prop-missing]
337
+ return Object.prototype[Symbol.toStringTag];
338
+
339
+ case '__esModule':
340
+ // Something is conditionally checking which export to use. We'll pretend to be
341
+ // an ESM compat module but then we'll check again on the client.
342
+ const moduleId = target.$$id;
343
+ target.default = registerClientReferenceImpl(function () {
344
+ throw new Error("Attempted to call the default export of " + moduleId + " from the server " + "but it's on the client. It's not possible to invoke a client function from " + "the server, it can only be rendered as a Component or passed to props of a " + "Client Component.");
345
+ }, target.$$id + '#', target.$$async);
346
+ return true;
347
+
348
+ case 'then':
349
+ if (target.then) {
350
+ // Use a cached value
351
+ return target.then;
352
+ }
353
+
354
+ if (!target.$$async) {
355
+ // If this module is expected to return a Promise (such as an AsyncModule) then
356
+ // we should resolve that with a client reference that unwraps the Promise on
357
+ // the client.
358
+ const clientReference = registerClientReferenceImpl({}, target.$$id, true);
359
+ const proxy = new Proxy(clientReference, proxyHandlers$1); // Treat this as a resolved Promise for React's use()
360
+
361
+ target.status = 'fulfilled';
362
+ target.value = proxy;
363
+ const then = target.then = registerClientReferenceImpl(function then(resolve, reject) {
364
+ // Expose to React.
365
+ return Promise.resolve(resolve(proxy));
366
+ }, // If this is not used as a Promise but is treated as a reference to a `.then`
367
+ // export then we should treat it as a reference to that name.
368
+ target.$$id + '#then', false);
369
+ return then;
370
+ } else {
371
+ // Since typeof .then === 'function' is a feature test we'd continue recursing
372
+ // indefinitely if we return a function. Instead, we return an object reference
373
+ // if we check further.
374
+ return undefined;
375
+ }
376
+
377
+ }
378
+
379
+ if (typeof name === 'symbol') {
380
+ throw new Error('Cannot read Symbol exports. Only named exports are supported on a client module ' + 'imported on the server.');
381
+ }
382
+
383
+ let cachedReference = target[name];
384
+
385
+ if (!cachedReference) {
386
+ const reference = registerClientReferenceImpl(function () {
387
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
388
+ "Attempted to call " + String(name) + "() from the server but " + String(name) + " is on the client. " + "It's not possible to invoke a client function from the server, it can " + "only be rendered as a Component or passed to props of a Client Component.");
389
+ }, target.$$id + '#' + name, target.$$async);
390
+ Object.defineProperty(reference, 'name', {
391
+ value: name
392
+ });
393
+ cachedReference = target[name] = new Proxy(reference, deepProxyHandlers);
394
+ }
395
+
396
+ return cachedReference;
397
+ }
398
+
399
+ const proxyHandlers$1 = {
400
+ get: function (target, name, receiver) {
401
+ return getReference(target, name);
402
+ },
403
+ getOwnPropertyDescriptor: function (target, name) {
404
+ let descriptor = Object.getOwnPropertyDescriptor(target, name);
405
+
406
+ if (!descriptor) {
407
+ descriptor = {
408
+ value: getReference(target, name),
409
+ writable: false,
410
+ configurable: false,
411
+ enumerable: false
412
+ };
413
+ Object.defineProperty(target, name, descriptor);
414
+ }
415
+
416
+ return descriptor;
417
+ },
418
+
419
+ getPrototypeOf(target) {
420
+ // Pretend to be a Promise in case anyone asks.
421
+ return PROMISE_PROTOTYPE;
422
+ },
423
+
424
+ set: function () {
425
+ throw new Error('Cannot assign to a client module from a server module.');
426
+ }
427
+ };
428
+ function createClientModuleProxy(moduleId) {
429
+ const clientReference = registerClientReferenceImpl({}, // Represents the whole Module object instead of a particular import.
430
+ moduleId, false);
431
+ return new Proxy(clientReference, proxyHandlers$1);
432
+ }
433
+
434
+ function getClientReferenceKey(reference) {
435
+ return reference.$$async ? reference.$$id + '#async' : reference.$$id;
436
+ }
437
+ function resolveClientReferenceMetadata(config, clientReference) {
438
+ const modulePath = clientReference.$$id;
439
+ let name = '';
440
+ let resolvedModuleData = config[modulePath];
441
+
442
+ if (resolvedModuleData) {
443
+ // The potentially aliased name.
444
+ name = resolvedModuleData.name;
445
+ } else {
446
+ // We didn't find this specific export name but we might have the * export
447
+ // which contains this name as well.
448
+ // TODO: It's unfortunate that we now have to parse this string. We should
449
+ // probably go back to encoding path and name separately on the client reference.
450
+ const idx = modulePath.lastIndexOf('#');
451
+
452
+ if (idx !== -1) {
453
+ name = modulePath.slice(idx + 1);
454
+ resolvedModuleData = config[modulePath.slice(0, idx)];
455
+ }
456
+
457
+ if (!resolvedModuleData) {
458
+ throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.');
459
+ }
460
+ }
461
+
462
+ if (clientReference.$$async === true) {
463
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1];
464
+ } else {
465
+ return [resolvedModuleData.id, resolvedModuleData.chunks, name];
466
+ }
467
+ }
468
+ function getServerReferenceId(config, serverReference) {
469
+ return serverReference.$$id;
470
+ }
471
+ function getServerReferenceBoundArguments(config, serverReference) {
472
+ return serverReference.$$bound;
473
+ }
474
+
475
+ const ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
476
+
477
+ const ReactDOMCurrentDispatcher = ReactDOMSharedInternals.ReactDOMCurrentDispatcher;
478
+ const previousDispatcher = ReactDOMCurrentDispatcher.current;
479
+ ReactDOMCurrentDispatcher.current = {
480
+ prefetchDNS,
481
+ preconnect,
482
+ preload,
483
+ preloadModule: preloadModule$1,
484
+ preinitStyle,
485
+ preinitScript,
486
+ preinitModuleScript
487
+ };
488
+
489
+ function prefetchDNS(href) {
490
+ if (typeof href === 'string' && href) {
491
+ const request = resolveRequest();
492
+
493
+ if (request) {
494
+ const hints = getHints(request);
495
+ const key = 'D|' + href;
496
+
497
+ if (hints.has(key)) {
498
+ // duplicate hint
499
+ return;
500
+ }
501
+
502
+ hints.add(key);
503
+ emitHint(request, 'D', href);
504
+ } else {
505
+ previousDispatcher.prefetchDNS(href);
506
+ }
507
+ }
508
+ }
509
+
510
+ function preconnect(href, crossOrigin) {
511
+ if (typeof href === 'string') {
512
+ const request = resolveRequest();
513
+
514
+ if (request) {
515
+ const hints = getHints(request);
516
+ const key = "C|" + (crossOrigin == null ? 'null' : crossOrigin) + "|" + href;
517
+
518
+ if (hints.has(key)) {
519
+ // duplicate hint
520
+ return;
521
+ }
522
+
523
+ hints.add(key);
524
+
525
+ if (typeof crossOrigin === 'string') {
526
+ emitHint(request, 'C', [href, crossOrigin]);
527
+ } else {
528
+ emitHint(request, 'C', href);
529
+ }
530
+ } else {
531
+ previousDispatcher.preconnect(href, crossOrigin);
532
+ }
533
+ }
534
+ }
535
+
536
+ function preload(href, as, options) {
537
+ if (typeof href === 'string') {
538
+ const request = resolveRequest();
539
+
540
+ if (request) {
541
+ const hints = getHints(request);
542
+ let key = 'L';
543
+
544
+ if (as === 'image' && options) {
545
+ key += getImagePreloadKey(href, options.imageSrcSet, options.imageSizes);
546
+ } else {
547
+ key += "[" + as + "]" + href;
548
+ }
549
+
550
+ if (hints.has(key)) {
551
+ // duplicate hint
552
+ return;
553
+ }
554
+
555
+ hints.add(key);
556
+ const trimmed = trimOptions(options);
557
+
558
+ if (trimmed) {
559
+ emitHint(request, 'L', [href, as, trimmed]);
560
+ } else {
561
+ emitHint(request, 'L', [href, as]);
562
+ }
563
+ } else {
564
+ previousDispatcher.preload(href, as, options);
565
+ }
566
+ }
567
+ }
568
+
569
+ function preloadModule$1(href, options) {
570
+ if (typeof href === 'string') {
571
+ const request = resolveRequest();
572
+
573
+ if (request) {
574
+ const hints = getHints(request);
575
+ const key = 'm|' + href;
576
+
577
+ if (hints.has(key)) {
578
+ // duplicate hint
579
+ return;
580
+ }
581
+
582
+ hints.add(key);
583
+ const trimmed = trimOptions(options);
584
+
585
+ if (trimmed) {
586
+ return emitHint(request, 'm', [href, trimmed]);
587
+ } else {
588
+ return emitHint(request, 'm', href);
589
+ }
590
+ } else {
591
+ previousDispatcher.preloadModule(href, options);
592
+ }
593
+ }
594
+ }
595
+
596
+ function preinitStyle(href, precedence, options) {
597
+ if (typeof href === 'string') {
598
+ const request = resolveRequest();
599
+
600
+ if (request) {
601
+ const hints = getHints(request);
602
+ const key = 'S|' + href;
603
+
604
+ if (hints.has(key)) {
605
+ // duplicate hint
606
+ return;
607
+ }
608
+
609
+ hints.add(key);
610
+ const trimmed = trimOptions(options);
611
+
612
+ if (trimmed) {
613
+ return emitHint(request, 'S', [href, typeof precedence === 'string' ? precedence : 0, trimmed]);
614
+ } else if (typeof precedence === 'string') {
615
+ return emitHint(request, 'S', [href, precedence]);
616
+ } else {
617
+ return emitHint(request, 'S', href);
618
+ }
619
+ } else {
620
+ previousDispatcher.preinitStyle(href, precedence, options);
621
+ }
622
+ }
623
+ }
624
+
625
+ function preinitScript(src, options) {
626
+ if (typeof src === 'string') {
627
+ const request = resolveRequest();
628
+
629
+ if (request) {
630
+ const hints = getHints(request);
631
+ const key = 'X|' + src;
632
+
633
+ if (hints.has(key)) {
634
+ // duplicate hint
635
+ return;
636
+ }
637
+
638
+ hints.add(key);
639
+ const trimmed = trimOptions(options);
640
+
641
+ if (trimmed) {
642
+ return emitHint(request, 'X', [src, trimmed]);
643
+ } else {
644
+ return emitHint(request, 'X', src);
645
+ }
646
+ } else {
647
+ previousDispatcher.preinitScript(src, options);
648
+ }
649
+ }
650
+ }
651
+
652
+ function preinitModuleScript(src, options) {
653
+ if (typeof src === 'string') {
654
+ const request = resolveRequest();
655
+
656
+ if (request) {
657
+ const hints = getHints(request);
658
+ const key = 'M|' + src;
659
+
660
+ if (hints.has(key)) {
661
+ // duplicate hint
662
+ return;
663
+ }
664
+
665
+ hints.add(key);
666
+ const trimmed = trimOptions(options);
667
+
668
+ if (trimmed) {
669
+ return emitHint(request, 'M', [src, trimmed]);
670
+ } else {
671
+ return emitHint(request, 'M', src);
672
+ }
673
+ } else {
674
+ previousDispatcher.preinitModuleScript(src, options);
675
+ }
676
+ }
677
+ } // Flight normally encodes undefined as a special character however for directive option
678
+ // arguments we don't want to send unnecessary keys and bloat the payload so we create a
679
+ // trimmed object which omits any keys with null or undefined values.
680
+ // This is only typesafe because these option objects have entirely optional fields where
681
+ // null and undefined represent the same thing as no property.
682
+
683
+
684
+ function trimOptions(options) {
685
+ if (options == null) return null;
686
+ let hasProperties = false;
687
+ const trimmed = {};
688
+
689
+ for (const key in options) {
690
+ if (options[key] != null) {
691
+ hasProperties = true;
692
+ trimmed[key] = options[key];
693
+ }
694
+ }
695
+
696
+ return hasProperties ? trimmed : null;
697
+ }
698
+
699
+ function getImagePreloadKey(href, imageSrcSet, imageSizes) {
700
+ let uniquePart = '';
701
+
702
+ if (typeof imageSrcSet === 'string' && imageSrcSet !== '') {
703
+ uniquePart += '[' + imageSrcSet + ']';
704
+
705
+ if (typeof imageSizes === 'string') {
706
+ uniquePart += '[' + imageSizes + ']';
707
+ }
708
+ } else {
709
+ uniquePart += '[][]' + href;
710
+ }
711
+
712
+ return "[image]" + uniquePart;
713
+ }
714
+
715
+ // This module registers the host dispatcher so it needs to be imported
716
+ // small, smaller than how we encode undefined, and is unambiguous. We could use
717
+ // a different tuple structure to encode this instead but this makes the runtime
718
+ // cost cheaper by eliminating a type checks in more positions.
719
+ // prettier-ignore
720
+
721
+ function createHints() {
722
+ return new Set();
723
+ }
724
+
725
+ const supportsRequestStorage = true;
726
+ const requestStorage = new async_hooks.AsyncLocalStorage();
727
+
728
+ const TEMPORARY_REFERENCE_TAG = Symbol.for('react.temporary.reference'); // eslint-disable-next-line no-unused-vars
729
+
730
+ function isTemporaryReference(reference) {
731
+ return reference.$$typeof === TEMPORARY_REFERENCE_TAG;
732
+ }
733
+ function resolveTemporaryReferenceID(temporaryReference) {
734
+ return temporaryReference.$$id;
735
+ }
736
+ const proxyHandlers = {
737
+ get: function (target, name, receiver) {
738
+ switch (name) {
739
+ // These names are read by the Flight runtime if you end up using the exports object.
740
+ case '$$typeof':
741
+ // These names are a little too common. We should probably have a way to
742
+ // have the Flight runtime extract the inner target instead.
743
+ return target.$$typeof;
744
+
745
+ case '$$id':
746
+ return target.$$id;
747
+
748
+ case '$$async':
749
+ return target.$$async;
750
+
751
+ case 'name':
752
+ return undefined;
753
+
754
+ case 'displayName':
755
+ return undefined;
756
+ // We need to special case this because createElement reads it if we pass this
757
+ // reference.
758
+
759
+ case 'defaultProps':
760
+ return undefined;
761
+ // Avoid this attempting to be serialized.
762
+
763
+ case 'toJSON':
764
+ return undefined;
765
+
766
+ case Symbol.toPrimitive:
767
+ // $FlowFixMe[prop-missing]
768
+ return Object.prototype[Symbol.toPrimitive];
769
+
770
+ case Symbol.toStringTag:
771
+ // $FlowFixMe[prop-missing]
772
+ return Object.prototype[Symbol.toStringTag];
773
+
774
+ case 'Provider':
775
+ throw new Error("Cannot render a Client Context Provider on the Server. " + "Instead, you can export a Client Component wrapper " + "that itself renders a Client Context Provider.");
776
+ }
777
+
778
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
779
+ "Cannot access " + String(name) + " on the server. " + 'You cannot dot into a temporary client reference from a server component. ' + 'You can only pass the value through to the client.');
780
+ },
781
+ set: function () {
782
+ throw new Error('Cannot assign to a temporary client reference from a server module.');
783
+ }
784
+ };
785
+ function createTemporaryReference(id) {
786
+ const reference = Object.defineProperties(function () {
787
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
788
+ "Attempted to call a temporary Client Reference from the server but it is on the client. " + "It's not possible to invoke a client function from the server, it can " + "only be rendered as a Component or passed to props of a Client Component.");
789
+ }, {
790
+ $$typeof: {
791
+ value: TEMPORARY_REFERENCE_TAG
792
+ },
793
+ $$id: {
794
+ value: id
795
+ }
796
+ });
797
+ return new Proxy(reference, proxyHandlers);
798
+ }
799
+
800
+ // ATTENTION
801
+ // When adding new symbols to this file,
802
+ // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
803
+ // The Symbol used to tag the ReactElement-like types.
804
+ const REACT_ELEMENT_TYPE = Symbol.for('react.element');
805
+ const REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
806
+ const REACT_CONTEXT_TYPE = Symbol.for('react.context');
807
+ const REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
808
+ const REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
809
+ const REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
810
+ const REACT_MEMO_TYPE = Symbol.for('react.memo');
811
+ const REACT_LAZY_TYPE = Symbol.for('react.lazy');
812
+ const REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel');
813
+ const REACT_POSTPONE_TYPE = Symbol.for('react.postpone');
814
+ const MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
815
+ const FAUX_ITERATOR_SYMBOL = '@@iterator';
816
+ function getIteratorFn(maybeIterable) {
817
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
818
+ return null;
819
+ }
820
+
821
+ const maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
822
+
823
+ if (typeof maybeIterator === 'function') {
824
+ return maybeIterator;
825
+ }
826
+
827
+ return null;
828
+ }
829
+
830
+ // Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally,
831
+ // changes to one module should be reflected in the others.
832
+ // TODO: Rename this module and the corresponding Fiber one to "Thenable"
833
+ // instead of "Wakeable". Or some other more appropriate name.
834
+ // An error that is thrown (e.g. by `use`) to trigger Suspense. If we
835
+ // detect this is caught by userspace, we'll log a warning in development.
836
+ const SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`");
837
+ function createThenableState() {
838
+ // The ThenableState is created the first time a component suspends. If it
839
+ // suspends again, we'll reuse the same state.
840
+ return [];
841
+ }
842
+
843
+ function noop() {}
844
+
845
+ function trackUsedThenable(thenableState, thenable, index) {
846
+ const previous = thenableState[index];
847
+
848
+ if (previous === undefined) {
849
+ thenableState.push(thenable);
850
+ } else {
851
+ if (previous !== thenable) {
852
+ // Reuse the previous thenable, and drop the new one. We can assume
853
+ // they represent the same value, because components are idempotent.
854
+ // Avoid an unhandled rejection errors for the Promises that we'll
855
+ // intentionally ignore.
856
+ thenable.then(noop, noop);
857
+ thenable = previous;
858
+ }
859
+ } // We use an expando to track the status and result of a thenable so that we
860
+ // can synchronously unwrap the value. Think of this as an extension of the
861
+ // Promise API, or a custom interface that is a superset of Thenable.
862
+ //
863
+ // If the thenable doesn't have a status, set it to "pending" and attach
864
+ // a listener that will update its status and result when it resolves.
865
+
866
+
867
+ switch (thenable.status) {
868
+ case 'fulfilled':
869
+ {
870
+ const fulfilledValue = thenable.value;
871
+ return fulfilledValue;
872
+ }
873
+
874
+ case 'rejected':
875
+ {
876
+ const rejectedError = thenable.reason;
877
+ throw rejectedError;
878
+ }
879
+
880
+ default:
881
+ {
882
+ if (typeof thenable.status === 'string') ; else {
883
+ const pendingThenable = thenable;
884
+ pendingThenable.status = 'pending';
885
+ pendingThenable.then(fulfilledValue => {
886
+ if (thenable.status === 'pending') {
887
+ const fulfilledThenable = thenable;
888
+ fulfilledThenable.status = 'fulfilled';
889
+ fulfilledThenable.value = fulfilledValue;
890
+ }
891
+ }, error => {
892
+ if (thenable.status === 'pending') {
893
+ const rejectedThenable = thenable;
894
+ rejectedThenable.status = 'rejected';
895
+ rejectedThenable.reason = error;
896
+ }
897
+ }); // Check one more time in case the thenable resolved synchronously
898
+
899
+ switch (thenable.status) {
900
+ case 'fulfilled':
901
+ {
902
+ const fulfilledThenable = thenable;
903
+ return fulfilledThenable.value;
904
+ }
905
+
906
+ case 'rejected':
907
+ {
908
+ const rejectedThenable = thenable;
909
+ throw rejectedThenable.reason;
910
+ }
911
+ }
912
+ } // Suspend.
913
+ //
914
+ // Throwing here is an implementation detail that allows us to unwind the
915
+ // call stack. But we shouldn't allow it to leak into userspace. Throw an
916
+ // opaque placeholder value instead of the actual thenable. If it doesn't
917
+ // get captured by the work loop, log a warning, because that means
918
+ // something in userspace must have caught it.
919
+
920
+
921
+ suspendedThenable = thenable;
922
+ throw SuspenseException;
923
+ }
924
+ }
925
+ } // This is used to track the actual thenable that suspended so it can be
926
+ // passed to the rest of the Suspense implementation — which, for historical
927
+ // reasons, expects to receive a thenable.
928
+
929
+ let suspendedThenable = null;
930
+ function getSuspendedThenable() {
931
+ // This is called right after `use` suspends by throwing an exception. `use`
932
+ // throws an opaque value instead of the thenable itself so that it can't be
933
+ // caught in userspace. Then the work loop accesses the actual thenable using
934
+ // this function.
935
+ if (suspendedThenable === null) {
936
+ throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.');
937
+ }
938
+
939
+ const thenable = suspendedThenable;
940
+ suspendedThenable = null;
941
+ return thenable;
942
+ }
943
+
944
+ let currentRequest$1 = null;
945
+ let thenableIndexCounter = 0;
946
+ let thenableState = null;
947
+ function prepareToUseHooksForRequest(request) {
948
+ currentRequest$1 = request;
949
+ }
950
+ function resetHooksForRequest() {
951
+ currentRequest$1 = null;
952
+ }
953
+ function prepareToUseHooksForComponent(prevThenableState) {
954
+ thenableIndexCounter = 0;
955
+ thenableState = prevThenableState;
956
+ }
957
+ function getThenableStateAfterSuspending() {
958
+ // If you use() to Suspend this should always exist but if you throw a Promise instead,
959
+ // which is not really supported anymore, it will be empty. We use the empty set as a
960
+ // marker to know if this was a replay of the same component or first attempt.
961
+ const state = thenableState || createThenableState();
962
+ thenableState = null;
963
+ return state;
964
+ }
965
+ const HooksDispatcher = {
966
+ useMemo(nextCreate) {
967
+ return nextCreate();
968
+ },
969
+
970
+ useCallback(callback) {
971
+ return callback;
972
+ },
973
+
974
+ useDebugValue() {},
975
+
976
+ useDeferredValue: unsupportedHook,
977
+ useTransition: unsupportedHook,
978
+ readContext: unsupportedContext,
979
+ useContext: unsupportedContext,
980
+ useReducer: unsupportedHook,
981
+ useRef: unsupportedHook,
982
+ useState: unsupportedHook,
983
+ useInsertionEffect: unsupportedHook,
984
+ useLayoutEffect: unsupportedHook,
985
+ useImperativeHandle: unsupportedHook,
986
+ useEffect: unsupportedHook,
987
+ useId,
988
+ useSyncExternalStore: unsupportedHook,
989
+
990
+ useCacheRefresh() {
991
+ return unsupportedRefresh;
992
+ },
993
+
994
+ useMemoCache(size) {
995
+ const data = new Array(size);
996
+
997
+ for (let i = 0; i < size; i++) {
998
+ data[i] = REACT_MEMO_CACHE_SENTINEL;
999
+ }
1000
+
1001
+ return data;
1002
+ },
1003
+
1004
+ use
1005
+ };
1006
+
1007
+ function unsupportedHook() {
1008
+ throw new Error('This Hook is not supported in Server Components.');
1009
+ }
1010
+
1011
+ function unsupportedRefresh() {
1012
+ throw new Error('Refreshing the cache is not supported in Server Components.');
1013
+ }
1014
+
1015
+ function unsupportedContext() {
1016
+ throw new Error('Cannot read a Client Context from a Server Component.');
1017
+ }
1018
+
1019
+ function useId() {
1020
+ if (currentRequest$1 === null) {
1021
+ throw new Error('useId can only be used while React is rendering');
1022
+ }
1023
+
1024
+ const id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client
1025
+
1026
+ return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':';
1027
+ }
1028
+
1029
+ function use(usable) {
1030
+ if (usable !== null && typeof usable === 'object' || typeof usable === 'function') {
1031
+ // $FlowFixMe[method-unbinding]
1032
+ if (typeof usable.then === 'function') {
1033
+ // This is a thenable.
1034
+ const thenable = usable; // Track the position of the thenable within this fiber.
1035
+
1036
+ const index = thenableIndexCounter;
1037
+ thenableIndexCounter += 1;
1038
+
1039
+ if (thenableState === null) {
1040
+ thenableState = createThenableState();
1041
+ }
1042
+
1043
+ return trackUsedThenable(thenableState, thenable, index);
1044
+ } else if (usable.$$typeof === REACT_CONTEXT_TYPE) {
1045
+ unsupportedContext();
1046
+ }
1047
+ }
1048
+
1049
+ if (isClientReference(usable)) {
1050
+ if (usable.value != null && usable.value.$$typeof === REACT_CONTEXT_TYPE) {
1051
+ // Show a more specific message since it's a common mistake.
1052
+ throw new Error('Cannot read a Client Context from a Server Component.');
1053
+ } else {
1054
+ throw new Error('Cannot use() an already resolved Client Reference.');
1055
+ }
1056
+ } else {
1057
+ throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion
1058
+ 'An unsupported type was passed to use(): ' + String(usable));
1059
+ }
1060
+ }
1061
+
1062
+ function createSignal() {
1063
+ return new AbortController().signal;
1064
+ }
1065
+
1066
+ function resolveCache() {
1067
+ const request = resolveRequest();
1068
+
1069
+ if (request) {
1070
+ return getCache(request);
1071
+ }
1072
+
1073
+ return new Map();
1074
+ }
1075
+
1076
+ const DefaultCacheDispatcher = {
1077
+ getCacheSignal() {
1078
+ const cache = resolveCache();
1079
+ let entry = cache.get(createSignal);
1080
+
1081
+ if (entry === undefined) {
1082
+ entry = createSignal();
1083
+ cache.set(createSignal, entry);
1084
+ }
1085
+
1086
+ return entry;
1087
+ },
1088
+
1089
+ getCacheForType(resourceType) {
1090
+ const cache = resolveCache();
1091
+ let entry = cache.get(resourceType);
1092
+
1093
+ if (entry === undefined) {
1094
+ entry = resourceType(); // TODO: Warn if undefined?
1095
+
1096
+ cache.set(resourceType, entry);
1097
+ }
1098
+
1099
+ return entry;
1100
+ }
1101
+
1102
+ };
1103
+
1104
+ const isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
1105
+
1106
+ function isArray(a) {
1107
+ return isArrayImpl(a);
1108
+ }
1109
+
1110
+ const getPrototypeOf = Object.getPrototypeOf;
1111
+
1112
+ function objectName(object) {
1113
+ // $FlowFixMe[method-unbinding]
1114
+ const name = Object.prototype.toString.call(object);
1115
+ return name.replace(/^\[object (.*)\]$/, function (m, p0) {
1116
+ return p0;
1117
+ });
1118
+ }
1119
+
1120
+ function describeKeyForErrorMessage(key) {
1121
+ const encodedKey = JSON.stringify(key);
1122
+ return '"' + key + '"' === encodedKey ? key : encodedKey;
1123
+ }
1124
+
1125
+ function describeValueForErrorMessage(value) {
1126
+ switch (typeof value) {
1127
+ case 'string':
1128
+ {
1129
+ return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...');
1130
+ }
1131
+
1132
+ case 'object':
1133
+ {
1134
+ if (isArray(value)) {
1135
+ return '[...]';
1136
+ }
1137
+
1138
+ if (value !== null && value.$$typeof === CLIENT_REFERENCE_TAG) {
1139
+ return describeClientReference();
1140
+ }
1141
+
1142
+ const name = objectName(value);
1143
+
1144
+ if (name === 'Object') {
1145
+ return '{...}';
1146
+ }
1147
+
1148
+ return name;
1149
+ }
1150
+
1151
+ case 'function':
1152
+ {
1153
+ if (value.$$typeof === CLIENT_REFERENCE_TAG) {
1154
+ return describeClientReference();
1155
+ }
1156
+
1157
+ const name = value.displayName || value.name;
1158
+ return name ? 'function ' + name : 'function';
1159
+ }
1160
+
1161
+ default:
1162
+ // eslint-disable-next-line react-internal/safe-string-coercion
1163
+ return String(value);
1164
+ }
1165
+ }
1166
+
1167
+ function describeElementType(type) {
1168
+ if (typeof type === 'string') {
1169
+ return type;
1170
+ }
1171
+
1172
+ switch (type) {
1173
+ case REACT_SUSPENSE_TYPE:
1174
+ return 'Suspense';
1175
+
1176
+ case REACT_SUSPENSE_LIST_TYPE:
1177
+ return 'SuspenseList';
1178
+ }
1179
+
1180
+ if (typeof type === 'object') {
1181
+ switch (type.$$typeof) {
1182
+ case REACT_FORWARD_REF_TYPE:
1183
+ return describeElementType(type.render);
1184
+
1185
+ case REACT_MEMO_TYPE:
1186
+ return describeElementType(type.type);
1187
+
1188
+ case REACT_LAZY_TYPE:
1189
+ {
1190
+ const lazyComponent = type;
1191
+ const payload = lazyComponent._payload;
1192
+ const init = lazyComponent._init;
1193
+
1194
+ try {
1195
+ // Lazy may contain any component type so we recursively resolve it.
1196
+ return describeElementType(init(payload));
1197
+ } catch (x) {}
1198
+ }
1199
+ }
1200
+ }
1201
+
1202
+ return '';
1203
+ }
1204
+
1205
+ const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
1206
+
1207
+ function describeClientReference(ref) {
1208
+ return 'client';
1209
+ }
1210
+
1211
+ function describeObjectForErrorMessage(objectOrArray, expandedName) {
1212
+ const objKind = objectName(objectOrArray);
1213
+
1214
+ if (objKind !== 'Object' && objKind !== 'Array') {
1215
+ return objKind;
1216
+ }
1217
+
1218
+ let str = '';
1219
+ let start = -1;
1220
+ let length = 0;
1221
+
1222
+ if (isArray(objectOrArray)) {
1223
+ {
1224
+ // Print Array
1225
+ str = '[';
1226
+ const array = objectOrArray;
1227
+
1228
+ for (let i = 0; i < array.length; i++) {
1229
+ if (i > 0) {
1230
+ str += ', ';
1231
+ }
1232
+
1233
+ const value = array[i];
1234
+ let substr;
1235
+
1236
+ if (typeof value === 'object' && value !== null) {
1237
+ substr = describeObjectForErrorMessage(value);
1238
+ } else {
1239
+ substr = describeValueForErrorMessage(value);
1240
+ }
1241
+
1242
+ if ('' + i === expandedName) {
1243
+ start = str.length;
1244
+ length = substr.length;
1245
+ str += substr;
1246
+ } else if (substr.length < 10 && str.length + substr.length < 40) {
1247
+ str += substr;
1248
+ } else {
1249
+ str += '...';
1250
+ }
1251
+ }
1252
+
1253
+ str += ']';
1254
+ }
1255
+ } else {
1256
+ if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) {
1257
+ str = '<' + describeElementType(objectOrArray.type) + '/>';
1258
+ } else if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) {
1259
+ return describeClientReference();
1260
+ } else {
1261
+ // Print Object
1262
+ str = '{';
1263
+ const object = objectOrArray;
1264
+ const names = Object.keys(object);
1265
+
1266
+ for (let i = 0; i < names.length; i++) {
1267
+ if (i > 0) {
1268
+ str += ', ';
1269
+ }
1270
+
1271
+ const name = names[i];
1272
+ str += describeKeyForErrorMessage(name) + ': ';
1273
+ const value = object[name];
1274
+ let substr;
1275
+
1276
+ if (typeof value === 'object' && value !== null) {
1277
+ substr = describeObjectForErrorMessage(value);
1278
+ } else {
1279
+ substr = describeValueForErrorMessage(value);
1280
+ }
1281
+
1282
+ if (name === expandedName) {
1283
+ start = str.length;
1284
+ length = substr.length;
1285
+ str += substr;
1286
+ } else if (substr.length < 10 && str.length + substr.length < 40) {
1287
+ str += substr;
1288
+ } else {
1289
+ str += '...';
1290
+ }
1291
+ }
1292
+
1293
+ str += '}';
1294
+ }
1295
+ }
1296
+
1297
+ if (expandedName === undefined) {
1298
+ return str;
1299
+ }
1300
+
1301
+ if (start > -1 && length > 0) {
1302
+ const highlight = ' '.repeat(start) + '^'.repeat(length);
1303
+ return '\n ' + str + '\n ' + highlight;
1304
+ }
1305
+
1306
+ return '\n ' + str;
1307
+ }
1308
+
1309
+ const ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1310
+
1311
+ const ReactSharedServerInternals = // $FlowFixMe: It's defined in the one we resolve to.
1312
+ React.__SECRET_SERVER_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1313
+
1314
+ if (!ReactSharedServerInternals) {
1315
+ throw new Error('The "react" package in this environment is not configured correctly. ' + 'The "react-server" condition must be enabled in any environment that ' + 'runs React Server Components.');
1316
+ }
1317
+
1318
+ const ObjectPrototype = Object.prototype;
1319
+ const stringify = JSON.stringify; // Serializable values
1320
+ // Thenable<ReactClientValue>
1321
+
1322
+ const PENDING$1 = 0;
1323
+ const COMPLETED = 1;
1324
+ const ABORTED = 3;
1325
+ const ERRORED$1 = 4;
1326
+ const ReactCurrentCache = ReactSharedServerInternals.ReactCurrentCache;
1327
+ const ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
1328
+
1329
+ function defaultErrorHandler(error) {
1330
+ console['error'](error); // Don't transform to our wrapper
1331
+ }
1332
+
1333
+ function defaultPostponeHandler(reason) {// Noop
1334
+ }
1335
+
1336
+ const OPEN = 0;
1337
+ const CLOSING = 1;
1338
+ const CLOSED = 2;
1339
+ function createRequest(model, bundlerConfig, onError, identifierPrefix, onPostpone, environmentName) {
1340
+ if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) {
1341
+ throw new Error('Currently React only supports one RSC renderer at a time.');
1342
+ }
1343
+
1344
+ ReactCurrentCache.current = DefaultCacheDispatcher;
1345
+ const abortSet = new Set();
1346
+ const pingedTasks = [];
1347
+ const cleanupQueue = [];
1348
+
1349
+ const hints = createHints();
1350
+ const request = {
1351
+ status: OPEN,
1352
+ flushScheduled: false,
1353
+ fatalError: null,
1354
+ destination: null,
1355
+ bundlerConfig,
1356
+ cache: new Map(),
1357
+ nextChunkId: 0,
1358
+ pendingChunks: 0,
1359
+ hints,
1360
+ abortableTasks: abortSet,
1361
+ pingedTasks: pingedTasks,
1362
+ completedImportChunks: [],
1363
+ completedHintChunks: [],
1364
+ completedRegularChunks: [],
1365
+ completedErrorChunks: [],
1366
+ writtenSymbols: new Map(),
1367
+ writtenClientReferences: new Map(),
1368
+ writtenServerReferences: new Map(),
1369
+ writtenObjects: new WeakMap(),
1370
+ identifierPrefix: identifierPrefix || '',
1371
+ identifierCount: 1,
1372
+ taintCleanupQueue: cleanupQueue,
1373
+ onError: onError === undefined ? defaultErrorHandler : onError,
1374
+ onPostpone: onPostpone === undefined ? defaultPostponeHandler : onPostpone
1375
+ };
1376
+
1377
+ const rootTask = createTask(request, model, null, false, abortSet);
1378
+ pingedTasks.push(rootTask);
1379
+ return request;
1380
+ }
1381
+ let currentRequest = null;
1382
+ function resolveRequest() {
1383
+ if (currentRequest) return currentRequest;
1384
+
1385
+ {
1386
+ const store = requestStorage.getStore();
1387
+ if (store) return store;
1388
+ }
1389
+
1390
+ return null;
1391
+ }
1392
+
1393
+ function serializeThenable(request, task, thenable) {
1394
+ const newTask = createTask(request, null, task.keyPath, // the server component sequence continues through Promise-as-a-child.
1395
+ task.implicitSlot, request.abortableTasks);
1396
+
1397
+ switch (thenable.status) {
1398
+ case 'fulfilled':
1399
+ {
1400
+ // We have the resolved value, we can go ahead and schedule it for serialization.
1401
+ newTask.model = thenable.value;
1402
+ pingTask(request, newTask);
1403
+ return newTask.id;
1404
+ }
1405
+
1406
+ case 'rejected':
1407
+ {
1408
+ const x = thenable.reason;
1409
+
1410
+ {
1411
+ const digest = logRecoverableError(request, x);
1412
+ emitErrorChunk(request, newTask.id, digest);
1413
+ }
1414
+
1415
+ return newTask.id;
1416
+ }
1417
+
1418
+ default:
1419
+ {
1420
+ if (typeof thenable.status === 'string') {
1421
+ // Only instrument the thenable if the status if not defined. If
1422
+ // it's defined, but an unknown value, assume it's been instrumented by
1423
+ // some custom userspace implementation. We treat it as "pending".
1424
+ break;
1425
+ }
1426
+
1427
+ const pendingThenable = thenable;
1428
+ pendingThenable.status = 'pending';
1429
+ pendingThenable.then(fulfilledValue => {
1430
+ if (thenable.status === 'pending') {
1431
+ const fulfilledThenable = thenable;
1432
+ fulfilledThenable.status = 'fulfilled';
1433
+ fulfilledThenable.value = fulfilledValue;
1434
+ }
1435
+ }, error => {
1436
+ if (thenable.status === 'pending') {
1437
+ const rejectedThenable = thenable;
1438
+ rejectedThenable.status = 'rejected';
1439
+ rejectedThenable.reason = error;
1440
+ }
1441
+ });
1442
+ break;
1443
+ }
1444
+ }
1445
+
1446
+ thenable.then(value => {
1447
+ newTask.model = value;
1448
+ pingTask(request, newTask);
1449
+ }, reason => {
1450
+ {
1451
+ newTask.status = ERRORED$1;
1452
+ const digest = logRecoverableError(request, reason);
1453
+ emitErrorChunk(request, newTask.id, digest);
1454
+ }
1455
+
1456
+ request.abortableTasks.delete(newTask);
1457
+
1458
+ if (request.destination !== null) {
1459
+ flushCompletedChunks(request, request.destination);
1460
+ }
1461
+ });
1462
+ return newTask.id;
1463
+ }
1464
+
1465
+ function emitHint(request, code, model) {
1466
+ emitHintChunk(request, code, model);
1467
+ enqueueFlush(request);
1468
+ }
1469
+ function getHints(request) {
1470
+ return request.hints;
1471
+ }
1472
+ function getCache(request) {
1473
+ return request.cache;
1474
+ }
1475
+
1476
+ function readThenable(thenable) {
1477
+ if (thenable.status === 'fulfilled') {
1478
+ return thenable.value;
1479
+ } else if (thenable.status === 'rejected') {
1480
+ throw thenable.reason;
1481
+ }
1482
+
1483
+ throw thenable;
1484
+ }
1485
+
1486
+ function createLazyWrapperAroundWakeable(wakeable) {
1487
+ // This is a temporary fork of the `use` implementation until we accept
1488
+ // promises everywhere.
1489
+ const thenable = wakeable;
1490
+
1491
+ switch (thenable.status) {
1492
+ case 'fulfilled':
1493
+ case 'rejected':
1494
+ break;
1495
+
1496
+ default:
1497
+ {
1498
+ if (typeof thenable.status === 'string') {
1499
+ // Only instrument the thenable if the status if not defined. If
1500
+ // it's defined, but an unknown value, assume it's been instrumented by
1501
+ // some custom userspace implementation. We treat it as "pending".
1502
+ break;
1503
+ }
1504
+
1505
+ const pendingThenable = thenable;
1506
+ pendingThenable.status = 'pending';
1507
+ pendingThenable.then(fulfilledValue => {
1508
+ if (thenable.status === 'pending') {
1509
+ const fulfilledThenable = thenable;
1510
+ fulfilledThenable.status = 'fulfilled';
1511
+ fulfilledThenable.value = fulfilledValue;
1512
+ }
1513
+ }, error => {
1514
+ if (thenable.status === 'pending') {
1515
+ const rejectedThenable = thenable;
1516
+ rejectedThenable.status = 'rejected';
1517
+ rejectedThenable.reason = error;
1518
+ }
1519
+ });
1520
+ break;
1521
+ }
1522
+ }
1523
+
1524
+ const lazyType = {
1525
+ $$typeof: REACT_LAZY_TYPE,
1526
+ _payload: thenable,
1527
+ _init: readThenable
1528
+ };
1529
+
1530
+ return lazyType;
1531
+ }
1532
+
1533
+ function renderFunctionComponent(request, task, key, Component, props) {
1534
+ // Reset the task's thenable state before continuing, so that if a later
1535
+ // component suspends we can reuse the same task object. If the same
1536
+ // component suspends again, the thenable state will be restored.
1537
+ const prevThenableState = task.thenableState;
1538
+ task.thenableState = null;
1539
+
1540
+ prepareToUseHooksForComponent(prevThenableState); // The secondArg is always undefined in Server Components since refs error early.
1541
+
1542
+ const secondArg = undefined;
1543
+ let result = Component(props, secondArg);
1544
+
1545
+ if (typeof result === 'object' && result !== null && typeof result.then === 'function') {
1546
+ // When the return value is in children position we can resolve it immediately,
1547
+ // to its value without a wrapper if it's synchronously available.
1548
+ const thenable = result;
1549
+
1550
+ if (thenable.status === 'fulfilled') {
1551
+ return thenable.value;
1552
+ } // TODO: Once we accept Promises as children on the client, we can just return
1553
+ // the thenable here.
1554
+
1555
+
1556
+ result = createLazyWrapperAroundWakeable(result);
1557
+ } // Track this element's key on the Server Component on the keyPath context..
1558
+
1559
+
1560
+ const prevKeyPath = task.keyPath;
1561
+ const prevImplicitSlot = task.implicitSlot;
1562
+
1563
+ if (key !== null) {
1564
+ // Append the key to the path. Technically a null key should really add the child
1565
+ // index. We don't do that to hold the payload small and implementation simple.
1566
+ task.keyPath = prevKeyPath === null ? key : prevKeyPath + ',' + key;
1567
+ } else if (prevKeyPath === null) {
1568
+ // This sequence of Server Components has no keys. This means that it was rendered
1569
+ // in a slot that needs to assign an implicit key. Even if children below have
1570
+ // explicit keys, they should not be used for the outer most key since it might
1571
+ // collide with other slots in that set.
1572
+ task.implicitSlot = true;
1573
+ }
1574
+
1575
+ const json = renderModelDestructive(request, task, emptyRoot, '', result);
1576
+ task.keyPath = prevKeyPath;
1577
+ task.implicitSlot = prevImplicitSlot;
1578
+ return json;
1579
+ }
1580
+
1581
+ function renderFragment(request, task, children) {
1582
+
1583
+ {
1584
+ return children;
1585
+ }
1586
+ }
1587
+
1588
+ function renderClientElement(task, type, key, props) {
1589
+ {
1590
+ return [REACT_ELEMENT_TYPE, type, key, props];
1591
+ } // We prepend the terminal client element that actually gets serialized with
1592
+ } // The chunk ID we're currently rendering that we can assign debug data to.
1593
+
1594
+
1595
+ let debugID = null;
1596
+
1597
+ function renderElement(request, task, type, key, ref, props) {
1598
+ if (ref !== null && ref !== undefined) {
1599
+ // When the ref moves to the regular props object this will implicitly
1600
+ // throw for functions. We could probably relax it to a DEV warning for other
1601
+ // cases.
1602
+ // TODO: `ref` is now just a prop when `enableRefAsProp` is on. Should we
1603
+ // do what the above comment says?
1604
+ throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.');
1605
+ }
1606
+
1607
+ if (typeof type === 'function') {
1608
+ if (isClientReference(type) || isTemporaryReference(type)) {
1609
+ // This is a reference to a Client Component.
1610
+ return renderClientElement(task, type, key, props);
1611
+ } // This is a Server Component.
1612
+
1613
+
1614
+ return renderFunctionComponent(request, task, key, type, props);
1615
+ } else if (typeof type === 'string') {
1616
+ // This is a host element. E.g. HTML.
1617
+ return renderClientElement(task, type, key, props);
1618
+ } else if (typeof type === 'symbol') {
1619
+ if (type === REACT_FRAGMENT_TYPE && key === null) {
1620
+ // For key-less fragments, we add a small optimization to avoid serializing
1621
+ // it as a wrapper.
1622
+ const prevImplicitSlot = task.implicitSlot;
1623
+
1624
+ if (task.keyPath === null) {
1625
+ task.implicitSlot = true;
1626
+ }
1627
+
1628
+ const json = renderModelDestructive(request, task, emptyRoot, '', props.children);
1629
+ task.implicitSlot = prevImplicitSlot;
1630
+ return json;
1631
+ } // This might be a built-in React component. We'll let the client decide.
1632
+ // Any built-in works as long as its props are serializable.
1633
+
1634
+
1635
+ return renderClientElement(task, type, key, props);
1636
+ } else if (type != null && typeof type === 'object') {
1637
+ if (isClientReference(type)) {
1638
+ // This is a reference to a Client Component.
1639
+ return renderClientElement(task, type, key, props);
1640
+ }
1641
+
1642
+ switch (type.$$typeof) {
1643
+ case REACT_LAZY_TYPE:
1644
+ {
1645
+ const payload = type._payload;
1646
+ const init = type._init;
1647
+ const wrappedType = init(payload);
1648
+ return renderElement(request, task, wrappedType, key, ref, props);
1649
+ }
1650
+
1651
+ case REACT_FORWARD_REF_TYPE:
1652
+ {
1653
+ return renderFunctionComponent(request, task, key, type.render, props);
1654
+ }
1655
+
1656
+ case REACT_MEMO_TYPE:
1657
+ {
1658
+ return renderElement(request, task, type.type, key, ref, props);
1659
+ }
1660
+ }
1661
+ }
1662
+
1663
+ throw new Error("Unsupported Server Component type: " + describeValueForErrorMessage(type));
1664
+ }
1665
+
1666
+ function pingTask(request, task) {
1667
+ const pingedTasks = request.pingedTasks;
1668
+ pingedTasks.push(task);
1669
+
1670
+ if (pingedTasks.length === 1) {
1671
+ request.flushScheduled = request.destination !== null;
1672
+ scheduleWork(() => performWork(request));
1673
+ }
1674
+ }
1675
+
1676
+ function createTask(request, model, keyPath, implicitSlot, abortSet) {
1677
+ request.pendingChunks++;
1678
+ const id = request.nextChunkId++;
1679
+
1680
+ if (typeof model === 'object' && model !== null) {
1681
+ // If we're about to write this into a new task we can assign it an ID early so that
1682
+ // any other references can refer to the value we're about to write.
1683
+ {
1684
+ request.writtenObjects.set(model, id);
1685
+ }
1686
+ }
1687
+
1688
+ const task = {
1689
+ id,
1690
+ status: PENDING$1,
1691
+ model,
1692
+ keyPath,
1693
+ implicitSlot,
1694
+ ping: () => pingTask(request, task),
1695
+ toJSON: function (parentPropertyName, value) {
1696
+ const parent = this; // Make sure that `parent[parentPropertyName]` wasn't JSONified before `value` was passed to us
1697
+
1698
+ return renderModel(request, task, parent, parentPropertyName, value);
1699
+ },
1700
+ thenableState: null
1701
+ };
1702
+ abortSet.add(task);
1703
+ return task;
1704
+ }
1705
+
1706
+ function serializeByValueID(id) {
1707
+ return '$' + id.toString(16);
1708
+ }
1709
+
1710
+ function serializeLazyID(id) {
1711
+ return '$L' + id.toString(16);
1712
+ }
1713
+
1714
+ function serializePromiseID(id) {
1715
+ return '$@' + id.toString(16);
1716
+ }
1717
+
1718
+ function serializeServerReferenceID(id) {
1719
+ return '$F' + id.toString(16);
1720
+ }
1721
+
1722
+ function serializeTemporaryReferenceID(id) {
1723
+ return '$T' + id;
1724
+ }
1725
+
1726
+ function serializeSymbolReference(name) {
1727
+ return '$S' + name;
1728
+ }
1729
+
1730
+ function serializeNumber(number) {
1731
+ if (Number.isFinite(number)) {
1732
+ if (number === 0 && 1 / number === -Infinity) {
1733
+ return '$-0';
1734
+ } else {
1735
+ return number;
1736
+ }
1737
+ } else {
1738
+ if (number === Infinity) {
1739
+ return '$Infinity';
1740
+ } else if (number === -Infinity) {
1741
+ return '$-Infinity';
1742
+ } else {
1743
+ return '$NaN';
1744
+ }
1745
+ }
1746
+ }
1747
+
1748
+ function serializeUndefined() {
1749
+ return '$undefined';
1750
+ }
1751
+
1752
+ function serializeDateFromDateJSON(dateJSON) {
1753
+ // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString.
1754
+ // We need only tack on a $D prefix.
1755
+ return '$D' + dateJSON;
1756
+ }
1757
+
1758
+ function serializeBigInt(n) {
1759
+ return '$n' + n.toString(10);
1760
+ }
1761
+
1762
+ function serializeRowHeader(tag, id) {
1763
+ return id.toString(16) + ':' + tag;
1764
+ }
1765
+
1766
+ function encodeReferenceChunk(request, id, reference) {
1767
+ const json = stringify(reference);
1768
+ const row = id.toString(16) + ':' + json + '\n';
1769
+ return stringToChunk(row);
1770
+ }
1771
+
1772
+ function serializeClientReference(request, parent, parentPropertyName, clientReference) {
1773
+ const clientReferenceKey = getClientReferenceKey(clientReference);
1774
+ const writtenClientReferences = request.writtenClientReferences;
1775
+ const existingId = writtenClientReferences.get(clientReferenceKey);
1776
+
1777
+ if (existingId !== undefined) {
1778
+ if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
1779
+ // If we're encoding the "type" of an element, we can refer
1780
+ // to that by a lazy reference instead of directly since React
1781
+ // knows how to deal with lazy values. This lets us suspend
1782
+ // on this component rather than its parent until the code has
1783
+ // loaded.
1784
+ return serializeLazyID(existingId);
1785
+ }
1786
+
1787
+ return serializeByValueID(existingId);
1788
+ }
1789
+
1790
+ try {
1791
+ const clientReferenceMetadata = resolveClientReferenceMetadata(request.bundlerConfig, clientReference);
1792
+ request.pendingChunks++;
1793
+ const importId = request.nextChunkId++;
1794
+ emitImportChunk(request, importId, clientReferenceMetadata);
1795
+ writtenClientReferences.set(clientReferenceKey, importId);
1796
+
1797
+ if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
1798
+ // If we're encoding the "type" of an element, we can refer
1799
+ // to that by a lazy reference instead of directly since React
1800
+ // knows how to deal with lazy values. This lets us suspend
1801
+ // on this component rather than its parent until the code has
1802
+ // loaded.
1803
+ return serializeLazyID(importId);
1804
+ }
1805
+
1806
+ return serializeByValueID(importId);
1807
+ } catch (x) {
1808
+ request.pendingChunks++;
1809
+ const errorId = request.nextChunkId++;
1810
+ const digest = logRecoverableError(request, x);
1811
+ emitErrorChunk(request, errorId, digest);
1812
+ return serializeByValueID(errorId);
1813
+ }
1814
+ }
1815
+
1816
+ function outlineModel(request, value) {
1817
+ const newTask = createTask(request, value, null, // The way we use outlining is for reusing an object.
1818
+ false, // It makes no sense for that use case to be contextual.
1819
+ request.abortableTasks);
1820
+ retryTask(request, newTask);
1821
+ return newTask.id;
1822
+ }
1823
+
1824
+ function serializeServerReference(request, serverReference) {
1825
+ const writtenServerReferences = request.writtenServerReferences;
1826
+ const existingId = writtenServerReferences.get(serverReference);
1827
+
1828
+ if (existingId !== undefined) {
1829
+ return serializeServerReferenceID(existingId);
1830
+ }
1831
+
1832
+ const bound = getServerReferenceBoundArguments(request.bundlerConfig, serverReference);
1833
+ const serverReferenceMetadata = {
1834
+ id: getServerReferenceId(request.bundlerConfig, serverReference),
1835
+ bound: bound ? Promise.resolve(bound) : null
1836
+ };
1837
+ const metadataId = outlineModel(request, serverReferenceMetadata);
1838
+ writtenServerReferences.set(serverReference, metadataId);
1839
+ return serializeServerReferenceID(metadataId);
1840
+ }
1841
+
1842
+ function serializeTemporaryReference(request, temporaryReference) {
1843
+ const id = resolveTemporaryReferenceID(temporaryReference);
1844
+ return serializeTemporaryReferenceID(id);
1845
+ }
1846
+
1847
+ function serializeLargeTextString(request, text) {
1848
+ request.pendingChunks += 2;
1849
+ const textId = request.nextChunkId++;
1850
+ const textChunk = stringToChunk(text);
1851
+ const binaryLength = byteLengthOfChunk(textChunk);
1852
+ const row = textId.toString(16) + ':T' + binaryLength.toString(16) + ',';
1853
+ const headerChunk = stringToChunk(row);
1854
+ request.completedRegularChunks.push(headerChunk, textChunk);
1855
+ return serializeByValueID(textId);
1856
+ }
1857
+
1858
+ function serializeMap(request, map) {
1859
+ const entries = Array.from(map);
1860
+
1861
+ for (let i = 0; i < entries.length; i++) {
1862
+ const key = entries[i][0];
1863
+
1864
+ if (typeof key === 'object' && key !== null) {
1865
+ const writtenObjects = request.writtenObjects;
1866
+ const existingId = writtenObjects.get(key);
1867
+
1868
+ if (existingId === undefined) {
1869
+ // Mark all object keys as seen so that they're always outlined.
1870
+ writtenObjects.set(key, -1);
1871
+ }
1872
+ }
1873
+ }
1874
+
1875
+ const id = outlineModel(request, entries);
1876
+ return '$Q' + id.toString(16);
1877
+ }
1878
+
1879
+ function serializeSet(request, set) {
1880
+ const entries = Array.from(set);
1881
+
1882
+ for (let i = 0; i < entries.length; i++) {
1883
+ const key = entries[i];
1884
+
1885
+ if (typeof key === 'object' && key !== null) {
1886
+ const writtenObjects = request.writtenObjects;
1887
+ const existingId = writtenObjects.get(key);
1888
+
1889
+ if (existingId === undefined) {
1890
+ // Mark all object keys as seen so that they're always outlined.
1891
+ writtenObjects.set(key, -1);
1892
+ }
1893
+ }
1894
+ }
1895
+
1896
+ const id = outlineModel(request, entries);
1897
+ return '$W' + id.toString(16);
1898
+ }
1899
+
1900
+ function escapeStringValue(value) {
1901
+ if (value[0] === '$') {
1902
+ // We need to escape $ prefixed strings since we use those to encode
1903
+ // references to IDs and as special symbol values.
1904
+ return '$' + value;
1905
+ } else {
1906
+ return value;
1907
+ }
1908
+ }
1909
+
1910
+ let modelRoot = false;
1911
+
1912
+ function renderModel(request, task, parent, key, value) {
1913
+ const prevKeyPath = task.keyPath;
1914
+ const prevImplicitSlot = task.implicitSlot;
1915
+
1916
+ try {
1917
+ return renderModelDestructive(request, task, parent, key, value);
1918
+ } catch (thrownValue) {
1919
+ const x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
1920
+ // reasons, the rest of the Suspense implementation expects the thrown
1921
+ // value to be a thenable, because before `use` existed that was the
1922
+ // (unstable) API for suspending. This implementation detail can change
1923
+ // later, once we deprecate the old API in favor of `use`.
1924
+ getSuspendedThenable() : thrownValue; // If the suspended/errored value was an element or lazy it can be reduced
1925
+ // to a lazy reference, so that it doesn't error the parent.
1926
+
1927
+ const model = task.model;
1928
+ const wasReactNode = typeof model === 'object' && model !== null && (model.$$typeof === REACT_ELEMENT_TYPE || model.$$typeof === REACT_LAZY_TYPE);
1929
+
1930
+ if (typeof x === 'object' && x !== null) {
1931
+ // $FlowFixMe[method-unbinding]
1932
+ if (typeof x.then === 'function') {
1933
+ // Something suspended, we'll need to create a new task and resolve it later.
1934
+ const newTask = createTask(request, task.model, task.keyPath, task.implicitSlot, request.abortableTasks);
1935
+ const ping = newTask.ping;
1936
+ x.then(ping, ping);
1937
+ newTask.thenableState = getThenableStateAfterSuspending(); // Restore the context. We assume that this will be restored by the inner
1938
+ // functions in case nothing throws so we don't use "finally" here.
1939
+
1940
+ task.keyPath = prevKeyPath;
1941
+ task.implicitSlot = prevImplicitSlot;
1942
+
1943
+ if (wasReactNode) {
1944
+ return serializeLazyID(newTask.id);
1945
+ }
1946
+
1947
+ return serializeByValueID(newTask.id);
1948
+ }
1949
+ } // Restore the context. We assume that this will be restored by the inner
1950
+ // functions in case nothing throws so we don't use "finally" here.
1951
+
1952
+
1953
+ task.keyPath = prevKeyPath;
1954
+ task.implicitSlot = prevImplicitSlot;
1955
+
1956
+ if (wasReactNode) {
1957
+ // Something errored. We'll still send everything we have up until this point.
1958
+ // We'll replace this element with a lazy reference that throws on the client
1959
+ // once it gets rendered.
1960
+ request.pendingChunks++;
1961
+ const errorId = request.nextChunkId++;
1962
+ const digest = logRecoverableError(request, x);
1963
+ emitErrorChunk(request, errorId, digest);
1964
+ return serializeLazyID(errorId);
1965
+ } // Something errored but it was not in a React Node. There's no need to serialize
1966
+ // it by value because it'll just error the whole parent row anyway so we can
1967
+ // just stop any siblings and error the whole parent row.
1968
+
1969
+
1970
+ throw x;
1971
+ }
1972
+ }
1973
+
1974
+ function renderModelDestructive(request, task, parent, parentPropertyName, value) {
1975
+ // Set the currently rendering model
1976
+ task.model = value; // Special Symbol, that's very common.
1977
+
1978
+ if (value === REACT_ELEMENT_TYPE) {
1979
+ return '$';
1980
+ }
1981
+
1982
+ if (value === null) {
1983
+ return null;
1984
+ }
1985
+
1986
+ if (typeof value === 'object') {
1987
+ switch (value.$$typeof) {
1988
+ case REACT_ELEMENT_TYPE:
1989
+ {
1990
+ const writtenObjects = request.writtenObjects;
1991
+ const existingId = writtenObjects.get(value);
1992
+
1993
+ if (existingId !== undefined) {
1994
+ if (modelRoot === value) {
1995
+ // This is the ID we're currently emitting so we need to write it
1996
+ // once but if we discover it again, we refer to it by id.
1997
+ modelRoot = null;
1998
+ } else if (existingId === -1) {
1999
+ // Seen but not yet outlined.
2000
+ // TODO: If we throw here we can treat this as suspending which causes an outline
2001
+ // but that is able to reuse the same task if we're already in one but then that
2002
+ // will be a lazy future value rather than guaranteed to exist but maybe that's good.
2003
+ const newId = outlineModel(request, value);
2004
+ return serializeByValueID(newId);
2005
+ } else {
2006
+ // We've already emitted this as an outlined object, so we can refer to that by its
2007
+ // existing ID. TODO: We should use a lazy reference since, unlike plain objects,
2008
+ // elements might suspend so it might not have emitted yet even if we have the ID for
2009
+ // it. However, this creates an extra wrapper when it's not needed. We should really
2010
+ // detect whether this already was emitted and synchronously available. In that
2011
+ // case we can refer to it synchronously and only make it lazy otherwise.
2012
+ // We currently don't have a data structure that lets us see that though.
2013
+ return serializeByValueID(existingId);
2014
+ }
2015
+ } else {
2016
+ // This is the first time we've seen this object. We may never see it again
2017
+ // so we'll inline it. Mark it as seen. If we see it again, we'll outline.
2018
+ writtenObjects.set(value, -1);
2019
+ }
2020
+
2021
+ const element = value;
2022
+
2023
+ const props = element.props;
2024
+ let ref;
2025
+
2026
+ {
2027
+ ref = element.ref;
2028
+ } // Attempt to render the Server Component.
2029
+
2030
+
2031
+ return renderElement(request, task, element.type, // $FlowFixMe[incompatible-call] the key of an element is null | string
2032
+ element.key, ref, props);
2033
+ }
2034
+
2035
+ case REACT_LAZY_TYPE:
2036
+ {
2037
+ // Reset the task's thenable state before continuing. If there was one, it was
2038
+ // from suspending the lazy before.
2039
+ task.thenableState = null;
2040
+ const lazy = value;
2041
+ const payload = lazy._payload;
2042
+ const init = lazy._init;
2043
+ const resolvedModel = init(payload);
2044
+
2045
+ return renderModelDestructive(request, task, emptyRoot, '', resolvedModel);
2046
+ }
2047
+ }
2048
+
2049
+ if (isClientReference(value)) {
2050
+ return serializeClientReference(request, parent, parentPropertyName, value);
2051
+ }
2052
+
2053
+ const writtenObjects = request.writtenObjects;
2054
+ const existingId = writtenObjects.get(value); // $FlowFixMe[method-unbinding]
2055
+
2056
+ if (typeof value.then === 'function') {
2057
+ if (existingId !== undefined) {
2058
+ if (modelRoot === value) {
2059
+ // This is the ID we're currently emitting so we need to write it
2060
+ // once but if we discover it again, we refer to it by id.
2061
+ modelRoot = null;
2062
+ } else {
2063
+ // We've seen this promise before, so we can just refer to the same result.
2064
+ return serializePromiseID(existingId);
2065
+ }
2066
+ } // We assume that any object with a .then property is a "Thenable" type,
2067
+ // or a Promise type. Either of which can be represented by a Promise.
2068
+
2069
+
2070
+ const promiseId = serializeThenable(request, task, value);
2071
+ writtenObjects.set(value, promiseId);
2072
+ return serializePromiseID(promiseId);
2073
+ }
2074
+
2075
+ if (existingId !== undefined) {
2076
+ if (modelRoot === value) {
2077
+ // This is the ID we're currently emitting so we need to write it
2078
+ // once but if we discover it again, we refer to it by id.
2079
+ modelRoot = null;
2080
+ } else if (existingId === -1) {
2081
+ // Seen but not yet outlined.
2082
+ const newId = outlineModel(request, value);
2083
+ return serializeByValueID(newId);
2084
+ } else {
2085
+ // We've already emitted this as an outlined object, so we can
2086
+ // just refer to that by its existing ID.
2087
+ return serializeByValueID(existingId);
2088
+ }
2089
+ } else {
2090
+ // This is the first time we've seen this object. We may never see it again
2091
+ // so we'll inline it. Mark it as seen. If we see it again, we'll outline.
2092
+ writtenObjects.set(value, -1);
2093
+ }
2094
+
2095
+ if (isArray(value)) {
2096
+ return renderFragment(request, task, value);
2097
+ }
2098
+
2099
+ if (value instanceof Map) {
2100
+ return serializeMap(request, value);
2101
+ }
2102
+
2103
+ if (value instanceof Set) {
2104
+ return serializeSet(request, value);
2105
+ }
2106
+
2107
+ const iteratorFn = getIteratorFn(value);
2108
+
2109
+ if (iteratorFn) {
2110
+ return renderFragment(request, task, Array.from(value));
2111
+ } // Verify that this is a simple plain object.
2112
+
2113
+
2114
+ const proto = getPrototypeOf(value);
2115
+
2116
+ if (proto !== ObjectPrototype && (proto === null || getPrototypeOf(proto) !== null)) {
2117
+ throw new Error('Only plain objects, and a few built-ins, can be passed to Client Components ' + 'from Server Components. Classes or null prototypes are not supported.');
2118
+ }
2119
+
2120
+
2121
+ return value;
2122
+ }
2123
+
2124
+ if (typeof value === 'string') {
2125
+
2126
+
2127
+ if (value[value.length - 1] === 'Z') {
2128
+ // Possibly a Date, whose toJSON automatically calls toISOString
2129
+ // $FlowFixMe[incompatible-use]
2130
+ const originalValue = parent[parentPropertyName];
2131
+
2132
+ if (originalValue instanceof Date) {
2133
+ return serializeDateFromDateJSON(value);
2134
+ }
2135
+ }
2136
+
2137
+ if (value.length >= 1024) {
2138
+ // For large strings, we encode them outside the JSON payload so that we
2139
+ // don't have to double encode and double parse the strings. This can also
2140
+ // be more compact in case the string has a lot of escaped characters.
2141
+ return serializeLargeTextString(request, value);
2142
+ }
2143
+
2144
+ return escapeStringValue(value);
2145
+ }
2146
+
2147
+ if (typeof value === 'boolean') {
2148
+ return value;
2149
+ }
2150
+
2151
+ if (typeof value === 'number') {
2152
+ return serializeNumber(value);
2153
+ }
2154
+
2155
+ if (typeof value === 'undefined') {
2156
+ return serializeUndefined();
2157
+ }
2158
+
2159
+ if (typeof value === 'function') {
2160
+ if (isClientReference(value)) {
2161
+ return serializeClientReference(request, parent, parentPropertyName, value);
2162
+ }
2163
+
2164
+ if (isServerReference(value)) {
2165
+ return serializeServerReference(request, value);
2166
+ }
2167
+
2168
+ if (isTemporaryReference(value)) {
2169
+ return serializeTemporaryReference(request, value);
2170
+ }
2171
+
2172
+ if (/^on[A-Z]/.test(parentPropertyName)) {
2173
+ throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, parentPropertyName) + '\nIf you need interactivity, consider converting part of this to a Client Component.');
2174
+ } else {
2175
+ throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server". ' + 'Or maybe you meant to call this function rather than return it.' + describeObjectForErrorMessage(parent, parentPropertyName));
2176
+ }
2177
+ }
2178
+
2179
+ if (typeof value === 'symbol') {
2180
+ const writtenSymbols = request.writtenSymbols;
2181
+ const existingId = writtenSymbols.get(value);
2182
+
2183
+ if (existingId !== undefined) {
2184
+ return serializeByValueID(existingId);
2185
+ } // $FlowFixMe[incompatible-type] `description` might be undefined
2186
+
2187
+
2188
+ const name = value.description;
2189
+
2190
+ if (Symbol.for(name) !== value) {
2191
+ throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined
2192
+ value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, parentPropertyName));
2193
+ }
2194
+
2195
+ request.pendingChunks++;
2196
+ const symbolId = request.nextChunkId++;
2197
+ emitSymbolChunk(request, symbolId, name);
2198
+ writtenSymbols.set(value, symbolId);
2199
+ return serializeByValueID(symbolId);
2200
+ }
2201
+
2202
+ if (typeof value === 'bigint') {
2203
+
2204
+ return serializeBigInt(value);
2205
+ }
2206
+
2207
+ throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, parentPropertyName));
2208
+ }
2209
+
2210
+ function logPostpone(request, reason) {
2211
+ const prevRequest = currentRequest;
2212
+ currentRequest = null;
2213
+
2214
+ try {
2215
+ const onPostpone = request.onPostpone;
2216
+
2217
+ if (supportsRequestStorage) {
2218
+ // Exit the request context while running callbacks.
2219
+ requestStorage.run(undefined, onPostpone, reason);
2220
+ }
2221
+ } finally {
2222
+ currentRequest = prevRequest;
2223
+ }
2224
+ }
2225
+
2226
+ function logRecoverableError(request, error) {
2227
+ const prevRequest = currentRequest;
2228
+ currentRequest = null;
2229
+ let errorDigest;
2230
+
2231
+ try {
2232
+ const onError = request.onError;
2233
+
2234
+ if (supportsRequestStorage) {
2235
+ // Exit the request context while running callbacks.
2236
+ errorDigest = requestStorage.run(undefined, onError, error);
2237
+ }
2238
+ } finally {
2239
+ currentRequest = prevRequest;
2240
+ }
2241
+
2242
+ if (errorDigest != null && typeof errorDigest !== 'string') {
2243
+ // eslint-disable-next-line react-internal/prod-error-codes
2244
+ throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead");
2245
+ }
2246
+
2247
+ return errorDigest || '';
2248
+ }
2249
+
2250
+ function fatalError(request, error) {
2251
+
2252
+
2253
+ if (request.destination !== null) {
2254
+ request.status = CLOSED;
2255
+ closeWithError(request.destination, error);
2256
+ } else {
2257
+ request.status = CLOSING;
2258
+ request.fatalError = error;
2259
+ }
2260
+ }
2261
+
2262
+ function emitPostponeChunk(request, id, postponeInstance) {
2263
+ let row;
2264
+
2265
+ {
2266
+ // No reason included in prod.
2267
+ row = serializeRowHeader('P', id) + '\n';
2268
+ }
2269
+
2270
+ const processedChunk = stringToChunk(row);
2271
+ request.completedErrorChunks.push(processedChunk);
2272
+ }
2273
+
2274
+ function emitErrorChunk(request, id, digest, error) {
2275
+ let errorInfo;
2276
+
2277
+ {
2278
+ errorInfo = {
2279
+ digest
2280
+ };
2281
+ }
2282
+
2283
+ const row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n';
2284
+ const processedChunk = stringToChunk(row);
2285
+ request.completedErrorChunks.push(processedChunk);
2286
+ }
2287
+
2288
+ function emitImportChunk(request, id, clientReferenceMetadata) {
2289
+ // $FlowFixMe[incompatible-type] stringify can return null
2290
+ const json = stringify(clientReferenceMetadata);
2291
+ const row = serializeRowHeader('I', id) + json + '\n';
2292
+ const processedChunk = stringToChunk(row);
2293
+ request.completedImportChunks.push(processedChunk);
2294
+ }
2295
+
2296
+ function emitHintChunk(request, code, model) {
2297
+ const json = stringify(model);
2298
+ const id = request.nextChunkId++;
2299
+ const row = serializeRowHeader('H' + code, id) + json + '\n';
2300
+ const processedChunk = stringToChunk(row);
2301
+ request.completedHintChunks.push(processedChunk);
2302
+ }
2303
+
2304
+ function emitSymbolChunk(request, id, name) {
2305
+ const symbolReference = serializeSymbolReference(name);
2306
+ const processedChunk = encodeReferenceChunk(request, id, symbolReference);
2307
+ request.completedImportChunks.push(processedChunk);
2308
+ }
2309
+
2310
+ function emitModelChunk(request, id, json) {
2311
+ const row = id.toString(16) + ':' + json + '\n';
2312
+ const processedChunk = stringToChunk(row);
2313
+ request.completedRegularChunks.push(processedChunk);
2314
+ }
2315
+
2316
+ const emptyRoot = {};
2317
+
2318
+ function retryTask(request, task) {
2319
+ if (task.status !== PENDING$1) {
2320
+ // We completed this by other means before we had a chance to retry it.
2321
+ return;
2322
+ }
2323
+
2324
+ try {
2325
+ // Track the root so we know that we have to emit this object even though it
2326
+ // already has an ID. This is needed because we might see this object twice
2327
+ // in the same toJSON if it is cyclic.
2328
+ modelRoot = task.model;
2329
+
2330
+ if (false) ; // We call the destructive form that mutates this task. That way if something
2331
+ // suspends again, we can reuse the same task instead of spawning a new one.
2332
+
2333
+
2334
+ const resolvedModel = renderModelDestructive(request, task, emptyRoot, '', task.model);
2335
+
2336
+ if (false) ; // Track the root again for the resolved object.
2337
+
2338
+
2339
+ modelRoot = resolvedModel; // The keyPath resets at any terminal child node.
2340
+
2341
+ task.keyPath = null;
2342
+ task.implicitSlot = false;
2343
+ let json;
2344
+
2345
+ if (typeof resolvedModel === 'object' && resolvedModel !== null) {
2346
+ // Object might contain unresolved values like additional elements.
2347
+ // This is simulating what the JSON loop would do if this was part of it.
2348
+ // $FlowFixMe[incompatible-type] stringify can return null for undefined but we never do
2349
+ json = stringify(resolvedModel, task.toJSON);
2350
+ } else {
2351
+ // If the value is a string, it means it's a terminal value and we already escaped it
2352
+ // We don't need to escape it again so it's not passed the toJSON replacer.
2353
+ // $FlowFixMe[incompatible-type] stringify can return null for undefined but we never do
2354
+ json = stringify(resolvedModel);
2355
+ }
2356
+
2357
+ emitModelChunk(request, task.id, json);
2358
+ request.abortableTasks.delete(task);
2359
+ task.status = COMPLETED;
2360
+ } catch (thrownValue) {
2361
+ const x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
2362
+ // reasons, the rest of the Suspense implementation expects the thrown
2363
+ // value to be a thenable, because before `use` existed that was the
2364
+ // (unstable) API for suspending. This implementation detail can change
2365
+ // later, once we deprecate the old API in favor of `use`.
2366
+ getSuspendedThenable() : thrownValue;
2367
+
2368
+ if (typeof x === 'object' && x !== null) {
2369
+ // $FlowFixMe[method-unbinding]
2370
+ if (typeof x.then === 'function') {
2371
+ // Something suspended again, let's pick it back up later.
2372
+ const ping = task.ping;
2373
+ x.then(ping, ping);
2374
+ task.thenableState = getThenableStateAfterSuspending();
2375
+ return;
2376
+ }
2377
+ }
2378
+
2379
+ request.abortableTasks.delete(task);
2380
+ task.status = ERRORED$1;
2381
+ const digest = logRecoverableError(request, x);
2382
+ emitErrorChunk(request, task.id, digest);
2383
+ } finally {
2384
+ }
2385
+ }
2386
+
2387
+ function performWork(request) {
2388
+ const prevDispatcher = ReactCurrentDispatcher.current;
2389
+ ReactCurrentDispatcher.current = HooksDispatcher;
2390
+ const prevRequest = currentRequest;
2391
+ currentRequest = request;
2392
+ prepareToUseHooksForRequest(request);
2393
+
2394
+ try {
2395
+ const pingedTasks = request.pingedTasks;
2396
+ request.pingedTasks = [];
2397
+
2398
+ for (let i = 0; i < pingedTasks.length; i++) {
2399
+ const task = pingedTasks[i];
2400
+ retryTask(request, task);
2401
+ }
2402
+
2403
+ if (request.destination !== null) {
2404
+ flushCompletedChunks(request, request.destination);
2405
+ }
2406
+ } catch (error) {
2407
+ logRecoverableError(request, error);
2408
+ fatalError(request, error);
2409
+ } finally {
2410
+ ReactCurrentDispatcher.current = prevDispatcher;
2411
+ resetHooksForRequest();
2412
+ currentRequest = prevRequest;
2413
+ }
2414
+ }
2415
+
2416
+ function abortTask(task, request, errorId) {
2417
+ task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only
2418
+ // has a single value referencing the error.
2419
+
2420
+ const ref = serializeByValueID(errorId);
2421
+ const processedChunk = encodeReferenceChunk(request, task.id, ref);
2422
+ request.completedErrorChunks.push(processedChunk);
2423
+ }
2424
+
2425
+ function flushCompletedChunks(request, destination) {
2426
+ beginWriting();
2427
+
2428
+ try {
2429
+ // We emit module chunks first in the stream so that
2430
+ // they can be preloaded as early as possible.
2431
+ const importsChunks = request.completedImportChunks;
2432
+ let i = 0;
2433
+
2434
+ for (; i < importsChunks.length; i++) {
2435
+ request.pendingChunks--;
2436
+ const chunk = importsChunks[i];
2437
+ const keepWriting = writeChunkAndReturn(destination, chunk);
2438
+
2439
+ if (!keepWriting) {
2440
+ request.destination = null;
2441
+ i++;
2442
+ break;
2443
+ }
2444
+ }
2445
+
2446
+ importsChunks.splice(0, i); // Next comes hints.
2447
+
2448
+ const hintChunks = request.completedHintChunks;
2449
+ i = 0;
2450
+
2451
+ for (; i < hintChunks.length; i++) {
2452
+ const chunk = hintChunks[i];
2453
+ const keepWriting = writeChunkAndReturn(destination, chunk);
2454
+
2455
+ if (!keepWriting) {
2456
+ request.destination = null;
2457
+ i++;
2458
+ break;
2459
+ }
2460
+ }
2461
+
2462
+ hintChunks.splice(0, i); // Next comes model data.
2463
+
2464
+ const regularChunks = request.completedRegularChunks;
2465
+ i = 0;
2466
+
2467
+ for (; i < regularChunks.length; i++) {
2468
+ request.pendingChunks--;
2469
+ const chunk = regularChunks[i];
2470
+ const keepWriting = writeChunkAndReturn(destination, chunk);
2471
+
2472
+ if (!keepWriting) {
2473
+ request.destination = null;
2474
+ i++;
2475
+ break;
2476
+ }
2477
+ }
2478
+
2479
+ regularChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay
2480
+ // any error messages and prioritize display of other parts of
2481
+ // the page.
2482
+
2483
+ const errorChunks = request.completedErrorChunks;
2484
+ i = 0;
2485
+
2486
+ for (; i < errorChunks.length; i++) {
2487
+ request.pendingChunks--;
2488
+ const chunk = errorChunks[i];
2489
+ const keepWriting = writeChunkAndReturn(destination, chunk);
2490
+
2491
+ if (!keepWriting) {
2492
+ request.destination = null;
2493
+ i++;
2494
+ break;
2495
+ }
2496
+ }
2497
+
2498
+ errorChunks.splice(0, i);
2499
+ } finally {
2500
+ request.flushScheduled = false;
2501
+ completeWriting(destination);
2502
+ }
2503
+
2504
+ flushBuffered(destination);
2505
+
2506
+ if (request.pendingChunks === 0) {
2507
+
2508
+ close$1(destination);
2509
+ }
2510
+ }
2511
+
2512
+ function startWork(request) {
2513
+ request.flushScheduled = request.destination !== null;
2514
+
2515
+ {
2516
+ scheduleWork(() => requestStorage.run(request, performWork, request));
2517
+ }
2518
+ }
2519
+
2520
+ function enqueueFlush(request) {
2521
+ if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes
2522
+ request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will
2523
+ // happen when we start flowing again
2524
+ request.destination !== null) {
2525
+ const destination = request.destination;
2526
+ request.flushScheduled = true;
2527
+ scheduleWork(() => flushCompletedChunks(request, destination));
2528
+ }
2529
+ }
2530
+
2531
+ function startFlowing(request, destination) {
2532
+ if (request.status === CLOSING) {
2533
+ request.status = CLOSED;
2534
+ closeWithError(destination, request.fatalError);
2535
+ return;
2536
+ }
2537
+
2538
+ if (request.status === CLOSED) {
2539
+ return;
2540
+ }
2541
+
2542
+ if (request.destination !== null) {
2543
+ // We're already flowing.
2544
+ return;
2545
+ }
2546
+
2547
+ request.destination = destination;
2548
+
2549
+ try {
2550
+ flushCompletedChunks(request, destination);
2551
+ } catch (error) {
2552
+ logRecoverableError(request, error);
2553
+ fatalError(request, error);
2554
+ }
2555
+ }
2556
+ function stopFlowing(request) {
2557
+ request.destination = null;
2558
+ } // This is called to early terminate a request. It creates an error at all pending tasks.
2559
+
2560
+ function abort(request, reason) {
2561
+ try {
2562
+ const abortableTasks = request.abortableTasks;
2563
+
2564
+ if (abortableTasks.size > 0) {
2565
+ // We have tasks to abort. We'll emit one error row and then emit a reference
2566
+ // to that row from every row that's still remaining.
2567
+ request.pendingChunks++;
2568
+ const errorId = request.nextChunkId++;
2569
+
2570
+ if (enablePostpone && typeof reason === 'object' && reason !== null && reason.$$typeof === REACT_POSTPONE_TYPE) ; else {
2571
+ const error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
2572
+ const digest = logRecoverableError(request, error);
2573
+ emitErrorChunk(request, errorId, digest, error);
2574
+ }
2575
+
2576
+ abortableTasks.forEach(task => abortTask(task, request, errorId));
2577
+ abortableTasks.clear();
2578
+ }
2579
+
2580
+ if (request.destination !== null) {
2581
+ flushCompletedChunks(request, request.destination);
2582
+ }
2583
+ } catch (error) {
2584
+ logRecoverableError(request, error);
2585
+ fatalError(request, error);
2586
+ }
2587
+ }
2588
+
2589
+ function resolveServerReference(bundlerConfig, id) {
2590
+ const idx = id.lastIndexOf('#');
2591
+ const specifier = id.slice(0, idx);
2592
+ const name = id.slice(idx + 1);
2593
+ return {
2594
+ specifier,
2595
+ name
2596
+ };
2597
+ }
2598
+ const asyncModuleCache = new Map();
2599
+ function preloadModule(metadata) {
2600
+ const existingPromise = asyncModuleCache.get(metadata.specifier);
2601
+
2602
+ if (existingPromise) {
2603
+ if (existingPromise.status === 'fulfilled') {
2604
+ return null;
2605
+ }
2606
+
2607
+ return existingPromise;
2608
+ } else {
2609
+ // $FlowFixMe[unsupported-syntax]
2610
+ let modulePromise = import(metadata.specifier);
2611
+
2612
+ if (metadata.async) {
2613
+ // If the module is async, it must have been a CJS module.
2614
+ // CJS modules are accessed through the default export in
2615
+ // Node.js so we have to get the default export to get the
2616
+ // full module exports.
2617
+ modulePromise = modulePromise.then(function (value) {
2618
+ return value.default;
2619
+ });
2620
+ }
2621
+
2622
+ modulePromise.then(value => {
2623
+ const fulfilledThenable = modulePromise;
2624
+ fulfilledThenable.status = 'fulfilled';
2625
+ fulfilledThenable.value = value;
2626
+ }, reason => {
2627
+ const rejectedThenable = modulePromise;
2628
+ rejectedThenable.status = 'rejected';
2629
+ rejectedThenable.reason = reason;
2630
+ });
2631
+ asyncModuleCache.set(metadata.specifier, modulePromise);
2632
+ return modulePromise;
2633
+ }
2634
+ }
2635
+ function requireModule(metadata) {
2636
+ let moduleExports; // We assume that preloadModule has been called before, which
2637
+ // should have added something to the module cache.
2638
+
2639
+ const promise = asyncModuleCache.get(metadata.specifier);
2640
+
2641
+ if (promise.status === 'fulfilled') {
2642
+ moduleExports = promise.value;
2643
+ } else {
2644
+ throw promise.reason;
2645
+ }
2646
+
2647
+ if (metadata.name === '*') {
2648
+ // This is a placeholder value that represents that the caller imported this
2649
+ // as a CommonJS module as is.
2650
+ return moduleExports;
2651
+ }
2652
+
2653
+ if (metadata.name === '') {
2654
+ // This is a placeholder value that represents that the caller accessed the
2655
+ // default property of this if it was an ESM interop module.
2656
+ return moduleExports.default;
2657
+ }
2658
+
2659
+ return moduleExports[metadata.name];
2660
+ }
2661
+
2662
+ // The server acts as a Client of itself when resolving Server References.
2663
+ const PENDING = 'pending';
2664
+ const BLOCKED = 'blocked';
2665
+ const RESOLVED_MODEL = 'resolved_model';
2666
+ const INITIALIZED = 'fulfilled';
2667
+ const ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot]
2668
+
2669
+ function Chunk(status, value, reason, response) {
2670
+ this.status = status;
2671
+ this.value = value;
2672
+ this.reason = reason;
2673
+ this._response = response;
2674
+ } // We subclass Promise.prototype so that we get other methods like .catch
2675
+
2676
+
2677
+ Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then
2678
+
2679
+ Chunk.prototype.then = function (resolve, reject) {
2680
+ const chunk = this; // If we have resolved content, we try to initialize it first which
2681
+ // might put us back into one of the other states.
2682
+
2683
+ switch (chunk.status) {
2684
+ case RESOLVED_MODEL:
2685
+ initializeModelChunk(chunk);
2686
+ break;
2687
+ } // The status might have changed after initialization.
2688
+
2689
+
2690
+ switch (chunk.status) {
2691
+ case INITIALIZED:
2692
+ resolve(chunk.value);
2693
+ break;
2694
+
2695
+ case PENDING:
2696
+ case BLOCKED:
2697
+ if (resolve) {
2698
+ if (chunk.value === null) {
2699
+ chunk.value = [];
2700
+ }
2701
+
2702
+ chunk.value.push(resolve);
2703
+ }
2704
+
2705
+ if (reject) {
2706
+ if (chunk.reason === null) {
2707
+ chunk.reason = [];
2708
+ }
2709
+
2710
+ chunk.reason.push(reject);
2711
+ }
2712
+
2713
+ break;
2714
+
2715
+ default:
2716
+ reject(chunk.reason);
2717
+ break;
2718
+ }
2719
+ };
2720
+
2721
+ function getRoot(response) {
2722
+ const chunk = getChunk(response, 0);
2723
+ return chunk;
2724
+ }
2725
+
2726
+ function createPendingChunk(response) {
2727
+ // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
2728
+ return new Chunk(PENDING, null, null, response);
2729
+ }
2730
+
2731
+ function wakeChunk(listeners, value) {
2732
+ for (let i = 0; i < listeners.length; i++) {
2733
+ const listener = listeners[i];
2734
+ listener(value);
2735
+ }
2736
+ }
2737
+
2738
+ function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) {
2739
+ switch (chunk.status) {
2740
+ case INITIALIZED:
2741
+ wakeChunk(resolveListeners, chunk.value);
2742
+ break;
2743
+
2744
+ case PENDING:
2745
+ case BLOCKED:
2746
+ chunk.value = resolveListeners;
2747
+ chunk.reason = rejectListeners;
2748
+ break;
2749
+
2750
+ case ERRORED:
2751
+ if (rejectListeners) {
2752
+ wakeChunk(rejectListeners, chunk.reason);
2753
+ }
2754
+
2755
+ break;
2756
+ }
2757
+ }
2758
+
2759
+ function triggerErrorOnChunk(chunk, error) {
2760
+ if (chunk.status !== PENDING && chunk.status !== BLOCKED) {
2761
+ // We already resolved. We didn't expect to see this.
2762
+ return;
2763
+ }
2764
+
2765
+ const listeners = chunk.reason;
2766
+ const erroredChunk = chunk;
2767
+ erroredChunk.status = ERRORED;
2768
+ erroredChunk.reason = error;
2769
+
2770
+ if (listeners !== null) {
2771
+ wakeChunk(listeners, error);
2772
+ }
2773
+ }
2774
+
2775
+ function createResolvedModelChunk(response, value) {
2776
+ // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
2777
+ return new Chunk(RESOLVED_MODEL, value, null, response);
2778
+ }
2779
+
2780
+ function resolveModelChunk(chunk, value) {
2781
+ if (chunk.status !== PENDING) {
2782
+ // We already resolved. We didn't expect to see this.
2783
+ return;
2784
+ }
2785
+
2786
+ const resolveListeners = chunk.value;
2787
+ const rejectListeners = chunk.reason;
2788
+ const resolvedChunk = chunk;
2789
+ resolvedChunk.status = RESOLVED_MODEL;
2790
+ resolvedChunk.value = value;
2791
+
2792
+ if (resolveListeners !== null) {
2793
+ // This is unfortunate that we're reading this eagerly if
2794
+ // we already have listeners attached since they might no
2795
+ // longer be rendered or might not be the highest pri.
2796
+ initializeModelChunk(resolvedChunk); // The status might have changed after initialization.
2797
+
2798
+ wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners);
2799
+ }
2800
+ }
2801
+
2802
+ function bindArgs$1(fn, args) {
2803
+ return fn.bind.apply(fn, [null].concat(args));
2804
+ }
2805
+
2806
+ function loadServerReference$1(response, id, bound, parentChunk, parentObject, key) {
2807
+ const serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all
2808
+ // the relevant modules already loaded but it allows for lazy loading of code
2809
+ // if needed.
2810
+
2811
+ const preloadPromise = preloadModule(serverReference);
2812
+ let promise;
2813
+
2814
+ if (bound) {
2815
+ promise = Promise.all([bound, preloadPromise]).then((_ref) => {
2816
+ let args = _ref[0];
2817
+ return bindArgs$1(requireModule(serverReference), args);
2818
+ });
2819
+ } else {
2820
+ if (preloadPromise) {
2821
+ promise = Promise.resolve(preloadPromise).then(() => requireModule(serverReference));
2822
+ } else {
2823
+ // Synchronously available
2824
+ return requireModule(serverReference);
2825
+ }
2826
+ }
2827
+
2828
+ promise.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); // We need a placeholder value that will be replaced later.
2829
+
2830
+ return null;
2831
+ }
2832
+
2833
+ let initializingChunk = null;
2834
+ let initializingChunkBlockedModel = null;
2835
+
2836
+ function initializeModelChunk(chunk) {
2837
+ const prevChunk = initializingChunk;
2838
+ const prevBlocked = initializingChunkBlockedModel;
2839
+ initializingChunk = chunk;
2840
+ initializingChunkBlockedModel = null;
2841
+
2842
+ try {
2843
+ const value = JSON.parse(chunk.value, chunk._response._fromJSON);
2844
+
2845
+ if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) {
2846
+ initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved.
2847
+ // We have to go the BLOCKED state until they're resolved.
2848
+
2849
+ const blockedChunk = chunk;
2850
+ blockedChunk.status = BLOCKED;
2851
+ blockedChunk.value = null;
2852
+ blockedChunk.reason = null;
2853
+ } else {
2854
+ const initializedChunk = chunk;
2855
+ initializedChunk.status = INITIALIZED;
2856
+ initializedChunk.value = value;
2857
+ }
2858
+ } catch (error) {
2859
+ const erroredChunk = chunk;
2860
+ erroredChunk.status = ERRORED;
2861
+ erroredChunk.reason = error;
2862
+ } finally {
2863
+ initializingChunk = prevChunk;
2864
+ initializingChunkBlockedModel = prevBlocked;
2865
+ }
2866
+ } // Report that any missing chunks in the model is now going to throw this
2867
+ // error upon read. Also notify any pending promises.
2868
+
2869
+
2870
+ function reportGlobalError(response, error) {
2871
+ response._chunks.forEach(chunk => {
2872
+ // If this chunk was already resolved or errored, it won't
2873
+ // trigger an error but if it wasn't then we need to
2874
+ // because we won't be getting any new data to resolve it.
2875
+ if (chunk.status === PENDING) {
2876
+ triggerErrorOnChunk(chunk, error);
2877
+ }
2878
+ });
2879
+ }
2880
+
2881
+ function getChunk(response, id) {
2882
+ const chunks = response._chunks;
2883
+ let chunk = chunks.get(id);
2884
+
2885
+ if (!chunk) {
2886
+ const prefix = response._prefix;
2887
+ const key = prefix + id; // Check if we have this field in the backing store already.
2888
+
2889
+ const backingEntry = response._formData.get(key);
2890
+
2891
+ if (backingEntry != null) {
2892
+ // We assume that this is a string entry for now.
2893
+ chunk = createResolvedModelChunk(response, backingEntry);
2894
+ } else {
2895
+ // We're still waiting on this entry to stream in.
2896
+ chunk = createPendingChunk(response);
2897
+ }
2898
+
2899
+ chunks.set(id, chunk);
2900
+ }
2901
+
2902
+ return chunk;
2903
+ }
2904
+
2905
+ function createModelResolver(chunk, parentObject, key) {
2906
+ let blocked;
2907
+
2908
+ if (initializingChunkBlockedModel) {
2909
+ blocked = initializingChunkBlockedModel;
2910
+ blocked.deps++;
2911
+ } else {
2912
+ blocked = initializingChunkBlockedModel = {
2913
+ deps: 1,
2914
+ value: null
2915
+ };
2916
+ }
2917
+
2918
+ return value => {
2919
+ parentObject[key] = value;
2920
+ blocked.deps--;
2921
+
2922
+ if (blocked.deps === 0) {
2923
+ if (chunk.status !== BLOCKED) {
2924
+ return;
2925
+ }
2926
+
2927
+ const resolveListeners = chunk.value;
2928
+ const initializedChunk = chunk;
2929
+ initializedChunk.status = INITIALIZED;
2930
+ initializedChunk.value = blocked.value;
2931
+
2932
+ if (resolveListeners !== null) {
2933
+ wakeChunk(resolveListeners, blocked.value);
2934
+ }
2935
+ }
2936
+ };
2937
+ }
2938
+
2939
+ function createModelReject(chunk) {
2940
+ return error => triggerErrorOnChunk(chunk, error);
2941
+ }
2942
+
2943
+ function getOutlinedModel(response, id) {
2944
+ const chunk = getChunk(response, id);
2945
+
2946
+ if (chunk.status === RESOLVED_MODEL) {
2947
+ initializeModelChunk(chunk);
2948
+ }
2949
+
2950
+ if (chunk.status !== INITIALIZED) {
2951
+ // We know that this is emitted earlier so otherwise it's an error.
2952
+ throw chunk.reason;
2953
+ }
2954
+
2955
+ return chunk.value;
2956
+ }
2957
+
2958
+ function parseModelString(response, parentObject, key, value) {
2959
+ if (value[0] === '$') {
2960
+ switch (value[1]) {
2961
+ case '$':
2962
+ {
2963
+ // This was an escaped string value.
2964
+ return value.slice(1);
2965
+ }
2966
+
2967
+ case '@':
2968
+ {
2969
+ // Promise
2970
+ const id = parseInt(value.slice(2), 16);
2971
+ const chunk = getChunk(response, id);
2972
+ return chunk;
2973
+ }
2974
+
2975
+ case 'F':
2976
+ {
2977
+ // Server Reference
2978
+ const id = parseInt(value.slice(2), 16); // TODO: Just encode this in the reference inline instead of as a model.
2979
+
2980
+ const metaData = getOutlinedModel(response, id);
2981
+ return loadServerReference$1(response, metaData.id, metaData.bound, initializingChunk, parentObject, key);
2982
+ }
2983
+
2984
+ case 'T':
2985
+ {
2986
+ // Temporary Reference
2987
+ return createTemporaryReference(value.slice(2));
2988
+ }
2989
+
2990
+ case 'Q':
2991
+ {
2992
+ // Map
2993
+ const id = parseInt(value.slice(2), 16);
2994
+ const data = getOutlinedModel(response, id);
2995
+ return new Map(data);
2996
+ }
2997
+
2998
+ case 'W':
2999
+ {
3000
+ // Set
3001
+ const id = parseInt(value.slice(2), 16);
3002
+ const data = getOutlinedModel(response, id);
3003
+ return new Set(data);
3004
+ }
3005
+
3006
+ case 'K':
3007
+ {
3008
+ // FormData
3009
+ const stringId = value.slice(2);
3010
+ const formPrefix = response._prefix + stringId + '_';
3011
+ const data = new FormData();
3012
+ const backingFormData = response._formData; // We assume that the reference to FormData always comes after each
3013
+ // entry that it references so we can assume they all exist in the
3014
+ // backing store already.
3015
+ // $FlowFixMe[prop-missing] FormData has forEach on it.
3016
+
3017
+ backingFormData.forEach((entry, entryKey) => {
3018
+ if (entryKey.startsWith(formPrefix)) {
3019
+ data.append(entryKey.slice(formPrefix.length), entry);
3020
+ }
3021
+ });
3022
+ return data;
3023
+ }
3024
+
3025
+ case 'I':
3026
+ {
3027
+ // $Infinity
3028
+ return Infinity;
3029
+ }
3030
+
3031
+ case '-':
3032
+ {
3033
+ // $-0 or $-Infinity
3034
+ if (value === '$-0') {
3035
+ return -0;
3036
+ } else {
3037
+ return -Infinity;
3038
+ }
3039
+ }
3040
+
3041
+ case 'N':
3042
+ {
3043
+ // $NaN
3044
+ return NaN;
3045
+ }
3046
+
3047
+ case 'u':
3048
+ {
3049
+ // matches "$undefined"
3050
+ // Special encoding for `undefined` which can't be serialized as JSON otherwise.
3051
+ return undefined;
3052
+ }
3053
+
3054
+ case 'D':
3055
+ {
3056
+ // Date
3057
+ return new Date(Date.parse(value.slice(2)));
3058
+ }
3059
+
3060
+ case 'n':
3061
+ {
3062
+ // BigInt
3063
+ return BigInt(value.slice(2));
3064
+ }
3065
+
3066
+ default:
3067
+ {
3068
+ // We assume that anything else is a reference ID.
3069
+ const id = parseInt(value.slice(1), 16);
3070
+ const chunk = getChunk(response, id);
3071
+
3072
+ switch (chunk.status) {
3073
+ case RESOLVED_MODEL:
3074
+ initializeModelChunk(chunk);
3075
+ break;
3076
+ } // The status might have changed after initialization.
3077
+
3078
+
3079
+ switch (chunk.status) {
3080
+ case INITIALIZED:
3081
+ return chunk.value;
3082
+
3083
+ case PENDING:
3084
+ case BLOCKED:
3085
+ const parentChunk = initializingChunk;
3086
+ chunk.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk));
3087
+ return null;
3088
+
3089
+ default:
3090
+ throw chunk.reason;
3091
+ }
3092
+ }
3093
+ }
3094
+ }
3095
+
3096
+ return value;
3097
+ }
3098
+
3099
+ function createResponse(bundlerConfig, formFieldPrefix) {
3100
+ let backingFormData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData();
3101
+ const chunks = new Map();
3102
+ const response = {
3103
+ _bundlerConfig: bundlerConfig,
3104
+ _prefix: formFieldPrefix,
3105
+ _formData: backingFormData,
3106
+ _chunks: chunks,
3107
+ _fromJSON: function (key, value) {
3108
+ if (typeof value === 'string') {
3109
+ // We can't use .bind here because we need the "this" value.
3110
+ return parseModelString(response, this, key, value);
3111
+ }
3112
+
3113
+ return value;
3114
+ }
3115
+ };
3116
+ return response;
3117
+ }
3118
+ function resolveField(response, key, value) {
3119
+ // Add this field to the backing store.
3120
+ response._formData.append(key, value);
3121
+
3122
+ const prefix = response._prefix;
3123
+
3124
+ if (key.startsWith(prefix)) {
3125
+ const chunks = response._chunks;
3126
+ const id = +key.slice(prefix.length);
3127
+ const chunk = chunks.get(id);
3128
+
3129
+ if (chunk) {
3130
+ // We were waiting on this key so now we can resolve it.
3131
+ resolveModelChunk(chunk, value);
3132
+ }
3133
+ }
3134
+ }
3135
+ function resolveFileInfo(response, key, filename, mime) {
3136
+ return {
3137
+ chunks: [],
3138
+ filename,
3139
+ mime
3140
+ };
3141
+ }
3142
+ function resolveFileChunk(response, handle, chunk) {
3143
+ handle.chunks.push(chunk);
3144
+ }
3145
+ function resolveFileComplete(response, key, handle) {
3146
+ // Add this file to the backing store.
3147
+ // Node.js doesn't expose a global File constructor so we need to use
3148
+ // the append() form that takes the file name as the third argument,
3149
+ // to create a File object.
3150
+ const blob = new Blob(handle.chunks, {
3151
+ type: handle.mime
3152
+ });
3153
+
3154
+ response._formData.append(key, blob, handle.filename);
3155
+ }
3156
+ function close(response) {
3157
+ // In case there are any remaining unresolved chunks, they won't
3158
+ // be resolved now. So we need to issue an error to those.
3159
+ // Ideally we should be able to early bail out if we kept a
3160
+ // ref count of pending chunks.
3161
+ reportGlobalError(response, new Error('Connection closed.'));
3162
+ }
3163
+
3164
+ function bindArgs(fn, args) {
3165
+ return fn.bind.apply(fn, [null].concat(args));
3166
+ }
3167
+
3168
+ function loadServerReference(bundlerConfig, id, bound) {
3169
+ const serverReference = resolveServerReference(bundlerConfig, id); // We expect most servers to not really need this because you'd just have all
3170
+ // the relevant modules already loaded but it allows for lazy loading of code
3171
+ // if needed.
3172
+
3173
+ const preloadPromise = preloadModule(serverReference);
3174
+
3175
+ if (bound) {
3176
+ return Promise.all([bound, preloadPromise]).then((_ref) => {
3177
+ let args = _ref[0];
3178
+ return bindArgs(requireModule(serverReference), args);
3179
+ });
3180
+ } else if (preloadPromise) {
3181
+ return Promise.resolve(preloadPromise).then(() => requireModule(serverReference));
3182
+ } else {
3183
+ // Synchronously available
3184
+ return Promise.resolve(requireModule(serverReference));
3185
+ }
3186
+ }
3187
+
3188
+ function decodeBoundActionMetaData(body, serverManifest, formFieldPrefix) {
3189
+ // The data for this reference is encoded in multiple fields under this prefix.
3190
+ const actionResponse = createResponse(serverManifest, formFieldPrefix, body);
3191
+ close(actionResponse);
3192
+ const refPromise = getRoot(actionResponse); // Force it to initialize
3193
+ // $FlowFixMe
3194
+
3195
+ refPromise.then(() => {});
3196
+
3197
+ if (refPromise.status !== 'fulfilled') {
3198
+ // $FlowFixMe
3199
+ throw refPromise.reason;
3200
+ }
3201
+
3202
+ return refPromise.value;
3203
+ }
3204
+
3205
+ function decodeAction(body, serverManifest) {
3206
+ // We're going to create a new formData object that holds all the fields except
3207
+ // the implementation details of the action data.
3208
+ const formData = new FormData();
3209
+ let action = null; // $FlowFixMe[prop-missing]
3210
+
3211
+ body.forEach((value, key) => {
3212
+ if (!key.startsWith('$ACTION_')) {
3213
+ formData.append(key, value);
3214
+ return;
3215
+ } // Later actions may override earlier actions if a button is used to override the default
3216
+ // form action.
3217
+
3218
+
3219
+ if (key.startsWith('$ACTION_REF_')) {
3220
+ const formFieldPrefix = '$ACTION_' + key.slice(12) + ':';
3221
+ const metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix);
3222
+ action = loadServerReference(serverManifest, metaData.id, metaData.bound);
3223
+ return;
3224
+ }
3225
+
3226
+ if (key.startsWith('$ACTION_ID_')) {
3227
+ const id = key.slice(11);
3228
+ action = loadServerReference(serverManifest, id, null);
3229
+ return;
3230
+ }
3231
+ });
3232
+
3233
+ if (action === null) {
3234
+ return null;
3235
+ } // Return the action with the remaining FormData bound to the first argument.
3236
+
3237
+
3238
+ return action.then(fn => fn.bind(null, formData));
3239
+ }
3240
+ function decodeFormState(actionResult, body, serverManifest) {
3241
+ const keyPath = body.get('$ACTION_KEY');
3242
+
3243
+ if (typeof keyPath !== 'string') {
3244
+ // This form submission did not include any form state.
3245
+ return Promise.resolve(null);
3246
+ } // Search through the form data object to get the reference id and the number
3247
+ // of bound arguments. This repeats some of the work done in decodeAction.
3248
+
3249
+
3250
+ let metaData = null; // $FlowFixMe[prop-missing]
3251
+
3252
+ body.forEach((value, key) => {
3253
+ if (key.startsWith('$ACTION_REF_')) {
3254
+ const formFieldPrefix = '$ACTION_' + key.slice(12) + ':';
3255
+ metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix);
3256
+ } // We don't check for the simple $ACTION_ID_ case because form state actions
3257
+ // are always bound to the state argument.
3258
+
3259
+ });
3260
+
3261
+ if (metaData === null) {
3262
+ // Should be unreachable.
3263
+ return Promise.resolve(null);
3264
+ }
3265
+
3266
+ const referenceId = metaData.id;
3267
+ return Promise.resolve(metaData.bound).then(bound => {
3268
+ if (bound === null) {
3269
+ // Should be unreachable because form state actions are always bound to the
3270
+ // state argument.
3271
+ return null;
3272
+ } // The form action dispatch method is always bound to the initial state.
3273
+ // But when comparing signatures, we compare to the original unbound action.
3274
+ // Subtract one from the arity to account for this.
3275
+
3276
+
3277
+ const boundArity = bound.length - 1;
3278
+ return [actionResult, keyPath, referenceId, boundArity];
3279
+ });
3280
+ }
3281
+
3282
+ function createDrainHandler(destination, request) {
3283
+ return () => startFlowing(request, destination);
3284
+ }
3285
+
3286
+ function createCancelHandler(request, reason) {
3287
+ return () => {
3288
+ stopFlowing(request); // eslint-disable-next-line react-internal/prod-error-codes
3289
+
3290
+ abort(request, new Error(reason));
3291
+ };
3292
+ }
3293
+
3294
+ function renderToPipeableStream(model, webpackMap, options) {
3295
+ const request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined);
3296
+ let hasStartedFlowing = false;
3297
+ startWork(request);
3298
+ return {
3299
+ pipe(destination) {
3300
+ if (hasStartedFlowing) {
3301
+ throw new Error('React currently only supports piping to one writable stream.');
3302
+ }
3303
+
3304
+ hasStartedFlowing = true;
3305
+ startFlowing(request, destination);
3306
+ destination.on('drain', createDrainHandler(destination, request));
3307
+ destination.on('error', createCancelHandler(request, 'The destination stream errored while writing data.'));
3308
+ destination.on('close', createCancelHandler(request, 'The destination stream closed early.'));
3309
+ return destination;
3310
+ },
3311
+
3312
+ abort(reason) {
3313
+ abort(request, reason);
3314
+ }
3315
+
3316
+ };
3317
+ }
3318
+
3319
+ function decodeReplyFromBusboy(busboyStream, webpackMap) {
3320
+ const response = createResponse(webpackMap, '');
3321
+ let pendingFiles = 0;
3322
+ const queuedFields = [];
3323
+ busboyStream.on('field', (name, value) => {
3324
+ if (pendingFiles > 0) {
3325
+ // Because the 'end' event fires two microtasks after the next 'field'
3326
+ // we would resolve files and fields out of order. To handle this properly
3327
+ // we queue any fields we receive until the previous file is done.
3328
+ queuedFields.push(name, value);
3329
+ } else {
3330
+ resolveField(response, name, value);
3331
+ }
3332
+ });
3333
+ busboyStream.on('file', (name, value, _ref) => {
3334
+ let filename = _ref.filename,
3335
+ encoding = _ref.encoding,
3336
+ mimeType = _ref.mimeType;
3337
+
3338
+ if (encoding.toLowerCase() === 'base64') {
3339
+ throw new Error("React doesn't accept base64 encoded file uploads because we don't expect " + "form data passed from a browser to ever encode data that way. If that's " + 'the wrong assumption, we can easily fix it.');
3340
+ }
3341
+
3342
+ pendingFiles++;
3343
+ const file = resolveFileInfo(response, name, filename, mimeType);
3344
+ value.on('data', chunk => {
3345
+ resolveFileChunk(response, file, chunk);
3346
+ });
3347
+ value.on('end', () => {
3348
+ resolveFileComplete(response, name, file);
3349
+ pendingFiles--;
3350
+
3351
+ if (pendingFiles === 0) {
3352
+ // Release any queued fields
3353
+ for (let i = 0; i < queuedFields.length; i += 2) {
3354
+ resolveField(response, queuedFields[i], queuedFields[i + 1]);
3355
+ }
3356
+
3357
+ queuedFields.length = 0;
3358
+ }
3359
+ });
3360
+ });
3361
+ busboyStream.on('finish', () => {
3362
+ close(response);
3363
+ });
3364
+ busboyStream.on('error', err => {
3365
+ reportGlobalError(response, // $FlowFixMe[incompatible-call] types Error and mixed are incompatible
3366
+ err);
3367
+ });
3368
+ return getRoot(response);
3369
+ }
3370
+
3371
+ function decodeReply(body, webpackMap) {
3372
+ if (typeof body === 'string') {
3373
+ const form = new FormData();
3374
+ form.append('0', body);
3375
+ body = form;
3376
+ }
3377
+
3378
+ const response = createResponse(webpackMap, '', body);
3379
+ const root = getRoot(response);
3380
+ close(response);
3381
+ return root;
3382
+ }
3383
+
3384
+ exports.createClientModuleProxy = createClientModuleProxy;
3385
+ exports.decodeAction = decodeAction;
3386
+ exports.decodeFormState = decodeFormState;
3387
+ exports.decodeReply = decodeReply;
3388
+ exports.decodeReplyFromBusboy = decodeReplyFromBusboy;
3389
+ exports.registerClientReference = registerClientReference;
3390
+ exports.registerServerReference = registerServerReference;
3391
+ exports.renderToPipeableStream = renderToPipeableStream;