UNPKG

416 kBJavaScriptView Raw
1/**
2 * @license React
3 * react-dom-server.browser.development.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
13if (process.env.NODE_ENV !== "production") {
14 (function() {
15'use strict';
16
17var React = require('react');
18var ReactDOM = require('react-dom');
19
20var ReactVersion = '19.0.0-beta-4508873393-20240430';
21
22var ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
23
24// by calls to these methods by a Babel plugin.
25//
26// In PROD (or in packages without access to React internals),
27// they are left as they are instead.
28
29function warn(format) {
30 {
31 {
32 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
33 args[_key - 1] = arguments[_key];
34 }
35
36 printWarning('warn', format, args);
37 }
38 }
39}
40function error(format) {
41 {
42 {
43 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
44 args[_key2 - 1] = arguments[_key2];
45 }
46
47 printWarning('error', format, args);
48 }
49 }
50}
51
52function printWarning(level, format, args) {
53 // When changing this logic, you might want to also
54 // update consoleWithStackDev.www.js as well.
55 {
56 var stack = ReactSharedInternals.getStackAddendum();
57
58 if (stack !== '') {
59 format += '%s';
60 args = args.concat([stack]);
61 } // eslint-disable-next-line react-internal/safe-string-coercion
62
63
64 var argsWithFormat = args.map(function (item) {
65 return String(item);
66 }); // Careful: RN currently depends on this prefix
67
68 argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
69 // breaks IE9: https://github.com/facebook/react/issues/13610
70 // eslint-disable-next-line react-internal/no-production-logging
71
72 Function.prototype.apply.call(console[level], console, argsWithFormat);
73 }
74}
75
76// -----------------------------------------------------------------------------
77
78var disableDefaultPropsExceptForClasses = true; // -----------------------------------------------------------------------------
79// Enables DOM-server to stream its instruction set as data-attributes
80// (handled with an MutationObserver) instead of inline-scripts
81
82var enableFizzExternalRuntime = false;
83
84var REACT_ELEMENT_TYPE = Symbol.for('react.transitional.element') ;
85var REACT_PORTAL_TYPE = Symbol.for('react.portal');
86var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
87var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
88var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
89var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); // TODO: Delete with enableRenderableContext
90
91var REACT_CONSUMER_TYPE = Symbol.for('react.consumer');
92var REACT_CONTEXT_TYPE = Symbol.for('react.context');
93var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
94var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
95var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
96var REACT_MEMO_TYPE = Symbol.for('react.memo');
97var REACT_LAZY_TYPE = Symbol.for('react.lazy');
98var REACT_SCOPE_TYPE = Symbol.for('react.scope');
99var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
100var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
101var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
102var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
103var FAUX_ITERATOR_SYMBOL = '@@iterator';
104function getIteratorFn(maybeIterable) {
105 if (maybeIterable === null || typeof maybeIterable !== 'object') {
106 return null;
107 }
108
109 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
110
111 if (typeof maybeIterator === 'function') {
112 return maybeIterator;
113 }
114
115 return null;
116}
117
118var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
119
120function isArray(a) {
121 return isArrayImpl(a);
122}
123
124// in case they error.
125
126var jsxPropsParents = new WeakMap();
127var jsxChildrenParents = new WeakMap();
128function objectName(object) {
129 // $FlowFixMe[method-unbinding]
130 var name = Object.prototype.toString.call(object);
131 return name.replace(/^\[object (.*)\]$/, function (m, p0) {
132 return p0;
133 });
134}
135
136function describeKeyForErrorMessage(key) {
137 var encodedKey = JSON.stringify(key);
138 return '"' + key + '"' === encodedKey ? key : encodedKey;
139}
140
141function describeValueForErrorMessage(value) {
142 switch (typeof value) {
143 case 'string':
144 {
145 return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...');
146 }
147
148 case 'object':
149 {
150 if (isArray(value)) {
151 return '[...]';
152 }
153
154 if (value !== null && value.$$typeof === CLIENT_REFERENCE_TAG) {
155 return describeClientReference();
156 }
157
158 var name = objectName(value);
159
160 if (name === 'Object') {
161 return '{...}';
162 }
163
164 return name;
165 }
166
167 case 'function':
168 {
169 if (value.$$typeof === CLIENT_REFERENCE_TAG) {
170 return describeClientReference();
171 }
172
173 var _name = value.displayName || value.name;
174
175 return _name ? 'function ' + _name : 'function';
176 }
177
178 default:
179 // eslint-disable-next-line react-internal/safe-string-coercion
180 return String(value);
181 }
182}
183
184function describeElementType(type) {
185 if (typeof type === 'string') {
186 return type;
187 }
188
189 switch (type) {
190 case REACT_SUSPENSE_TYPE:
191 return 'Suspense';
192
193 case REACT_SUSPENSE_LIST_TYPE:
194 return 'SuspenseList';
195 }
196
197 if (typeof type === 'object') {
198 switch (type.$$typeof) {
199 case REACT_FORWARD_REF_TYPE:
200 return describeElementType(type.render);
201
202 case REACT_MEMO_TYPE:
203 return describeElementType(type.type);
204
205 case REACT_LAZY_TYPE:
206 {
207 var lazyComponent = type;
208 var payload = lazyComponent._payload;
209 var init = lazyComponent._init;
210
211 try {
212 // Lazy may contain any component type so we recursively resolve it.
213 return describeElementType(init(payload));
214 } catch (x) {}
215 }
216 }
217 }
218
219 return '';
220}
221
222var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
223
224function describeClientReference(ref) {
225 return 'client';
226}
227
228function describeObjectForErrorMessage(objectOrArray, expandedName) {
229 var objKind = objectName(objectOrArray);
230
231 if (objKind !== 'Object' && objKind !== 'Array') {
232 return objKind;
233 }
234
235 var str = '';
236 var start = -1;
237 var length = 0;
238
239 if (isArray(objectOrArray)) {
240 if (jsxChildrenParents.has(objectOrArray)) {
241 // Print JSX Children
242 var type = jsxChildrenParents.get(objectOrArray);
243 str = '<' + describeElementType(type) + '>';
244 var array = objectOrArray;
245
246 for (var i = 0; i < array.length; i++) {
247 var value = array[i];
248 var substr = void 0;
249
250 if (typeof value === 'string') {
251 substr = value;
252 } else if (typeof value === 'object' && value !== null) {
253 substr = '{' + describeObjectForErrorMessage(value) + '}';
254 } else {
255 substr = '{' + describeValueForErrorMessage(value) + '}';
256 }
257
258 if ('' + i === expandedName) {
259 start = str.length;
260 length = substr.length;
261 str += substr;
262 } else if (substr.length < 15 && str.length + substr.length < 40) {
263 str += substr;
264 } else {
265 str += '{...}';
266 }
267 }
268
269 str += '</' + describeElementType(type) + '>';
270 } else {
271 // Print Array
272 str = '[';
273 var _array = objectOrArray;
274
275 for (var _i = 0; _i < _array.length; _i++) {
276 if (_i > 0) {
277 str += ', ';
278 }
279
280 var _value = _array[_i];
281
282 var _substr = void 0;
283
284 if (typeof _value === 'object' && _value !== null) {
285 _substr = describeObjectForErrorMessage(_value);
286 } else {
287 _substr = describeValueForErrorMessage(_value);
288 }
289
290 if ('' + _i === expandedName) {
291 start = str.length;
292 length = _substr.length;
293 str += _substr;
294 } else if (_substr.length < 10 && str.length + _substr.length < 40) {
295 str += _substr;
296 } else {
297 str += '...';
298 }
299 }
300
301 str += ']';
302 }
303 } else {
304 if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) {
305 str = '<' + describeElementType(objectOrArray.type) + '/>';
306 } else if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) {
307 return describeClientReference();
308 } else if (jsxPropsParents.has(objectOrArray)) {
309 // Print JSX
310 var _type = jsxPropsParents.get(objectOrArray);
311
312 str = '<' + (describeElementType(_type) || '...');
313 var object = objectOrArray;
314 var names = Object.keys(object);
315
316 for (var _i2 = 0; _i2 < names.length; _i2++) {
317 str += ' ';
318 var name = names[_i2];
319 str += describeKeyForErrorMessage(name) + '=';
320 var _value2 = object[name];
321
322 var _substr2 = void 0;
323
324 if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) {
325 _substr2 = describeObjectForErrorMessage(_value2);
326 } else {
327 _substr2 = describeValueForErrorMessage(_value2);
328 }
329
330 if (typeof _value2 !== 'string') {
331 _substr2 = '{' + _substr2 + '}';
332 }
333
334 if (name === expandedName) {
335 start = str.length;
336 length = _substr2.length;
337 str += _substr2;
338 } else if (_substr2.length < 10 && str.length + _substr2.length < 40) {
339 str += _substr2;
340 } else {
341 str += '...';
342 }
343 }
344
345 str += '>';
346 } else {
347 // Print Object
348 str = '{';
349 var _object = objectOrArray;
350
351 var _names = Object.keys(_object);
352
353 for (var _i3 = 0; _i3 < _names.length; _i3++) {
354 if (_i3 > 0) {
355 str += ', ';
356 }
357
358 var _name2 = _names[_i3];
359 str += describeKeyForErrorMessage(_name2) + ': ';
360 var _value3 = _object[_name2];
361
362 var _substr3 = void 0;
363
364 if (typeof _value3 === 'object' && _value3 !== null) {
365 _substr3 = describeObjectForErrorMessage(_value3);
366 } else {
367 _substr3 = describeValueForErrorMessage(_value3);
368 }
369
370 if (_name2 === expandedName) {
371 start = str.length;
372 length = _substr3.length;
373 str += _substr3;
374 } else if (_substr3.length < 10 && str.length + _substr3.length < 40) {
375 str += _substr3;
376 } else {
377 str += '...';
378 }
379 }
380
381 str += '}';
382 }
383 }
384
385 if (expandedName === undefined) {
386 return str;
387 }
388
389 if (start > -1 && length > 0) {
390 var highlight = ' '.repeat(start) + '^'.repeat(length);
391 return '\n ' + str + '\n ' + highlight;
392 }
393
394 return '\n ' + str;
395}
396
397// A pure JS implementation of a string hashing function. We do not use it for
398// security or obfuscation purposes, only to create compact hashes. So we
399// prioritize speed over collision avoidance. For example, we use this to hash
400// the component key path used by useActionState for MPA-style submissions.
401//
402// In environments where built-in hashing functions are available, we prefer
403// those instead. Like Node's crypto module, or Bun.hash. Unfortunately this
404// does not include the web standard crypto API because those methods are all
405// async. For our purposes, we need it to be sync because the cost of context
406// switching is too high to be worth it.
407//
408// The most popular hashing algorithm that meets these requirements in the JS
409// ecosystem is MurmurHash3, and almost all implementations I could find used
410// some version of the implementation by Gary Court inlined below.
411function createFastHashJS(key) {
412 return murmurhash3_32_gc(key, 0);
413}
414/* eslint-disable prefer-const, no-fallthrough */
415
416/**
417 * @license
418 *
419 * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
420 *
421 * Copyright (c) 2011 Gary Court
422 * Permission is hereby granted, free of charge, to any person obtaining a copy
423 * of this software and associated documentation files (the "Software"), to deal
424 * in the Software without restriction, including without limitation the rights
425 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
426 * copies of the Software, and to permit persons to whom the Software is
427 * furnished to do so, subject to the following conditions:
428 *
429 * The above copyright notice and this permission notice shall be included in
430 * all copies or substantial portions of the Software.
431 *
432 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
433 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
434 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
435 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
436 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
437 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
438 * SOFTWARE.
439 */
440
441function murmurhash3_32_gc(key, seed) {
442 var remainder, bytes, h1, h1b, c1, c2, k1, i;
443 remainder = key.length & 3; // key.length % 4
444
445 bytes = key.length - remainder;
446 h1 = seed;
447 c1 = 0xcc9e2d51;
448 c2 = 0x1b873593;
449 i = 0;
450
451 while (i < bytes) {
452 k1 = key.charCodeAt(i) & 0xff | (key.charCodeAt(++i) & 0xff) << 8 | (key.charCodeAt(++i) & 0xff) << 16 | (key.charCodeAt(++i) & 0xff) << 24;
453 ++i;
454 k1 = (k1 & 0xffff) * c1 + (((k1 >>> 16) * c1 & 0xffff) << 16) & 0xffffffff;
455 k1 = k1 << 15 | k1 >>> 17;
456 k1 = (k1 & 0xffff) * c2 + (((k1 >>> 16) * c2 & 0xffff) << 16) & 0xffffffff;
457 h1 ^= k1;
458 h1 = h1 << 13 | h1 >>> 19;
459 h1b = (h1 & 0xffff) * 5 + (((h1 >>> 16) * 5 & 0xffff) << 16) & 0xffffffff;
460 h1 = (h1b & 0xffff) + 0x6b64 + (((h1b >>> 16) + 0xe654 & 0xffff) << 16);
461 }
462
463 k1 = 0;
464
465 switch (remainder) {
466 case 3:
467 k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
468
469 case 2:
470 k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
471
472 case 1:
473 k1 ^= key.charCodeAt(i) & 0xff;
474 k1 = (k1 & 0xffff) * c1 + (((k1 >>> 16) * c1 & 0xffff) << 16) & 0xffffffff;
475 k1 = k1 << 15 | k1 >>> 17;
476 k1 = (k1 & 0xffff) * c2 + (((k1 >>> 16) * c2 & 0xffff) << 16) & 0xffffffff;
477 h1 ^= k1;
478 }
479
480 h1 ^= key.length;
481 h1 ^= h1 >>> 16;
482 h1 = (h1 & 0xffff) * 0x85ebca6b + (((h1 >>> 16) * 0x85ebca6b & 0xffff) << 16) & 0xffffffff;
483 h1 ^= h1 >>> 13;
484 h1 = (h1 & 0xffff) * 0xc2b2ae35 + (((h1 >>> 16) * 0xc2b2ae35 & 0xffff) << 16) & 0xffffffff;
485 h1 ^= h1 >>> 16;
486 return h1 >>> 0;
487}
488
489function scheduleWork(callback) {
490 callback();
491}
492var VIEW_SIZE = 2048;
493var currentView = null;
494var writtenBytes = 0;
495function beginWriting(destination) {
496 currentView = new Uint8Array(VIEW_SIZE);
497 writtenBytes = 0;
498}
499function writeChunk(destination, chunk) {
500 if (chunk.byteLength === 0) {
501 return;
502 }
503
504 if (chunk.byteLength > VIEW_SIZE) {
505 // this chunk may overflow a single view which implies it was not
506 // one that is cached by the streaming renderer. We will enqueu
507 // it directly and expect it is not re-used
508 if (writtenBytes > 0) {
509 destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
510 currentView = new Uint8Array(VIEW_SIZE);
511 writtenBytes = 0;
512 }
513
514 destination.enqueue(chunk);
515 return;
516 }
517
518 var bytesToWrite = chunk;
519 var allowableBytes = currentView.length - writtenBytes;
520
521 if (allowableBytes < bytesToWrite.byteLength) {
522 // this chunk would overflow the current view. We enqueue a full view
523 // and start a new view with the remaining chunk
524 if (allowableBytes === 0) {
525 // the current view is already full, send it
526 destination.enqueue(currentView);
527 } else {
528 // fill up the current view and apply the remaining chunk bytes
529 // to a new view.
530 currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view
531
532 destination.enqueue(currentView);
533 bytesToWrite = bytesToWrite.subarray(allowableBytes);
534 }
535
536 currentView = new Uint8Array(VIEW_SIZE);
537 writtenBytes = 0;
538 }
539
540 currentView.set(bytesToWrite, writtenBytes);
541 writtenBytes += bytesToWrite.byteLength;
542}
543function writeChunkAndReturn(destination, chunk) {
544 writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more
545
546 return true;
547}
548function completeWriting(destination) {
549 if (currentView && writtenBytes > 0) {
550 destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
551 currentView = null;
552 writtenBytes = 0;
553 }
554}
555function close(destination) {
556 destination.close();
557}
558var textEncoder = new TextEncoder();
559function stringToChunk(content) {
560 return textEncoder.encode(content);
561}
562function stringToPrecomputedChunk(content) {
563 var precomputedChunk = textEncoder.encode(content);
564
565 {
566 if (precomputedChunk.byteLength > VIEW_SIZE) {
567 error('precomputed chunks must be smaller than the view size configured for this host. This is a bug in React.');
568 }
569 }
570
571 return precomputedChunk;
572}
573function closeWithError(destination, error) {
574 // $FlowFixMe[method-unbinding]
575 if (typeof destination.error === 'function') {
576 // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types.
577 destination.error(error);
578 } else {
579 // Earlier implementations doesn't support this method. In that environment you're
580 // supposed to throw from a promise returned but we don't return a promise in our
581 // approach. We could fork this implementation but this is environment is an edge
582 // case to begin with. It's even less common to run this in an older environment.
583 // Even then, this is not where errors are supposed to happen and they get reported
584 // to a global callback in addition to this anyway. So it's fine just to close this.
585 destination.close();
586 }
587}
588
589var assign = Object.assign;
590
591/*
592 * The `'' + value` pattern (used in perf-sensitive code) throws for Symbol
593 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
594 *
595 * The functions in this module will throw an easier-to-understand,
596 * easier-to-debug exception with a clear errors message message explaining the
597 * problem. (Instead of a confusing exception thrown inside the implementation
598 * of the `value` object).
599 */
600// $FlowFixMe[incompatible-return] only called in DEV, so void return is not possible.
601function typeName(value) {
602 {
603 // toStringTag is needed for namespaced types like Temporal.Instant
604 var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
605 var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; // $FlowFixMe[incompatible-return]
606
607 return type;
608 }
609} // $FlowFixMe[incompatible-return] only called in DEV, so void return is not possible.
610
611
612function willCoercionThrow(value) {
613 {
614 try {
615 testStringCoercion(value);
616 return false;
617 } catch (e) {
618 return true;
619 }
620 }
621}
622
623function testStringCoercion(value) {
624 // If you ended up here by following an exception call stack, here's what's
625 // happened: you supplied an object or symbol value to React (as a prop, key,
626 // DOM attribute, CSS property, string ref, etc.) and when React tried to
627 // coerce it to a string using `'' + value`, an exception was thrown.
628 //
629 // The most common types that will cause this exception are `Symbol` instances
630 // and Temporal objects like `Temporal.Instant`. But any object that has a
631 // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
632 // exception. (Library authors do this to prevent users from using built-in
633 // numeric operators like `+` or comparison operators like `>=` because custom
634 // methods are needed to perform accurate arithmetic or comparison.)
635 //
636 // To fix the problem, coerce this object or symbol value to a string before
637 // passing it to React. The most reliable way is usually `String(value)`.
638 //
639 // To find which value is throwing, check the browser or debugger console.
640 // Before this exception was thrown, there should be `console.error` output
641 // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
642 // problem and how that type was used: key, atrribute, input value prop, etc.
643 // In most cases, this console output also shows the component and its
644 // ancestor components where the exception happened.
645 //
646 // eslint-disable-next-line react-internal/safe-string-coercion
647 return '' + value;
648}
649
650function checkAttributeStringCoercion(value, attributeName) {
651 {
652 if (willCoercionThrow(value)) {
653 error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before using it here.', attributeName, typeName(value));
654
655 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
656 }
657 }
658}
659function checkOptionStringCoercion(value, propName) {
660 {
661 if (willCoercionThrow(value)) {
662 error('The provided `%s` option is an unsupported type %s.' + ' This value must be coerced to a string before using it here.', propName, typeName(value));
663
664 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
665 }
666 }
667}
668function checkCSSPropertyStringCoercion(value, propName) {
669 {
670 if (willCoercionThrow(value)) {
671 error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before using it here.', propName, typeName(value));
672
673 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
674 }
675 }
676}
677function checkHtmlStringCoercion(value) {
678 {
679 if (willCoercionThrow(value)) {
680 error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before using it here.', typeName(value));
681
682 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
683 }
684 }
685}
686
687// $FlowFixMe[method-unbinding]
688var hasOwnProperty = Object.prototype.hasOwnProperty;
689
690/* eslint-disable max-len */
691
692var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
693/* eslint-enable max-len */
694
695var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
696var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
697var illegalAttributeNameCache = {};
698var validatedAttributeNameCache = {};
699function isAttributeNameSafe(attributeName) {
700 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
701 return true;
702 }
703
704 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
705 return false;
706 }
707
708 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
709 validatedAttributeNameCache[attributeName] = true;
710 return true;
711 }
712
713 illegalAttributeNameCache[attributeName] = true;
714
715 {
716 error('Invalid attribute name: `%s`', attributeName);
717 }
718
719 return false;
720}
721
722/**
723 * CSS properties which accept numbers but are not in units of "px".
724 */
725var unitlessNumbers = new Set(['animationIterationCount', 'aspectRatio', 'borderImageOutset', 'borderImageSlice', 'borderImageWidth', 'boxFlex', 'boxFlexGroup', 'boxOrdinalGroup', 'columnCount', 'columns', 'flex', 'flexGrow', 'flexPositive', 'flexShrink', 'flexNegative', 'flexOrder', 'gridArea', 'gridRow', 'gridRowEnd', 'gridRowSpan', 'gridRowStart', 'gridColumn', 'gridColumnEnd', 'gridColumnSpan', 'gridColumnStart', 'fontWeight', 'lineClamp', 'lineHeight', 'opacity', 'order', 'orphans', 'scale', 'tabSize', 'widows', 'zIndex', 'zoom', 'fillOpacity', // SVG-related properties
726'floodOpacity', 'stopOpacity', 'strokeDasharray', 'strokeDashoffset', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'MozAnimationIterationCount', // Known Prefixed Properties
727'MozBoxFlex', // TODO: Remove these since they shouldn't be used in modern code
728'MozBoxFlexGroup', 'MozLineClamp', 'msAnimationIterationCount', 'msFlex', 'msZoom', 'msFlexGrow', 'msFlexNegative', 'msFlexOrder', 'msFlexPositive', 'msFlexShrink', 'msGridColumn', 'msGridColumnSpan', 'msGridRow', 'msGridRowSpan', 'WebkitAnimationIterationCount', 'WebkitBoxFlex', 'WebKitBoxFlexGroup', 'WebkitBoxOrdinalGroup', 'WebkitColumnCount', 'WebkitColumns', 'WebkitFlex', 'WebkitFlexGrow', 'WebkitFlexPositive', 'WebkitFlexShrink', 'WebkitLineClamp']);
729function isUnitlessNumber (name) {
730 return unitlessNumbers.has(name);
731}
732
733var aliases = new Map([['acceptCharset', 'accept-charset'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv'], // HTML and SVG attributes, but the SVG attribute is case sensitive.],
734['crossOrigin', 'crossorigin'], // This is a list of all SVG attributes that need special casing.
735// Regular attributes that just accept strings.],
736['accentHeight', 'accent-height'], ['alignmentBaseline', 'alignment-baseline'], ['arabicForm', 'arabic-form'], ['baselineShift', 'baseline-shift'], ['capHeight', 'cap-height'], ['clipPath', 'clip-path'], ['clipRule', 'clip-rule'], ['colorInterpolation', 'color-interpolation'], ['colorInterpolationFilters', 'color-interpolation-filters'], ['colorProfile', 'color-profile'], ['colorRendering', 'color-rendering'], ['dominantBaseline', 'dominant-baseline'], ['enableBackground', 'enable-background'], ['fillOpacity', 'fill-opacity'], ['fillRule', 'fill-rule'], ['floodColor', 'flood-color'], ['floodOpacity', 'flood-opacity'], ['fontFamily', 'font-family'], ['fontSize', 'font-size'], ['fontSizeAdjust', 'font-size-adjust'], ['fontStretch', 'font-stretch'], ['fontStyle', 'font-style'], ['fontVariant', 'font-variant'], ['fontWeight', 'font-weight'], ['glyphName', 'glyph-name'], ['glyphOrientationHorizontal', 'glyph-orientation-horizontal'], ['glyphOrientationVertical', 'glyph-orientation-vertical'], ['horizAdvX', 'horiz-adv-x'], ['horizOriginX', 'horiz-origin-x'], ['imageRendering', 'image-rendering'], ['letterSpacing', 'letter-spacing'], ['lightingColor', 'lighting-color'], ['markerEnd', 'marker-end'], ['markerMid', 'marker-mid'], ['markerStart', 'marker-start'], ['overlinePosition', 'overline-position'], ['overlineThickness', 'overline-thickness'], ['paintOrder', 'paint-order'], ['panose-1', 'panose-1'], ['pointerEvents', 'pointer-events'], ['renderingIntent', 'rendering-intent'], ['shapeRendering', 'shape-rendering'], ['stopColor', 'stop-color'], ['stopOpacity', 'stop-opacity'], ['strikethroughPosition', 'strikethrough-position'], ['strikethroughThickness', 'strikethrough-thickness'], ['strokeDasharray', 'stroke-dasharray'], ['strokeDashoffset', 'stroke-dashoffset'], ['strokeLinecap', 'stroke-linecap'], ['strokeLinejoin', 'stroke-linejoin'], ['strokeMiterlimit', 'stroke-miterlimit'], ['strokeOpacity', 'stroke-opacity'], ['strokeWidth', 'stroke-width'], ['textAnchor', 'text-anchor'], ['textDecoration', 'text-decoration'], ['textRendering', 'text-rendering'], ['transformOrigin', 'transform-origin'], ['underlinePosition', 'underline-position'], ['underlineThickness', 'underline-thickness'], ['unicodeBidi', 'unicode-bidi'], ['unicodeRange', 'unicode-range'], ['unitsPerEm', 'units-per-em'], ['vAlphabetic', 'v-alphabetic'], ['vHanging', 'v-hanging'], ['vIdeographic', 'v-ideographic'], ['vMathematical', 'v-mathematical'], ['vectorEffect', 'vector-effect'], ['vertAdvY', 'vert-adv-y'], ['vertOriginX', 'vert-origin-x'], ['vertOriginY', 'vert-origin-y'], ['wordSpacing', 'word-spacing'], ['writingMode', 'writing-mode'], ['xmlnsXlink', 'xmlns:xlink'], ['xHeight', 'x-height']]);
737function getAttributeAlias (name) {
738 return aliases.get(name) || name;
739}
740
741var hasReadOnlyValue = {
742 button: true,
743 checkbox: true,
744 image: true,
745 hidden: true,
746 radio: true,
747 reset: true,
748 submit: true
749};
750function checkControlledValueProps(tagName, props) {
751 {
752 if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
753 if (tagName === 'select') {
754 error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, set `onChange`.');
755 } else {
756 error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.');
757 }
758 }
759
760 if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
761 error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
762 }
763 }
764}
765
766var ariaProperties = {
767 'aria-current': 0,
768 // state
769 'aria-description': 0,
770 'aria-details': 0,
771 'aria-disabled': 0,
772 // state
773 'aria-hidden': 0,
774 // state
775 'aria-invalid': 0,
776 // state
777 'aria-keyshortcuts': 0,
778 'aria-label': 0,
779 'aria-roledescription': 0,
780 // Widget Attributes
781 'aria-autocomplete': 0,
782 'aria-checked': 0,
783 'aria-expanded': 0,
784 'aria-haspopup': 0,
785 'aria-level': 0,
786 'aria-modal': 0,
787 'aria-multiline': 0,
788 'aria-multiselectable': 0,
789 'aria-orientation': 0,
790 'aria-placeholder': 0,
791 'aria-pressed': 0,
792 'aria-readonly': 0,
793 'aria-required': 0,
794 'aria-selected': 0,
795 'aria-sort': 0,
796 'aria-valuemax': 0,
797 'aria-valuemin': 0,
798 'aria-valuenow': 0,
799 'aria-valuetext': 0,
800 // Live Region Attributes
801 'aria-atomic': 0,
802 'aria-busy': 0,
803 'aria-live': 0,
804 'aria-relevant': 0,
805 // Drag-and-Drop Attributes
806 'aria-dropeffect': 0,
807 'aria-grabbed': 0,
808 // Relationship Attributes
809 'aria-activedescendant': 0,
810 'aria-colcount': 0,
811 'aria-colindex': 0,
812 'aria-colspan': 0,
813 'aria-controls': 0,
814 'aria-describedby': 0,
815 'aria-errormessage': 0,
816 'aria-flowto': 0,
817 'aria-labelledby': 0,
818 'aria-owns': 0,
819 'aria-posinset': 0,
820 'aria-rowcount': 0,
821 'aria-rowindex': 0,
822 'aria-rowspan': 0,
823 'aria-setsize': 0
824};
825
826var warnedProperties$1 = {};
827var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
828var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
829
830function validateProperty$1(tagName, name) {
831 {
832 if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
833 return true;
834 }
835
836 if (rARIACamel$1.test(name)) {
837 var ariaName = 'aria-' + name.slice(4).toLowerCase();
838 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
839 // DOM properties, then it is an invalid aria-* attribute.
840
841 if (correctName == null) {
842 error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
843
844 warnedProperties$1[name] = true;
845 return true;
846 } // aria-* attributes should be lowercase; suggest the lowercase version.
847
848
849 if (name !== correctName) {
850 error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
851
852 warnedProperties$1[name] = true;
853 return true;
854 }
855 }
856
857 if (rARIA$1.test(name)) {
858 var lowerCasedName = name.toLowerCase();
859 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
860 // DOM properties, then it is an invalid aria-* attribute.
861
862 if (standardName == null) {
863 warnedProperties$1[name] = true;
864 return false;
865 } // aria-* attributes should be lowercase; suggest the lowercase version.
866
867
868 if (name !== standardName) {
869 error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
870
871 warnedProperties$1[name] = true;
872 return true;
873 }
874 }
875 }
876
877 return true;
878}
879
880function validateProperties$2(type, props) {
881 {
882 var invalidProps = [];
883
884 for (var key in props) {
885 var isValid = validateProperty$1(type, key);
886
887 if (!isValid) {
888 invalidProps.push(key);
889 }
890 }
891
892 var unknownPropString = invalidProps.map(function (prop) {
893 return '`' + prop + '`';
894 }).join(', ');
895
896 if (invalidProps.length === 1) {
897 error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://react.dev/link/invalid-aria-props', unknownPropString, type);
898 } else if (invalidProps.length > 1) {
899 error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://react.dev/link/invalid-aria-props', unknownPropString, type);
900 }
901 }
902}
903
904var didWarnValueNull = false;
905function validateProperties$1(type, props) {
906 {
907 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
908 return;
909 }
910
911 if (props != null && props.value === null && !didWarnValueNull) {
912 didWarnValueNull = true;
913
914 if (type === 'select' && props.multiple) {
915 error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
916 } else {
917 error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
918 }
919 }
920 }
921}
922
923function isCustomElement(tagName, props) {
924 if (tagName.indexOf('-') === -1) {
925 return false;
926 }
927
928 switch (tagName) {
929 // These are reserved SVG and MathML elements.
930 // We don't mind this list too much because we expect it to never grow.
931 // The alternative is to track the namespace in a few places which is convoluted.
932 // https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-core-concepts
933 case 'annotation-xml':
934 case 'color-profile':
935 case 'font-face':
936 case 'font-face-src':
937 case 'font-face-uri':
938 case 'font-face-format':
939 case 'font-face-name':
940 case 'missing-glyph':
941 return false;
942
943 default:
944 return true;
945 }
946}
947
948// When adding attributes to the HTML or SVG allowed attribute list, be sure to
949// also add them to this module to ensure casing and incorrect name
950// warnings.
951var possibleStandardNames = {
952 // HTML
953 accept: 'accept',
954 acceptcharset: 'acceptCharset',
955 'accept-charset': 'acceptCharset',
956 accesskey: 'accessKey',
957 action: 'action',
958 allowfullscreen: 'allowFullScreen',
959 alt: 'alt',
960 as: 'as',
961 async: 'async',
962 autocapitalize: 'autoCapitalize',
963 autocomplete: 'autoComplete',
964 autocorrect: 'autoCorrect',
965 autofocus: 'autoFocus',
966 autoplay: 'autoPlay',
967 autosave: 'autoSave',
968 capture: 'capture',
969 cellpadding: 'cellPadding',
970 cellspacing: 'cellSpacing',
971 challenge: 'challenge',
972 charset: 'charSet',
973 checked: 'checked',
974 children: 'children',
975 cite: 'cite',
976 class: 'className',
977 classid: 'classID',
978 classname: 'className',
979 cols: 'cols',
980 colspan: 'colSpan',
981 content: 'content',
982 contenteditable: 'contentEditable',
983 contextmenu: 'contextMenu',
984 controls: 'controls',
985 controlslist: 'controlsList',
986 coords: 'coords',
987 crossorigin: 'crossOrigin',
988 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
989 data: 'data',
990 datetime: 'dateTime',
991 default: 'default',
992 defaultchecked: 'defaultChecked',
993 defaultvalue: 'defaultValue',
994 defer: 'defer',
995 dir: 'dir',
996 disabled: 'disabled',
997 disablepictureinpicture: 'disablePictureInPicture',
998 disableremoteplayback: 'disableRemotePlayback',
999 download: 'download',
1000 draggable: 'draggable',
1001 enctype: 'encType',
1002 enterkeyhint: 'enterKeyHint',
1003 fetchpriority: 'fetchPriority',
1004 for: 'htmlFor',
1005 form: 'form',
1006 formmethod: 'formMethod',
1007 formaction: 'formAction',
1008 formenctype: 'formEncType',
1009 formnovalidate: 'formNoValidate',
1010 formtarget: 'formTarget',
1011 frameborder: 'frameBorder',
1012 headers: 'headers',
1013 height: 'height',
1014 hidden: 'hidden',
1015 high: 'high',
1016 href: 'href',
1017 hreflang: 'hrefLang',
1018 htmlfor: 'htmlFor',
1019 httpequiv: 'httpEquiv',
1020 'http-equiv': 'httpEquiv',
1021 icon: 'icon',
1022 id: 'id',
1023 imagesizes: 'imageSizes',
1024 imagesrcset: 'imageSrcSet',
1025 inert: 'inert',
1026 innerhtml: 'innerHTML',
1027 inputmode: 'inputMode',
1028 integrity: 'integrity',
1029 is: 'is',
1030 itemid: 'itemID',
1031 itemprop: 'itemProp',
1032 itemref: 'itemRef',
1033 itemscope: 'itemScope',
1034 itemtype: 'itemType',
1035 keyparams: 'keyParams',
1036 keytype: 'keyType',
1037 kind: 'kind',
1038 label: 'label',
1039 lang: 'lang',
1040 list: 'list',
1041 loop: 'loop',
1042 low: 'low',
1043 manifest: 'manifest',
1044 marginwidth: 'marginWidth',
1045 marginheight: 'marginHeight',
1046 max: 'max',
1047 maxlength: 'maxLength',
1048 media: 'media',
1049 mediagroup: 'mediaGroup',
1050 method: 'method',
1051 min: 'min',
1052 minlength: 'minLength',
1053 multiple: 'multiple',
1054 muted: 'muted',
1055 name: 'name',
1056 nomodule: 'noModule',
1057 nonce: 'nonce',
1058 novalidate: 'noValidate',
1059 open: 'open',
1060 optimum: 'optimum',
1061 pattern: 'pattern',
1062 placeholder: 'placeholder',
1063 playsinline: 'playsInline',
1064 poster: 'poster',
1065 preload: 'preload',
1066 profile: 'profile',
1067 radiogroup: 'radioGroup',
1068 readonly: 'readOnly',
1069 referrerpolicy: 'referrerPolicy',
1070 rel: 'rel',
1071 required: 'required',
1072 reversed: 'reversed',
1073 role: 'role',
1074 rows: 'rows',
1075 rowspan: 'rowSpan',
1076 sandbox: 'sandbox',
1077 scope: 'scope',
1078 scoped: 'scoped',
1079 scrolling: 'scrolling',
1080 seamless: 'seamless',
1081 selected: 'selected',
1082 shape: 'shape',
1083 size: 'size',
1084 sizes: 'sizes',
1085 span: 'span',
1086 spellcheck: 'spellCheck',
1087 src: 'src',
1088 srcdoc: 'srcDoc',
1089 srclang: 'srcLang',
1090 srcset: 'srcSet',
1091 start: 'start',
1092 step: 'step',
1093 style: 'style',
1094 summary: 'summary',
1095 tabindex: 'tabIndex',
1096 target: 'target',
1097 title: 'title',
1098 type: 'type',
1099 usemap: 'useMap',
1100 value: 'value',
1101 width: 'width',
1102 wmode: 'wmode',
1103 wrap: 'wrap',
1104 // SVG
1105 about: 'about',
1106 accentheight: 'accentHeight',
1107 'accent-height': 'accentHeight',
1108 accumulate: 'accumulate',
1109 additive: 'additive',
1110 alignmentbaseline: 'alignmentBaseline',
1111 'alignment-baseline': 'alignmentBaseline',
1112 allowreorder: 'allowReorder',
1113 alphabetic: 'alphabetic',
1114 amplitude: 'amplitude',
1115 arabicform: 'arabicForm',
1116 'arabic-form': 'arabicForm',
1117 ascent: 'ascent',
1118 attributename: 'attributeName',
1119 attributetype: 'attributeType',
1120 autoreverse: 'autoReverse',
1121 azimuth: 'azimuth',
1122 basefrequency: 'baseFrequency',
1123 baselineshift: 'baselineShift',
1124 'baseline-shift': 'baselineShift',
1125 baseprofile: 'baseProfile',
1126 bbox: 'bbox',
1127 begin: 'begin',
1128 bias: 'bias',
1129 by: 'by',
1130 calcmode: 'calcMode',
1131 capheight: 'capHeight',
1132 'cap-height': 'capHeight',
1133 clip: 'clip',
1134 clippath: 'clipPath',
1135 'clip-path': 'clipPath',
1136 clippathunits: 'clipPathUnits',
1137 cliprule: 'clipRule',
1138 'clip-rule': 'clipRule',
1139 color: 'color',
1140 colorinterpolation: 'colorInterpolation',
1141 'color-interpolation': 'colorInterpolation',
1142 colorinterpolationfilters: 'colorInterpolationFilters',
1143 'color-interpolation-filters': 'colorInterpolationFilters',
1144 colorprofile: 'colorProfile',
1145 'color-profile': 'colorProfile',
1146 colorrendering: 'colorRendering',
1147 'color-rendering': 'colorRendering',
1148 contentscripttype: 'contentScriptType',
1149 contentstyletype: 'contentStyleType',
1150 cursor: 'cursor',
1151 cx: 'cx',
1152 cy: 'cy',
1153 d: 'd',
1154 datatype: 'datatype',
1155 decelerate: 'decelerate',
1156 descent: 'descent',
1157 diffuseconstant: 'diffuseConstant',
1158 direction: 'direction',
1159 display: 'display',
1160 divisor: 'divisor',
1161 dominantbaseline: 'dominantBaseline',
1162 'dominant-baseline': 'dominantBaseline',
1163 dur: 'dur',
1164 dx: 'dx',
1165 dy: 'dy',
1166 edgemode: 'edgeMode',
1167 elevation: 'elevation',
1168 enablebackground: 'enableBackground',
1169 'enable-background': 'enableBackground',
1170 end: 'end',
1171 exponent: 'exponent',
1172 externalresourcesrequired: 'externalResourcesRequired',
1173 fill: 'fill',
1174 fillopacity: 'fillOpacity',
1175 'fill-opacity': 'fillOpacity',
1176 fillrule: 'fillRule',
1177 'fill-rule': 'fillRule',
1178 filter: 'filter',
1179 filterres: 'filterRes',
1180 filterunits: 'filterUnits',
1181 floodopacity: 'floodOpacity',
1182 'flood-opacity': 'floodOpacity',
1183 floodcolor: 'floodColor',
1184 'flood-color': 'floodColor',
1185 focusable: 'focusable',
1186 fontfamily: 'fontFamily',
1187 'font-family': 'fontFamily',
1188 fontsize: 'fontSize',
1189 'font-size': 'fontSize',
1190 fontsizeadjust: 'fontSizeAdjust',
1191 'font-size-adjust': 'fontSizeAdjust',
1192 fontstretch: 'fontStretch',
1193 'font-stretch': 'fontStretch',
1194 fontstyle: 'fontStyle',
1195 'font-style': 'fontStyle',
1196 fontvariant: 'fontVariant',
1197 'font-variant': 'fontVariant',
1198 fontweight: 'fontWeight',
1199 'font-weight': 'fontWeight',
1200 format: 'format',
1201 from: 'from',
1202 fx: 'fx',
1203 fy: 'fy',
1204 g1: 'g1',
1205 g2: 'g2',
1206 glyphname: 'glyphName',
1207 'glyph-name': 'glyphName',
1208 glyphorientationhorizontal: 'glyphOrientationHorizontal',
1209 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
1210 glyphorientationvertical: 'glyphOrientationVertical',
1211 'glyph-orientation-vertical': 'glyphOrientationVertical',
1212 glyphref: 'glyphRef',
1213 gradienttransform: 'gradientTransform',
1214 gradientunits: 'gradientUnits',
1215 hanging: 'hanging',
1216 horizadvx: 'horizAdvX',
1217 'horiz-adv-x': 'horizAdvX',
1218 horizoriginx: 'horizOriginX',
1219 'horiz-origin-x': 'horizOriginX',
1220 ideographic: 'ideographic',
1221 imagerendering: 'imageRendering',
1222 'image-rendering': 'imageRendering',
1223 in2: 'in2',
1224 in: 'in',
1225 inlist: 'inlist',
1226 intercept: 'intercept',
1227 k1: 'k1',
1228 k2: 'k2',
1229 k3: 'k3',
1230 k4: 'k4',
1231 k: 'k',
1232 kernelmatrix: 'kernelMatrix',
1233 kernelunitlength: 'kernelUnitLength',
1234 kerning: 'kerning',
1235 keypoints: 'keyPoints',
1236 keysplines: 'keySplines',
1237 keytimes: 'keyTimes',
1238 lengthadjust: 'lengthAdjust',
1239 letterspacing: 'letterSpacing',
1240 'letter-spacing': 'letterSpacing',
1241 lightingcolor: 'lightingColor',
1242 'lighting-color': 'lightingColor',
1243 limitingconeangle: 'limitingConeAngle',
1244 local: 'local',
1245 markerend: 'markerEnd',
1246 'marker-end': 'markerEnd',
1247 markerheight: 'markerHeight',
1248 markermid: 'markerMid',
1249 'marker-mid': 'markerMid',
1250 markerstart: 'markerStart',
1251 'marker-start': 'markerStart',
1252 markerunits: 'markerUnits',
1253 markerwidth: 'markerWidth',
1254 mask: 'mask',
1255 maskcontentunits: 'maskContentUnits',
1256 maskunits: 'maskUnits',
1257 mathematical: 'mathematical',
1258 mode: 'mode',
1259 numoctaves: 'numOctaves',
1260 offset: 'offset',
1261 opacity: 'opacity',
1262 operator: 'operator',
1263 order: 'order',
1264 orient: 'orient',
1265 orientation: 'orientation',
1266 origin: 'origin',
1267 overflow: 'overflow',
1268 overlineposition: 'overlinePosition',
1269 'overline-position': 'overlinePosition',
1270 overlinethickness: 'overlineThickness',
1271 'overline-thickness': 'overlineThickness',
1272 paintorder: 'paintOrder',
1273 'paint-order': 'paintOrder',
1274 panose1: 'panose1',
1275 'panose-1': 'panose1',
1276 pathlength: 'pathLength',
1277 patterncontentunits: 'patternContentUnits',
1278 patterntransform: 'patternTransform',
1279 patternunits: 'patternUnits',
1280 pointerevents: 'pointerEvents',
1281 'pointer-events': 'pointerEvents',
1282 points: 'points',
1283 pointsatx: 'pointsAtX',
1284 pointsaty: 'pointsAtY',
1285 pointsatz: 'pointsAtZ',
1286 prefix: 'prefix',
1287 preservealpha: 'preserveAlpha',
1288 preserveaspectratio: 'preserveAspectRatio',
1289 primitiveunits: 'primitiveUnits',
1290 property: 'property',
1291 r: 'r',
1292 radius: 'radius',
1293 refx: 'refX',
1294 refy: 'refY',
1295 renderingintent: 'renderingIntent',
1296 'rendering-intent': 'renderingIntent',
1297 repeatcount: 'repeatCount',
1298 repeatdur: 'repeatDur',
1299 requiredextensions: 'requiredExtensions',
1300 requiredfeatures: 'requiredFeatures',
1301 resource: 'resource',
1302 restart: 'restart',
1303 result: 'result',
1304 results: 'results',
1305 rotate: 'rotate',
1306 rx: 'rx',
1307 ry: 'ry',
1308 scale: 'scale',
1309 security: 'security',
1310 seed: 'seed',
1311 shaperendering: 'shapeRendering',
1312 'shape-rendering': 'shapeRendering',
1313 slope: 'slope',
1314 spacing: 'spacing',
1315 specularconstant: 'specularConstant',
1316 specularexponent: 'specularExponent',
1317 speed: 'speed',
1318 spreadmethod: 'spreadMethod',
1319 startoffset: 'startOffset',
1320 stddeviation: 'stdDeviation',
1321 stemh: 'stemh',
1322 stemv: 'stemv',
1323 stitchtiles: 'stitchTiles',
1324 stopcolor: 'stopColor',
1325 'stop-color': 'stopColor',
1326 stopopacity: 'stopOpacity',
1327 'stop-opacity': 'stopOpacity',
1328 strikethroughposition: 'strikethroughPosition',
1329 'strikethrough-position': 'strikethroughPosition',
1330 strikethroughthickness: 'strikethroughThickness',
1331 'strikethrough-thickness': 'strikethroughThickness',
1332 string: 'string',
1333 stroke: 'stroke',
1334 strokedasharray: 'strokeDasharray',
1335 'stroke-dasharray': 'strokeDasharray',
1336 strokedashoffset: 'strokeDashoffset',
1337 'stroke-dashoffset': 'strokeDashoffset',
1338 strokelinecap: 'strokeLinecap',
1339 'stroke-linecap': 'strokeLinecap',
1340 strokelinejoin: 'strokeLinejoin',
1341 'stroke-linejoin': 'strokeLinejoin',
1342 strokemiterlimit: 'strokeMiterlimit',
1343 'stroke-miterlimit': 'strokeMiterlimit',
1344 strokewidth: 'strokeWidth',
1345 'stroke-width': 'strokeWidth',
1346 strokeopacity: 'strokeOpacity',
1347 'stroke-opacity': 'strokeOpacity',
1348 suppresscontenteditablewarning: 'suppressContentEditableWarning',
1349 suppresshydrationwarning: 'suppressHydrationWarning',
1350 surfacescale: 'surfaceScale',
1351 systemlanguage: 'systemLanguage',
1352 tablevalues: 'tableValues',
1353 targetx: 'targetX',
1354 targety: 'targetY',
1355 textanchor: 'textAnchor',
1356 'text-anchor': 'textAnchor',
1357 textdecoration: 'textDecoration',
1358 'text-decoration': 'textDecoration',
1359 textlength: 'textLength',
1360 textrendering: 'textRendering',
1361 'text-rendering': 'textRendering',
1362 to: 'to',
1363 transform: 'transform',
1364 transformorigin: 'transformOrigin',
1365 'transform-origin': 'transformOrigin',
1366 typeof: 'typeof',
1367 u1: 'u1',
1368 u2: 'u2',
1369 underlineposition: 'underlinePosition',
1370 'underline-position': 'underlinePosition',
1371 underlinethickness: 'underlineThickness',
1372 'underline-thickness': 'underlineThickness',
1373 unicode: 'unicode',
1374 unicodebidi: 'unicodeBidi',
1375 'unicode-bidi': 'unicodeBidi',
1376 unicoderange: 'unicodeRange',
1377 'unicode-range': 'unicodeRange',
1378 unitsperem: 'unitsPerEm',
1379 'units-per-em': 'unitsPerEm',
1380 unselectable: 'unselectable',
1381 valphabetic: 'vAlphabetic',
1382 'v-alphabetic': 'vAlphabetic',
1383 values: 'values',
1384 vectoreffect: 'vectorEffect',
1385 'vector-effect': 'vectorEffect',
1386 version: 'version',
1387 vertadvy: 'vertAdvY',
1388 'vert-adv-y': 'vertAdvY',
1389 vertoriginx: 'vertOriginX',
1390 'vert-origin-x': 'vertOriginX',
1391 vertoriginy: 'vertOriginY',
1392 'vert-origin-y': 'vertOriginY',
1393 vhanging: 'vHanging',
1394 'v-hanging': 'vHanging',
1395 videographic: 'vIdeographic',
1396 'v-ideographic': 'vIdeographic',
1397 viewbox: 'viewBox',
1398 viewtarget: 'viewTarget',
1399 visibility: 'visibility',
1400 vmathematical: 'vMathematical',
1401 'v-mathematical': 'vMathematical',
1402 vocab: 'vocab',
1403 widths: 'widths',
1404 wordspacing: 'wordSpacing',
1405 'word-spacing': 'wordSpacing',
1406 writingmode: 'writingMode',
1407 'writing-mode': 'writingMode',
1408 x1: 'x1',
1409 x2: 'x2',
1410 x: 'x',
1411 xchannelselector: 'xChannelSelector',
1412 xheight: 'xHeight',
1413 'x-height': 'xHeight',
1414 xlinkactuate: 'xlinkActuate',
1415 'xlink:actuate': 'xlinkActuate',
1416 xlinkarcrole: 'xlinkArcrole',
1417 'xlink:arcrole': 'xlinkArcrole',
1418 xlinkhref: 'xlinkHref',
1419 'xlink:href': 'xlinkHref',
1420 xlinkrole: 'xlinkRole',
1421 'xlink:role': 'xlinkRole',
1422 xlinkshow: 'xlinkShow',
1423 'xlink:show': 'xlinkShow',
1424 xlinktitle: 'xlinkTitle',
1425 'xlink:title': 'xlinkTitle',
1426 xlinktype: 'xlinkType',
1427 'xlink:type': 'xlinkType',
1428 xmlbase: 'xmlBase',
1429 'xml:base': 'xmlBase',
1430 xmllang: 'xmlLang',
1431 'xml:lang': 'xmlLang',
1432 xmlns: 'xmlns',
1433 'xml:space': 'xmlSpace',
1434 xmlnsxlink: 'xmlnsXlink',
1435 'xmlns:xlink': 'xmlnsXlink',
1436 xmlspace: 'xmlSpace',
1437 y1: 'y1',
1438 y2: 'y2',
1439 y: 'y',
1440 ychannelselector: 'yChannelSelector',
1441 z: 'z',
1442 zoomandpan: 'zoomAndPan'
1443};
1444
1445var warnedProperties = {};
1446var EVENT_NAME_REGEX = /^on./;
1447var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
1448var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$') ;
1449var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$') ;
1450
1451function validateProperty(tagName, name, value, eventRegistry) {
1452 {
1453 if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
1454 return true;
1455 }
1456
1457 var lowerCasedName = name.toLowerCase();
1458
1459 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
1460 error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');
1461
1462 warnedProperties[name] = true;
1463 return true;
1464 } // Actions are special because unlike events they can have other value types.
1465
1466
1467 if (typeof value === 'function') {
1468 if (tagName === 'form' && name === 'action') {
1469 return true;
1470 }
1471
1472 if (tagName === 'input' && name === 'formAction') {
1473 return true;
1474 }
1475
1476 if (tagName === 'button' && name === 'formAction') {
1477 return true;
1478 }
1479 } // We can't rely on the event system being injected on the server.
1480
1481
1482 if (eventRegistry != null) {
1483 var registrationNameDependencies = eventRegistry.registrationNameDependencies,
1484 possibleRegistrationNames = eventRegistry.possibleRegistrationNames;
1485
1486 if (registrationNameDependencies.hasOwnProperty(name)) {
1487 return true;
1488 }
1489
1490 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
1491
1492 if (registrationName != null) {
1493 error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
1494
1495 warnedProperties[name] = true;
1496 return true;
1497 }
1498
1499 if (EVENT_NAME_REGEX.test(name)) {
1500 error('Unknown event handler property `%s`. It will be ignored.', name);
1501
1502 warnedProperties[name] = true;
1503 return true;
1504 }
1505 } else if (EVENT_NAME_REGEX.test(name)) {
1506 // If no event plugins have been injected, we are in a server environment.
1507 // So we can't tell if the event name is correct for sure, but we can filter
1508 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
1509 if (INVALID_EVENT_NAME_REGEX.test(name)) {
1510 error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
1511 }
1512
1513 warnedProperties[name] = true;
1514 return true;
1515 } // Let the ARIA attribute hook validate ARIA attributes
1516
1517
1518 if (rARIA.test(name) || rARIACamel.test(name)) {
1519 return true;
1520 }
1521
1522 if (lowerCasedName === 'innerhtml') {
1523 error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
1524
1525 warnedProperties[name] = true;
1526 return true;
1527 }
1528
1529 if (lowerCasedName === 'aria') {
1530 error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
1531
1532 warnedProperties[name] = true;
1533 return true;
1534 }
1535
1536 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
1537 error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
1538
1539 warnedProperties[name] = true;
1540 return true;
1541 }
1542
1543 if (typeof value === 'number' && isNaN(value)) {
1544 error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
1545
1546 warnedProperties[name] = true;
1547 return true;
1548 } // Known attributes should match the casing specified in the property config.
1549
1550
1551 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
1552 var standardName = possibleStandardNames[lowerCasedName];
1553
1554 if (standardName !== name) {
1555 error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
1556
1557 warnedProperties[name] = true;
1558 return true;
1559 }
1560 } else if (name !== lowerCasedName) {
1561 // Unknown attributes should have lowercase casing since that's how they
1562 // will be cased anyway with server rendering.
1563 error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);
1564
1565 warnedProperties[name] = true;
1566 return true;
1567 } // Now that we've validated casing, do not validate
1568 // data types for reserved props
1569
1570
1571 switch (name) {
1572 case 'dangerouslySetInnerHTML':
1573 case 'children':
1574 case 'style':
1575 case 'suppressContentEditableWarning':
1576 case 'suppressHydrationWarning':
1577 case 'defaultValue': // Reserved
1578
1579 case 'defaultChecked':
1580 case 'innerHTML':
1581 case 'ref':
1582 {
1583 return true;
1584 }
1585
1586 case 'innerText': // Properties
1587
1588 case 'textContent':
1589 return true;
1590 }
1591
1592 switch (typeof value) {
1593 case 'boolean':
1594 {
1595 switch (name) {
1596 case 'autoFocus':
1597 case 'checked':
1598 case 'multiple':
1599 case 'muted':
1600 case 'selected':
1601 case 'contentEditable':
1602 case 'spellCheck':
1603 case 'draggable':
1604 case 'value':
1605 case 'autoReverse':
1606 case 'externalResourcesRequired':
1607 case 'focusable':
1608 case 'preserveAlpha':
1609 case 'allowFullScreen':
1610 case 'async':
1611 case 'autoPlay':
1612 case 'controls':
1613 case 'default':
1614 case 'defer':
1615 case 'disabled':
1616 case 'disablePictureInPicture':
1617 case 'disableRemotePlayback':
1618 case 'formNoValidate':
1619 case 'hidden':
1620 case 'loop':
1621 case 'noModule':
1622 case 'noValidate':
1623 case 'open':
1624 case 'playsInline':
1625 case 'readOnly':
1626 case 'required':
1627 case 'reversed':
1628 case 'scoped':
1629 case 'seamless':
1630 case 'itemScope':
1631 case 'capture':
1632 case 'download':
1633 case 'inert':
1634 {
1635 // Boolean properties can accept boolean values
1636 return true;
1637 }
1638 // fallthrough
1639
1640 default:
1641 {
1642 var prefix = name.toLowerCase().slice(0, 5);
1643
1644 if (prefix === 'data-' || prefix === 'aria-') {
1645 return true;
1646 }
1647
1648 if (value) {
1649 error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
1650 } else {
1651 error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
1652 }
1653
1654 warnedProperties[name] = true;
1655 return true;
1656 }
1657 }
1658 }
1659
1660 case 'function':
1661 case 'symbol':
1662 // eslint-disable-line
1663 // Warn when a known attribute is a bad type
1664 warnedProperties[name] = true;
1665 return false;
1666
1667 case 'string':
1668 {
1669 // Warn when passing the strings 'false' or 'true' into a boolean prop
1670 if (value === 'false' || value === 'true') {
1671 switch (name) {
1672 case 'checked':
1673 case 'selected':
1674 case 'multiple':
1675 case 'muted':
1676 case 'allowFullScreen':
1677 case 'async':
1678 case 'autoPlay':
1679 case 'controls':
1680 case 'default':
1681 case 'defer':
1682 case 'disabled':
1683 case 'disablePictureInPicture':
1684 case 'disableRemotePlayback':
1685 case 'formNoValidate':
1686 case 'hidden':
1687 case 'loop':
1688 case 'noModule':
1689 case 'noValidate':
1690 case 'open':
1691 case 'playsInline':
1692 case 'readOnly':
1693 case 'required':
1694 case 'reversed':
1695 case 'scoped':
1696 case 'seamless':
1697 case 'itemScope':
1698 case 'inert':
1699 {
1700 break;
1701 }
1702
1703 default:
1704 {
1705 return true;
1706 }
1707 }
1708
1709 error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);
1710
1711 warnedProperties[name] = true;
1712 return true;
1713 }
1714 }
1715 }
1716
1717 return true;
1718 }
1719}
1720
1721function warnUnknownProperties(type, props, eventRegistry) {
1722 {
1723 var unknownProps = [];
1724
1725 for (var key in props) {
1726 var isValid = validateProperty(type, key, props[key], eventRegistry);
1727
1728 if (!isValid) {
1729 unknownProps.push(key);
1730 }
1731 }
1732
1733 var unknownPropString = unknownProps.map(function (prop) {
1734 return '`' + prop + '`';
1735 }).join(', ');
1736
1737 if (unknownProps.length === 1) {
1738 error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://react.dev/link/attribute-behavior ', unknownPropString, type);
1739 } else if (unknownProps.length > 1) {
1740 error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://react.dev/link/attribute-behavior ', unknownPropString, type);
1741 }
1742 }
1743}
1744
1745function validateProperties(type, props, eventRegistry) {
1746 if (isCustomElement(type) || typeof props.is === 'string') {
1747 return;
1748 }
1749
1750 warnUnknownProperties(type, props, eventRegistry);
1751}
1752
1753// 'msTransform' is correct, but the other prefixes should be capitalized
1754var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
1755var msPattern$1 = /^-ms-/;
1756var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon
1757
1758var badStyleValueWithSemicolonPattern = /;\s*$/;
1759var warnedStyleNames = {};
1760var warnedStyleValues = {};
1761var warnedForNaNValue = false;
1762var warnedForInfinityValue = false;
1763
1764function camelize(string) {
1765 return string.replace(hyphenPattern, function (_, character) {
1766 return character.toUpperCase();
1767 });
1768}
1769
1770function warnHyphenatedStyleName(name) {
1771 {
1772 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
1773 return;
1774 }
1775
1776 warnedStyleNames[name] = true;
1777
1778 error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
1779 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
1780 // is converted to lowercase `ms`.
1781 camelize(name.replace(msPattern$1, 'ms-')));
1782 }
1783}
1784
1785function warnBadVendoredStyleName(name) {
1786 {
1787 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
1788 return;
1789 }
1790
1791 warnedStyleNames[name] = true;
1792
1793 error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
1794 }
1795}
1796
1797function warnStyleValueWithSemicolon(name, value) {
1798 {
1799 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
1800 return;
1801 }
1802
1803 warnedStyleValues[value] = true;
1804
1805 error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
1806 }
1807}
1808
1809function warnStyleValueIsNaN(name, value) {
1810 {
1811 if (warnedForNaNValue) {
1812 return;
1813 }
1814
1815 warnedForNaNValue = true;
1816
1817 error('`NaN` is an invalid value for the `%s` css style property.', name);
1818 }
1819}
1820
1821function warnStyleValueIsInfinity(name, value) {
1822 {
1823 if (warnedForInfinityValue) {
1824 return;
1825 }
1826
1827 warnedForInfinityValue = true;
1828
1829 error('`Infinity` is an invalid value for the `%s` css style property.', name);
1830 }
1831}
1832
1833function warnValidStyle(name, value) {
1834 {
1835 if (name.indexOf('-') > -1) {
1836 warnHyphenatedStyleName(name);
1837 } else if (badVendoredStyleNamePattern.test(name)) {
1838 warnBadVendoredStyleName(name);
1839 } else if (badStyleValueWithSemicolonPattern.test(value)) {
1840 warnStyleValueWithSemicolon(name, value);
1841 }
1842
1843 if (typeof value === 'number') {
1844 if (isNaN(value)) {
1845 warnStyleValueIsNaN(name);
1846 } else if (!isFinite(value)) {
1847 warnStyleValueIsInfinity(name);
1848 }
1849 }
1850 }
1851}
1852
1853function getCrossOriginString(input) {
1854 if (typeof input === 'string') {
1855 return input === 'use-credentials' ? input : '';
1856 }
1857
1858 return undefined;
1859}
1860
1861// code copied and modified from escape-html
1862var matchHtmlRegExp = /["'&<>]/;
1863/**
1864 * Escapes special characters and HTML entities in a given html string.
1865 *
1866 * @param {string} string HTML string to escape for later insertion
1867 * @return {string}
1868 * @public
1869 */
1870
1871function escapeHtml(string) {
1872 {
1873 checkHtmlStringCoercion(string);
1874 }
1875
1876 var str = '' + string;
1877 var match = matchHtmlRegExp.exec(str);
1878
1879 if (!match) {
1880 return str;
1881 }
1882
1883 var escape;
1884 var html = '';
1885 var index;
1886 var lastIndex = 0;
1887
1888 for (index = match.index; index < str.length; index++) {
1889 switch (str.charCodeAt(index)) {
1890 case 34:
1891 // "
1892 escape = '&quot;';
1893 break;
1894
1895 case 38:
1896 // &
1897 escape = '&amp;';
1898 break;
1899
1900 case 39:
1901 // '
1902 escape = '&#x27;'; // modified from escape-html; used to be '&#39'
1903
1904 break;
1905
1906 case 60:
1907 // <
1908 escape = '&lt;';
1909 break;
1910
1911 case 62:
1912 // >
1913 escape = '&gt;';
1914 break;
1915
1916 default:
1917 continue;
1918 }
1919
1920 if (lastIndex !== index) {
1921 html += str.slice(lastIndex, index);
1922 }
1923
1924 lastIndex = index + 1;
1925 html += escape;
1926 }
1927
1928 return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
1929} // end code copied and modified from escape-html
1930
1931/**
1932 * Escapes text to prevent scripting attacks.
1933 *
1934 * @param {*} text Text value to escape.
1935 * @return {string} An escaped string.
1936 */
1937
1938
1939function escapeTextForBrowser(text) {
1940 if (typeof text === 'boolean' || typeof text === 'number' || typeof text === 'bigint') {
1941 // this shortcircuit helps perf for types that we know will never have
1942 // special characters, especially given that this function is used often
1943 // for numeric dom ids.
1944 return '' + text;
1945 }
1946
1947 return escapeHtml(text);
1948}
1949
1950var uppercasePattern = /([A-Z])/g;
1951var msPattern = /^ms-/;
1952/**
1953 * Hyphenates a camelcased CSS property name, for example:
1954 *
1955 * > hyphenateStyleName('backgroundColor')
1956 * < "background-color"
1957 * > hyphenateStyleName('MozTransition')
1958 * < "-moz-transition"
1959 * > hyphenateStyleName('msTransition')
1960 * < "-ms-transition"
1961 *
1962 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
1963 * is converted to `-ms-`.
1964 */
1965
1966function hyphenateStyleName(name) {
1967 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
1968}
1969
1970// A javascript: URL can contain leading C0 control or \u0020 SPACE,
1971// and any newline or tab are filtered out as if they're not part of the URL.
1972// https://url.spec.whatwg.org/#url-parsing
1973// Tab or newline are defined as \r\n\t:
1974// https://infra.spec.whatwg.org/#ascii-tab-or-newline
1975// A C0 control is a code point in the range \u0000 NULL to \u001F
1976// INFORMATION SEPARATOR ONE, inclusive:
1977// https://infra.spec.whatwg.org/#c0-control-or-space
1978
1979/* eslint-disable max-len */
1980var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
1981
1982function sanitizeURL(url) {
1983 // We should never have symbols here because they get filtered out elsewhere.
1984 // eslint-disable-next-line react-internal/safe-string-coercion
1985 if (isJavaScriptProtocol.test('' + url)) {
1986 // Return a different javascript: url that doesn't cause any side-effects and just
1987 // throws if ever visited.
1988 // eslint-disable-next-line no-script-url
1989 return "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')";
1990 }
1991
1992 return url;
1993}
1994
1995// The build script is at scripts/rollup/generate-inline-fizz-runtime.js.
1996// Run `yarn generate-inline-fizz-runtime` to generate.
1997var clientRenderBoundary = '$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};';
1998var completeBoundary = '$RC=function(b,c,e){c=document.getElementById(c);c.parentNode.removeChild(c);var a=document.getElementById(b);if(a){b=a.previousSibling;if(e)b.data="$!",a.setAttribute("data-dgst",e);else{e=b.parentNode;a=b.nextSibling;var f=0;do{if(a&&8===a.nodeType){var d=a.data;if("/$"===d)if(0===f)break;else f--;else"$"!==d&&"$?"!==d&&"$!"!==d||f++}d=a.nextSibling;e.removeChild(a);a=d}while(a);for(;c.firstChild;)e.insertBefore(c.firstChild,a);b.data="$"}b._reactRetry&&b._reactRetry()}};';
1999var completeBoundaryWithStyles = '$RM=new Map;\n$RR=function(r,t,w){for(var u=$RC,n=$RM,p=new Map,q=document,g,b,h=q.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=h[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&n.set(b.getAttribute("href"),b),p.set(b.dataset.precedence,g=b));b=0;h=[];var l,a;for(k=!0;;){if(k){var f=w[b++];if(!f){k=!1;b=0;continue}var c=!1,m=0;var d=f[m++];if(a=n.get(d)){var e=a._p;c=!0}else{a=q.createElement("link");a.href=d;a.rel="stylesheet";for(a.dataset.precedence=\nl=f[m++];e=f[m++];)a.setAttribute(e,f[m++]);e=a._p=new Promise(function(x,y){a.onload=x;a.onerror=y});n.set(d,a)}d=a.getAttribute("media");!e||"l"===e.s||d&&!matchMedia(d).matches||h.push(e);if(c)continue}else{a=v[b++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=p.get(l)||g;c===g&&(g=a);p.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=q.head,c.insertBefore(a,c.firstChild))}Promise.all(h).then(u.bind(null,r,t,""),u.bind(null,r,t,"Resource failed to load"))};';
2000var completeSegment = '$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};';
2001var formReplaying = 'addEventListener("submit",function(a){if(!a.defaultPrevented){var c=a.target,d=a.submitter,e=c.action,b=d;if(d){var f=d.getAttribute("formAction");null!=f&&(e=f,b=null)}"javascript:throw new Error(\'React form unexpectedly submitted.\')"===e&&(a.preventDefault(),b?(a=document.createElement("input"),a.name=b.name,a.value=b.value,b.parentNode.insertBefore(a,b),b=new FormData(c),a.parentNode.removeChild(a)):b=new FormData(c),a=c.ownerDocument||c,(a.$$reactFormReplay=a.$$reactFormReplay||[]).push(c,d,b))}});';
2002
2003function getValueDescriptorExpectingObjectForWarning(thing) {
2004 return thing === null ? '`null`' : thing === undefined ? '`undefined`' : thing === '' ? 'an empty string' : "something with type \"" + typeof thing + "\"";
2005}
2006
2007var ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
2008
2009// same object across all transitions.
2010
2011var sharedNotPendingObject = {
2012 pending: false,
2013 data: null,
2014 method: null,
2015 action: null
2016};
2017var NotPending = Object.freeze(sharedNotPendingObject) ;
2018
2019var previousDispatcher = ReactDOMSharedInternals.d;
2020/* ReactDOMCurrentDispatcher */
2021
2022ReactDOMSharedInternals.d
2023/* ReactDOMCurrentDispatcher */
2024= {
2025 f
2026 /* flushSyncWork */
2027 : previousDispatcher.f
2028 /* flushSyncWork */
2029 ,
2030 r
2031 /* requestFormReset */
2032 : previousDispatcher.r
2033 /* requestFormReset */
2034 ,
2035 D
2036 /* prefetchDNS */
2037 : prefetchDNS,
2038 C
2039 /* preconnect */
2040 : preconnect,
2041 L
2042 /* preload */
2043 : preload,
2044 m
2045 /* preloadModule */
2046 : preloadModule,
2047 X
2048 /* preinitScript */
2049 : preinitScript,
2050 S
2051 /* preinitStyle */
2052 : preinitStyle,
2053 M
2054 /* preinitModuleScript */
2055 : preinitModuleScript
2056}; // We make every property of the descriptor optional because it is not a contract that
2057var ScriptStreamingFormat = 0;
2058var NothingSent
2059/* */
2060= 0;
2061var SentCompleteSegmentFunction
2062/* */
2063= 1;
2064var SentCompleteBoundaryFunction
2065/* */
2066= 2;
2067var SentClientRenderFunction
2068/* */
2069= 4;
2070var SentStyleInsertionFunction
2071/* */
2072= 8;
2073var SentFormReplayingRuntime
2074/* */
2075= 16; // Per request, global state that is not contextual to the rendering subtree.
2076// This cannot be resumed and therefore should only contain things that are
2077// temporary working state or are never used in the prerender pass.
2078// Credentials here are things that affect whether a browser will make a request
2079// as well as things that affect which connection the browser will use for that request.
2080// We want these to be aligned across preloads and resources because otherwise the preload
2081// will be wasted.
2082// We investigated whether referrerPolicy should be included here but from experimentation
2083// it seems that browsers do not treat this as part of the http cache key and does not affect
2084// which connection is used.
2085
2086var EXISTS = null; // This constant is to mark preloads that have no unique credentials
2087// to convey. It should never be checked by identity and we should not
2088// assume Preload values in ResumableState equal this value because they
2089// will have come from some parsed input.
2090
2091var PRELOAD_NO_CREDS = [];
2092
2093{
2094 Object.freeze(PRELOAD_NO_CREDS);
2095} // Per response, global state that is not contextual to the rendering subtree.
2096// This is resumable and therefore should be serializable.
2097
2098
2099stringToPrecomputedChunk('"></template>');
2100var startInlineScript = stringToPrecomputedChunk('<script>');
2101var endInlineScript = stringToPrecomputedChunk('</script>');
2102var startScriptSrc = stringToPrecomputedChunk('<script src="');
2103var startModuleSrc = stringToPrecomputedChunk('<script type="module" src="');
2104var scriptNonce = stringToPrecomputedChunk('" nonce="');
2105var scriptIntegirty = stringToPrecomputedChunk('" integrity="');
2106var scriptCrossOrigin = stringToPrecomputedChunk('" crossorigin="');
2107var endAsyncScript = stringToPrecomputedChunk('" async=""></script>');
2108/**
2109 * This escaping function is designed to work with with inline scripts where the entire
2110 * contents are escaped. Because we know we are escaping the entire script we can avoid for instance
2111 * escaping html comment string sequences that are valid javascript as well because
2112 * if there are no sebsequent <script sequences the html parser will never enter
2113 * script data double escaped state (see: https://www.w3.org/TR/html53/syntax.html#script-data-double-escaped-state)
2114 *
2115 * While untrusted script content should be made safe before using this api it will
2116 * ensure that the script cannot be early terminated or never terminated state
2117 */
2118
2119function escapeEntireInlineScriptContent(scriptText) {
2120 {
2121 checkHtmlStringCoercion(scriptText);
2122 }
2123
2124 return ('' + scriptText).replace(scriptRegex, scriptReplacer);
2125}
2126
2127var scriptRegex = /(<\/|<)(s)(cript)/gi;
2128
2129var scriptReplacer = function (match, prefix, s, suffix) {
2130 return "" + prefix + (s === 's' ? "\\u0073" : "\\u0053") + suffix;
2131};
2132
2133var importMapScriptStart = stringToPrecomputedChunk('<script type="importmap">');
2134var importMapScriptEnd = stringToPrecomputedChunk('</script>'); // Since we store headers as strings we deal with their length in utf16 code units
2135// rather than visual characters or the utf8 encoding that is used for most binary
2136// serialization. Some common HTTP servers only allow for headers to be 4kB in length.
2137// We choose a default length that is likely to be well under this already limited length however
2138// pathological cases may still cause the utf-8 encoding of the headers to approach this limit.
2139// It should also be noted that this maximum is a soft maximum. we have not reached the limit we will
2140// allow one more header to be captured which means in practice if the limit is approached it will be exceeded
2141
2142var DEFAULT_HEADERS_CAPACITY_IN_UTF16_CODE_UNITS = 2000;
2143var didWarnForNewBooleanPropsWithEmptyValue;
2144
2145{
2146 didWarnForNewBooleanPropsWithEmptyValue = {};
2147} // Allows us to keep track of what we've already written so we can refer back to it.
2148// if passed externalRuntimeConfig and the enableFizzExternalRuntime feature flag
2149// is set, the server will send instructions via data attributes (instead of inline scripts)
2150
2151
2152function createRenderState(resumableState, nonce, externalRuntimeConfig, importMap, onHeaders, maxHeadersLength) {
2153 var inlineScriptWithNonce = nonce === undefined ? startInlineScript : stringToPrecomputedChunk('<script nonce="' + escapeTextForBrowser(nonce) + '">');
2154 var idPrefix = resumableState.idPrefix;
2155 var bootstrapChunks = [];
2156 var externalRuntimeScript = null;
2157 var bootstrapScriptContent = resumableState.bootstrapScriptContent,
2158 bootstrapScripts = resumableState.bootstrapScripts,
2159 bootstrapModules = resumableState.bootstrapModules;
2160
2161 if (bootstrapScriptContent !== undefined) {
2162 bootstrapChunks.push(inlineScriptWithNonce, stringToChunk(escapeEntireInlineScriptContent(bootstrapScriptContent)), endInlineScript);
2163 }
2164
2165 var importMapChunks = [];
2166
2167 if (importMap !== undefined) {
2168 var map = importMap;
2169 importMapChunks.push(importMapScriptStart);
2170 importMapChunks.push(stringToChunk(escapeEntireInlineScriptContent(JSON.stringify(map))));
2171 importMapChunks.push(importMapScriptEnd);
2172 }
2173
2174 {
2175 if (onHeaders && typeof maxHeadersLength === 'number') {
2176 if (maxHeadersLength <= 0) {
2177 error('React expected a positive non-zero `maxHeadersLength` option but found %s instead. When using the `onHeaders` option you may supply an optional `maxHeadersLength` option as well however, when setting this value to zero or less no headers will be captured.', maxHeadersLength === 0 ? 'zero' : maxHeadersLength);
2178 }
2179 }
2180 }
2181
2182 var headers = onHeaders ? {
2183 preconnects: '',
2184 fontPreloads: '',
2185 highImagePreloads: '',
2186 remainingCapacity: typeof maxHeadersLength === 'number' ? maxHeadersLength : DEFAULT_HEADERS_CAPACITY_IN_UTF16_CODE_UNITS
2187 } : null;
2188 var renderState = {
2189 placeholderPrefix: stringToPrecomputedChunk(idPrefix + 'P:'),
2190 segmentPrefix: stringToPrecomputedChunk(idPrefix + 'S:'),
2191 boundaryPrefix: stringToPrecomputedChunk(idPrefix + 'B:'),
2192 startInlineScript: inlineScriptWithNonce,
2193 htmlChunks: null,
2194 headChunks: null,
2195 externalRuntimeScript: externalRuntimeScript,
2196 bootstrapChunks: bootstrapChunks,
2197 importMapChunks: importMapChunks,
2198 onHeaders: onHeaders,
2199 headers: headers,
2200 resets: {
2201 font: {},
2202 dns: {},
2203 connect: {
2204 default: {},
2205 anonymous: {},
2206 credentials: {}
2207 },
2208 image: {},
2209 style: {}
2210 },
2211 charsetChunks: [],
2212 viewportChunks: [],
2213 hoistableChunks: [],
2214 // cleared on flush
2215 preconnects: new Set(),
2216 fontPreloads: new Set(),
2217 highImagePreloads: new Set(),
2218 // usedImagePreloads: new Set(),
2219 styles: new Map(),
2220 bootstrapScripts: new Set(),
2221 scripts: new Set(),
2222 bulkPreloads: new Set(),
2223 preloads: {
2224 images: new Map(),
2225 stylesheets: new Map(),
2226 scripts: new Map(),
2227 moduleScripts: new Map()
2228 },
2229 nonce: nonce,
2230 // like a module global for currently rendering boundary
2231 hoistableState: null,
2232 stylesToHoist: false
2233 };
2234
2235 if (bootstrapScripts !== undefined) {
2236 for (var i = 0; i < bootstrapScripts.length; i++) {
2237 var scriptConfig = bootstrapScripts[i];
2238 var src = void 0,
2239 crossOrigin = void 0,
2240 integrity = void 0;
2241 var props = {
2242 rel: 'preload',
2243 as: 'script',
2244 fetchPriority: 'low',
2245 nonce: nonce
2246 };
2247
2248 if (typeof scriptConfig === 'string') {
2249 props.href = src = scriptConfig;
2250 } else {
2251 props.href = src = scriptConfig.src;
2252 props.integrity = integrity = typeof scriptConfig.integrity === 'string' ? scriptConfig.integrity : undefined;
2253 props.crossOrigin = crossOrigin = typeof scriptConfig === 'string' || scriptConfig.crossOrigin == null ? undefined : scriptConfig.crossOrigin === 'use-credentials' ? 'use-credentials' : '';
2254 }
2255
2256 preloadBootstrapScriptOrModule(resumableState, renderState, src, props);
2257 bootstrapChunks.push(startScriptSrc, stringToChunk(escapeTextForBrowser(src)));
2258
2259 if (nonce) {
2260 bootstrapChunks.push(scriptNonce, stringToChunk(escapeTextForBrowser(nonce)));
2261 }
2262
2263 if (typeof integrity === 'string') {
2264 bootstrapChunks.push(scriptIntegirty, stringToChunk(escapeTextForBrowser(integrity)));
2265 }
2266
2267 if (typeof crossOrigin === 'string') {
2268 bootstrapChunks.push(scriptCrossOrigin, stringToChunk(escapeTextForBrowser(crossOrigin)));
2269 }
2270
2271 bootstrapChunks.push(endAsyncScript);
2272 }
2273 }
2274
2275 if (bootstrapModules !== undefined) {
2276 for (var _i = 0; _i < bootstrapModules.length; _i++) {
2277 var _scriptConfig = bootstrapModules[_i];
2278
2279 var _src = void 0,
2280 _crossOrigin = void 0,
2281 _integrity = void 0;
2282
2283 var _props = {
2284 rel: 'modulepreload',
2285 fetchPriority: 'low',
2286 nonce: nonce
2287 };
2288
2289 if (typeof _scriptConfig === 'string') {
2290 _props.href = _src = _scriptConfig;
2291 } else {
2292 _props.href = _src = _scriptConfig.src;
2293 _props.integrity = _integrity = typeof _scriptConfig.integrity === 'string' ? _scriptConfig.integrity : undefined;
2294 _props.crossOrigin = _crossOrigin = typeof _scriptConfig === 'string' || _scriptConfig.crossOrigin == null ? undefined : _scriptConfig.crossOrigin === 'use-credentials' ? 'use-credentials' : '';
2295 }
2296
2297 preloadBootstrapScriptOrModule(resumableState, renderState, _src, _props);
2298 bootstrapChunks.push(startModuleSrc, stringToChunk(escapeTextForBrowser(_src)));
2299
2300 if (nonce) {
2301 bootstrapChunks.push(scriptNonce, stringToChunk(escapeTextForBrowser(nonce)));
2302 }
2303
2304 if (typeof _integrity === 'string') {
2305 bootstrapChunks.push(scriptIntegirty, stringToChunk(escapeTextForBrowser(_integrity)));
2306 }
2307
2308 if (typeof _crossOrigin === 'string') {
2309 bootstrapChunks.push(scriptCrossOrigin, stringToChunk(escapeTextForBrowser(_crossOrigin)));
2310 }
2311
2312 bootstrapChunks.push(endAsyncScript);
2313 }
2314 }
2315
2316 return renderState;
2317}
2318function createResumableState(identifierPrefix, externalRuntimeConfig, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
2319 var idPrefix = identifierPrefix === undefined ? '' : identifierPrefix;
2320 var streamingFormat = ScriptStreamingFormat;
2321
2322 return {
2323 idPrefix: idPrefix,
2324 nextFormID: 0,
2325 streamingFormat: streamingFormat,
2326 bootstrapScriptContent: bootstrapScriptContent,
2327 bootstrapScripts: bootstrapScripts,
2328 bootstrapModules: bootstrapModules,
2329 instructions: NothingSent,
2330 hasBody: false,
2331 hasHtml: false,
2332 // @TODO add bootstrap script to implicit preloads
2333 // persistent
2334 unknownResources: {},
2335 dnsResources: {},
2336 connectResources: {
2337 default: {},
2338 anonymous: {},
2339 credentials: {}
2340 },
2341 imageResources: {},
2342 styleResources: {},
2343 scriptResources: {},
2344 moduleUnknownResources: {},
2345 moduleScriptResources: {}
2346 };
2347}
2348// modes. We only include the variants as they matter for the sake of our purposes.
2349// We don't actually provide the namespace therefore we use constants instead of the string.
2350
2351var ROOT_HTML_MODE = 0; // Used for the root most element tag.
2352// We have a less than HTML_HTML_MODE check elsewhere. If you add more cases here, make sure it
2353// still makes sense
2354
2355var HTML_HTML_MODE = 1; // Used for the <html> if it is at the top level.
2356
2357var HTML_MODE = 2;
2358var SVG_MODE = 3;
2359var MATHML_MODE = 4;
2360var HTML_TABLE_MODE = 5;
2361var HTML_TABLE_BODY_MODE = 6;
2362var HTML_TABLE_ROW_MODE = 7;
2363var HTML_COLGROUP_MODE = 8; // We have a greater than HTML_TABLE_MODE check elsewhere. If you add more cases here, make sure it
2364// still makes sense
2365
2366var NO_SCOPE =
2367/* */
23680;
2369var NOSCRIPT_SCOPE =
2370/* */
23711;
2372var PICTURE_SCOPE =
2373/* */
23742; // Lets us keep track of contextual state and pick it back up after suspending.
2375
2376function createFormatContext(insertionMode, selectedValue, tagScope) {
2377 return {
2378 insertionMode: insertionMode,
2379 selectedValue: selectedValue,
2380 tagScope: tagScope
2381 };
2382}
2383
2384function createRootFormatContext(namespaceURI) {
2385 var insertionMode = namespaceURI === 'http://www.w3.org/2000/svg' ? SVG_MODE : namespaceURI === 'http://www.w3.org/1998/Math/MathML' ? MATHML_MODE : ROOT_HTML_MODE;
2386 return createFormatContext(insertionMode, null, NO_SCOPE);
2387}
2388function getChildFormatContext(parentContext, type, props) {
2389 switch (type) {
2390 case 'noscript':
2391 return createFormatContext(HTML_MODE, null, parentContext.tagScope | NOSCRIPT_SCOPE);
2392
2393 case 'select':
2394 return createFormatContext(HTML_MODE, props.value != null ? props.value : props.defaultValue, parentContext.tagScope);
2395
2396 case 'svg':
2397 return createFormatContext(SVG_MODE, null, parentContext.tagScope);
2398
2399 case 'picture':
2400 return createFormatContext(HTML_MODE, null, parentContext.tagScope | PICTURE_SCOPE);
2401
2402 case 'math':
2403 return createFormatContext(MATHML_MODE, null, parentContext.tagScope);
2404
2405 case 'foreignObject':
2406 return createFormatContext(HTML_MODE, null, parentContext.tagScope);
2407 // Table parents are special in that their children can only be created at all if they're
2408 // wrapped in a table parent. So we need to encode that we're entering this mode.
2409
2410 case 'table':
2411 return createFormatContext(HTML_TABLE_MODE, null, parentContext.tagScope);
2412
2413 case 'thead':
2414 case 'tbody':
2415 case 'tfoot':
2416 return createFormatContext(HTML_TABLE_BODY_MODE, null, parentContext.tagScope);
2417
2418 case 'colgroup':
2419 return createFormatContext(HTML_COLGROUP_MODE, null, parentContext.tagScope);
2420
2421 case 'tr':
2422 return createFormatContext(HTML_TABLE_ROW_MODE, null, parentContext.tagScope);
2423 }
2424
2425 if (parentContext.insertionMode >= HTML_TABLE_MODE) {
2426 // Whatever tag this was, it wasn't a table parent or other special parent, so we must have
2427 // entered plain HTML again.
2428 return createFormatContext(HTML_MODE, null, parentContext.tagScope);
2429 }
2430
2431 if (parentContext.insertionMode === ROOT_HTML_MODE) {
2432 if (type === 'html') {
2433 // We've emitted the root and is now in <html> mode.
2434 return createFormatContext(HTML_HTML_MODE, null, parentContext.tagScope);
2435 } else {
2436 // We've emitted the root and is now in plain HTML mode.
2437 return createFormatContext(HTML_MODE, null, parentContext.tagScope);
2438 }
2439 } else if (parentContext.insertionMode === HTML_HTML_MODE) {
2440 // We've emitted the document element and is now in plain HTML mode.
2441 return createFormatContext(HTML_MODE, null, parentContext.tagScope);
2442 }
2443
2444 return parentContext;
2445}
2446function makeId(resumableState, treeId, localId) {
2447 var idPrefix = resumableState.idPrefix;
2448 var id = ':' + idPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
2449 // that represents the position of this useId hook among all the useId
2450 // hooks for this fiber.
2451
2452 if (localId > 0) {
2453 id += 'H' + localId.toString(32);
2454 }
2455
2456 return id + ':';
2457}
2458
2459function encodeHTMLTextNode(text) {
2460 return escapeTextForBrowser(text);
2461}
2462
2463var textSeparator = stringToPrecomputedChunk('<!-- -->');
2464function pushTextInstance(target, text, renderState, textEmbedded) {
2465 if (text === '') {
2466 // Empty text doesn't have a DOM node representation and the hydration is aware of this.
2467 return textEmbedded;
2468 }
2469
2470 if (textEmbedded) {
2471 target.push(textSeparator);
2472 }
2473
2474 target.push(stringToChunk(encodeHTMLTextNode(text)));
2475 return true;
2476} // Called when Fizz is done with a Segment. Currently the only purpose is to conditionally
2477// emit a text separator when we don't know for sure it is safe to omit
2478
2479function pushSegmentFinale(target, renderState, lastPushedText, textEmbedded) {
2480 if (lastPushedText && textEmbedded) {
2481 target.push(textSeparator);
2482 }
2483}
2484var styleNameCache = new Map();
2485
2486function processStyleName(styleName) {
2487 var chunk = styleNameCache.get(styleName);
2488
2489 if (chunk !== undefined) {
2490 return chunk;
2491 }
2492
2493 var result = stringToPrecomputedChunk(escapeTextForBrowser(hyphenateStyleName(styleName)));
2494 styleNameCache.set(styleName, result);
2495 return result;
2496}
2497
2498var styleAttributeStart = stringToPrecomputedChunk(' style="');
2499var styleAssign = stringToPrecomputedChunk(':');
2500var styleSeparator = stringToPrecomputedChunk(';');
2501
2502function pushStyleAttribute(target, style) {
2503 if (typeof style !== 'object') {
2504 throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
2505 }
2506
2507 var isFirst = true;
2508
2509 for (var styleName in style) {
2510 if (!hasOwnProperty.call(style, styleName)) {
2511 continue;
2512 } // If you provide unsafe user data here they can inject arbitrary CSS
2513 // which may be problematic (I couldn't repro this):
2514 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
2515 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
2516 // This is not an XSS hole but instead a potential CSS injection issue
2517 // which has lead to a greater discussion about how we're going to
2518 // trust URLs moving forward. See #2115901
2519
2520
2521 var styleValue = style[styleName];
2522
2523 if (styleValue == null || typeof styleValue === 'boolean' || styleValue === '') {
2524 // TODO: We used to set empty string as a style with an empty value. Does that ever make sense?
2525 continue;
2526 }
2527
2528 var nameChunk = void 0;
2529 var valueChunk = void 0;
2530 var isCustomProperty = styleName.indexOf('--') === 0;
2531
2532 if (isCustomProperty) {
2533 nameChunk = stringToChunk(escapeTextForBrowser(styleName));
2534
2535 {
2536 checkCSSPropertyStringCoercion(styleValue, styleName);
2537 }
2538
2539 valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
2540 } else {
2541 {
2542 warnValidStyle(styleName, styleValue);
2543 }
2544
2545 nameChunk = processStyleName(styleName);
2546
2547 if (typeof styleValue === 'number') {
2548 if (styleValue !== 0 && !isUnitlessNumber(styleName)) {
2549 valueChunk = stringToChunk(styleValue + 'px'); // Presumes implicit 'px' suffix for unitless numbers
2550 } else {
2551 valueChunk = stringToChunk('' + styleValue);
2552 }
2553 } else {
2554 {
2555 checkCSSPropertyStringCoercion(styleValue, styleName);
2556 }
2557
2558 valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
2559 }
2560 }
2561
2562 if (isFirst) {
2563 isFirst = false; // If it's first, we don't need any separators prefixed.
2564
2565 target.push(styleAttributeStart, nameChunk, styleAssign, valueChunk);
2566 } else {
2567 target.push(styleSeparator, nameChunk, styleAssign, valueChunk);
2568 }
2569 }
2570
2571 if (!isFirst) {
2572 target.push(attributeEnd);
2573 }
2574}
2575
2576var attributeSeparator = stringToPrecomputedChunk(' ');
2577var attributeAssign = stringToPrecomputedChunk('="');
2578var attributeEnd = stringToPrecomputedChunk('"');
2579var attributeEmptyString = stringToPrecomputedChunk('=""');
2580
2581function pushBooleanAttribute(target, name, value) // not null or undefined
2582{
2583 if (value && typeof value !== 'function' && typeof value !== 'symbol') {
2584 target.push(attributeSeparator, stringToChunk(name), attributeEmptyString);
2585 }
2586}
2587
2588function pushStringAttribute(target, name, value) // not null or undefined
2589{
2590 if (typeof value !== 'function' && typeof value !== 'symbol' && typeof value !== 'boolean') {
2591 target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
2592 }
2593}
2594
2595function makeFormFieldPrefix(resumableState) {
2596 var id = resumableState.nextFormID++;
2597 return resumableState.idPrefix + id;
2598} // Since this will likely be repeated a lot in the HTML, we use a more concise message
2599// than on the client and hopefully it's googleable.
2600
2601
2602var actionJavaScriptURL = stringToPrecomputedChunk(escapeTextForBrowser( // eslint-disable-next-line no-script-url
2603"javascript:throw new Error('React form unexpectedly submitted.')"));
2604var startHiddenInputChunk = stringToPrecomputedChunk('<input type="hidden"');
2605
2606function pushAdditionalFormField(value, key) {
2607 var target = this;
2608 target.push(startHiddenInputChunk);
2609
2610 if (typeof value !== 'string') {
2611 throw new Error('File/Blob fields are not yet supported in progressive forms. ' + 'It probably means you are closing over binary data or FormData in a Server Action.');
2612 }
2613
2614 pushStringAttribute(target, 'name', key);
2615 pushStringAttribute(target, 'value', value);
2616 target.push(endOfStartTagSelfClosing);
2617}
2618
2619function pushAdditionalFormFields(target, formData) {
2620 if (formData != null) {
2621 // $FlowFixMe[prop-missing]: FormData has forEach.
2622 formData.forEach(pushAdditionalFormField, target);
2623 }
2624}
2625
2626function getCustomFormFields(resumableState, formAction) {
2627 var customAction = formAction.$$FORM_ACTION;
2628
2629 if (typeof customAction === 'function') {
2630 var prefix = makeFormFieldPrefix(resumableState);
2631
2632 try {
2633 return formAction.$$FORM_ACTION(prefix);
2634 } catch (x) {
2635 if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
2636 // Rethrow suspense.
2637 throw x;
2638 } // If we fail to encode the form action for progressive enhancement for some reason,
2639 // fallback to trying replaying on the client instead of failing the page. It might
2640 // work there.
2641
2642
2643 {
2644 // TODO: Should this be some kind of recoverable error?
2645 error('Failed to serialize an action for progressive enhancement:\n%s', x);
2646 }
2647 }
2648 }
2649
2650 return null;
2651}
2652
2653function pushFormActionAttribute(target, resumableState, renderState, formAction, formEncType, formMethod, formTarget, name) {
2654 var formData = null;
2655
2656 if (typeof formAction === 'function') {
2657 // Function form actions cannot control the form properties
2658 {
2659 if (name !== null && !didWarnFormActionName) {
2660 didWarnFormActionName = true;
2661
2662 error('Cannot specify a "name" prop for a button that specifies a function as a formAction. ' + 'React needs it to encode which action should be invoked. It will get overridden.');
2663 }
2664
2665 if ((formEncType !== null || formMethod !== null) && !didWarnFormActionMethod) {
2666 didWarnFormActionMethod = true;
2667
2668 error('Cannot specify a formEncType or formMethod for a button that specifies a ' + 'function as a formAction. React provides those automatically. They will get overridden.');
2669 }
2670
2671 if (formTarget !== null && !didWarnFormActionTarget) {
2672 didWarnFormActionTarget = true;
2673
2674 error('Cannot specify a formTarget for a button that specifies a function as a formAction. ' + 'The function will always be executed in the same window.');
2675 }
2676 }
2677
2678 var customFields = getCustomFormFields(resumableState, formAction);
2679
2680 if (customFields !== null) {
2681 // This action has a custom progressive enhancement form that can submit the form
2682 // back to the server if it's invoked before hydration. Such as a Server Action.
2683 name = customFields.name;
2684 formAction = customFields.action || '';
2685 formEncType = customFields.encType;
2686 formMethod = customFields.method;
2687 formTarget = customFields.target;
2688 formData = customFields.data;
2689 } else {
2690 // Set a javascript URL that doesn't do anything. We don't expect this to be invoked
2691 // because we'll preventDefault in the Fizz runtime, but it can happen if a form is
2692 // manually submitted or if someone calls stopPropagation before React gets the event.
2693 // If CSP is used to block javascript: URLs that's fine too. It just won't show this
2694 // error message but the URL will be logged.
2695 target.push(attributeSeparator, stringToChunk('formAction'), attributeAssign, actionJavaScriptURL, attributeEnd);
2696 name = null;
2697 formAction = null;
2698 formEncType = null;
2699 formMethod = null;
2700 formTarget = null;
2701 injectFormReplayingRuntime(resumableState, renderState);
2702 }
2703 }
2704
2705 if (name != null) {
2706 pushAttribute(target, 'name', name);
2707 }
2708
2709 if (formAction != null) {
2710 pushAttribute(target, 'formAction', formAction);
2711 }
2712
2713 if (formEncType != null) {
2714 pushAttribute(target, 'formEncType', formEncType);
2715 }
2716
2717 if (formMethod != null) {
2718 pushAttribute(target, 'formMethod', formMethod);
2719 }
2720
2721 if (formTarget != null) {
2722 pushAttribute(target, 'formTarget', formTarget);
2723 }
2724
2725 return formData;
2726}
2727
2728function pushAttribute(target, name, value) // not null or undefined
2729{
2730 switch (name) {
2731 // These are very common props and therefore are in the beginning of the switch.
2732 // TODO: aria-label is a very common prop but allows booleans so is not like the others
2733 // but should ideally go in this list too.
2734 case 'className':
2735 {
2736 pushStringAttribute(target, 'class', value);
2737 break;
2738 }
2739
2740 case 'tabIndex':
2741 {
2742 pushStringAttribute(target, 'tabindex', value);
2743 break;
2744 }
2745
2746 case 'dir':
2747 case 'role':
2748 case 'viewBox':
2749 case 'width':
2750 case 'height':
2751 {
2752 pushStringAttribute(target, name, value);
2753 break;
2754 }
2755
2756 case 'style':
2757 {
2758 pushStyleAttribute(target, value);
2759 return;
2760 }
2761
2762 case 'src':
2763 case 'href':
2764 {
2765 {
2766 if (value === '') {
2767 {
2768 if (name === 'src') {
2769 error('An empty string ("") was passed to the %s attribute. ' + 'This may cause the browser to download the whole page again over the network. ' + 'To fix this, either do not render the element at all ' + 'or pass null to %s instead of an empty string.', name, name);
2770 } else {
2771 error('An empty string ("") was passed to the %s attribute. ' + 'To fix this, either do not render the element at all ' + 'or pass null to %s instead of an empty string.', name, name);
2772 }
2773 }
2774
2775 return;
2776 }
2777 }
2778 }
2779 // Fall through to the last case which shouldn't remove empty strings.
2780
2781 case 'action':
2782 case 'formAction':
2783 {
2784 // TODO: Consider only special casing these for each tag.
2785 if (value == null || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'boolean') {
2786 return;
2787 }
2788
2789 {
2790 checkAttributeStringCoercion(value, name);
2791 }
2792
2793 var sanitizedValue = sanitizeURL('' + value);
2794 target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(sanitizedValue)), attributeEnd);
2795 return;
2796 }
2797
2798 case 'defaultValue':
2799 case 'defaultChecked': // These shouldn't be set as attributes on generic HTML elements.
2800
2801 case 'innerHTML': // Must use dangerouslySetInnerHTML instead.
2802
2803 case 'suppressContentEditableWarning':
2804 case 'suppressHydrationWarning':
2805 case 'ref':
2806 // Ignored. These are built-in to React on the client.
2807 return;
2808
2809 case 'autoFocus':
2810 case 'multiple':
2811 case 'muted':
2812 {
2813 pushBooleanAttribute(target, name.toLowerCase(), value);
2814 return;
2815 }
2816
2817 case 'xlinkHref':
2818 {
2819 if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'boolean') {
2820 return;
2821 }
2822
2823 {
2824 checkAttributeStringCoercion(value, name);
2825 }
2826
2827 var _sanitizedValue = sanitizeURL('' + value);
2828
2829 target.push(attributeSeparator, stringToChunk('xlink:href'), attributeAssign, stringToChunk(escapeTextForBrowser(_sanitizedValue)), attributeEnd);
2830 return;
2831 }
2832
2833 case 'contentEditable':
2834 case 'spellCheck':
2835 case 'draggable':
2836 case 'value':
2837 case 'autoReverse':
2838 case 'externalResourcesRequired':
2839 case 'focusable':
2840 case 'preserveAlpha':
2841 {
2842 // Booleanish String
2843 // These are "enumerated" attributes that accept "true" and "false".
2844 // In React, we let users pass `true` and `false` even though technically
2845 // these aren't boolean attributes (they are coerced to strings).
2846 if (typeof value !== 'function' && typeof value !== 'symbol') {
2847 target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
2848 }
2849
2850 return;
2851 }
2852
2853 case 'inert':
2854 {
2855 {
2856 if (value === '' && !didWarnForNewBooleanPropsWithEmptyValue[name]) {
2857 didWarnForNewBooleanPropsWithEmptyValue[name] = true;
2858
2859 error('Received an empty string for a boolean attribute `%s`. ' + 'This will treat the attribute as if it were false. ' + 'Either pass `false` to silence this warning, or ' + 'pass `true` if you used an empty string in earlier versions of React to indicate this attribute is true.', name);
2860 }
2861 }
2862 }
2863 // Fallthrough for boolean props that don't have a warning for empty strings.
2864
2865 case 'allowFullScreen':
2866 case 'async':
2867 case 'autoPlay':
2868 case 'controls':
2869 case 'default':
2870 case 'defer':
2871 case 'disabled':
2872 case 'disablePictureInPicture':
2873 case 'disableRemotePlayback':
2874 case 'formNoValidate':
2875 case 'hidden':
2876 case 'loop':
2877 case 'noModule':
2878 case 'noValidate':
2879 case 'open':
2880 case 'playsInline':
2881 case 'readOnly':
2882 case 'required':
2883 case 'reversed':
2884 case 'scoped':
2885 case 'seamless':
2886 case 'itemScope':
2887 {
2888 // Boolean
2889 if (value && typeof value !== 'function' && typeof value !== 'symbol') {
2890 target.push(attributeSeparator, stringToChunk(name), attributeEmptyString);
2891 }
2892
2893 return;
2894 }
2895
2896 case 'capture':
2897 case 'download':
2898 {
2899 // Overloaded Boolean
2900 if (value === true) {
2901 target.push(attributeSeparator, stringToChunk(name), attributeEmptyString);
2902 } else if (value === false) ; else if (typeof value !== 'function' && typeof value !== 'symbol') {
2903 target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
2904 }
2905
2906 return;
2907 }
2908
2909 case 'cols':
2910 case 'rows':
2911 case 'size':
2912 case 'span':
2913 {
2914 // These are HTML attributes that must be positive numbers.
2915 if (typeof value !== 'function' && typeof value !== 'symbol' && !isNaN(value) && value >= 1) {
2916 target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
2917 }
2918
2919 return;
2920 }
2921
2922 case 'rowSpan':
2923 case 'start':
2924 {
2925 // These are HTML attributes that must be numbers.
2926 if (typeof value !== 'function' && typeof value !== 'symbol' && !isNaN(value)) {
2927 target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
2928 }
2929
2930 return;
2931 }
2932
2933 case 'xlinkActuate':
2934 pushStringAttribute(target, 'xlink:actuate', value);
2935 return;
2936
2937 case 'xlinkArcrole':
2938 pushStringAttribute(target, 'xlink:arcrole', value);
2939 return;
2940
2941 case 'xlinkRole':
2942 pushStringAttribute(target, 'xlink:role', value);
2943 return;
2944
2945 case 'xlinkShow':
2946 pushStringAttribute(target, 'xlink:show', value);
2947 return;
2948
2949 case 'xlinkTitle':
2950 pushStringAttribute(target, 'xlink:title', value);
2951 return;
2952
2953 case 'xlinkType':
2954 pushStringAttribute(target, 'xlink:type', value);
2955 return;
2956
2957 case 'xmlBase':
2958 pushStringAttribute(target, 'xml:base', value);
2959 return;
2960
2961 case 'xmlLang':
2962 pushStringAttribute(target, 'xml:lang', value);
2963 return;
2964
2965 case 'xmlSpace':
2966 pushStringAttribute(target, 'xml:space', value);
2967 return;
2968
2969 default:
2970 if ( // shouldIgnoreAttribute
2971 // We have already filtered out null/undefined and reserved words.
2972 name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
2973 return;
2974 }
2975
2976 var attributeName = getAttributeAlias(name);
2977
2978 if (isAttributeNameSafe(attributeName)) {
2979 // shouldRemoveAttribute
2980 switch (typeof value) {
2981 case 'function':
2982 case 'symbol':
2983 // eslint-disable-line
2984 return;
2985
2986 case 'boolean':
2987 {
2988 var prefix = attributeName.toLowerCase().slice(0, 5);
2989
2990 if (prefix !== 'data-' && prefix !== 'aria-') {
2991 return;
2992 }
2993 }
2994 }
2995
2996 target.push(attributeSeparator, stringToChunk(attributeName), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
2997 }
2998
2999 }
3000}
3001
3002var endOfStartTag = stringToPrecomputedChunk('>');
3003var endOfStartTagSelfClosing = stringToPrecomputedChunk('/>');
3004
3005function pushInnerHTML(target, innerHTML, children) {
3006 if (innerHTML != null) {
3007 if (children != null) {
3008 throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
3009 }
3010
3011 if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
3012 throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://react.dev/link/dangerously-set-inner-html ' + 'for more information.');
3013 }
3014
3015 var html = innerHTML.__html;
3016
3017 if (html !== null && html !== undefined) {
3018 {
3019 checkHtmlStringCoercion(html);
3020 }
3021
3022 target.push(stringToChunk('' + html));
3023 }
3024 }
3025} // TODO: Move these to RenderState so that we warn for every request.
3026// It would help debugging in stateful servers (e.g. service worker).
3027
3028
3029var didWarnDefaultInputValue = false;
3030var didWarnDefaultChecked = false;
3031var didWarnDefaultSelectValue = false;
3032var didWarnDefaultTextareaValue = false;
3033var didWarnInvalidOptionChildren = false;
3034var didWarnInvalidOptionInnerHTML = false;
3035var didWarnSelectedSetOnOption = false;
3036var didWarnFormActionType = false;
3037var didWarnFormActionName = false;
3038var didWarnFormActionTarget = false;
3039var didWarnFormActionMethod = false;
3040
3041function checkSelectProp(props, propName) {
3042 {
3043 var value = props[propName];
3044
3045 if (value != null) {
3046 var array = isArray(value);
3047
3048 if (props.multiple && !array) {
3049 error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.', propName);
3050 } else if (!props.multiple && array) {
3051 error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.', propName);
3052 }
3053 }
3054 }
3055}
3056
3057function pushStartAnchor(target, props) {
3058 target.push(startChunkForTag('a'));
3059 var children = null;
3060 var innerHTML = null;
3061
3062 for (var propKey in props) {
3063 if (hasOwnProperty.call(props, propKey)) {
3064 var propValue = props[propKey];
3065
3066 if (propValue == null) {
3067 continue;
3068 }
3069
3070 switch (propKey) {
3071 case 'children':
3072 children = propValue;
3073 break;
3074
3075 case 'dangerouslySetInnerHTML':
3076 innerHTML = propValue;
3077 break;
3078
3079 case 'href':
3080 if (propValue === '') {
3081 // Empty `href` is special on anchors so we're short-circuiting here.
3082 // On other tags it should trigger a warning
3083 pushStringAttribute(target, 'href', '');
3084 } else {
3085 pushAttribute(target, propKey, propValue);
3086 }
3087
3088 break;
3089
3090 default:
3091 pushAttribute(target, propKey, propValue);
3092 break;
3093 }
3094 }
3095 }
3096
3097 target.push(endOfStartTag);
3098 pushInnerHTML(target, innerHTML, children);
3099
3100 if (typeof children === 'string') {
3101 // Special case children as a string to avoid the unnecessary comment.
3102 // TODO: Remove this special case after the general optimization is in place.
3103 target.push(stringToChunk(encodeHTMLTextNode(children)));
3104 return null;
3105 }
3106
3107 return children;
3108}
3109
3110function pushStartSelect(target, props) {
3111 {
3112 checkControlledValueProps('select', props);
3113 checkSelectProp(props, 'value');
3114 checkSelectProp(props, 'defaultValue');
3115
3116 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) {
3117 error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://react.dev/link/controlled-components');
3118
3119 didWarnDefaultSelectValue = true;
3120 }
3121 }
3122
3123 target.push(startChunkForTag('select'));
3124 var children = null;
3125 var innerHTML = null;
3126
3127 for (var propKey in props) {
3128 if (hasOwnProperty.call(props, propKey)) {
3129 var propValue = props[propKey];
3130
3131 if (propValue == null) {
3132 continue;
3133 }
3134
3135 switch (propKey) {
3136 case 'children':
3137 children = propValue;
3138 break;
3139
3140 case 'dangerouslySetInnerHTML':
3141 // TODO: This doesn't really make sense for select since it can't use the controlled
3142 // value in the innerHTML.
3143 innerHTML = propValue;
3144 break;
3145
3146 case 'defaultValue':
3147 case 'value':
3148 // These are set on the Context instead and applied to the nested options.
3149 break;
3150
3151 default:
3152 pushAttribute(target, propKey, propValue);
3153 break;
3154 }
3155 }
3156 }
3157
3158 target.push(endOfStartTag);
3159 pushInnerHTML(target, innerHTML, children);
3160 return children;
3161}
3162
3163function flattenOptionChildren(children) {
3164 var content = ''; // Flatten children and warn if they aren't strings or numbers;
3165 // invalid types are ignored.
3166
3167 React.Children.forEach(children, function (child) {
3168 if (child == null) {
3169 return;
3170 }
3171
3172 content += child;
3173
3174 {
3175 if (!didWarnInvalidOptionChildren && typeof child !== 'string' && typeof child !== 'number' && typeof child !== 'bigint') {
3176 didWarnInvalidOptionChildren = true;
3177
3178 error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
3179 }
3180 }
3181 });
3182 return content;
3183}
3184
3185var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""');
3186
3187function pushStartOption(target, props, formatContext) {
3188 var selectedValue = formatContext.selectedValue;
3189 target.push(startChunkForTag('option'));
3190 var children = null;
3191 var value = null;
3192 var selected = null;
3193 var innerHTML = null;
3194
3195 for (var propKey in props) {
3196 if (hasOwnProperty.call(props, propKey)) {
3197 var propValue = props[propKey];
3198
3199 if (propValue == null) {
3200 continue;
3201 }
3202
3203 switch (propKey) {
3204 case 'children':
3205 children = propValue;
3206 break;
3207
3208 case 'selected':
3209 // ignore
3210 selected = propValue;
3211
3212 {
3213 // TODO: Remove support for `selected` in <option>.
3214 if (!didWarnSelectedSetOnOption) {
3215 error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
3216
3217 didWarnSelectedSetOnOption = true;
3218 }
3219 }
3220
3221 break;
3222
3223 case 'dangerouslySetInnerHTML':
3224 innerHTML = propValue;
3225 break;
3226
3227 case 'value':
3228 value = propValue;
3229 // We intentionally fallthrough to also set the attribute on the node.
3230
3231 default:
3232 pushAttribute(target, propKey, propValue);
3233 break;
3234 }
3235 }
3236 }
3237
3238 if (selectedValue != null) {
3239 var stringValue;
3240
3241 if (value !== null) {
3242 {
3243 checkAttributeStringCoercion(value, 'value');
3244 }
3245
3246 stringValue = '' + value;
3247 } else {
3248 {
3249 if (innerHTML !== null) {
3250 if (!didWarnInvalidOptionInnerHTML) {
3251 didWarnInvalidOptionInnerHTML = true;
3252
3253 error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
3254 }
3255 }
3256 }
3257
3258 stringValue = flattenOptionChildren(children);
3259 }
3260
3261 if (isArray(selectedValue)) {
3262 // multiple
3263 for (var i = 0; i < selectedValue.length; i++) {
3264 {
3265 checkAttributeStringCoercion(selectedValue[i], 'value');
3266 }
3267
3268 var v = '' + selectedValue[i];
3269
3270 if (v === stringValue) {
3271 target.push(selectedMarkerAttribute);
3272 break;
3273 }
3274 }
3275 } else {
3276 {
3277 checkAttributeStringCoercion(selectedValue, 'select.value');
3278 }
3279
3280 if ('' + selectedValue === stringValue) {
3281 target.push(selectedMarkerAttribute);
3282 }
3283 }
3284 } else if (selected) {
3285 target.push(selectedMarkerAttribute);
3286 }
3287
3288 target.push(endOfStartTag);
3289 pushInnerHTML(target, innerHTML, children);
3290 return children;
3291}
3292
3293var formReplayingRuntimeScript = stringToPrecomputedChunk(formReplaying);
3294
3295function injectFormReplayingRuntime(resumableState, renderState) {
3296 // If we haven't sent it yet, inject the runtime that tracks submitted JS actions
3297 // for later replaying by Fiber. If we use an external runtime, we don't need
3298 // to emit anything. It's always used.
3299 if ((resumableState.instructions & SentFormReplayingRuntime) === NothingSent && (!enableFizzExternalRuntime )) {
3300 resumableState.instructions |= SentFormReplayingRuntime;
3301 renderState.bootstrapChunks.unshift(renderState.startInlineScript, formReplayingRuntimeScript, endInlineScript);
3302 }
3303}
3304
3305var formStateMarkerIsMatching = stringToPrecomputedChunk('<!--F!-->');
3306var formStateMarkerIsNotMatching = stringToPrecomputedChunk('<!--F-->');
3307function pushFormStateMarkerIsMatching(target) {
3308 target.push(formStateMarkerIsMatching);
3309}
3310function pushFormStateMarkerIsNotMatching(target) {
3311 target.push(formStateMarkerIsNotMatching);
3312}
3313
3314function pushStartForm(target, props, resumableState, renderState) {
3315 target.push(startChunkForTag('form'));
3316 var children = null;
3317 var innerHTML = null;
3318 var formAction = null;
3319 var formEncType = null;
3320 var formMethod = null;
3321 var formTarget = null;
3322
3323 for (var propKey in props) {
3324 if (hasOwnProperty.call(props, propKey)) {
3325 var propValue = props[propKey];
3326
3327 if (propValue == null) {
3328 continue;
3329 }
3330
3331 switch (propKey) {
3332 case 'children':
3333 children = propValue;
3334 break;
3335
3336 case 'dangerouslySetInnerHTML':
3337 innerHTML = propValue;
3338 break;
3339
3340 case 'action':
3341 formAction = propValue;
3342 break;
3343
3344 case 'encType':
3345 formEncType = propValue;
3346 break;
3347
3348 case 'method':
3349 formMethod = propValue;
3350 break;
3351
3352 case 'target':
3353 formTarget = propValue;
3354 break;
3355
3356 default:
3357 pushAttribute(target, propKey, propValue);
3358 break;
3359 }
3360 }
3361 }
3362
3363 var formData = null;
3364 var formActionName = null;
3365
3366 if (typeof formAction === 'function') {
3367 // Function form actions cannot control the form properties
3368 {
3369 if ((formEncType !== null || formMethod !== null) && !didWarnFormActionMethod) {
3370 didWarnFormActionMethod = true;
3371
3372 error('Cannot specify a encType or method for a form that specifies a ' + 'function as the action. React provides those automatically. ' + 'They will get overridden.');
3373 }
3374
3375 if (formTarget !== null && !didWarnFormActionTarget) {
3376 didWarnFormActionTarget = true;
3377
3378 error('Cannot specify a target for a form that specifies a function as the action. ' + 'The function will always be executed in the same window.');
3379 }
3380 }
3381
3382 var customFields = getCustomFormFields(resumableState, formAction);
3383
3384 if (customFields !== null) {
3385 // This action has a custom progressive enhancement form that can submit the form
3386 // back to the server if it's invoked before hydration. Such as a Server Action.
3387 formAction = customFields.action || '';
3388 formEncType = customFields.encType;
3389 formMethod = customFields.method;
3390 formTarget = customFields.target;
3391 formData = customFields.data;
3392 formActionName = customFields.name;
3393 } else {
3394 // Set a javascript URL that doesn't do anything. We don't expect this to be invoked
3395 // because we'll preventDefault in the Fizz runtime, but it can happen if a form is
3396 // manually submitted or if someone calls stopPropagation before React gets the event.
3397 // If CSP is used to block javascript: URLs that's fine too. It just won't show this
3398 // error message but the URL will be logged.
3399 target.push(attributeSeparator, stringToChunk('action'), attributeAssign, actionJavaScriptURL, attributeEnd);
3400 formAction = null;
3401 formEncType = null;
3402 formMethod = null;
3403 formTarget = null;
3404 injectFormReplayingRuntime(resumableState, renderState);
3405 }
3406 }
3407
3408 if (formAction != null) {
3409 pushAttribute(target, 'action', formAction);
3410 }
3411
3412 if (formEncType != null) {
3413 pushAttribute(target, 'encType', formEncType);
3414 }
3415
3416 if (formMethod != null) {
3417 pushAttribute(target, 'method', formMethod);
3418 }
3419
3420 if (formTarget != null) {
3421 pushAttribute(target, 'target', formTarget);
3422 }
3423
3424 target.push(endOfStartTag);
3425
3426 if (formActionName !== null) {
3427 target.push(startHiddenInputChunk);
3428 pushStringAttribute(target, 'name', formActionName);
3429 target.push(endOfStartTagSelfClosing);
3430 pushAdditionalFormFields(target, formData);
3431 }
3432
3433 pushInnerHTML(target, innerHTML, children);
3434
3435 if (typeof children === 'string') {
3436 // Special case children as a string to avoid the unnecessary comment.
3437 // TODO: Remove this special case after the general optimization is in place.
3438 target.push(stringToChunk(encodeHTMLTextNode(children)));
3439 return null;
3440 }
3441
3442 return children;
3443}
3444
3445function pushInput(target, props, resumableState, renderState) {
3446 {
3447 checkControlledValueProps('input', props);
3448 }
3449
3450 target.push(startChunkForTag('input'));
3451 var name = null;
3452 var formAction = null;
3453 var formEncType = null;
3454 var formMethod = null;
3455 var formTarget = null;
3456 var value = null;
3457 var defaultValue = null;
3458 var checked = null;
3459 var defaultChecked = null;
3460
3461 for (var propKey in props) {
3462 if (hasOwnProperty.call(props, propKey)) {
3463 var propValue = props[propKey];
3464
3465 if (propValue == null) {
3466 continue;
3467 }
3468
3469 switch (propKey) {
3470 case 'children':
3471 case 'dangerouslySetInnerHTML':
3472 throw new Error('input' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
3473
3474 case 'name':
3475 name = propValue;
3476 break;
3477
3478 case 'formAction':
3479 formAction = propValue;
3480 break;
3481
3482 case 'formEncType':
3483 formEncType = propValue;
3484 break;
3485
3486 case 'formMethod':
3487 formMethod = propValue;
3488 break;
3489
3490 case 'formTarget':
3491 formTarget = propValue;
3492 break;
3493
3494 case 'defaultChecked':
3495 defaultChecked = propValue;
3496 break;
3497
3498 case 'defaultValue':
3499 defaultValue = propValue;
3500 break;
3501
3502 case 'checked':
3503 checked = propValue;
3504 break;
3505
3506 case 'value':
3507 value = propValue;
3508 break;
3509
3510 default:
3511 pushAttribute(target, propKey, propValue);
3512 break;
3513 }
3514 }
3515 }
3516
3517 {
3518 if (formAction !== null && props.type !== 'image' && props.type !== 'submit' && !didWarnFormActionType) {
3519 didWarnFormActionType = true;
3520
3521 error('An input can only specify a formAction along with type="submit" or type="image".');
3522 }
3523 }
3524
3525 var formData = pushFormActionAttribute(target, resumableState, renderState, formAction, formEncType, formMethod, formTarget, name);
3526
3527 {
3528 if (checked !== null && defaultChecked !== null && !didWarnDefaultChecked) {
3529 error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://react.dev/link/controlled-components', 'A component', props.type);
3530
3531 didWarnDefaultChecked = true;
3532 }
3533
3534 if (value !== null && defaultValue !== null && !didWarnDefaultInputValue) {
3535 error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://react.dev/link/controlled-components', 'A component', props.type);
3536
3537 didWarnDefaultInputValue = true;
3538 }
3539 }
3540
3541 if (checked !== null) {
3542 pushBooleanAttribute(target, 'checked', checked);
3543 } else if (defaultChecked !== null) {
3544 pushBooleanAttribute(target, 'checked', defaultChecked);
3545 }
3546
3547 if (value !== null) {
3548 pushAttribute(target, 'value', value);
3549 } else if (defaultValue !== null) {
3550 pushAttribute(target, 'value', defaultValue);
3551 }
3552
3553 target.push(endOfStartTagSelfClosing); // We place any additional hidden form fields after the input.
3554
3555 pushAdditionalFormFields(target, formData);
3556 return null;
3557}
3558
3559function pushStartButton(target, props, resumableState, renderState) {
3560 target.push(startChunkForTag('button'));
3561 var children = null;
3562 var innerHTML = null;
3563 var name = null;
3564 var formAction = null;
3565 var formEncType = null;
3566 var formMethod = null;
3567 var formTarget = null;
3568
3569 for (var propKey in props) {
3570 if (hasOwnProperty.call(props, propKey)) {
3571 var propValue = props[propKey];
3572
3573 if (propValue == null) {
3574 continue;
3575 }
3576
3577 switch (propKey) {
3578 case 'children':
3579 children = propValue;
3580 break;
3581
3582 case 'dangerouslySetInnerHTML':
3583 innerHTML = propValue;
3584 break;
3585
3586 case 'name':
3587 name = propValue;
3588 break;
3589
3590 case 'formAction':
3591 formAction = propValue;
3592 break;
3593
3594 case 'formEncType':
3595 formEncType = propValue;
3596 break;
3597
3598 case 'formMethod':
3599 formMethod = propValue;
3600 break;
3601
3602 case 'formTarget':
3603 formTarget = propValue;
3604 break;
3605
3606 default:
3607 pushAttribute(target, propKey, propValue);
3608 break;
3609 }
3610 }
3611 }
3612
3613 {
3614 if (formAction !== null && props.type != null && props.type !== 'submit' && !didWarnFormActionType) {
3615 didWarnFormActionType = true;
3616
3617 error('A button can only specify a formAction along with type="submit" or no type.');
3618 }
3619 }
3620
3621 var formData = pushFormActionAttribute(target, resumableState, renderState, formAction, formEncType, formMethod, formTarget, name);
3622 target.push(endOfStartTag); // We place any additional hidden form fields we need to include inside the button itself.
3623
3624 pushAdditionalFormFields(target, formData);
3625 pushInnerHTML(target, innerHTML, children);
3626
3627 if (typeof children === 'string') {
3628 // Special case children as a string to avoid the unnecessary comment.
3629 // TODO: Remove this special case after the general optimization is in place.
3630 target.push(stringToChunk(encodeHTMLTextNode(children)));
3631 return null;
3632 }
3633
3634 return children;
3635}
3636
3637function pushStartTextArea(target, props) {
3638 {
3639 checkControlledValueProps('textarea', props);
3640
3641 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) {
3642 error('Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://react.dev/link/controlled-components');
3643
3644 didWarnDefaultTextareaValue = true;
3645 }
3646 }
3647
3648 target.push(startChunkForTag('textarea'));
3649 var value = null;
3650 var defaultValue = null;
3651 var children = null;
3652
3653 for (var propKey in props) {
3654 if (hasOwnProperty.call(props, propKey)) {
3655 var propValue = props[propKey];
3656
3657 if (propValue == null) {
3658 continue;
3659 }
3660
3661 switch (propKey) {
3662 case 'children':
3663 children = propValue;
3664 break;
3665
3666 case 'value':
3667 value = propValue;
3668 break;
3669
3670 case 'defaultValue':
3671 defaultValue = propValue;
3672 break;
3673
3674 case 'dangerouslySetInnerHTML':
3675 throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
3676
3677 default:
3678 pushAttribute(target, propKey, propValue);
3679 break;
3680 }
3681 }
3682 }
3683
3684 if (value === null && defaultValue !== null) {
3685 value = defaultValue;
3686 }
3687
3688 target.push(endOfStartTag); // TODO (yungsters): Remove support for children content in <textarea>.
3689
3690 if (children != null) {
3691 {
3692 error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
3693 }
3694
3695 if (value != null) {
3696 throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
3697 }
3698
3699 if (isArray(children)) {
3700 if (children.length > 1) {
3701 throw new Error('<textarea> can only have at most one child.');
3702 } // TODO: remove the coercion and the DEV check below because it will
3703 // always be overwritten by the coercion several lines below it. #22309
3704
3705
3706 {
3707 checkHtmlStringCoercion(children[0]);
3708 }
3709
3710 value = '' + children[0];
3711 }
3712
3713 {
3714 checkHtmlStringCoercion(children);
3715 }
3716
3717 value = '' + children;
3718 }
3719
3720 if (typeof value === 'string' && value[0] === '\n') {
3721 // text/html ignores the first character in these tags if it's a newline
3722 // Prefer to break application/xml over text/html (for now) by adding
3723 // a newline specifically to get eaten by the parser. (Alternately for
3724 // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
3725 // \r is normalized out by HTMLTextAreaElement#value.)
3726 // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
3727 // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
3728 // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
3729 // See: Parsing of "textarea" "listing" and "pre" elements
3730 // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
3731 target.push(leadingNewline);
3732 } // ToString and push directly instead of recurse over children.
3733 // We don't really support complex children in the value anyway.
3734 // This also currently avoids a trailing comment node which breaks textarea.
3735
3736
3737 if (value !== null) {
3738 {
3739 checkAttributeStringCoercion(value, 'value');
3740 }
3741
3742 target.push(stringToChunk(encodeHTMLTextNode('' + value)));
3743 }
3744
3745 return null;
3746}
3747
3748function pushMeta(target, props, renderState, textEmbedded, insertionMode, noscriptTagInScope, isFallback) {
3749 if (insertionMode === SVG_MODE || noscriptTagInScope || props.itemProp != null) {
3750 return pushSelfClosing(target, props, 'meta');
3751 } else {
3752 if (textEmbedded) {
3753 // This link follows text but we aren't writing a tag. while not as efficient as possible we need
3754 // to be safe and assume text will follow by inserting a textSeparator
3755 target.push(textSeparator);
3756 }
3757
3758 if (isFallback) {
3759 // Hoistable Elements for fallbacks are simply omitted. we don't want to emit them early
3760 // because they are likely superceded by primary content and we want to avoid needing to clean
3761 // them up when the primary content is ready. They are never hydrated on the client anyway because
3762 // boundaries in fallback are awaited or client render, in either case there is never hydration
3763 return null;
3764 } else if (typeof props.charSet === 'string') {
3765 // "charset" Should really be config and not picked up from tags however since this is
3766 // the only way to embed the tag today we flush it on a special queue on the Request so it
3767 // can go before everything else. Like viewport this means that the tag will escape it's
3768 // parent container.
3769 return pushSelfClosing(renderState.charsetChunks, props, 'meta');
3770 } else if (props.name === 'viewport') {
3771 // "viewport" is flushed on the Request so it can go earlier that Float resources that
3772 // might be affected by it. This means it can escape the boundary it is rendered within.
3773 // This is a pragmatic solution to viewport being incredibly sensitive to document order
3774 // without requiring all hoistables to be flushed too early.
3775 return pushSelfClosing(renderState.viewportChunks, props, 'meta');
3776 } else {
3777 return pushSelfClosing(renderState.hoistableChunks, props, 'meta');
3778 }
3779 }
3780}
3781
3782function pushLink(target, props, resumableState, renderState, hoistableState, textEmbedded, insertionMode, noscriptTagInScope, isFallback) {
3783 var rel = props.rel;
3784 var href = props.href;
3785 var precedence = props.precedence;
3786
3787 if (insertionMode === SVG_MODE || noscriptTagInScope || props.itemProp != null || typeof rel !== 'string' || typeof href !== 'string' || href === '') {
3788 {
3789 if (rel === 'stylesheet' && typeof props.precedence === 'string') {
3790 if (typeof href !== 'string' || !href) {
3791 error('React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and expected the `href` prop to be a non-empty string but ecountered %s instead. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop ensure there is a non-empty string `href` prop as well, otherwise remove the `precedence` prop.', getValueDescriptorExpectingObjectForWarning(href));
3792 }
3793 }
3794 }
3795
3796 pushLinkImpl(target, props);
3797 return null;
3798 }
3799
3800 if (props.rel === 'stylesheet') {
3801 // This <link> may hoistable as a Stylesheet Resource, otherwise it will emit in place
3802 var key = getResourceKey(href);
3803
3804 if (typeof precedence !== 'string' || props.disabled != null || props.onLoad || props.onError) {
3805 // This stylesheet is either not opted into Resource semantics or has conflicting properties which
3806 // disqualify it for such. We can still create a preload resource to help it load faster on the
3807 // client
3808 {
3809 if (typeof precedence === 'string') {
3810 if (props.disabled != null) {
3811 error('React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and a `disabled` prop. The presence of the `disabled` prop indicates an intent to manage the stylesheet active state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the `disabled` prop, otherwise remove the `precedence` prop.');
3812 } else if (props.onLoad || props.onError) {
3813 var propDescription = props.onLoad && props.onError ? '`onLoad` and `onError` props' : props.onLoad ? '`onLoad` prop' : '`onError` prop';
3814
3815 error('React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and %s. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the %s, otherwise remove the `precedence` prop.', propDescription, propDescription);
3816 }
3817 }
3818 }
3819
3820 return pushLinkImpl(target, props);
3821 } else {
3822 // This stylesheet refers to a Resource and we create a new one if necessary
3823 var styleQueue = renderState.styles.get(precedence);
3824 var hasKey = resumableState.styleResources.hasOwnProperty(key);
3825 var resourceState = hasKey ? resumableState.styleResources[key] : undefined;
3826
3827 if (resourceState !== EXISTS) {
3828 // We are going to create this resource now so it is marked as Exists
3829 resumableState.styleResources[key] = EXISTS; // If this is the first time we've encountered this precedence we need
3830 // to create a StyleQueue
3831
3832 if (!styleQueue) {
3833 styleQueue = {
3834 precedence: stringToChunk(escapeTextForBrowser(precedence)),
3835 rules: [],
3836 hrefs: [],
3837 sheets: new Map()
3838 };
3839 renderState.styles.set(precedence, styleQueue);
3840 }
3841
3842 var resource = {
3843 state: PENDING$1,
3844 props: stylesheetPropsFromRawProps(props)
3845 };
3846
3847 if (resourceState) {
3848 // When resourceState is truty it is a Preload state. We cast it for clarity
3849 var preloadState = resourceState;
3850
3851 if (preloadState.length === 2) {
3852 adoptPreloadCredentials(resource.props, preloadState);
3853 }
3854
3855 var preloadResource = renderState.preloads.stylesheets.get(key);
3856
3857 if (preloadResource && preloadResource.length > 0) {
3858 // The Preload for this resource was created in this render pass and has not flushed yet so
3859 // we need to clear it to avoid it flushing.
3860 preloadResource.length = 0;
3861 } else {
3862 // Either the preload resource from this render already flushed in this render pass
3863 // or the preload flushed in a prior pass (prerender). In either case we need to mark
3864 // this resource as already having been preloaded.
3865 resource.state = PRELOADED;
3866 }
3867 } // We add the newly created resource to our StyleQueue and if necessary
3868 // track the resource with the currently rendering boundary
3869
3870
3871 styleQueue.sheets.set(key, resource);
3872
3873 if (hoistableState) {
3874 hoistableState.stylesheets.add(resource);
3875 }
3876 } else {
3877 // We need to track whether this boundary should wait on this resource or not.
3878 // Typically this resource should always exist since we either had it or just created
3879 // it. However, it's possible when you resume that the style has already been emitted
3880 // and then it wouldn't be recreated in the RenderState and there's no need to track
3881 // it again since we should've hoisted it to the shell already.
3882 if (styleQueue) {
3883 var _resource = styleQueue.sheets.get(key);
3884
3885 if (_resource) {
3886 if (hoistableState) {
3887 hoistableState.stylesheets.add(_resource);
3888 }
3889 }
3890 }
3891 }
3892
3893 if (textEmbedded) {
3894 // This link follows text but we aren't writing a tag. while not as efficient as possible we need
3895 // to be safe and assume text will follow by inserting a textSeparator
3896 target.push(textSeparator);
3897 }
3898
3899 return null;
3900 }
3901 } else if (props.onLoad || props.onError) {
3902 // When using load handlers we cannot hoist and need to emit links in place
3903 return pushLinkImpl(target, props);
3904 } else {
3905 // We can hoist this link so we may need to emit a text separator.
3906 // @TODO refactor text separators so we don't have to defensively add
3907 // them when we don't end up emitting a tag as a result of pushStartInstance
3908 if (textEmbedded) {
3909 // This link follows text but we aren't writing a tag. while not as efficient as possible we need
3910 // to be safe and assume text will follow by inserting a textSeparator
3911 target.push(textSeparator);
3912 }
3913
3914 if (isFallback) {
3915 // Hoistable Elements for fallbacks are simply omitted. we don't want to emit them early
3916 // because they are likely superceded by primary content and we want to avoid needing to clean
3917 // them up when the primary content is ready. They are never hydrated on the client anyway because
3918 // boundaries in fallback are awaited or client render, in either case there is never hydration
3919 return null;
3920 } else {
3921 return pushLinkImpl(renderState.hoistableChunks, props);
3922 }
3923 }
3924}
3925
3926function pushLinkImpl(target, props) {
3927 target.push(startChunkForTag('link'));
3928
3929 for (var propKey in props) {
3930 if (hasOwnProperty.call(props, propKey)) {
3931 var propValue = props[propKey];
3932
3933 if (propValue == null) {
3934 continue;
3935 }
3936
3937 switch (propKey) {
3938 case 'children':
3939 case 'dangerouslySetInnerHTML':
3940 throw new Error('link' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
3941
3942 default:
3943 pushAttribute(target, propKey, propValue);
3944 break;
3945 }
3946 }
3947 }
3948
3949 target.push(endOfStartTagSelfClosing);
3950 return null;
3951}
3952
3953function pushStyle(target, props, resumableState, renderState, hoistableState, textEmbedded, insertionMode, noscriptTagInScope) {
3954 {
3955 if (hasOwnProperty.call(props, 'children')) {
3956 var children = props.children;
3957 var child = Array.isArray(children) ? children.length < 2 ? children[0] : null : children;
3958
3959 if (typeof child === 'function' || typeof child === 'symbol' || Array.isArray(child)) {
3960 var childType = typeof child === 'function' ? 'a Function' : typeof child === 'symbol' ? 'a Sybmol' : 'an Array';
3961
3962 error('React expect children of <style> tags to be a string, number, or object with a `toString` method but found %s instead. ' + 'In browsers style Elements can only have `Text` Nodes as children.', childType);
3963 }
3964 }
3965 }
3966
3967 var precedence = props.precedence;
3968 var href = props.href;
3969
3970 if (insertionMode === SVG_MODE || noscriptTagInScope || props.itemProp != null || typeof precedence !== 'string' || typeof href !== 'string' || href === '') {
3971 // This style tag is not able to be turned into a Style Resource
3972 return pushStyleImpl(target, props);
3973 }
3974
3975 {
3976 if (href.includes(' ')) {
3977 error('React expected the `href` prop for a <style> tag opting into hoisting semantics using the `precedence` prop to not have any spaces but ecountered spaces instead. using spaces in this prop will cause hydration of this style to fail on the client. The href for the <style> where this ocurred is "%s".', href);
3978 }
3979 }
3980
3981 var key = getResourceKey(href);
3982 var styleQueue = renderState.styles.get(precedence);
3983 var hasKey = resumableState.styleResources.hasOwnProperty(key);
3984 var resourceState = hasKey ? resumableState.styleResources[key] : undefined;
3985
3986 if (resourceState !== EXISTS) {
3987 // We are going to create this resource now so it is marked as Exists
3988 resumableState.styleResources[key] = EXISTS;
3989
3990 {
3991 if (resourceState) {
3992 error('React encountered a hoistable style tag for the same href as a preload: "%s". When using a style tag to inline styles you should not also preload it as a stylsheet.', href);
3993 }
3994 }
3995
3996 if (!styleQueue) {
3997 // This is the first time we've encountered this precedence we need
3998 // to create a StyleQueue.
3999 styleQueue = {
4000 precedence: stringToChunk(escapeTextForBrowser(precedence)),
4001 rules: [],
4002 hrefs: [stringToChunk(escapeTextForBrowser(href))],
4003 sheets: new Map()
4004 };
4005 renderState.styles.set(precedence, styleQueue);
4006 } else {
4007 // We have seen this precedence before and need to track this href
4008 styleQueue.hrefs.push(stringToChunk(escapeTextForBrowser(href)));
4009 }
4010
4011 pushStyleContents(styleQueue.rules, props);
4012 }
4013
4014 if (styleQueue) {
4015 // We need to track whether this boundary should wait on this resource or not.
4016 // Typically this resource should always exist since we either had it or just created
4017 // it. However, it's possible when you resume that the style has already been emitted
4018 // and then it wouldn't be recreated in the RenderState and there's no need to track
4019 // it again since we should've hoisted it to the shell already.
4020 if (hoistableState) {
4021 hoistableState.styles.add(styleQueue);
4022 }
4023 }
4024
4025 if (textEmbedded) {
4026 // This link follows text but we aren't writing a tag. while not as efficient as possible we need
4027 // to be safe and assume text will follow by inserting a textSeparator
4028 target.push(textSeparator);
4029 }
4030}
4031/**
4032 * This escaping function is designed to work with style tag textContent only.
4033 *
4034 * While untrusted style content should be made safe before using this api it will
4035 * ensure that the style cannot be early terminated or never terminated state
4036 */
4037
4038
4039function escapeStyleTextContent(styleText) {
4040 {
4041 checkHtmlStringCoercion(styleText);
4042 }
4043
4044 return ('' + styleText).replace(styleRegex, styleReplacer);
4045}
4046
4047var styleRegex = /(<\/|<)(s)(tyle)/gi;
4048
4049var styleReplacer = function (match, prefix, s, suffix) {
4050 return "" + prefix + (s === 's' ? '\\73 ' : '\\53 ') + suffix;
4051};
4052
4053function pushStyleImpl(target, props) {
4054 target.push(startChunkForTag('style'));
4055 var children = null;
4056 var innerHTML = null;
4057
4058 for (var propKey in props) {
4059 if (hasOwnProperty.call(props, propKey)) {
4060 var propValue = props[propKey];
4061
4062 if (propValue == null) {
4063 continue;
4064 }
4065
4066 switch (propKey) {
4067 case 'children':
4068 children = propValue;
4069 break;
4070
4071 case 'dangerouslySetInnerHTML':
4072 innerHTML = propValue;
4073 break;
4074
4075 default:
4076 pushAttribute(target, propKey, propValue);
4077 break;
4078 }
4079 }
4080 }
4081
4082 target.push(endOfStartTag);
4083 var child = Array.isArray(children) ? children.length < 2 ? children[0] : null : children;
4084
4085 if (typeof child !== 'function' && typeof child !== 'symbol' && child !== null && child !== undefined) {
4086 // eslint-disable-next-line react-internal/safe-string-coercion
4087 target.push(stringToChunk(escapeStyleTextContent(child)));
4088 }
4089
4090 pushInnerHTML(target, innerHTML, children);
4091 target.push(endChunkForTag('style'));
4092 return null;
4093}
4094
4095function pushStyleContents(target, props) {
4096 var children = null;
4097 var innerHTML = null;
4098
4099 for (var propKey in props) {
4100 if (hasOwnProperty.call(props, propKey)) {
4101 var propValue = props[propKey];
4102
4103 if (propValue == null) {
4104 continue;
4105 }
4106
4107 switch (propKey) {
4108 case 'children':
4109 children = propValue;
4110 break;
4111
4112 case 'dangerouslySetInnerHTML':
4113 innerHTML = propValue;
4114 break;
4115 }
4116 }
4117 }
4118
4119 var child = Array.isArray(children) ? children.length < 2 ? children[0] : null : children;
4120
4121 if (typeof child !== 'function' && typeof child !== 'symbol' && child !== null && child !== undefined) {
4122 // eslint-disable-next-line react-internal/safe-string-coercion
4123 target.push(stringToChunk(escapeStyleTextContent(child)));
4124 }
4125
4126 pushInnerHTML(target, innerHTML, children);
4127 return;
4128}
4129
4130function pushImg(target, props, resumableState, renderState, pictureOrNoScriptTagInScope) {
4131 var src = props.src,
4132 srcSet = props.srcSet;
4133
4134 if (props.loading !== 'lazy' && (src || srcSet) && (typeof src === 'string' || src == null) && (typeof srcSet === 'string' || srcSet == null) && props.fetchPriority !== 'low' && pictureOrNoScriptTagInScope === false && // We exclude data URIs in src and srcSet since these should not be preloaded
4135 !(typeof src === 'string' && src[4] === ':' && (src[0] === 'd' || src[0] === 'D') && (src[1] === 'a' || src[1] === 'A') && (src[2] === 't' || src[2] === 'T') && (src[3] === 'a' || src[3] === 'A')) && !(typeof srcSet === 'string' && srcSet[4] === ':' && (srcSet[0] === 'd' || srcSet[0] === 'D') && (srcSet[1] === 'a' || srcSet[1] === 'A') && (srcSet[2] === 't' || srcSet[2] === 'T') && (srcSet[3] === 'a' || srcSet[3] === 'A'))) {
4136 // We have a suspensey image and ought to preload it to optimize the loading of display blocking
4137 // resumableState.
4138 var sizes = typeof props.sizes === 'string' ? props.sizes : undefined;
4139 var key = getImageResourceKey(src, srcSet, sizes);
4140 var promotablePreloads = renderState.preloads.images;
4141 var resource = promotablePreloads.get(key);
4142
4143 if (resource) {
4144 // We consider whether this preload can be promoted to higher priority flushing queue.
4145 // The only time a resource will exist here is if it was created during this render
4146 // and was not already in the high priority queue.
4147 if (props.fetchPriority === 'high' || renderState.highImagePreloads.size < 10) {
4148 // Delete the resource from the map since we are promoting it and don't want to
4149 // reenter this branch in a second pass for duplicate img hrefs.
4150 promotablePreloads.delete(key); // $FlowFixMe - Flow should understand that this is a Resource if the condition was true
4151
4152 renderState.highImagePreloads.add(resource);
4153 }
4154 } else if (!resumableState.imageResources.hasOwnProperty(key)) {
4155 // We must construct a new preload resource
4156 resumableState.imageResources[key] = PRELOAD_NO_CREDS;
4157 var crossOrigin = getCrossOriginString(props.crossOrigin);
4158 var headers = renderState.headers;
4159 var header;
4160
4161 if (headers && headers.remainingCapacity > 0 && ( // this is a hueristic similar to capping element preloads to 10 unless explicitly
4162 // fetchPriority="high". We use length here which means it will fit fewer images when
4163 // the urls are long and more when short. arguably byte size is a better hueristic because
4164 // it directly translates to how much we send down before content is actually seen.
4165 // We could unify the counts and also make it so the total is tracked regardless of
4166 // flushing output but since the headers are likely to be go earlier than content
4167 // they don't really conflict so for now I've kept them separate
4168 props.fetchPriority === 'high' || headers.highImagePreloads.length < 500) && ( // We manually construct the options for the preload only from strings. We don't want to pollute
4169 // the params list with arbitrary props and if we copied everything over as it we might get
4170 // coercion errors. We have checks for this in Dev but it seems safer to just only accept values
4171 // that are strings
4172 header = getPreloadAsHeader(src, 'image', {
4173 imageSrcSet: props.srcSet,
4174 imageSizes: props.sizes,
4175 crossOrigin: crossOrigin,
4176 integrity: props.integrity,
4177 nonce: props.nonce,
4178 type: props.type,
4179 fetchPriority: props.fetchPriority,
4180 referrerPolicy: props.refererPolicy
4181 }), // We always consume the header length since once we find one header that doesn't fit
4182 // we assume all the rest won't as well. This is to avoid getting into a situation
4183 // where we have a very small remaining capacity but no headers will ever fit and we end
4184 // up constantly trying to see if the next resource might make it. In the future we can
4185 // make this behavior different between render and prerender since in the latter case
4186 // we are less sensitive to the current requests runtime per and more sensitive to maximizing
4187 // headers.
4188 (headers.remainingCapacity -= header.length) >= 2)) {
4189 // If we postpone in the shell we will still emit this preload so we track
4190 // it to make sure we don't reset it.
4191 renderState.resets.image[key] = PRELOAD_NO_CREDS;
4192
4193 if (headers.highImagePreloads) {
4194 headers.highImagePreloads += ', ';
4195 } // $FlowFixMe[unsafe-addition]: we assign header during the if condition
4196
4197
4198 headers.highImagePreloads += header;
4199 } else {
4200 resource = [];
4201 pushLinkImpl(resource, {
4202 rel: 'preload',
4203 as: 'image',
4204 // There is a bug in Safari where imageSrcSet is not respected on preload links
4205 // so we omit the href here if we have imageSrcSet b/c safari will load the wrong image.
4206 // This harms older browers that do not support imageSrcSet by making their preloads not work
4207 // but this population is shrinking fast and is already small so we accept this tradeoff.
4208 href: srcSet ? undefined : src,
4209 imageSrcSet: srcSet,
4210 imageSizes: sizes,
4211 crossOrigin: crossOrigin,
4212 integrity: props.integrity,
4213 type: props.type,
4214 fetchPriority: props.fetchPriority,
4215 referrerPolicy: props.referrerPolicy
4216 });
4217
4218 if (props.fetchPriority === 'high' || renderState.highImagePreloads.size < 10) {
4219 renderState.highImagePreloads.add(resource);
4220 } else {
4221 renderState.bulkPreloads.add(resource); // We can bump the priority up if the same img is rendered later
4222 // with fetchPriority="high"
4223
4224 promotablePreloads.set(key, resource);
4225 }
4226 }
4227 }
4228 }
4229
4230 return pushSelfClosing(target, props, 'img');
4231}
4232
4233function pushSelfClosing(target, props, tag) {
4234 target.push(startChunkForTag(tag));
4235
4236 for (var propKey in props) {
4237 if (hasOwnProperty.call(props, propKey)) {
4238 var propValue = props[propKey];
4239
4240 if (propValue == null) {
4241 continue;
4242 }
4243
4244 switch (propKey) {
4245 case 'children':
4246 case 'dangerouslySetInnerHTML':
4247 throw new Error(tag + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
4248
4249 default:
4250 pushAttribute(target, propKey, propValue);
4251 break;
4252 }
4253 }
4254 }
4255
4256 target.push(endOfStartTagSelfClosing);
4257 return null;
4258}
4259
4260function pushStartMenuItem(target, props) {
4261 target.push(startChunkForTag('menuitem'));
4262
4263 for (var propKey in props) {
4264 if (hasOwnProperty.call(props, propKey)) {
4265 var propValue = props[propKey];
4266
4267 if (propValue == null) {
4268 continue;
4269 }
4270
4271 switch (propKey) {
4272 case 'children':
4273 case 'dangerouslySetInnerHTML':
4274 throw new Error('menuitems cannot have `children` nor `dangerouslySetInnerHTML`.');
4275
4276 default:
4277 pushAttribute(target, propKey, propValue);
4278 break;
4279 }
4280 }
4281 }
4282
4283 target.push(endOfStartTag);
4284 return null;
4285}
4286
4287function pushTitle(target, props, renderState, insertionMode, noscriptTagInScope, isFallback) {
4288 {
4289 if (hasOwnProperty.call(props, 'children')) {
4290 var children = props.children;
4291 var child = Array.isArray(children) ? children.length < 2 ? children[0] : null : children;
4292
4293 if (Array.isArray(children) && children.length > 1) {
4294 error('React expects the `children` prop of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found an Array with length %s instead.' + ' Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert `children` of <title> tags to a single string value' + ' which is why Arrays of length greater than 1 are not supported. When using JSX it can be commong to combine text nodes and value nodes.' + ' For example: <title>hello {nameOfUser}</title>. While not immediately apparent, `children` in this case is an Array with length 2. If your `children` prop' + ' is using this form try rewriting it using a template string: <title>{`hello ${nameOfUser}`}</title>.', children.length);
4295 } else if (typeof child === 'function' || typeof child === 'symbol') {
4296 var childType = typeof child === 'function' ? 'a Function' : 'a Sybmol';
4297
4298 error('React expect children of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found %s instead.' + ' Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert children of <title>' + ' tags to a single string value.', childType);
4299 } else if (child && child.toString === {}.toString) {
4300 if (child.$$typeof != null) {
4301 error('React expects the `children` prop of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found an object that appears to be' + ' a React element which never implements a suitable `toString` method. Browsers treat all child Nodes of <title> tags as Text content and React expects to' + ' be able to convert children of <title> tags to a single string value which is why rendering React elements is not supported. If the `children` of <title> is' + ' a React Component try moving the <title> tag into that component. If the `children` of <title> is some HTML markup change it to be Text only to be valid HTML.');
4302 } else {
4303 error('React expects the `children` prop of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found an object that does not implement' + ' a suitable `toString` method. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert children of <title> tags' + ' to a single string value. Using the default `toString` method available on every object is almost certainly an error. Consider whether the `children` of this <title>' + ' is an object in error and change it to a string or number value if so. Otherwise implement a `toString` method that React can use to produce a valid <title>.');
4304 }
4305 }
4306 }
4307 }
4308
4309 if (insertionMode !== SVG_MODE && !noscriptTagInScope && props.itemProp == null) {
4310 if (isFallback) {
4311 // Hoistable Elements for fallbacks are simply omitted. we don't want to emit them early
4312 // because they are likely superceded by primary content and we want to avoid needing to clean
4313 // them up when the primary content is ready. They are never hydrated on the client anyway because
4314 // boundaries in fallback are awaited or client render, in either case there is never hydration
4315 return null;
4316 } else {
4317 pushTitleImpl(renderState.hoistableChunks, props);
4318 }
4319 } else {
4320 return pushTitleImpl(target, props);
4321 }
4322}
4323
4324function pushTitleImpl(target, props) {
4325 target.push(startChunkForTag('title'));
4326 var children = null;
4327 var innerHTML = null;
4328
4329 for (var propKey in props) {
4330 if (hasOwnProperty.call(props, propKey)) {
4331 var propValue = props[propKey];
4332
4333 if (propValue == null) {
4334 continue;
4335 }
4336
4337 switch (propKey) {
4338 case 'children':
4339 children = propValue;
4340 break;
4341
4342 case 'dangerouslySetInnerHTML':
4343 innerHTML = propValue;
4344 break;
4345
4346 default:
4347 pushAttribute(target, propKey, propValue);
4348 break;
4349 }
4350 }
4351 }
4352
4353 target.push(endOfStartTag);
4354 var child = Array.isArray(children) ? children.length < 2 ? children[0] : null : children;
4355
4356 if (typeof child !== 'function' && typeof child !== 'symbol' && child !== null && child !== undefined) {
4357 // eslint-disable-next-line react-internal/safe-string-coercion
4358 target.push(stringToChunk(escapeTextForBrowser('' + child)));
4359 }
4360
4361 pushInnerHTML(target, innerHTML, children);
4362 target.push(endChunkForTag('title'));
4363 return null;
4364}
4365
4366function pushStartHead(target, props, renderState, insertionMode) {
4367 if (insertionMode < HTML_MODE && renderState.headChunks === null) {
4368 // This <head> is the Document.head and should be part of the preamble
4369 renderState.headChunks = [];
4370 return pushStartGenericElement(renderState.headChunks, props, 'head');
4371 } else {
4372 // This <head> is deep and is likely just an error. we emit it inline though.
4373 // Validation should warn that this tag is the the wrong spot.
4374 return pushStartGenericElement(target, props, 'head');
4375 }
4376}
4377
4378function pushStartHtml(target, props, renderState, insertionMode) {
4379 if (insertionMode === ROOT_HTML_MODE && renderState.htmlChunks === null) {
4380 // This <html> is the Document.documentElement and should be part of the preamble
4381 renderState.htmlChunks = [doctypeChunk];
4382 return pushStartGenericElement(renderState.htmlChunks, props, 'html');
4383 } else {
4384 // This <html> is deep and is likely just an error. we emit it inline though.
4385 // Validation should warn that this tag is the the wrong spot.
4386 return pushStartGenericElement(target, props, 'html');
4387 }
4388}
4389
4390function pushScript(target, props, resumableState, renderState, textEmbedded, insertionMode, noscriptTagInScope) {
4391 var asyncProp = props.async;
4392
4393 if (typeof props.src !== 'string' || !props.src || !(asyncProp && typeof asyncProp !== 'function' && typeof asyncProp !== 'symbol') || props.onLoad || props.onError || insertionMode === SVG_MODE || noscriptTagInScope || props.itemProp != null) {
4394 // This script will not be a resource, we bailout early and emit it in place.
4395 return pushScriptImpl(target, props);
4396 }
4397
4398 var src = props.src;
4399 var key = getResourceKey(src); // We can make this <script> into a ScriptResource
4400
4401 var resources, preloads;
4402
4403 if (props.type === 'module') {
4404 resources = resumableState.moduleScriptResources;
4405 preloads = renderState.preloads.moduleScripts;
4406 } else {
4407 resources = resumableState.scriptResources;
4408 preloads = renderState.preloads.scripts;
4409 }
4410
4411 var hasKey = resources.hasOwnProperty(key);
4412 var resourceState = hasKey ? resources[key] : undefined;
4413
4414 if (resourceState !== EXISTS) {
4415 // We are going to create this resource now so it is marked as Exists
4416 resources[key] = EXISTS;
4417 var scriptProps = props;
4418
4419 if (resourceState) {
4420 // When resourceState is truty it is a Preload state. We cast it for clarity
4421 var preloadState = resourceState;
4422
4423 if (preloadState.length === 2) {
4424 scriptProps = assign({}, props);
4425 adoptPreloadCredentials(scriptProps, preloadState);
4426 }
4427
4428 var preloadResource = preloads.get(key);
4429
4430 if (preloadResource) {
4431 // the preload resource exists was created in this render. Now that we have
4432 // a script resource which will emit earlier than a preload would if it
4433 // hasn't already flushed we prevent it from flushing by zeroing the length
4434 preloadResource.length = 0;
4435 }
4436 }
4437
4438 var resource = []; // Add to the script flushing queue
4439
4440 renderState.scripts.add(resource); // encode the tag as Chunks
4441
4442 pushScriptImpl(resource, scriptProps);
4443 }
4444
4445 if (textEmbedded) {
4446 // This script follows text but we aren't writing a tag. while not as efficient as possible we need
4447 // to be safe and assume text will follow by inserting a textSeparator
4448 target.push(textSeparator);
4449 }
4450
4451 return null;
4452}
4453
4454function pushScriptImpl(target, props) {
4455 target.push(startChunkForTag('script'));
4456 var children = null;
4457 var innerHTML = null;
4458
4459 for (var propKey in props) {
4460 if (hasOwnProperty.call(props, propKey)) {
4461 var propValue = props[propKey];
4462
4463 if (propValue == null) {
4464 continue;
4465 }
4466
4467 switch (propKey) {
4468 case 'children':
4469 children = propValue;
4470 break;
4471
4472 case 'dangerouslySetInnerHTML':
4473 innerHTML = propValue;
4474 break;
4475
4476 default:
4477 pushAttribute(target, propKey, propValue);
4478 break;
4479 }
4480 }
4481 }
4482
4483 target.push(endOfStartTag);
4484
4485 {
4486 if (children != null && typeof children !== 'string') {
4487 var descriptiveStatement = typeof children === 'number' ? 'a number for children' : Array.isArray(children) ? 'an array for children' : 'something unexpected for children';
4488
4489 error('A script element was rendered with %s. If script element has children it must be a single string.' + ' Consider using dangerouslySetInnerHTML or passing a plain string as children.', descriptiveStatement);
4490 }
4491 }
4492
4493 pushInnerHTML(target, innerHTML, children);
4494
4495 if (typeof children === 'string') {
4496 target.push(stringToChunk(escapeEntireInlineScriptContent(children)));
4497 }
4498
4499 target.push(endChunkForTag('script'));
4500 return null;
4501}
4502
4503function pushStartGenericElement(target, props, tag) {
4504 target.push(startChunkForTag(tag));
4505 var children = null;
4506 var innerHTML = null;
4507
4508 for (var propKey in props) {
4509 if (hasOwnProperty.call(props, propKey)) {
4510 var propValue = props[propKey];
4511
4512 if (propValue == null) {
4513 continue;
4514 }
4515
4516 switch (propKey) {
4517 case 'children':
4518 children = propValue;
4519 break;
4520
4521 case 'dangerouslySetInnerHTML':
4522 innerHTML = propValue;
4523 break;
4524
4525 default:
4526 pushAttribute(target, propKey, propValue);
4527 break;
4528 }
4529 }
4530 }
4531
4532 target.push(endOfStartTag);
4533 pushInnerHTML(target, innerHTML, children);
4534
4535 if (typeof children === 'string') {
4536 // Special case children as a string to avoid the unnecessary comment.
4537 // TODO: Remove this special case after the general optimization is in place.
4538 target.push(stringToChunk(encodeHTMLTextNode(children)));
4539 return null;
4540 }
4541
4542 return children;
4543}
4544
4545function pushStartCustomElement(target, props, tag) {
4546 target.push(startChunkForTag(tag));
4547 var children = null;
4548 var innerHTML = null;
4549
4550 for (var propKey in props) {
4551 if (hasOwnProperty.call(props, propKey)) {
4552 var propValue = props[propKey];
4553
4554 if (propValue == null) {
4555 continue;
4556 }
4557
4558 var attributeName = propKey;
4559
4560 switch (propKey) {
4561 case 'children':
4562 children = propValue;
4563 break;
4564
4565 case 'dangerouslySetInnerHTML':
4566 innerHTML = propValue;
4567 break;
4568
4569 case 'style':
4570 pushStyleAttribute(target, propValue);
4571 break;
4572
4573 case 'suppressContentEditableWarning':
4574 case 'suppressHydrationWarning':
4575 case 'ref':
4576 // Ignored. These are built-in to React on the client.
4577 break;
4578
4579 case 'className':
4580 // className gets rendered as class on the client, so it should be
4581 // rendered as class on the server.
4582 attributeName = 'class';
4583 // intentional fallthrough
4584
4585 default:
4586 if (isAttributeNameSafe(propKey) && typeof propValue !== 'function' && typeof propValue !== 'symbol') {
4587 if (propValue === false) {
4588 continue;
4589 } else if (propValue === true) {
4590 propValue = '';
4591 } else if (typeof propValue === 'object') {
4592 continue;
4593 }
4594
4595 target.push(attributeSeparator, stringToChunk(attributeName), attributeAssign, stringToChunk(escapeTextForBrowser(propValue)), attributeEnd);
4596 }
4597
4598 break;
4599 }
4600 }
4601 }
4602
4603 target.push(endOfStartTag);
4604 pushInnerHTML(target, innerHTML, children);
4605 return children;
4606}
4607
4608var leadingNewline = stringToPrecomputedChunk('\n');
4609
4610function pushStartPreformattedElement(target, props, tag) {
4611 target.push(startChunkForTag(tag));
4612 var children = null;
4613 var innerHTML = null;
4614
4615 for (var propKey in props) {
4616 if (hasOwnProperty.call(props, propKey)) {
4617 var propValue = props[propKey];
4618
4619 if (propValue == null) {
4620 continue;
4621 }
4622
4623 switch (propKey) {
4624 case 'children':
4625 children = propValue;
4626 break;
4627
4628 case 'dangerouslySetInnerHTML':
4629 innerHTML = propValue;
4630 break;
4631
4632 default:
4633 pushAttribute(target, propKey, propValue);
4634 break;
4635 }
4636 }
4637 }
4638
4639 target.push(endOfStartTag); // text/html ignores the first character in these tags if it's a newline
4640 // Prefer to break application/xml over text/html (for now) by adding
4641 // a newline specifically to get eaten by the parser. (Alternately for
4642 // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
4643 // \r is normalized out by HTMLTextAreaElement#value.)
4644 // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
4645 // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
4646 // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
4647 // See: Parsing of "textarea" "listing" and "pre" elements
4648 // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
4649 // TODO: This doesn't deal with the case where the child is an array
4650 // or component that returns a string.
4651
4652 if (innerHTML != null) {
4653 if (children != null) {
4654 throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
4655 }
4656
4657 if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
4658 throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://react.dev/link/dangerously-set-inner-html ' + 'for more information.');
4659 }
4660
4661 var html = innerHTML.__html;
4662
4663 if (html !== null && html !== undefined) {
4664 if (typeof html === 'string' && html.length > 0 && html[0] === '\n') {
4665 target.push(leadingNewline, stringToChunk(html));
4666 } else {
4667 {
4668 checkHtmlStringCoercion(html);
4669 }
4670
4671 target.push(stringToChunk('' + html));
4672 }
4673 }
4674 }
4675
4676 if (typeof children === 'string' && children[0] === '\n') {
4677 target.push(leadingNewline);
4678 }
4679
4680 return children;
4681} // We accept any tag to be rendered but since this gets injected into arbitrary
4682// HTML, we want to make sure that it's a safe tag.
4683// http://www.w3.org/TR/REC-xml/#NT-Name
4684
4685
4686var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
4687
4688var validatedTagCache = new Map();
4689
4690function startChunkForTag(tag) {
4691 var tagStartChunk = validatedTagCache.get(tag);
4692
4693 if (tagStartChunk === undefined) {
4694 if (!VALID_TAG_REGEX.test(tag)) {
4695 throw new Error("Invalid tag: " + tag);
4696 }
4697
4698 tagStartChunk = stringToPrecomputedChunk('<' + tag);
4699 validatedTagCache.set(tag, tagStartChunk);
4700 }
4701
4702 return tagStartChunk;
4703}
4704
4705var doctypeChunk = stringToPrecomputedChunk('<!DOCTYPE html>');
4706function pushStartInstance(target, type, props, resumableState, renderState, hoistableState, formatContext, textEmbedded, isFallback) {
4707 {
4708 validateProperties$2(type, props);
4709 validateProperties$1(type, props);
4710 validateProperties(type, props, null);
4711
4712 if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
4713 error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
4714 }
4715
4716 if (formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE) {
4717 if (type.indexOf('-') === -1 && type.toLowerCase() !== type) {
4718 error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
4719 }
4720 }
4721 }
4722
4723 switch (type) {
4724 case 'div':
4725 case 'span':
4726 case 'svg':
4727 case 'path':
4728 // Fast track very common tags
4729 break;
4730
4731 case 'a':
4732 {
4733 return pushStartAnchor(target, props);
4734 }
4735
4736 case 'g':
4737 case 'p':
4738 case 'li':
4739 // Fast track very common tags
4740 break;
4741 // Special tags
4742
4743 case 'select':
4744 return pushStartSelect(target, props);
4745
4746 case 'option':
4747 return pushStartOption(target, props, formatContext);
4748
4749 case 'textarea':
4750 return pushStartTextArea(target, props);
4751
4752 case 'input':
4753 return pushInput(target, props, resumableState, renderState);
4754
4755 case 'button':
4756 return pushStartButton(target, props, resumableState, renderState);
4757
4758 case 'form':
4759 return pushStartForm(target, props, resumableState, renderState);
4760
4761 case 'menuitem':
4762 return pushStartMenuItem(target, props);
4763
4764 case 'title':
4765 return pushTitle(target, props, renderState, formatContext.insertionMode, !!(formatContext.tagScope & NOSCRIPT_SCOPE), isFallback);
4766
4767 case 'link':
4768 return pushLink(target, props, resumableState, renderState, hoistableState, textEmbedded, formatContext.insertionMode, !!(formatContext.tagScope & NOSCRIPT_SCOPE), isFallback);
4769
4770 case 'script':
4771 return pushScript(target, props, resumableState, renderState, textEmbedded, formatContext.insertionMode, !!(formatContext.tagScope & NOSCRIPT_SCOPE));
4772
4773 case 'style':
4774 return pushStyle(target, props, resumableState, renderState, hoistableState, textEmbedded, formatContext.insertionMode, !!(formatContext.tagScope & NOSCRIPT_SCOPE));
4775
4776 case 'meta':
4777 return pushMeta(target, props, renderState, textEmbedded, formatContext.insertionMode, !!(formatContext.tagScope & NOSCRIPT_SCOPE), isFallback);
4778 // Newline eating tags
4779
4780 case 'listing':
4781 case 'pre':
4782 {
4783 return pushStartPreformattedElement(target, props, type);
4784 }
4785
4786 case 'img':
4787 {
4788 return pushImg(target, props, resumableState, renderState, !!(formatContext.tagScope & (PICTURE_SCOPE | NOSCRIPT_SCOPE)));
4789 }
4790 // Omitted close tags
4791
4792 case 'base':
4793 case 'area':
4794 case 'br':
4795 case 'col':
4796 case 'embed':
4797 case 'hr':
4798 case 'keygen':
4799 case 'param':
4800 case 'source':
4801 case 'track':
4802 case 'wbr':
4803 {
4804 return pushSelfClosing(target, props, type);
4805 }
4806 // These are reserved SVG and MathML elements, that are never custom elements.
4807 // https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-core-concepts
4808
4809 case 'annotation-xml':
4810 case 'color-profile':
4811 case 'font-face':
4812 case 'font-face-src':
4813 case 'font-face-uri':
4814 case 'font-face-format':
4815 case 'font-face-name':
4816 case 'missing-glyph':
4817 {
4818 break;
4819 }
4820 // Preamble start tags
4821
4822 case 'head':
4823 return pushStartHead(target, props, renderState, formatContext.insertionMode);
4824
4825 case 'html':
4826 {
4827 return pushStartHtml(target, props, renderState, formatContext.insertionMode);
4828 }
4829
4830 default:
4831 {
4832 if (type.indexOf('-') !== -1) {
4833 // Custom element
4834 return pushStartCustomElement(target, props, type);
4835 }
4836 }
4837 } // Generic element
4838
4839
4840 return pushStartGenericElement(target, props, type);
4841}
4842var endTagCache = new Map();
4843
4844function endChunkForTag(tag) {
4845 var chunk = endTagCache.get(tag);
4846
4847 if (chunk === undefined) {
4848 chunk = stringToPrecomputedChunk('</' + tag + '>');
4849 endTagCache.set(tag, chunk);
4850 }
4851
4852 return chunk;
4853}
4854
4855function pushEndInstance(target, type, props, resumableState, formatContext) {
4856 switch (type) {
4857 // We expect title and script tags to always be pushed in a unit and never
4858 // return children. when we end up pushing the end tag we want to ensure
4859 // there is no extra closing tag pushed
4860 case 'title':
4861 case 'style':
4862 case 'script': // Omitted close tags
4863 // TODO: Instead of repeating this switch we could try to pass a flag from above.
4864 // That would require returning a tuple. Which might be ok if it gets inlined.
4865 // fallthrough
4866
4867 case 'area':
4868 case 'base':
4869 case 'br':
4870 case 'col':
4871 case 'embed':
4872 case 'hr':
4873 case 'img':
4874 case 'input':
4875 case 'keygen':
4876 case 'link':
4877 case 'meta':
4878 case 'param':
4879 case 'source':
4880 case 'track':
4881 case 'wbr':
4882 {
4883 // No close tag needed.
4884 return;
4885 }
4886 // Postamble end tags
4887 // When float is enabled we omit the end tags for body and html when
4888 // they represent the Document.body and Document.documentElement Nodes.
4889 // This is so we can withhold them until the postamble when we know
4890 // we won't emit any more tags
4891
4892 case 'body':
4893 {
4894 if (formatContext.insertionMode <= HTML_HTML_MODE) {
4895 resumableState.hasBody = true;
4896 return;
4897 }
4898
4899 break;
4900 }
4901
4902 case 'html':
4903 if (formatContext.insertionMode === ROOT_HTML_MODE) {
4904 resumableState.hasHtml = true;
4905 return;
4906 }
4907
4908 break;
4909 }
4910
4911 target.push(endChunkForTag(type));
4912}
4913
4914function writeBootstrap(destination, renderState) {
4915 var bootstrapChunks = renderState.bootstrapChunks;
4916 var i = 0;
4917
4918 for (; i < bootstrapChunks.length - 1; i++) {
4919 writeChunk(destination, bootstrapChunks[i]);
4920 }
4921
4922 if (i < bootstrapChunks.length) {
4923 var lastChunk = bootstrapChunks[i];
4924 bootstrapChunks.length = 0;
4925 return writeChunkAndReturn(destination, lastChunk);
4926 }
4927
4928 return true;
4929}
4930
4931function writeCompletedRoot(destination, renderState) {
4932 return writeBootstrap(destination, renderState);
4933} // Structural Nodes
4934// A placeholder is a node inside a hidden partial tree that can be filled in later, but before
4935// display. It's never visible to users. We use the template tag because it can be used in every
4936// type of parent. <script> tags also work in every other tag except <colgroup>.
4937
4938var placeholder1 = stringToPrecomputedChunk('<template id="');
4939var placeholder2 = stringToPrecomputedChunk('"></template>');
4940function writePlaceholder(destination, renderState, id) {
4941 writeChunk(destination, placeholder1);
4942 writeChunk(destination, renderState.placeholderPrefix);
4943 var formattedID = stringToChunk(id.toString(16));
4944 writeChunk(destination, formattedID);
4945 return writeChunkAndReturn(destination, placeholder2);
4946} // Suspense boundaries are encoded as comments.
4947
4948var startCompletedSuspenseBoundary = stringToPrecomputedChunk('<!--$-->');
4949var startPendingSuspenseBoundary1 = stringToPrecomputedChunk('<!--$?--><template id="');
4950var startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>');
4951var startClientRenderedSuspenseBoundary = stringToPrecomputedChunk('<!--$!-->');
4952var endSuspenseBoundary = stringToPrecomputedChunk('<!--/$-->');
4953var clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk('<template');
4954var clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"');
4955var clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="');
4956var clientRenderedSuspenseBoundaryError1B = stringToPrecomputedChunk(' data-msg="');
4957var clientRenderedSuspenseBoundaryError1C = stringToPrecomputedChunk(' data-stck="');
4958var clientRenderedSuspenseBoundaryError1D = stringToPrecomputedChunk(' data-cstck="');
4959var clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk('></template>');
4960function writeStartCompletedSuspenseBoundary(destination, renderState) {
4961 return writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
4962}
4963function writeStartPendingSuspenseBoundary(destination, renderState, id) {
4964 writeChunk(destination, startPendingSuspenseBoundary1);
4965
4966 if (id === null) {
4967 throw new Error('An ID must have been assigned before we can complete the boundary.');
4968 }
4969
4970 writeChunk(destination, renderState.boundaryPrefix);
4971 writeChunk(destination, stringToChunk(id.toString(16)));
4972 return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
4973}
4974function writeStartClientRenderedSuspenseBoundary(destination, renderState, errorDigest, errorMessage, errorStack, errorComponentStack) {
4975 var result;
4976 result = writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
4977 writeChunk(destination, clientRenderedSuspenseBoundaryError1);
4978
4979 if (errorDigest) {
4980 writeChunk(destination, clientRenderedSuspenseBoundaryError1A);
4981 writeChunk(destination, stringToChunk(escapeTextForBrowser(errorDigest)));
4982 writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
4983 }
4984
4985 {
4986 if (errorMessage) {
4987 writeChunk(destination, clientRenderedSuspenseBoundaryError1B);
4988 writeChunk(destination, stringToChunk(escapeTextForBrowser(errorMessage)));
4989 writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
4990 }
4991
4992 if (errorStack) {
4993 writeChunk(destination, clientRenderedSuspenseBoundaryError1C);
4994 writeChunk(destination, stringToChunk(escapeTextForBrowser(errorStack)));
4995 writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
4996 }
4997
4998 if (errorComponentStack) {
4999 writeChunk(destination, clientRenderedSuspenseBoundaryError1D);
5000 writeChunk(destination, stringToChunk(escapeTextForBrowser(errorComponentStack)));
5001 writeChunk(destination, clientRenderedSuspenseBoundaryErrorAttrInterstitial);
5002 }
5003 }
5004
5005 result = writeChunkAndReturn(destination, clientRenderedSuspenseBoundaryError2);
5006 return result;
5007}
5008function writeEndCompletedSuspenseBoundary(destination, renderState) {
5009 return writeChunkAndReturn(destination, endSuspenseBoundary);
5010}
5011function writeEndPendingSuspenseBoundary(destination, renderState) {
5012 return writeChunkAndReturn(destination, endSuspenseBoundary);
5013}
5014function writeEndClientRenderedSuspenseBoundary(destination, renderState) {
5015 return writeChunkAndReturn(destination, endSuspenseBoundary);
5016}
5017var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="');
5018var startSegmentHTML2 = stringToPrecomputedChunk('">');
5019var endSegmentHTML = stringToPrecomputedChunk('</div>');
5020var startSegmentSVG = stringToPrecomputedChunk('<svg aria-hidden="true" style="display:none" id="');
5021var startSegmentSVG2 = stringToPrecomputedChunk('">');
5022var endSegmentSVG = stringToPrecomputedChunk('</svg>');
5023var startSegmentMathML = stringToPrecomputedChunk('<math aria-hidden="true" style="display:none" id="');
5024var startSegmentMathML2 = stringToPrecomputedChunk('">');
5025var endSegmentMathML = stringToPrecomputedChunk('</math>');
5026var startSegmentTable = stringToPrecomputedChunk('<table hidden id="');
5027var startSegmentTable2 = stringToPrecomputedChunk('">');
5028var endSegmentTable = stringToPrecomputedChunk('</table>');
5029var startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="');
5030var startSegmentTableBody2 = stringToPrecomputedChunk('">');
5031var endSegmentTableBody = stringToPrecomputedChunk('</tbody></table>');
5032var startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="');
5033var startSegmentTableRow2 = stringToPrecomputedChunk('">');
5034var endSegmentTableRow = stringToPrecomputedChunk('</tr></table>');
5035var startSegmentColGroup = stringToPrecomputedChunk('<table hidden><colgroup id="');
5036var startSegmentColGroup2 = stringToPrecomputedChunk('">');
5037var endSegmentColGroup = stringToPrecomputedChunk('</colgroup></table>');
5038function writeStartSegment(destination, renderState, formatContext, id) {
5039 switch (formatContext.insertionMode) {
5040 case ROOT_HTML_MODE:
5041 case HTML_HTML_MODE:
5042 case HTML_MODE:
5043 {
5044 writeChunk(destination, startSegmentHTML);
5045 writeChunk(destination, renderState.segmentPrefix);
5046 writeChunk(destination, stringToChunk(id.toString(16)));
5047 return writeChunkAndReturn(destination, startSegmentHTML2);
5048 }
5049
5050 case SVG_MODE:
5051 {
5052 writeChunk(destination, startSegmentSVG);
5053 writeChunk(destination, renderState.segmentPrefix);
5054 writeChunk(destination, stringToChunk(id.toString(16)));
5055 return writeChunkAndReturn(destination, startSegmentSVG2);
5056 }
5057
5058 case MATHML_MODE:
5059 {
5060 writeChunk(destination, startSegmentMathML);
5061 writeChunk(destination, renderState.segmentPrefix);
5062 writeChunk(destination, stringToChunk(id.toString(16)));
5063 return writeChunkAndReturn(destination, startSegmentMathML2);
5064 }
5065
5066 case HTML_TABLE_MODE:
5067 {
5068 writeChunk(destination, startSegmentTable);
5069 writeChunk(destination, renderState.segmentPrefix);
5070 writeChunk(destination, stringToChunk(id.toString(16)));
5071 return writeChunkAndReturn(destination, startSegmentTable2);
5072 }
5073 // TODO: For the rest of these, there will be extra wrapper nodes that never
5074 // get deleted from the document. We need to delete the table too as part
5075 // of the injected scripts. They are invisible though so it's not too terrible
5076 // and it's kind of an edge case to suspend in a table. Totally supported though.
5077
5078 case HTML_TABLE_BODY_MODE:
5079 {
5080 writeChunk(destination, startSegmentTableBody);
5081 writeChunk(destination, renderState.segmentPrefix);
5082 writeChunk(destination, stringToChunk(id.toString(16)));
5083 return writeChunkAndReturn(destination, startSegmentTableBody2);
5084 }
5085
5086 case HTML_TABLE_ROW_MODE:
5087 {
5088 writeChunk(destination, startSegmentTableRow);
5089 writeChunk(destination, renderState.segmentPrefix);
5090 writeChunk(destination, stringToChunk(id.toString(16)));
5091 return writeChunkAndReturn(destination, startSegmentTableRow2);
5092 }
5093
5094 case HTML_COLGROUP_MODE:
5095 {
5096 writeChunk(destination, startSegmentColGroup);
5097 writeChunk(destination, renderState.segmentPrefix);
5098 writeChunk(destination, stringToChunk(id.toString(16)));
5099 return writeChunkAndReturn(destination, startSegmentColGroup2);
5100 }
5101
5102 default:
5103 {
5104 throw new Error('Unknown insertion mode. This is a bug in React.');
5105 }
5106 }
5107}
5108function writeEndSegment(destination, formatContext) {
5109 switch (formatContext.insertionMode) {
5110 case ROOT_HTML_MODE:
5111 case HTML_HTML_MODE:
5112 case HTML_MODE:
5113 {
5114 return writeChunkAndReturn(destination, endSegmentHTML);
5115 }
5116
5117 case SVG_MODE:
5118 {
5119 return writeChunkAndReturn(destination, endSegmentSVG);
5120 }
5121
5122 case MATHML_MODE:
5123 {
5124 return writeChunkAndReturn(destination, endSegmentMathML);
5125 }
5126
5127 case HTML_TABLE_MODE:
5128 {
5129 return writeChunkAndReturn(destination, endSegmentTable);
5130 }
5131
5132 case HTML_TABLE_BODY_MODE:
5133 {
5134 return writeChunkAndReturn(destination, endSegmentTableBody);
5135 }
5136
5137 case HTML_TABLE_ROW_MODE:
5138 {
5139 return writeChunkAndReturn(destination, endSegmentTableRow);
5140 }
5141
5142 case HTML_COLGROUP_MODE:
5143 {
5144 return writeChunkAndReturn(destination, endSegmentColGroup);
5145 }
5146
5147 default:
5148 {
5149 throw new Error('Unknown insertion mode. This is a bug in React.');
5150 }
5151 }
5152}
5153var completeSegmentScript1Full = stringToPrecomputedChunk(completeSegment + '$RS("');
5154var completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("');
5155var completeSegmentScript2 = stringToPrecomputedChunk('","');
5156var completeSegmentScriptEnd = stringToPrecomputedChunk('")</script>');
5157stringToPrecomputedChunk('<template data-rsi="" data-sid="');
5158stringToPrecomputedChunk('" data-pid="');
5159function writeCompletedSegmentInstruction(destination, resumableState, renderState, contentSegmentID) {
5160
5161 {
5162 writeChunk(destination, renderState.startInlineScript);
5163
5164 if ((resumableState.instructions & SentCompleteSegmentFunction) === NothingSent) {
5165 // The first time we write this, we'll need to include the full implementation.
5166 resumableState.instructions |= SentCompleteSegmentFunction;
5167 writeChunk(destination, completeSegmentScript1Full);
5168 } else {
5169 // Future calls can just reuse the same function.
5170 writeChunk(destination, completeSegmentScript1Partial);
5171 }
5172 } // Write function arguments, which are string literals
5173
5174
5175 writeChunk(destination, renderState.segmentPrefix);
5176 var formattedID = stringToChunk(contentSegmentID.toString(16));
5177 writeChunk(destination, formattedID);
5178
5179 {
5180 writeChunk(destination, completeSegmentScript2);
5181 }
5182
5183 writeChunk(destination, renderState.placeholderPrefix);
5184 writeChunk(destination, formattedID);
5185
5186 {
5187 return writeChunkAndReturn(destination, completeSegmentScriptEnd);
5188 }
5189}
5190var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundary + '$RC("');
5191var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
5192var completeBoundaryWithStylesScript1FullBoth = stringToPrecomputedChunk(completeBoundary + completeBoundaryWithStyles + '$RR("');
5193var completeBoundaryWithStylesScript1FullPartial = stringToPrecomputedChunk(completeBoundaryWithStyles + '$RR("');
5194var completeBoundaryWithStylesScript1Partial = stringToPrecomputedChunk('$RR("');
5195var completeBoundaryScript2 = stringToPrecomputedChunk('","');
5196var completeBoundaryScript3a = stringToPrecomputedChunk('",');
5197var completeBoundaryScript3b = stringToPrecomputedChunk('"');
5198var completeBoundaryScriptEnd = stringToPrecomputedChunk(')</script>');
5199stringToPrecomputedChunk('<template data-rci="" data-bid="');
5200stringToPrecomputedChunk('<template data-rri="" data-bid="');
5201stringToPrecomputedChunk('" data-sid="');
5202stringToPrecomputedChunk('" data-sty="');
5203function writeCompletedBoundaryInstruction(destination, resumableState, renderState, id, hoistableState) {
5204 var requiresStyleInsertion = renderState.stylesToHoist; // If necessary stylesheets will be flushed with this instruction.
5205 // Any style tags not yet hoisted in the Document will also be hoisted.
5206 // We reset this state since after this instruction executes all styles
5207 // up to this point will have been hoisted
5208
5209 renderState.stylesToHoist = false;
5210
5211 {
5212 writeChunk(destination, renderState.startInlineScript);
5213
5214 if (requiresStyleInsertion) {
5215 if ((resumableState.instructions & SentCompleteBoundaryFunction) === NothingSent) {
5216 resumableState.instructions |= SentStyleInsertionFunction | SentCompleteBoundaryFunction;
5217 writeChunk(destination, completeBoundaryWithStylesScript1FullBoth);
5218 } else if ((resumableState.instructions & SentStyleInsertionFunction) === NothingSent) {
5219 resumableState.instructions |= SentStyleInsertionFunction;
5220 writeChunk(destination, completeBoundaryWithStylesScript1FullPartial);
5221 } else {
5222 writeChunk(destination, completeBoundaryWithStylesScript1Partial);
5223 }
5224 } else {
5225 if ((resumableState.instructions & SentCompleteBoundaryFunction) === NothingSent) {
5226 resumableState.instructions |= SentCompleteBoundaryFunction;
5227 writeChunk(destination, completeBoundaryScript1Full);
5228 } else {
5229 writeChunk(destination, completeBoundaryScript1Partial);
5230 }
5231 }
5232 }
5233
5234 var idChunk = stringToChunk(id.toString(16));
5235 writeChunk(destination, renderState.boundaryPrefix);
5236 writeChunk(destination, idChunk); // Write function arguments, which are string and array literals
5237
5238 {
5239 writeChunk(destination, completeBoundaryScript2);
5240 }
5241
5242 writeChunk(destination, renderState.segmentPrefix);
5243 writeChunk(destination, idChunk);
5244
5245 if (requiresStyleInsertion) {
5246 // Script and data writers must format this differently:
5247 // - script writer emits an array literal, whose string elements are
5248 // escaped for javascript e.g. ["A", "B"]
5249 // - data writer emits a string literal, which is escaped as html
5250 // e.g. [&#34;A&#34;, &#34;B&#34;]
5251 {
5252 writeChunk(destination, completeBoundaryScript3a); // hoistableState encodes an array literal
5253
5254 writeStyleResourceDependenciesInJS(destination, hoistableState);
5255 }
5256 } else {
5257 {
5258 writeChunk(destination, completeBoundaryScript3b);
5259 }
5260 }
5261
5262 var writeMore;
5263
5264 {
5265 writeMore = writeChunkAndReturn(destination, completeBoundaryScriptEnd);
5266 }
5267
5268 return writeBootstrap(destination, renderState) && writeMore;
5269}
5270var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderBoundary + ';$RX("');
5271var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("');
5272var clientRenderScript1A = stringToPrecomputedChunk('"');
5273var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');
5274var clientRenderScriptEnd = stringToPrecomputedChunk(')</script>');
5275stringToPrecomputedChunk('<template data-rxi="" data-bid="');
5276stringToPrecomputedChunk('" data-dgst="');
5277stringToPrecomputedChunk('" data-msg="');
5278stringToPrecomputedChunk('" data-stck="');
5279stringToPrecomputedChunk('" data-cstck="');
5280function writeClientRenderBoundaryInstruction(destination, resumableState, renderState, id, errorDigest, errorMessage, errorStack, errorComponentStack) {
5281
5282 {
5283 writeChunk(destination, renderState.startInlineScript);
5284
5285 if ((resumableState.instructions & SentClientRenderFunction) === NothingSent) {
5286 // The first time we write this, we'll need to include the full implementation.
5287 resumableState.instructions |= SentClientRenderFunction;
5288 writeChunk(destination, clientRenderScript1Full);
5289 } else {
5290 // Future calls can just reuse the same function.
5291 writeChunk(destination, clientRenderScript1Partial);
5292 }
5293 }
5294
5295 writeChunk(destination, renderState.boundaryPrefix);
5296 writeChunk(destination, stringToChunk(id.toString(16)));
5297
5298 {
5299 // " needs to be inserted for scripts, since ArgInterstitual does not contain
5300 // leading or trailing quotes
5301 writeChunk(destination, clientRenderScript1A);
5302 }
5303
5304 if (errorDigest || errorMessage || errorStack || errorComponentStack) {
5305 {
5306 // ,"JSONString"
5307 writeChunk(destination, clientRenderErrorScriptArgInterstitial);
5308 writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || '')));
5309 }
5310 }
5311
5312 if (errorMessage || errorStack || errorComponentStack) {
5313 {
5314 // ,"JSONString"
5315 writeChunk(destination, clientRenderErrorScriptArgInterstitial);
5316 writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || '')));
5317 }
5318 }
5319
5320 if (errorStack || errorComponentStack) {
5321 // ,"JSONString"
5322 {
5323 writeChunk(destination, clientRenderErrorScriptArgInterstitial);
5324 writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorStack || '')));
5325 }
5326 }
5327
5328 if (errorComponentStack) {
5329 // ,"JSONString"
5330 {
5331 writeChunk(destination, clientRenderErrorScriptArgInterstitial);
5332 writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack)));
5333 }
5334 }
5335
5336 {
5337 // ></script>
5338 return writeChunkAndReturn(destination, clientRenderScriptEnd);
5339 }
5340}
5341var regexForJSStringsInInstructionScripts = /[<\u2028\u2029]/g;
5342
5343function escapeJSStringsForInstructionScripts(input) {
5344 var escaped = JSON.stringify(input);
5345 return escaped.replace(regexForJSStringsInInstructionScripts, function (match) {
5346 switch (match) {
5347 // santizing breaking out of strings and script tags
5348 case '<':
5349 return "\\u003c";
5350
5351 case "\u2028":
5352 return "\\u2028";
5353
5354 case "\u2029":
5355 return "\\u2029";
5356
5357 default:
5358 {
5359 // eslint-disable-next-line react-internal/prod-error-codes
5360 throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
5361 }
5362 }
5363 });
5364}
5365
5366var regexForJSStringsInScripts = /[&><\u2028\u2029]/g;
5367
5368function escapeJSObjectForInstructionScripts(input) {
5369 var escaped = JSON.stringify(input);
5370 return escaped.replace(regexForJSStringsInScripts, function (match) {
5371 switch (match) {
5372 // santizing breaking out of strings and script tags
5373 case '&':
5374 return "\\u0026";
5375
5376 case '>':
5377 return "\\u003e";
5378
5379 case '<':
5380 return "\\u003c";
5381
5382 case "\u2028":
5383 return "\\u2028";
5384
5385 case "\u2029":
5386 return "\\u2029";
5387
5388 default:
5389 {
5390 // eslint-disable-next-line react-internal/prod-error-codes
5391 throw new Error('escapeJSObjectForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
5392 }
5393 }
5394 });
5395}
5396
5397var lateStyleTagResourceOpen1 = stringToPrecomputedChunk('<style media="not all" data-precedence="');
5398var lateStyleTagResourceOpen2 = stringToPrecomputedChunk('" data-href="');
5399var lateStyleTagResourceOpen3 = stringToPrecomputedChunk('">');
5400var lateStyleTagTemplateClose = stringToPrecomputedChunk('</style>'); // Tracks whether the boundary currently flushing is flushign style tags or has any
5401// stylesheet dependencies not flushed in the Preamble.
5402
5403var currentlyRenderingBoundaryHasStylesToHoist = false; // Acts as a return value for the forEach execution of style tag flushing.
5404
5405var destinationHasCapacity = true;
5406
5407function flushStyleTagsLateForBoundary(styleQueue) {
5408 var rules = styleQueue.rules;
5409 var hrefs = styleQueue.hrefs;
5410
5411 {
5412 if (rules.length > 0 && hrefs.length === 0) {
5413 error('React expected to have at least one href for an a hoistable style but found none. This is a bug in React.');
5414 }
5415 }
5416
5417 var i = 0;
5418
5419 if (hrefs.length) {
5420 writeChunk(this, lateStyleTagResourceOpen1);
5421 writeChunk(this, styleQueue.precedence);
5422 writeChunk(this, lateStyleTagResourceOpen2);
5423
5424 for (; i < hrefs.length - 1; i++) {
5425 writeChunk(this, hrefs[i]);
5426 writeChunk(this, spaceSeparator);
5427 }
5428
5429 writeChunk(this, hrefs[i]);
5430 writeChunk(this, lateStyleTagResourceOpen3);
5431
5432 for (i = 0; i < rules.length; i++) {
5433 writeChunk(this, rules[i]);
5434 }
5435
5436 destinationHasCapacity = writeChunkAndReturn(this, lateStyleTagTemplateClose); // We wrote style tags for this boundary and we may need to emit a script
5437 // to hoist them.
5438
5439 currentlyRenderingBoundaryHasStylesToHoist = true; // style resources can flush continuously since more rules may be written into
5440 // them with new hrefs. Instead of marking it flushed, we simply reset the chunks
5441 // and hrefs
5442
5443 rules.length = 0;
5444 hrefs.length = 0;
5445 }
5446}
5447
5448function hasStylesToHoist(stylesheet) {
5449 // We need to reveal boundaries with styles whenever a stylesheet it depends on is either
5450 // not flushed or flushed after the preamble (shell).
5451 if (stylesheet.state !== PREAMBLE) {
5452 currentlyRenderingBoundaryHasStylesToHoist = true;
5453 return true;
5454 }
5455
5456 return false;
5457}
5458
5459function writeHoistablesForBoundary(destination, hoistableState, renderState) {
5460 // Reset these on each invocation, they are only safe to read in this function
5461 currentlyRenderingBoundaryHasStylesToHoist = false;
5462 destinationHasCapacity = true; // Flush style tags for each precedence this boundary depends on
5463
5464 hoistableState.styles.forEach(flushStyleTagsLateForBoundary, destination); // Determine if this boundary has stylesheets that need to be awaited upon completion
5465
5466 hoistableState.stylesheets.forEach(hasStylesToHoist); // We don't actually want to flush any hoistables until the boundary is complete so we omit
5467 // any further writing here. This is becuase unlike Resources, Hoistable Elements act more like
5468 // regular elements, each rendered element has a unique representation in the DOM. We don't want
5469 // these elements to appear in the DOM early, before the boundary has actually completed
5470
5471 if (currentlyRenderingBoundaryHasStylesToHoist) {
5472 renderState.stylesToHoist = true;
5473 }
5474
5475 return destinationHasCapacity;
5476}
5477
5478function flushResource(resource) {
5479 for (var i = 0; i < resource.length; i++) {
5480 writeChunk(this, resource[i]);
5481 }
5482
5483 resource.length = 0;
5484}
5485
5486var stylesheetFlushingQueue = [];
5487
5488function flushStyleInPreamble(stylesheet, key, map) {
5489 // We still need to encode stylesheet chunks
5490 // because unlike most Hoistables and Resources we do not eagerly encode
5491 // them during render. This is because if we flush late we have to send a
5492 // different encoding and we don't want to encode multiple times
5493 pushLinkImpl(stylesheetFlushingQueue, stylesheet.props);
5494
5495 for (var i = 0; i < stylesheetFlushingQueue.length; i++) {
5496 writeChunk(this, stylesheetFlushingQueue[i]);
5497 }
5498
5499 stylesheetFlushingQueue.length = 0;
5500 stylesheet.state = PREAMBLE;
5501}
5502
5503var styleTagResourceOpen1 = stringToPrecomputedChunk('<style data-precedence="');
5504var styleTagResourceOpen2 = stringToPrecomputedChunk('" data-href="');
5505var spaceSeparator = stringToPrecomputedChunk(' ');
5506var styleTagResourceOpen3 = stringToPrecomputedChunk('">');
5507var styleTagResourceClose = stringToPrecomputedChunk('</style>');
5508
5509function flushStylesInPreamble(styleQueue, precedence) {
5510 var hasStylesheets = styleQueue.sheets.size > 0;
5511 styleQueue.sheets.forEach(flushStyleInPreamble, this);
5512 styleQueue.sheets.clear();
5513 var rules = styleQueue.rules;
5514 var hrefs = styleQueue.hrefs; // If we don't emit any stylesheets at this precedence we still need to maintain the precedence
5515 // order so even if there are no rules for style tags at this precedence we emit an empty style
5516 // tag with the data-precedence attribute
5517
5518 if (!hasStylesheets || hrefs.length) {
5519 writeChunk(this, styleTagResourceOpen1);
5520 writeChunk(this, styleQueue.precedence);
5521 var i = 0;
5522
5523 if (hrefs.length) {
5524 writeChunk(this, styleTagResourceOpen2);
5525
5526 for (; i < hrefs.length - 1; i++) {
5527 writeChunk(this, hrefs[i]);
5528 writeChunk(this, spaceSeparator);
5529 }
5530
5531 writeChunk(this, hrefs[i]);
5532 }
5533
5534 writeChunk(this, styleTagResourceOpen3);
5535
5536 for (i = 0; i < rules.length; i++) {
5537 writeChunk(this, rules[i]);
5538 }
5539
5540 writeChunk(this, styleTagResourceClose); // style resources can flush continuously since more rules may be written into
5541 // them with new hrefs. Instead of marking it flushed, we simply reset the chunks
5542 // and hrefs
5543
5544 rules.length = 0;
5545 hrefs.length = 0;
5546 }
5547}
5548
5549function preloadLateStyle(stylesheet) {
5550 if (stylesheet.state === PENDING$1) {
5551 stylesheet.state = PRELOADED;
5552 var preloadProps = preloadAsStylePropsFromProps(stylesheet.props.href, stylesheet.props);
5553 pushLinkImpl(stylesheetFlushingQueue, preloadProps);
5554
5555 for (var i = 0; i < stylesheetFlushingQueue.length; i++) {
5556 writeChunk(this, stylesheetFlushingQueue[i]);
5557 }
5558
5559 stylesheetFlushingQueue.length = 0;
5560 }
5561}
5562
5563function preloadLateStyles(styleQueue) {
5564 styleQueue.sheets.forEach(preloadLateStyle, this);
5565 styleQueue.sheets.clear();
5566} // We don't bother reporting backpressure at the moment because we expect to
5567// flush the entire preamble in a single pass. This probably should be modified
5568// in the future to be backpressure sensitive but that requires a larger refactor
5569// of the flushing code in Fizz.
5570
5571
5572function writePreamble(destination, resumableState, renderState, willFlushAllSegments) {
5573
5574 var htmlChunks = renderState.htmlChunks;
5575 var headChunks = renderState.headChunks;
5576 var i = 0; // Emit open tags before Hoistables and Resources
5577
5578 if (htmlChunks) {
5579 // We have an <html> to emit as part of the preamble
5580 for (i = 0; i < htmlChunks.length; i++) {
5581 writeChunk(destination, htmlChunks[i]);
5582 }
5583
5584 if (headChunks) {
5585 for (i = 0; i < headChunks.length; i++) {
5586 writeChunk(destination, headChunks[i]);
5587 }
5588 } else {
5589 // We did not render a head but we emitted an <html> so we emit one now
5590 writeChunk(destination, startChunkForTag('head'));
5591 writeChunk(destination, endOfStartTag);
5592 }
5593 } else if (headChunks) {
5594 // We do not have an <html> but we do have a <head>
5595 for (i = 0; i < headChunks.length; i++) {
5596 writeChunk(destination, headChunks[i]);
5597 }
5598 } // Emit high priority Hoistables
5599
5600
5601 var charsetChunks = renderState.charsetChunks;
5602
5603 for (i = 0; i < charsetChunks.length; i++) {
5604 writeChunk(destination, charsetChunks[i]);
5605 }
5606
5607 charsetChunks.length = 0; // emit preconnect resources
5608
5609 renderState.preconnects.forEach(flushResource, destination);
5610 renderState.preconnects.clear();
5611 var viewportChunks = renderState.viewportChunks;
5612
5613 for (i = 0; i < viewportChunks.length; i++) {
5614 writeChunk(destination, viewportChunks[i]);
5615 }
5616
5617 viewportChunks.length = 0;
5618 renderState.fontPreloads.forEach(flushResource, destination);
5619 renderState.fontPreloads.clear();
5620 renderState.highImagePreloads.forEach(flushResource, destination);
5621 renderState.highImagePreloads.clear(); // Flush unblocked stylesheets by precedence
5622
5623 renderState.styles.forEach(flushStylesInPreamble, destination);
5624 var importMapChunks = renderState.importMapChunks;
5625
5626 for (i = 0; i < importMapChunks.length; i++) {
5627 writeChunk(destination, importMapChunks[i]);
5628 }
5629
5630 importMapChunks.length = 0;
5631 renderState.bootstrapScripts.forEach(flushResource, destination);
5632 renderState.scripts.forEach(flushResource, destination);
5633 renderState.scripts.clear();
5634 renderState.bulkPreloads.forEach(flushResource, destination);
5635 renderState.bulkPreloads.clear(); // Write embedding hoistableChunks
5636
5637 var hoistableChunks = renderState.hoistableChunks;
5638
5639 for (i = 0; i < hoistableChunks.length; i++) {
5640 writeChunk(destination, hoistableChunks[i]);
5641 }
5642
5643 hoistableChunks.length = 0;
5644
5645 if (htmlChunks && headChunks === null) {
5646 // we have an <html> but we inserted an implicit <head> tag. We need
5647 // to close it since the main content won't have it
5648 writeChunk(destination, endChunkForTag('head'));
5649 }
5650} // We don't bother reporting backpressure at the moment because we expect to
5651// flush the entire preamble in a single pass. This probably should be modified
5652// in the future to be backpressure sensitive but that requires a larger refactor
5653// of the flushing code in Fizz.
5654
5655function writeHoistables(destination, resumableState, renderState) {
5656 var i = 0; // Emit high priority Hoistables
5657 // We omit charsetChunks because we have already sent the shell and if it wasn't
5658 // already sent it is too late now.
5659
5660 var viewportChunks = renderState.viewportChunks;
5661
5662 for (i = 0; i < viewportChunks.length; i++) {
5663 writeChunk(destination, viewportChunks[i]);
5664 }
5665
5666 viewportChunks.length = 0;
5667 renderState.preconnects.forEach(flushResource, destination);
5668 renderState.preconnects.clear();
5669 renderState.fontPreloads.forEach(flushResource, destination);
5670 renderState.fontPreloads.clear();
5671 renderState.highImagePreloads.forEach(flushResource, destination);
5672 renderState.highImagePreloads.clear(); // Preload any stylesheets. these will emit in a render instruction that follows this
5673 // but we want to kick off preloading as soon as possible
5674
5675 renderState.styles.forEach(preloadLateStyles, destination); // We only hoist importmaps that are configured through createResponse and that will
5676 // always flush in the preamble. Generally we don't expect people to render them as
5677 // tags when using React but if you do they are going to be treated like regular inline
5678 // scripts and flush after other hoistables which is problematic
5679 // bootstrap scripts should flush above script priority but these can only flush in the preamble
5680 // so we elide the code here for performance
5681
5682 renderState.scripts.forEach(flushResource, destination);
5683 renderState.scripts.clear();
5684 renderState.bulkPreloads.forEach(flushResource, destination);
5685 renderState.bulkPreloads.clear(); // Write embedding hoistableChunks
5686
5687 var hoistableChunks = renderState.hoistableChunks;
5688
5689 for (i = 0; i < hoistableChunks.length; i++) {
5690 writeChunk(destination, hoistableChunks[i]);
5691 }
5692
5693 hoistableChunks.length = 0;
5694}
5695function writePostamble(destination, resumableState) {
5696 if (resumableState.hasBody) {
5697 writeChunk(destination, endChunkForTag('body'));
5698 }
5699
5700 if (resumableState.hasHtml) {
5701 writeChunk(destination, endChunkForTag('html'));
5702 }
5703}
5704var arrayFirstOpenBracket = stringToPrecomputedChunk('[');
5705var arraySubsequentOpenBracket = stringToPrecomputedChunk(',[');
5706var arrayInterstitial = stringToPrecomputedChunk(',');
5707var arrayCloseBracket = stringToPrecomputedChunk(']'); // This function writes a 2D array of strings to be embedded in javascript.
5708// E.g.
5709// [["JS_escaped_string1", "JS_escaped_string2"]]
5710
5711function writeStyleResourceDependenciesInJS(destination, hoistableState) {
5712 writeChunk(destination, arrayFirstOpenBracket);
5713 var nextArrayOpenBrackChunk = arrayFirstOpenBracket;
5714 hoistableState.stylesheets.forEach(function (resource) {
5715 if (resource.state === PREAMBLE) ; else if (resource.state === LATE) {
5716 // We only need to emit the href because this resource flushed in an earlier
5717 // boundary already which encoded the attributes necessary to construct
5718 // the resource instance on the client.
5719 writeChunk(destination, nextArrayOpenBrackChunk);
5720 writeStyleResourceDependencyHrefOnlyInJS(destination, resource.props.href);
5721 writeChunk(destination, arrayCloseBracket);
5722 nextArrayOpenBrackChunk = arraySubsequentOpenBracket;
5723 } else {
5724 // We need to emit the whole resource for insertion on the client
5725 writeChunk(destination, nextArrayOpenBrackChunk);
5726 writeStyleResourceDependencyInJS(destination, resource.props.href, resource.props['data-precedence'], resource.props);
5727 writeChunk(destination, arrayCloseBracket);
5728 nextArrayOpenBrackChunk = arraySubsequentOpenBracket;
5729 resource.state = LATE;
5730 }
5731 });
5732 writeChunk(destination, arrayCloseBracket);
5733}
5734/* Helper functions */
5735
5736
5737function writeStyleResourceDependencyHrefOnlyInJS(destination, href) {
5738 // We should actually enforce this earlier when the resource is created but for
5739 // now we make sure we are actually dealing with a string here.
5740 {
5741 checkAttributeStringCoercion(href, 'href');
5742 }
5743
5744 var coercedHref = '' + href;
5745 writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(coercedHref)));
5746}
5747
5748function writeStyleResourceDependencyInJS(destination, href, precedence, props) {
5749 // eslint-disable-next-line react-internal/safe-string-coercion
5750 var coercedHref = sanitizeURL('' + href);
5751 writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(coercedHref)));
5752
5753 {
5754 checkAttributeStringCoercion(precedence, 'precedence');
5755 }
5756
5757 var coercedPrecedence = '' + precedence;
5758 writeChunk(destination, arrayInterstitial);
5759 writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(coercedPrecedence)));
5760
5761 for (var propKey in props) {
5762 if (hasOwnProperty.call(props, propKey)) {
5763 var propValue = props[propKey];
5764
5765 if (propValue == null) {
5766 continue;
5767 }
5768
5769 switch (propKey) {
5770 case 'href':
5771 case 'rel':
5772 case 'precedence':
5773 case 'data-precedence':
5774 {
5775 break;
5776 }
5777
5778 case 'children':
5779 case 'dangerouslySetInnerHTML':
5780 throw new Error('link' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
5781
5782 default:
5783 writeStyleResourceAttributeInJS(destination, propKey, propValue);
5784 break;
5785 }
5786 }
5787 }
5788
5789 return null;
5790}
5791
5792function writeStyleResourceAttributeInJS(destination, name, value) // not null or undefined
5793{
5794 var attributeName = name.toLowerCase();
5795 var attributeValue;
5796
5797 switch (typeof value) {
5798 case 'function':
5799 case 'symbol':
5800 return;
5801 }
5802
5803 switch (name) {
5804 // Reserved names
5805 case 'innerHTML':
5806 case 'dangerouslySetInnerHTML':
5807 case 'suppressContentEditableWarning':
5808 case 'suppressHydrationWarning':
5809 case 'style':
5810 case 'ref':
5811 // Ignored
5812 return;
5813 // Attribute renames
5814
5815 case 'className':
5816 {
5817 attributeName = 'class';
5818
5819 {
5820 checkAttributeStringCoercion(value, attributeName);
5821 }
5822
5823 attributeValue = '' + value;
5824 break;
5825 }
5826 // Booleans
5827
5828 case 'hidden':
5829 {
5830 if (value === false) {
5831 return;
5832 }
5833
5834 attributeValue = '';
5835 break;
5836 }
5837 // Santized URLs
5838
5839 case 'src':
5840 case 'href':
5841 {
5842 value = sanitizeURL(value);
5843
5844 {
5845 checkAttributeStringCoercion(value, attributeName);
5846 }
5847
5848 attributeValue = '' + value;
5849 break;
5850 }
5851
5852 default:
5853 {
5854 if ( // unrecognized event handlers are not SSR'd and we (apparently)
5855 // use on* as hueristic for these handler props
5856 name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
5857 return;
5858 }
5859
5860 if (!isAttributeNameSafe(name)) {
5861 return;
5862 }
5863
5864 {
5865 checkAttributeStringCoercion(value, attributeName);
5866 }
5867
5868 attributeValue = '' + value;
5869 }
5870 }
5871
5872 writeChunk(destination, arrayInterstitial);
5873 writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(attributeName)));
5874 writeChunk(destination, arrayInterstitial);
5875 writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(attributeValue)));
5876} // This function writes a 2D array of strings to be embedded in an attribute
5877/**
5878 * Resources
5879 */
5880
5881
5882var PENDING$1 = 0;
5883var PRELOADED = 1;
5884var PREAMBLE = 2;
5885var LATE = 3;
5886function createHoistableState() {
5887 return {
5888 styles: new Set(),
5889 stylesheets: new Set()
5890 };
5891}
5892
5893function getResourceKey(href) {
5894 return href;
5895}
5896
5897function getImageResourceKey(href, imageSrcSet, imageSizes) {
5898 if (imageSrcSet) {
5899 return imageSrcSet + '\n' + (imageSizes || '');
5900 }
5901
5902 return href;
5903}
5904
5905function prefetchDNS(href) {
5906 var request = resolveRequest();
5907
5908 if (!request) {
5909 // In async contexts we can sometimes resolve resources from AsyncLocalStorage. If we can't we can also
5910 // possibly get them from the stack if we are not in an async context. Since we were not able to resolve
5911 // the resources for this call in either case we opt to do nothing. We can consider making this a warning
5912 // but there may be times where calling a function outside of render is intentional (i.e. to warm up data
5913 // fetching) and we don't want to warn in those cases.
5914 previousDispatcher.D(
5915 /* prefetchDNS */
5916 href);
5917 return;
5918 }
5919
5920 var resumableState = getResumableState(request);
5921 var renderState = getRenderState(request);
5922
5923 if (typeof href === 'string' && href) {
5924 var key = getResourceKey(href);
5925
5926 if (!resumableState.dnsResources.hasOwnProperty(key)) {
5927 resumableState.dnsResources[key] = EXISTS;
5928 var headers = renderState.headers;
5929 var header;
5930
5931 if (headers && headers.remainingCapacity > 0 && ( // Compute the header since we might be able to fit it in the max length
5932 header = getPrefetchDNSAsHeader(href), // We always consume the header length since once we find one header that doesn't fit
5933 // we assume all the rest won't as well. This is to avoid getting into a situation
5934 // where we have a very small remaining capacity but no headers will ever fit and we end
5935 // up constantly trying to see if the next resource might make it. In the future we can
5936 // make this behavior different between render and prerender since in the latter case
5937 // we are less sensitive to the current requests runtime per and more sensitive to maximizing
5938 // headers.
5939 (headers.remainingCapacity -= header.length) >= 2)) {
5940 // Store this as resettable in case we are prerendering and postpone in the Shell
5941 renderState.resets.dns[key] = EXISTS;
5942
5943 if (headers.preconnects) {
5944 headers.preconnects += ', ';
5945 } // $FlowFixMe[unsafe-addition]: we assign header during the if condition
5946
5947
5948 headers.preconnects += header;
5949 } else {
5950 // Encode as element
5951 var resource = [];
5952 pushLinkImpl(resource, {
5953 href: href,
5954 rel: 'dns-prefetch'
5955 });
5956 renderState.preconnects.add(resource);
5957 }
5958 }
5959
5960 flushResources(request);
5961 }
5962}
5963
5964function preconnect(href, crossOrigin) {
5965 var request = resolveRequest();
5966
5967 if (!request) {
5968 // In async contexts we can sometimes resolve resources from AsyncLocalStorage. If we can't we can also
5969 // possibly get them from the stack if we are not in an async context. Since we were not able to resolve
5970 // the resources for this call in either case we opt to do nothing. We can consider making this a warning
5971 // but there may be times where calling a function outside of render is intentional (i.e. to warm up data
5972 // fetching) and we don't want to warn in those cases.
5973 previousDispatcher.C(
5974 /* preconnect */
5975 href, crossOrigin);
5976 return;
5977 }
5978
5979 var resumableState = getResumableState(request);
5980 var renderState = getRenderState(request);
5981
5982 if (typeof href === 'string' && href) {
5983 var bucket = crossOrigin === 'use-credentials' ? 'credentials' : typeof crossOrigin === 'string' ? 'anonymous' : 'default';
5984 var key = getResourceKey(href);
5985
5986 if (!resumableState.connectResources[bucket].hasOwnProperty(key)) {
5987 resumableState.connectResources[bucket][key] = EXISTS;
5988 var headers = renderState.headers;
5989 var header;
5990
5991 if (headers && headers.remainingCapacity > 0 && ( // Compute the header since we might be able to fit it in the max length
5992 header = getPreconnectAsHeader(href, crossOrigin), // We always consume the header length since once we find one header that doesn't fit
5993 // we assume all the rest won't as well. This is to avoid getting into a situation
5994 // where we have a very small remaining capacity but no headers will ever fit and we end
5995 // up constantly trying to see if the next resource might make it. In the future we can
5996 // make this behavior different between render and prerender since in the latter case
5997 // we are less sensitive to the current requests runtime per and more sensitive to maximizing
5998 // headers.
5999 (headers.remainingCapacity -= header.length) >= 2)) {
6000 // Store this in resettableState in case we are prerending and postpone in the Shell
6001 renderState.resets.connect[bucket][key] = EXISTS;
6002
6003 if (headers.preconnects) {
6004 headers.preconnects += ', ';
6005 } // $FlowFixMe[unsafe-addition]: we assign header during the if condition
6006
6007
6008 headers.preconnects += header;
6009 } else {
6010 var resource = [];
6011 pushLinkImpl(resource, {
6012 rel: 'preconnect',
6013 href: href,
6014 crossOrigin: crossOrigin
6015 });
6016 renderState.preconnects.add(resource);
6017 }
6018 }
6019
6020 flushResources(request);
6021 }
6022}
6023
6024function preload(href, as, options) {
6025 var request = resolveRequest();
6026
6027 if (!request) {
6028 // In async contexts we can sometimes resolve resources from AsyncLocalStorage. If we can't we can also
6029 // possibly get them from the stack if we are not in an async context. Since we were not able to resolve
6030 // the resources for this call in either case we opt to do nothing. We can consider making this a warning
6031 // but there may be times where calling a function outside of render is intentional (i.e. to warm up data
6032 // fetching) and we don't want to warn in those cases.
6033 previousDispatcher.L(
6034 /* preload */
6035 href, as, options);
6036 return;
6037 }
6038
6039 var resumableState = getResumableState(request);
6040 var renderState = getRenderState(request);
6041
6042 if (as && href) {
6043 switch (as) {
6044 case 'image':
6045 {
6046 var imageSrcSet, imageSizes, fetchPriority;
6047
6048 if (options) {
6049 imageSrcSet = options.imageSrcSet;
6050 imageSizes = options.imageSizes;
6051 fetchPriority = options.fetchPriority;
6052 }
6053
6054 var key = getImageResourceKey(href, imageSrcSet, imageSizes);
6055
6056 if (resumableState.imageResources.hasOwnProperty(key)) {
6057 // we can return if we already have this resource
6058 return;
6059 }
6060
6061 resumableState.imageResources[key] = PRELOAD_NO_CREDS;
6062 var headers = renderState.headers;
6063 var header;
6064
6065 if (headers && headers.remainingCapacity > 0 && fetchPriority === 'high' && ( // Compute the header since we might be able to fit it in the max length
6066 header = getPreloadAsHeader(href, as, options), // We always consume the header length since once we find one header that doesn't fit
6067 // we assume all the rest won't as well. This is to avoid getting into a situation
6068 // where we have a very small remaining capacity but no headers will ever fit and we end
6069 // up constantly trying to see if the next resource might make it. In the future we can
6070 // make this behavior different between render and prerender since in the latter case
6071 // we are less sensitive to the current requests runtime per and more sensitive to maximizing
6072 // headers.
6073 (headers.remainingCapacity -= header.length) >= 2)) {
6074 // If we postpone in the shell we will still emit a preload as a header so we
6075 // track this to make sure we don't reset it.
6076 renderState.resets.image[key] = PRELOAD_NO_CREDS;
6077
6078 if (headers.highImagePreloads) {
6079 headers.highImagePreloads += ', ';
6080 } // $FlowFixMe[unsafe-addition]: we assign header during the if condition
6081
6082
6083 headers.highImagePreloads += header;
6084 } else {
6085 // If we don't have headers to write to we have to encode as elements to flush in the head
6086 // When we have imageSrcSet the browser probably cannot load the right version from headers
6087 // (this should be verified by testing). For now we assume these need to go in the head
6088 // as elements even if headers are available.
6089 var resource = [];
6090 pushLinkImpl(resource, assign({
6091 rel: 'preload',
6092 // There is a bug in Safari where imageSrcSet is not respected on preload links
6093 // so we omit the href here if we have imageSrcSet b/c safari will load the wrong image.
6094 // This harms older browers that do not support imageSrcSet by making their preloads not work
6095 // but this population is shrinking fast and is already small so we accept this tradeoff.
6096 href: imageSrcSet ? undefined : href,
6097 as: as
6098 }, options));
6099
6100 if (fetchPriority === 'high') {
6101 renderState.highImagePreloads.add(resource);
6102 } else {
6103 renderState.bulkPreloads.add(resource); // Stash the resource in case we need to promote it to higher priority
6104 // when an img tag is rendered
6105
6106 renderState.preloads.images.set(key, resource);
6107 }
6108 }
6109
6110 break;
6111 }
6112
6113 case 'style':
6114 {
6115 var _key = getResourceKey(href);
6116
6117 if (resumableState.styleResources.hasOwnProperty(_key)) {
6118 // we can return if we already have this resource
6119 return;
6120 }
6121
6122 var _resource2 = [];
6123 pushLinkImpl(_resource2, assign({
6124 rel: 'preload',
6125 href: href,
6126 as: as
6127 }, options));
6128 resumableState.styleResources[_key] = options && (typeof options.crossOrigin === 'string' || typeof options.integrity === 'string') ? [options.crossOrigin, options.integrity] : PRELOAD_NO_CREDS;
6129 renderState.preloads.stylesheets.set(_key, _resource2);
6130 renderState.bulkPreloads.add(_resource2);
6131 break;
6132 }
6133
6134 case 'script':
6135 {
6136 var _key2 = getResourceKey(href);
6137
6138 if (resumableState.scriptResources.hasOwnProperty(_key2)) {
6139 // we can return if we already have this resource
6140 return;
6141 }
6142
6143 var _resource3 = [];
6144 renderState.preloads.scripts.set(_key2, _resource3);
6145 renderState.bulkPreloads.add(_resource3);
6146 pushLinkImpl(_resource3, assign({
6147 rel: 'preload',
6148 href: href,
6149 as: as
6150 }, options));
6151 resumableState.scriptResources[_key2] = options && (typeof options.crossOrigin === 'string' || typeof options.integrity === 'string') ? [options.crossOrigin, options.integrity] : PRELOAD_NO_CREDS;
6152 break;
6153 }
6154
6155 default:
6156 {
6157 var _key3 = getResourceKey(href);
6158
6159 var hasAsType = resumableState.unknownResources.hasOwnProperty(as);
6160 var resources;
6161
6162 if (hasAsType) {
6163 resources = resumableState.unknownResources[as];
6164
6165 if (resources.hasOwnProperty(_key3)) {
6166 // we can return if we already have this resource
6167 return;
6168 }
6169 } else {
6170 resources = {};
6171 resumableState.unknownResources[as] = resources;
6172 }
6173
6174 resources[_key3] = PRELOAD_NO_CREDS;
6175 var _headers = renderState.headers;
6176
6177 var _header;
6178
6179 if (_headers && _headers.remainingCapacity > 0 && as === 'font' && ( // We compute the header here because we might be able to fit it in the max length
6180 _header = getPreloadAsHeader(href, as, options), // We always consume the header length since once we find one header that doesn't fit
6181 // we assume all the rest won't as well. This is to avoid getting into a situation
6182 // where we have a very small remaining capacity but no headers will ever fit and we end
6183 // up constantly trying to see if the next resource might make it. In the future we can
6184 // make this behavior different between render and prerender since in the latter case
6185 // we are less sensitive to the current requests runtime per and more sensitive to maximizing
6186 // headers.
6187 (_headers.remainingCapacity -= _header.length) >= 2)) {
6188 // If we postpone in the shell we will still emit this preload so we
6189 // track it here to prevent it from being reset.
6190 renderState.resets.font[_key3] = PRELOAD_NO_CREDS;
6191
6192 if (_headers.fontPreloads) {
6193 _headers.fontPreloads += ', ';
6194 } // $FlowFixMe[unsafe-addition]: we assign header during the if condition
6195
6196
6197 _headers.fontPreloads += _header;
6198 } else {
6199 // We either don't have headers or we are preloading something that does
6200 // not warrant elevated priority so we encode as an element.
6201 var _resource4 = [];
6202
6203 var props = assign({
6204 rel: 'preload',
6205 href: href,
6206 as: as
6207 }, options);
6208
6209 pushLinkImpl(_resource4, props);
6210
6211 switch (as) {
6212 case 'font':
6213 renderState.fontPreloads.add(_resource4);
6214 break;
6215 // intentional fall through
6216
6217 default:
6218 renderState.bulkPreloads.add(_resource4);
6219 }
6220 }
6221 }
6222 } // If we got this far we created a new resource
6223
6224
6225 flushResources(request);
6226 }
6227}
6228
6229function preloadModule(href, options) {
6230 var request = resolveRequest();
6231
6232 if (!request) {
6233 // In async contexts we can sometimes resolve resources from AsyncLocalStorage. If we can't we can also
6234 // possibly get them from the stack if we are not in an async context. Since we were not able to resolve
6235 // the resources for this call in either case we opt to do nothing. We can consider making this a warning
6236 // but there may be times where calling a function outside of render is intentional (i.e. to warm up data
6237 // fetching) and we don't want to warn in those cases.
6238 previousDispatcher.m(
6239 /* preloadModule */
6240 href, options);
6241 return;
6242 }
6243
6244 var resumableState = getResumableState(request);
6245 var renderState = getRenderState(request);
6246
6247 if (href) {
6248 var key = getResourceKey(href);
6249 var as = options && typeof options.as === 'string' ? options.as : 'script';
6250 var resource;
6251
6252 switch (as) {
6253 case 'script':
6254 {
6255 if (resumableState.moduleScriptResources.hasOwnProperty(key)) {
6256 // we can return if we already have this resource
6257 return;
6258 }
6259
6260 resource = [];
6261 resumableState.moduleScriptResources[key] = options && (typeof options.crossOrigin === 'string' || typeof options.integrity === 'string') ? [options.crossOrigin, options.integrity] : PRELOAD_NO_CREDS;
6262 renderState.preloads.moduleScripts.set(key, resource);
6263 break;
6264 }
6265
6266 default:
6267 {
6268 var hasAsType = resumableState.moduleUnknownResources.hasOwnProperty(as);
6269 var resources;
6270
6271 if (hasAsType) {
6272 resources = resumableState.unknownResources[as];
6273
6274 if (resources.hasOwnProperty(key)) {
6275 // we can return if we already have this resource
6276 return;
6277 }
6278 } else {
6279 resources = {};
6280 resumableState.moduleUnknownResources[as] = resources;
6281 }
6282
6283 resource = [];
6284 resources[key] = PRELOAD_NO_CREDS;
6285 }
6286 }
6287
6288 pushLinkImpl(resource, assign({
6289 rel: 'modulepreload',
6290 href: href
6291 }, options));
6292 renderState.bulkPreloads.add(resource); // If we got this far we created a new resource
6293
6294 flushResources(request);
6295 }
6296}
6297
6298function preinitStyle(href, precedence, options) {
6299 var request = resolveRequest();
6300
6301 if (!request) {
6302 // In async contexts we can sometimes resolve resources from AsyncLocalStorage. If we can't we can also
6303 // possibly get them from the stack if we are not in an async context. Since we were not able to resolve
6304 // the resources for this call in either case we opt to do nothing. We can consider making this a warning
6305 // but there may be times where calling a function outside of render is intentional (i.e. to warm up data
6306 // fetching) and we don't want to warn in those cases.
6307 previousDispatcher.S(
6308 /* preinitStyle */
6309 href, precedence, options);
6310 return;
6311 }
6312
6313 var resumableState = getResumableState(request);
6314 var renderState = getRenderState(request);
6315
6316 if (href) {
6317 precedence = precedence || 'default';
6318 var key = getResourceKey(href);
6319 var styleQueue = renderState.styles.get(precedence);
6320 var hasKey = resumableState.styleResources.hasOwnProperty(key);
6321 var resourceState = hasKey ? resumableState.styleResources[key] : undefined;
6322
6323 if (resourceState !== EXISTS) {
6324 // We are going to create this resource now so it is marked as Exists
6325 resumableState.styleResources[key] = EXISTS; // If this is the first time we've encountered this precedence we need
6326 // to create a StyleQueue
6327
6328 if (!styleQueue) {
6329 styleQueue = {
6330 precedence: stringToChunk(escapeTextForBrowser(precedence)),
6331 rules: [],
6332 hrefs: [],
6333 sheets: new Map()
6334 };
6335 renderState.styles.set(precedence, styleQueue);
6336 }
6337
6338 var resource = {
6339 state: PENDING$1,
6340 props: assign({
6341 rel: 'stylesheet',
6342 href: href,
6343 'data-precedence': precedence
6344 }, options)
6345 };
6346
6347 if (resourceState) {
6348 // When resourceState is truty it is a Preload state. We cast it for clarity
6349 var preloadState = resourceState;
6350
6351 if (preloadState.length === 2) {
6352 adoptPreloadCredentials(resource.props, preloadState);
6353 }
6354
6355 var preloadResource = renderState.preloads.stylesheets.get(key);
6356
6357 if (preloadResource && preloadResource.length > 0) {
6358 // The Preload for this resource was created in this render pass and has not flushed yet so
6359 // we need to clear it to avoid it flushing.
6360 preloadResource.length = 0;
6361 } else {
6362 // Either the preload resource from this render already flushed in this render pass
6363 // or the preload flushed in a prior pass (prerender). In either case we need to mark
6364 // this resource as already having been preloaded.
6365 resource.state = PRELOADED;
6366 }
6367 } // We add the newly created resource to our StyleQueue and if necessary
6368 // track the resource with the currently rendering boundary
6369
6370
6371 styleQueue.sheets.set(key, resource); // Notify the request that there are resources to flush even if no work is currently happening
6372
6373 flushResources(request);
6374 }
6375 }
6376}
6377
6378function preinitScript(src, options) {
6379 var request = resolveRequest();
6380
6381 if (!request) {
6382 // In async contexts we can sometimes resolve resources from AsyncLocalStorage. If we can't we can also
6383 // possibly get them from the stack if we are not in an async context. Since we were not able to resolve
6384 // the resources for this call in either case we opt to do nothing. We can consider making this a warning
6385 // but there may be times where calling a function outside of render is intentional (i.e. to warm up data
6386 // fetching) and we don't want to warn in those cases.
6387 previousDispatcher.X(
6388 /* preinitScript */
6389 src, options);
6390 return;
6391 }
6392
6393 var resumableState = getResumableState(request);
6394 var renderState = getRenderState(request);
6395
6396 if (src) {
6397 var key = getResourceKey(src);
6398 var hasKey = resumableState.scriptResources.hasOwnProperty(key);
6399 var resourceState = hasKey ? resumableState.scriptResources[key] : undefined;
6400
6401 if (resourceState !== EXISTS) {
6402 // We are going to create this resource now so it is marked as Exists
6403 resumableState.scriptResources[key] = EXISTS;
6404
6405 var props = assign({
6406 src: src,
6407 async: true
6408 }, options);
6409
6410 if (resourceState) {
6411 // When resourceState is truty it is a Preload state. We cast it for clarity
6412 var preloadState = resourceState;
6413
6414 if (preloadState.length === 2) {
6415 adoptPreloadCredentials(props, preloadState);
6416 }
6417
6418 var preloadResource = renderState.preloads.scripts.get(key);
6419
6420 if (preloadResource) {
6421 // the preload resource exists was created in this render. Now that we have
6422 // a script resource which will emit earlier than a preload would if it
6423 // hasn't already flushed we prevent it from flushing by zeroing the length
6424 preloadResource.length = 0;
6425 }
6426 }
6427
6428 var resource = []; // Add to the script flushing queue
6429
6430 renderState.scripts.add(resource); // encode the tag as Chunks
6431
6432 pushScriptImpl(resource, props); // Notify the request that there are resources to flush even if no work is currently happening
6433
6434 flushResources(request);
6435 }
6436
6437 return;
6438 }
6439}
6440
6441function preinitModuleScript(src, options) {
6442 var request = resolveRequest();
6443
6444 if (!request) {
6445 // In async contexts we can sometimes resolve resources from AsyncLocalStorage. If we can't we can also
6446 // possibly get them from the stack if we are not in an async context. Since we were not able to resolve
6447 // the resources for this call in either case we opt to do nothing. We can consider making this a warning
6448 // but there may be times where calling a function outside of render is intentional (i.e. to warm up data
6449 // fetching) and we don't want to warn in those cases.
6450 previousDispatcher.M(
6451 /* preinitModuleScript */
6452 src, options);
6453 return;
6454 }
6455
6456 var resumableState = getResumableState(request);
6457 var renderState = getRenderState(request);
6458
6459 if (src) {
6460 var key = getResourceKey(src);
6461 var hasKey = resumableState.moduleScriptResources.hasOwnProperty(key);
6462 var resourceState = hasKey ? resumableState.moduleScriptResources[key] : undefined;
6463
6464 if (resourceState !== EXISTS) {
6465 // We are going to create this resource now so it is marked as Exists
6466 resumableState.moduleScriptResources[key] = EXISTS;
6467
6468 var props = assign({
6469 src: src,
6470 type: 'module',
6471 async: true
6472 }, options);
6473
6474 if (resourceState) {
6475 // When resourceState is truty it is a Preload state. We cast it for clarity
6476 var preloadState = resourceState;
6477
6478 if (preloadState.length === 2) {
6479 adoptPreloadCredentials(props, preloadState);
6480 }
6481
6482 var preloadResource = renderState.preloads.moduleScripts.get(key);
6483
6484 if (preloadResource) {
6485 // the preload resource exists was created in this render. Now that we have
6486 // a script resource which will emit earlier than a preload would if it
6487 // hasn't already flushed we prevent it from flushing by zeroing the length
6488 preloadResource.length = 0;
6489 }
6490 }
6491
6492 var resource = []; // Add to the script flushing queue
6493
6494 renderState.scripts.add(resource); // encode the tag as Chunks
6495
6496 pushScriptImpl(resource, props); // Notify the request that there are resources to flush even if no work is currently happening
6497
6498 flushResources(request);
6499 }
6500
6501 return;
6502 }
6503} // This function is only safe to call at Request start time since it assumes
6504// that each module has not already been preloaded. If we find a need to preload
6505// scripts at any other point in time we will need to check whether the preload
6506// already exists and not assume it
6507
6508
6509function preloadBootstrapScriptOrModule(resumableState, renderState, href, props) {
6510 var key = getResourceKey(href);
6511
6512 {
6513 if (resumableState.scriptResources.hasOwnProperty(key) || resumableState.moduleScriptResources.hasOwnProperty(key)) {
6514 // This is coded as a React error because it should be impossible for a userspace preload to preempt this call
6515 // If a userspace preload can preempt it then this assumption is broken and we need to reconsider this strategy
6516 // rather than instruct the user to not preload their bootstrap scripts themselves
6517 error('Internal React Error: React expected bootstrap script or module with src "%s" to not have been preloaded already. please file an issue', href);
6518 }
6519 } // The href used for bootstrap scripts and bootstrap modules should never be
6520 // used to preinit the resource. If a script can be preinited then it shouldn't
6521 // be a bootstrap script/module and if it is a bootstrap script/module then it
6522 // must not be safe to emit early. To avoid possibly allowing for preinits of
6523 // bootstrap scripts/modules we occlude these keys.
6524
6525
6526 resumableState.scriptResources[key] = EXISTS;
6527 resumableState.moduleScriptResources[key] = EXISTS;
6528 var resource = [];
6529 pushLinkImpl(resource, props);
6530 renderState.bootstrapScripts.add(resource);
6531}
6532
6533function preloadAsStylePropsFromProps(href, props) {
6534 return {
6535 rel: 'preload',
6536 as: 'style',
6537 href: href,
6538 crossOrigin: props.crossOrigin,
6539 fetchPriority: props.fetchPriority,
6540 integrity: props.integrity,
6541 media: props.media,
6542 hrefLang: props.hrefLang,
6543 referrerPolicy: props.referrerPolicy
6544 };
6545}
6546
6547function stylesheetPropsFromRawProps(rawProps) {
6548 return assign({}, rawProps, {
6549 'data-precedence': rawProps.precedence,
6550 precedence: null
6551 });
6552}
6553
6554function adoptPreloadCredentials(target, preloadState) {
6555 if (target.crossOrigin == null) target.crossOrigin = preloadState[0];
6556 if (target.integrity == null) target.integrity = preloadState[1];
6557}
6558
6559function getPrefetchDNSAsHeader(href) {
6560 var escapedHref = escapeHrefForLinkHeaderURLContext(href);
6561 return "<" + escapedHref + ">; rel=dns-prefetch";
6562}
6563
6564function getPreconnectAsHeader(href, crossOrigin) {
6565 var escapedHref = escapeHrefForLinkHeaderURLContext(href);
6566 var value = "<" + escapedHref + ">; rel=preconnect";
6567
6568 if (typeof crossOrigin === 'string') {
6569 var escapedCrossOrigin = escapeStringForLinkHeaderQuotedParamValueContext(crossOrigin, 'crossOrigin');
6570 value += "; crossorigin=\"" + escapedCrossOrigin + "\"";
6571 }
6572
6573 return value;
6574}
6575
6576function getPreloadAsHeader(href, as, params) {
6577 var escapedHref = escapeHrefForLinkHeaderURLContext(href);
6578 var escapedAs = escapeStringForLinkHeaderQuotedParamValueContext(as, 'as');
6579 var value = "<" + escapedHref + ">; rel=preload; as=\"" + escapedAs + "\"";
6580
6581 for (var paramName in params) {
6582 if (hasOwnProperty.call(params, paramName)) {
6583 var paramValue = params[paramName];
6584
6585 if (typeof paramValue === 'string') {
6586 value += "; " + paramName.toLowerCase() + "=\"" + escapeStringForLinkHeaderQuotedParamValueContext(paramValue, paramName) + "\"";
6587 }
6588 }
6589 }
6590
6591 return value;
6592}
6593
6594function getStylesheetPreloadAsHeader(stylesheet) {
6595 var props = stylesheet.props;
6596 var preloadOptions = {
6597 crossOrigin: props.crossOrigin,
6598 integrity: props.integrity,
6599 nonce: props.nonce,
6600 type: props.type,
6601 fetchPriority: props.fetchPriority,
6602 referrerPolicy: props.referrerPolicy,
6603 media: props.media
6604 };
6605 return getPreloadAsHeader(props.href, 'style', preloadOptions);
6606} // This escaping function is only safe to use for href values being written into
6607// a "Link" header in between `<` and `>` characters. The primary concern with the href is
6608// to escape the bounding characters as well as new lines. This is unsafe to use in any other
6609// context
6610
6611
6612var regexForHrefInLinkHeaderURLContext = /[<>\r\n]/g;
6613
6614function escapeHrefForLinkHeaderURLContext(hrefInput) {
6615 {
6616 checkAttributeStringCoercion(hrefInput, 'href');
6617 }
6618
6619 var coercedHref = '' + hrefInput;
6620 return coercedHref.replace(regexForHrefInLinkHeaderURLContext, escapeHrefForLinkHeaderURLContextReplacer);
6621}
6622
6623function escapeHrefForLinkHeaderURLContextReplacer(match) {
6624 switch (match) {
6625 case '<':
6626 return '%3C';
6627
6628 case '>':
6629 return '%3E';
6630
6631 case '\n':
6632 return '%0A';
6633
6634 case '\r':
6635 return '%0D';
6636
6637 default:
6638 {
6639 // eslint-disable-next-line react-internal/prod-error-codes
6640 throw new Error('escapeLinkHrefForHeaderContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
6641 }
6642 }
6643} // This escaping function is only safe to use for quoted param values in an HTTP header.
6644// It is unsafe to use for any value not inside quote marks in parater value position.
6645
6646
6647var regexForLinkHeaderQuotedParamValueContext = /["';,\r\n]/g;
6648
6649function escapeStringForLinkHeaderQuotedParamValueContext(value, name) {
6650 {
6651 checkOptionStringCoercion(value, name);
6652 }
6653
6654 var coerced = '' + value;
6655 return coerced.replace(regexForLinkHeaderQuotedParamValueContext, escapeStringForLinkHeaderQuotedParamValueContextReplacer);
6656}
6657
6658function escapeStringForLinkHeaderQuotedParamValueContextReplacer(match) {
6659 switch (match) {
6660 case '"':
6661 return '%22';
6662
6663 case "'":
6664 return '%27';
6665
6666 case ';':
6667 return '%3B';
6668
6669 case ',':
6670 return '%2C';
6671
6672 case '\n':
6673 return '%0A';
6674
6675 case '\r':
6676 return '%0D';
6677
6678 default:
6679 {
6680 // eslint-disable-next-line react-internal/prod-error-codes
6681 throw new Error('escapeStringForLinkHeaderQuotedParamValueContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');
6682 }
6683 }
6684}
6685
6686function hoistStyleQueueDependency(styleQueue) {
6687 this.styles.add(styleQueue);
6688}
6689
6690function hoistStylesheetDependency(stylesheet) {
6691 this.stylesheets.add(stylesheet);
6692}
6693
6694function hoistHoistables(parentState, childState) {
6695 childState.styles.forEach(hoistStyleQueueDependency, parentState);
6696 childState.stylesheets.forEach(hoistStylesheetDependency, parentState);
6697} // This function is called at various times depending on whether we are rendering
6698// or prerendering. In this implementation we only actually emit headers once and
6699// subsequent calls are ignored. We track whether the request has a completed shell
6700// to determine whether we will follow headers with a flush including stylesheets.
6701// In the context of prerrender we don't have a completed shell when the request finishes
6702// with a postpone in the shell. In the context of a render we don't have a completed shell
6703// if this is called before the shell finishes rendering which usually will happen anytime
6704// anything suspends in the shell.
6705
6706function emitEarlyPreloads(renderState, resumableState, shellComplete) {
6707 var onHeaders = renderState.onHeaders;
6708
6709 if (onHeaders) {
6710 var headers = renderState.headers;
6711
6712 if (headers) {
6713 // Even if onHeaders throws we don't want to call this again so
6714 // we drop the headers state from this point onwards.
6715 renderState.headers = null;
6716 var linkHeader = headers.preconnects;
6717
6718 if (headers.fontPreloads) {
6719 if (linkHeader) {
6720 linkHeader += ', ';
6721 }
6722
6723 linkHeader += headers.fontPreloads;
6724 }
6725
6726 if (headers.highImagePreloads) {
6727 if (linkHeader) {
6728 linkHeader += ', ';
6729 }
6730
6731 linkHeader += headers.highImagePreloads;
6732 }
6733
6734 if (!shellComplete) {
6735 // We use raw iterators because we want to be able to halt iteration
6736 // We could refactor renderState to store these dually in arrays to
6737 // make this more efficient at the cost of additional memory and
6738 // write overhead. However this code only runs once per request so
6739 // for now I consider this sufficient.
6740 var queueIter = renderState.styles.values();
6741
6742 outer: for (var queueStep = queueIter.next(); headers.remainingCapacity > 0 && !queueStep.done; queueStep = queueIter.next()) {
6743 var sheets = queueStep.value.sheets;
6744 var sheetIter = sheets.values();
6745
6746 for (var sheetStep = sheetIter.next(); headers.remainingCapacity > 0 && !sheetStep.done; sheetStep = sheetIter.next()) {
6747 var sheet = sheetStep.value;
6748 var props = sheet.props;
6749 var key = getResourceKey(props.href);
6750 var header = getStylesheetPreloadAsHeader(sheet); // We mutate the capacity b/c we don't want to keep checking if later headers will fit.
6751 // This means that a particularly long header might close out the header queue where later
6752 // headers could still fit. We could in the future alter the behavior here based on prerender vs render
6753 // since during prerender we aren't as concerned with pure runtime performance.
6754
6755 if ((headers.remainingCapacity -= header.length) >= 2) {
6756 renderState.resets.style[key] = PRELOAD_NO_CREDS;
6757
6758 if (linkHeader) {
6759 linkHeader += ', ';
6760 }
6761
6762 linkHeader += header; // We already track that the resource exists in resumableState however
6763 // if the resumableState resets because we postponed in the shell
6764 // which is what is happening in this branch if we are prerendering
6765 // then we will end up resetting the resumableState. When it resets we
6766 // want to record the fact that this stylesheet was already preloaded
6767
6768 renderState.resets.style[key] = typeof props.crossOrigin === 'string' || typeof props.integrity === 'string' ? [props.crossOrigin, props.integrity] : PRELOAD_NO_CREDS;
6769 } else {
6770 break outer;
6771 }
6772 }
6773 }
6774 }
6775
6776 if (linkHeader) {
6777 onHeaders({
6778 Link: linkHeader
6779 });
6780 } else {
6781 // We still call this with no headers because a user may be using it as a signal that
6782 // it React will not provide any headers
6783 onHeaders({});
6784 }
6785
6786 return;
6787 }
6788 }
6789}
6790var NotPendingTransition = NotPending;
6791
6792function getWrappedName(outerType, innerType, wrapperName) {
6793 var displayName = outerType.displayName;
6794
6795 if (displayName) {
6796 return displayName;
6797 }
6798
6799 var functionName = innerType.displayName || innerType.name || '';
6800 return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
6801} // Keep in sync with react-reconciler/getComponentNameFromFiber
6802
6803
6804function getContextName(type) {
6805 return type.displayName || 'Context';
6806}
6807
6808var REACT_CLIENT_REFERENCE = Symbol.for('react.client.reference'); // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
6809
6810function getComponentNameFromType(type) {
6811 if (type == null) {
6812 // Host root, text node or just invalid type.
6813 return null;
6814 }
6815
6816 if (typeof type === 'function') {
6817 if (type.$$typeof === REACT_CLIENT_REFERENCE) {
6818 // TODO: Create a convention for naming client references with debug info.
6819 return null;
6820 }
6821
6822 return type.displayName || type.name || null;
6823 }
6824
6825 if (typeof type === 'string') {
6826 return type;
6827 }
6828
6829 switch (type) {
6830 case REACT_FRAGMENT_TYPE:
6831 return 'Fragment';
6832
6833 case REACT_PORTAL_TYPE:
6834 return 'Portal';
6835
6836 case REACT_PROFILER_TYPE:
6837 return 'Profiler';
6838
6839 case REACT_STRICT_MODE_TYPE:
6840 return 'StrictMode';
6841
6842 case REACT_SUSPENSE_TYPE:
6843 return 'Suspense';
6844
6845 case REACT_SUSPENSE_LIST_TYPE:
6846 return 'SuspenseList';
6847
6848 }
6849
6850 if (typeof type === 'object') {
6851 {
6852 if (typeof type.tag === 'number') {
6853 error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
6854 }
6855 }
6856
6857 switch (type.$$typeof) {
6858 case REACT_PROVIDER_TYPE:
6859 {
6860 return null;
6861 }
6862
6863 case REACT_CONTEXT_TYPE:
6864 var context = type;
6865
6866 {
6867 return getContextName(context) + '.Provider';
6868 }
6869
6870 case REACT_CONSUMER_TYPE:
6871 {
6872 var consumer = type;
6873 return getContextName(consumer._context) + '.Consumer';
6874 }
6875
6876 case REACT_FORWARD_REF_TYPE:
6877 return getWrappedName(type, type.render, 'ForwardRef');
6878
6879 case REACT_MEMO_TYPE:
6880 var outerName = type.displayName || null;
6881
6882 if (outerName !== null) {
6883 return outerName;
6884 }
6885
6886 return getComponentNameFromType(type.type) || 'Memo';
6887
6888 case REACT_LAZY_TYPE:
6889 {
6890 var lazyComponent = type;
6891 var payload = lazyComponent._payload;
6892 var init = lazyComponent._init;
6893
6894 try {
6895 return getComponentNameFromType(init(payload));
6896 } catch (x) {
6897 return null;
6898 }
6899 }
6900 }
6901 }
6902
6903 return null;
6904}
6905
6906var emptyContextObject = {};
6907
6908{
6909 Object.freeze(emptyContextObject);
6910}
6911
6912var rendererSigil;
6913
6914{
6915 // Use this to detect multiple renderers using the same context
6916 rendererSigil = {};
6917} // Used to store the parent path of all context overrides in a shared linked list.
6918// Forming a reverse tree.
6919// The structure of a context snapshot is an implementation of this file.
6920// Currently, it's implemented as tracking the current active node.
6921
6922
6923var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
6924// This global (actually thread local) state represents what state all those "current",
6925// fields are currently in.
6926
6927var currentActiveSnapshot = null;
6928
6929function popNode(prev) {
6930 {
6931 prev.context._currentValue = prev.parentValue;
6932 }
6933}
6934
6935function pushNode(next) {
6936 {
6937 next.context._currentValue = next.value;
6938 }
6939}
6940
6941function popToNearestCommonAncestor(prev, next) {
6942 if (prev === next) ; else {
6943 popNode(prev);
6944 var parentPrev = prev.parent;
6945 var parentNext = next.parent;
6946
6947 if (parentPrev === null) {
6948 if (parentNext !== null) {
6949 throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
6950 }
6951 } else {
6952 if (parentNext === null) {
6953 throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
6954 }
6955
6956 popToNearestCommonAncestor(parentPrev, parentNext);
6957 } // On the way back, we push the new ones that weren't common.
6958
6959
6960 pushNode(next);
6961 }
6962}
6963
6964function popAllPrevious(prev) {
6965 popNode(prev);
6966 var parentPrev = prev.parent;
6967
6968 if (parentPrev !== null) {
6969 popAllPrevious(parentPrev);
6970 }
6971}
6972
6973function pushAllNext(next) {
6974 var parentNext = next.parent;
6975
6976 if (parentNext !== null) {
6977 pushAllNext(parentNext);
6978 }
6979
6980 pushNode(next);
6981}
6982
6983function popPreviousToCommonLevel(prev, next) {
6984 popNode(prev);
6985 var parentPrev = prev.parent;
6986
6987 if (parentPrev === null) {
6988 throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
6989 }
6990
6991 if (parentPrev.depth === next.depth) {
6992 // We found the same level. Now we just need to find a shared ancestor.
6993 popToNearestCommonAncestor(parentPrev, next);
6994 } else {
6995 // We must still be deeper.
6996 popPreviousToCommonLevel(parentPrev, next);
6997 }
6998}
6999
7000function popNextToCommonLevel(prev, next) {
7001 var parentNext = next.parent;
7002
7003 if (parentNext === null) {
7004 throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
7005 }
7006
7007 if (prev.depth === parentNext.depth) {
7008 // We found the same level. Now we just need to find a shared ancestor.
7009 popToNearestCommonAncestor(prev, parentNext);
7010 } else {
7011 // We must still be deeper.
7012 popNextToCommonLevel(prev, parentNext);
7013 }
7014
7015 pushNode(next);
7016} // Perform context switching to the new snapshot.
7017// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
7018// updating all the context's current values. That way reads, always just read the current value.
7019// At the cost of updating contexts even if they're never read by this subtree.
7020
7021
7022function switchContext(newSnapshot) {
7023 // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
7024 // We also need to update any new contexts that are now on the stack with the deepest value.
7025 // The easiest way to update new contexts is to just reapply them in reverse order from the
7026 // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
7027 // for that. Therefore this algorithm is recursive.
7028 // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
7029 // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
7030 // 3) Then we reapply new contexts on the way back up the stack.
7031 var prev = currentActiveSnapshot;
7032 var next = newSnapshot;
7033
7034 if (prev !== next) {
7035 if (prev === null) {
7036 // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev.
7037 pushAllNext(next);
7038 } else if (next === null) {
7039 popAllPrevious(prev);
7040 } else if (prev.depth === next.depth) {
7041 popToNearestCommonAncestor(prev, next);
7042 } else if (prev.depth > next.depth) {
7043 popPreviousToCommonLevel(prev, next);
7044 } else {
7045 popNextToCommonLevel(prev, next);
7046 }
7047
7048 currentActiveSnapshot = next;
7049 }
7050}
7051function pushProvider(context, nextValue) {
7052 var prevValue;
7053
7054 {
7055 prevValue = context._currentValue;
7056 context._currentValue = nextValue;
7057
7058 {
7059 if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
7060 error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
7061 }
7062
7063 context._currentRenderer = rendererSigil;
7064 }
7065 }
7066
7067 var prevNode = currentActiveSnapshot;
7068 var newNode = {
7069 parent: prevNode,
7070 depth: prevNode === null ? 0 : prevNode.depth + 1,
7071 context: context,
7072 parentValue: prevValue,
7073 value: nextValue
7074 };
7075 currentActiveSnapshot = newNode;
7076 return newNode;
7077}
7078function popProvider(context) {
7079 var prevSnapshot = currentActiveSnapshot;
7080
7081 if (prevSnapshot === null) {
7082 throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
7083 }
7084
7085 {
7086 if (prevSnapshot.context !== context) {
7087 error('The parent context is not the expected context. This is probably a bug in React.');
7088 }
7089 }
7090
7091 {
7092 var value = prevSnapshot.parentValue;
7093 prevSnapshot.context._currentValue = value;
7094
7095 {
7096 if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
7097 error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
7098 }
7099
7100 context._currentRenderer = rendererSigil;
7101 }
7102 }
7103
7104 return currentActiveSnapshot = prevSnapshot.parent;
7105}
7106function getActiveContext() {
7107 return currentActiveSnapshot;
7108}
7109function readContext$1(context) {
7110 var value = context._currentValue ;
7111 return value;
7112}
7113
7114/**
7115 * `ReactInstanceMap` maintains a mapping from a public facing stateful
7116 * instance (key) and the internal representation (value). This allows public
7117 * methods to accept the user facing instance as an argument and map them back
7118 * to internal methods.
7119 *
7120 * Note that this module is currently shared and assumed to be stateless.
7121 * If this becomes an actual Map, that will break.
7122 */
7123function get(key) {
7124 return key._reactInternals;
7125}
7126function set(key, value) {
7127 key._reactInternals = value;
7128}
7129
7130var didWarnAboutNoopUpdateForComponent = {};
7131var didWarnAboutDeprecatedWillMount = {};
7132var didWarnAboutUninitializedState;
7133var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
7134var didWarnAboutLegacyLifecyclesAndDerivedState;
7135var didWarnAboutUndefinedDerivedState;
7136var didWarnAboutDirectlyAssigningPropsToState;
7137var didWarnAboutInvalidateContextType;
7138var didWarnOnInvalidCallback;
7139
7140{
7141 didWarnAboutUninitializedState = new Set();
7142 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
7143 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
7144 didWarnAboutDirectlyAssigningPropsToState = new Set();
7145 didWarnAboutUndefinedDerivedState = new Set();
7146 didWarnAboutInvalidateContextType = new Set();
7147 didWarnOnInvalidCallback = new Set();
7148}
7149
7150function warnOnInvalidCallback(callback) {
7151 {
7152 if (callback === null || typeof callback === 'function') {
7153 return;
7154 } // eslint-disable-next-line react-internal/safe-string-coercion
7155
7156
7157 var key = String(callback);
7158
7159 if (!didWarnOnInvalidCallback.has(key)) {
7160 didWarnOnInvalidCallback.add(key);
7161
7162 error('Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
7163 }
7164 }
7165}
7166
7167function warnOnUndefinedDerivedState(type, partialState) {
7168 {
7169 if (partialState === undefined) {
7170 var componentName = getComponentNameFromType(type) || 'Component';
7171
7172 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
7173 didWarnAboutUndefinedDerivedState.add(componentName);
7174
7175 error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
7176 }
7177 }
7178 }
7179}
7180
7181function warnNoop(publicInstance, callerName) {
7182 {
7183 var _constructor = publicInstance.constructor;
7184 var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';
7185 var warningKey = componentName + '.' + callerName;
7186
7187 if (didWarnAboutNoopUpdateForComponent[warningKey]) {
7188 return;
7189 }
7190
7191 error('Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, componentName);
7192
7193 didWarnAboutNoopUpdateForComponent[warningKey] = true;
7194 }
7195}
7196
7197var classComponentUpdater = {
7198 isMounted: function (inst) {
7199 return false;
7200 },
7201 // $FlowFixMe[missing-local-annot]
7202 enqueueSetState: function (inst, payload, callback) {
7203 var internals = get(inst);
7204
7205 if (internals.queue === null) {
7206 warnNoop(inst, 'setState');
7207 } else {
7208 internals.queue.push(payload);
7209
7210 {
7211 if (callback !== undefined && callback !== null) {
7212 warnOnInvalidCallback(callback);
7213 }
7214 }
7215 }
7216 },
7217 enqueueReplaceState: function (inst, payload, callback) {
7218 var internals = get(inst);
7219 internals.replace = true;
7220 internals.queue = [payload];
7221
7222 {
7223 if (callback !== undefined && callback !== null) {
7224 warnOnInvalidCallback(callback);
7225 }
7226 }
7227 },
7228 // $FlowFixMe[missing-local-annot]
7229 enqueueForceUpdate: function (inst, callback) {
7230 var internals = get(inst);
7231
7232 if (internals.queue === null) {
7233 warnNoop(inst, 'forceUpdate');
7234 } else {
7235 {
7236 if (callback !== undefined && callback !== null) {
7237 warnOnInvalidCallback(callback);
7238 }
7239 }
7240 }
7241 }
7242};
7243
7244function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {
7245 var partialState = getDerivedStateFromProps(nextProps, prevState);
7246
7247 {
7248 warnOnUndefinedDerivedState(ctor, partialState);
7249 } // Merge the partial state and the previous state.
7250
7251
7252 var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
7253 return newState;
7254}
7255
7256function constructClassInstance(ctor, props, maskedLegacyContext) {
7257 var context = emptyContextObject;
7258 var contextType = ctor.contextType;
7259
7260 {
7261 if ('contextType' in ctor) {
7262 var isValid = // Allow null for conditional declaration
7263 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE;
7264
7265 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
7266 didWarnAboutInvalidateContextType.add(ctor);
7267 var addendum = '';
7268
7269 if (contextType === undefined) {
7270 addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
7271 } else if (typeof contextType !== 'object') {
7272 addendum = ' However, it is set to a ' + typeof contextType + '.';
7273 } else if (contextType.$$typeof === REACT_CONSUMER_TYPE) {
7274 addendum = ' Did you accidentally pass the Context.Consumer instead?';
7275 } else {
7276 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
7277 }
7278
7279 error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
7280 }
7281 }
7282 }
7283
7284 if (typeof contextType === 'object' && contextType !== null) {
7285 context = readContext$1(contextType);
7286 }
7287
7288 var instance = new ctor(props, context);
7289
7290 {
7291 if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {
7292 var componentName = getComponentNameFromType(ctor) || 'Component';
7293
7294 if (!didWarnAboutUninitializedState.has(componentName)) {
7295 didWarnAboutUninitializedState.add(componentName);
7296
7297 error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
7298 }
7299 } // If new component APIs are defined, "unsafe" lifecycles won't be called.
7300 // Warn about these lifecycles if they are present.
7301 // Don't warn about react-lifecycles-compat polyfilled methods though.
7302
7303
7304 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
7305 var foundWillMountName = null;
7306 var foundWillReceivePropsName = null;
7307 var foundWillUpdateName = null;
7308
7309 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
7310 foundWillMountName = 'componentWillMount';
7311 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
7312 foundWillMountName = 'UNSAFE_componentWillMount';
7313 }
7314
7315 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
7316 foundWillReceivePropsName = 'componentWillReceiveProps';
7317 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
7318 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
7319 }
7320
7321 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
7322 foundWillUpdateName = 'componentWillUpdate';
7323 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
7324 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
7325 }
7326
7327 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
7328 var _componentName = getComponentNameFromType(ctor) || 'Component';
7329
7330 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
7331
7332 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
7333 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
7334
7335 error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://react.dev/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : '');
7336 }
7337 }
7338 }
7339 }
7340
7341 return instance;
7342}
7343
7344function checkClassInstance(instance, ctor, newProps) {
7345 {
7346 var name = getComponentNameFromType(ctor) || 'Component';
7347 var renderPresent = instance.render;
7348
7349 if (!renderPresent) {
7350 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
7351 error('No `render` method found on the %s ' + 'instance: did you accidentally return an object from the constructor?', name);
7352 } else {
7353 error('No `render` method found on the %s ' + 'instance: you may have forgotten to define `render`.', name);
7354 }
7355 }
7356
7357 if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
7358 error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
7359 }
7360
7361 if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
7362 error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
7363 }
7364
7365 if (instance.propTypes) {
7366 error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
7367 }
7368
7369 if (instance.contextType) {
7370 error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
7371 }
7372
7373 {
7374 if (ctor.childContextTypes) {
7375 error('%s uses the legacy childContextTypes API which was removed in React 19. ' + 'Use React.createContext() instead.', name);
7376 }
7377
7378 if (ctor.contextTypes) {
7379 error('%s uses the legacy contextTypes API which was removed in React 19. ' + 'Use React.createContext() with static contextType instead.', name);
7380 }
7381 }
7382
7383 if (typeof instance.componentShouldUpdate === 'function') {
7384 error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
7385 }
7386
7387 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
7388 error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
7389 }
7390
7391 if (typeof instance.componentDidUnmount === 'function') {
7392 error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
7393 }
7394
7395 if (typeof instance.componentDidReceiveProps === 'function') {
7396 error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
7397 }
7398
7399 if (typeof instance.componentWillRecieveProps === 'function') {
7400 error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
7401 }
7402
7403 if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
7404 error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
7405 }
7406
7407 var hasMutatedProps = instance.props !== newProps;
7408
7409 if (instance.props !== undefined && hasMutatedProps) {
7410 error('When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name);
7411 }
7412
7413 if (instance.defaultProps) {
7414 error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
7415 }
7416
7417 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
7418 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
7419
7420 error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
7421 }
7422
7423 if (typeof instance.getDerivedStateFromProps === 'function') {
7424 error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
7425 }
7426
7427 if (typeof instance.getDerivedStateFromError === 'function') {
7428 error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
7429 }
7430
7431 if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
7432 error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
7433 }
7434
7435 var state = instance.state;
7436
7437 if (state && (typeof state !== 'object' || isArray(state))) {
7438 error('%s.state: must be set to an object or null', name);
7439 }
7440
7441 if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
7442 error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
7443 }
7444 }
7445}
7446
7447function callComponentWillMount(type, instance) {
7448 var oldState = instance.state;
7449
7450 if (typeof instance.componentWillMount === 'function') {
7451 {
7452 if (instance.componentWillMount.__suppressDeprecationWarning !== true) {
7453 var componentName = getComponentNameFromType(type) || 'Unknown';
7454
7455 if (!didWarnAboutDeprecatedWillMount[componentName]) {
7456 warn( // keep this warning in sync with ReactStrictModeWarning.js
7457 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://react.dev/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName);
7458
7459 didWarnAboutDeprecatedWillMount[componentName] = true;
7460 }
7461 }
7462 }
7463
7464 instance.componentWillMount();
7465 }
7466
7467 if (typeof instance.UNSAFE_componentWillMount === 'function') {
7468 instance.UNSAFE_componentWillMount();
7469 }
7470
7471 if (oldState !== instance.state) {
7472 {
7473 error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');
7474 }
7475
7476 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
7477 }
7478}
7479
7480function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {
7481 if (internalInstance.queue !== null && internalInstance.queue.length > 0) {
7482 var oldQueue = internalInstance.queue;
7483 var oldReplace = internalInstance.replace;
7484 internalInstance.queue = null;
7485 internalInstance.replace = false;
7486
7487 if (oldReplace && oldQueue.length === 1) {
7488 inst.state = oldQueue[0];
7489 } else {
7490 var nextState = oldReplace ? oldQueue[0] : inst.state;
7491 var dontMutate = true;
7492
7493 for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
7494 var partial = oldQueue[i];
7495 var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;
7496
7497 if (partialState != null) {
7498 if (dontMutate) {
7499 dontMutate = false;
7500 nextState = assign({}, nextState, partialState);
7501 } else {
7502 assign(nextState, partialState);
7503 }
7504 }
7505 }
7506
7507 inst.state = nextState;
7508 }
7509 } else {
7510 internalInstance.queue = null;
7511 }
7512} // Invokes the mount life-cycles on a previously never rendered instance.
7513
7514
7515function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {
7516 {
7517 checkClassInstance(instance, ctor, newProps);
7518 }
7519
7520 var initialState = instance.state !== undefined ? instance.state : null;
7521 instance.updater = classComponentUpdater;
7522 instance.props = newProps;
7523 instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.
7524 // The internal instance will be used to manage updates that happen during this mount.
7525
7526 var internalInstance = {
7527 queue: [],
7528 replace: false
7529 };
7530 set(instance, internalInstance);
7531 var contextType = ctor.contextType;
7532
7533 if (typeof contextType === 'object' && contextType !== null) {
7534 instance.context = readContext$1(contextType);
7535 } else {
7536 instance.context = emptyContextObject;
7537 }
7538
7539 {
7540 if (instance.state === newProps) {
7541 var componentName = getComponentNameFromType(ctor) || 'Component';
7542
7543 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
7544 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
7545
7546 error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
7547 }
7548 }
7549 }
7550
7551 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
7552
7553 if (typeof getDerivedStateFromProps === 'function') {
7554 instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);
7555 } // In order to support react-lifecycles-compat polyfilled components,
7556 // Unsafe lifecycles should not be invoked for components using the new APIs.
7557
7558
7559 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
7560 callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's
7561 // process them now.
7562
7563 processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);
7564 }
7565}
7566
7567// Ids are base 32 strings whose binary representation corresponds to the
7568// position of a node in a tree.
7569// Every time the tree forks into multiple children, we add additional bits to
7570// the left of the sequence that represent the position of the child within the
7571// current level of children.
7572//
7573// 00101 00010001011010101
7574// ╰─┬─╯ ╰───────┬───────╯
7575// Fork 5 of 20 Parent id
7576//
7577// The leading 0s are important. In the above example, you only need 3 bits to
7578// represent slot 5. However, you need 5 bits to represent all the forks at
7579// the current level, so we must account for the empty bits at the end.
7580//
7581// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
7582// the zeroth id at a level would be indistinguishable from its parent.
7583//
7584// If a node has only one child, and does not materialize an id (i.e. does not
7585// contain a useId hook), then we don't need to allocate any space in the
7586// sequence. It's treated as a transparent indirection. For example, these two
7587// trees produce the same ids:
7588//
7589// <> <>
7590// <Indirection> <A />
7591// <A /> <B />
7592// </Indirection> </>
7593// <B />
7594// </>
7595//
7596// However, we cannot skip any node that materializes an id. Otherwise, a parent
7597// id that does not fork would be indistinguishable from its child id. For
7598// example, this tree does not fork, but the parent and child must have
7599// different ids.
7600//
7601// <Parent>
7602// <Child />
7603// </Parent>
7604//
7605// To handle this scenario, every time we materialize an id, we allocate a
7606// new level with a single slot. You can think of this as a fork with only one
7607// prong, or an array of children with length 1.
7608//
7609// It's possible for the size of the sequence to exceed 32 bits, the max
7610// size for bitwise operations. When this happens, we make more room by
7611// converting the right part of the id to a string and storing it in an overflow
7612// variable. We use a base 32 string representation, because 32 is the largest
7613// power of 2 that is supported by toString(). We want the base to be large so
7614// that the resulting ids are compact, and we want the base to be a power of 2
7615// because every log2(base) bits corresponds to a single character, i.e. every
7616// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
7617// affecting the final result.
7618var emptyTreeContext = {
7619 id: 1,
7620 overflow: ''
7621};
7622function getTreeId(context) {
7623 var overflow = context.overflow;
7624 var idWithLeadingBit = context.id;
7625 var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
7626 return id.toString(32) + overflow;
7627}
7628function pushTreeContext(baseContext, totalChildren, index) {
7629 var baseIdWithLeadingBit = baseContext.id;
7630 var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
7631 // of the id; we use it to account for leading 0s.
7632
7633 var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
7634 var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
7635 var slot = index + 1;
7636 var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
7637 // consideration the leading 1 we use to mark the end of the sequence.
7638
7639 if (length > 30) {
7640 // We overflowed the bitwise-safe range. Fall back to slower algorithm.
7641 // This branch assumes the length of the base id is greater than 5; it won't
7642 // work for smaller ids, because you need 5 bits per character.
7643 //
7644 // We encode the id in multiple steps: first the base id, then the
7645 // remaining digits.
7646 //
7647 // Each 5 bit sequence corresponds to a single base 32 character. So for
7648 // example, if the current id is 23 bits long, we can convert 20 of those
7649 // bits into a string of 4 characters, with 3 bits left over.
7650 //
7651 // First calculate how many bits in the base id represent a complete
7652 // sequence of characters.
7653 var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.
7654
7655 var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.
7656
7657 var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.
7658
7659 var restOfBaseId = baseId >> numberOfOverflowBits;
7660 var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
7661 // we made more room, this time it won't overflow.
7662
7663 var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
7664 var restOfNewBits = slot << restOfBaseLength;
7665 var id = restOfNewBits | restOfBaseId;
7666 var overflow = newOverflow + baseOverflow;
7667 return {
7668 id: 1 << restOfLength | id,
7669 overflow: overflow
7670 };
7671 } else {
7672 // Normal path
7673 var newBits = slot << baseLength;
7674
7675 var _id = newBits | baseId;
7676
7677 var _overflow = baseOverflow;
7678 return {
7679 id: 1 << length | _id,
7680 overflow: _overflow
7681 };
7682 }
7683}
7684
7685function getBitLength(number) {
7686 return 32 - clz32(number);
7687}
7688
7689function getLeadingBit(id) {
7690 return 1 << getBitLength(id) - 1;
7691} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.
7692
7693
7694var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
7695// Based on:
7696// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
7697
7698var log = Math.log;
7699var LN2 = Math.LN2;
7700
7701function clz32Fallback(x) {
7702 var asUint = x >>> 0;
7703
7704 if (asUint === 0) {
7705 return 32;
7706 }
7707
7708 return 31 - (log(asUint) / LN2 | 0) | 0;
7709}
7710
7711// Corresponds to ReactFiberWakeable and ReactFlightWakeable modules. Generally,
7712// changes to one module should be reflected in the others.
7713// TODO: Rename this module and the corresponding Fiber one to "Thenable"
7714// instead of "Wakeable". Or some other more appropriate name.
7715// An error that is thrown (e.g. by `use`) to trigger Suspense. If we
7716// detect this is caught by userspace, we'll log a warning in development.
7717var 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`");
7718function createThenableState() {
7719 // The ThenableState is created the first time a component suspends. If it
7720 // suspends again, we'll reuse the same state.
7721 return [];
7722}
7723
7724function noop$2() {}
7725
7726function trackUsedThenable(thenableState, thenable, index) {
7727 var previous = thenableState[index];
7728
7729 if (previous === undefined) {
7730 thenableState.push(thenable);
7731 } else {
7732 if (previous !== thenable) {
7733 // Reuse the previous thenable, and drop the new one. We can assume
7734 // they represent the same value, because components are idempotent.
7735 // Avoid an unhandled rejection errors for the Promises that we'll
7736 // intentionally ignore.
7737 thenable.then(noop$2, noop$2);
7738 thenable = previous;
7739 }
7740 } // We use an expando to track the status and result of a thenable so that we
7741 // can synchronously unwrap the value. Think of this as an extension of the
7742 // Promise API, or a custom interface that is a superset of Thenable.
7743 //
7744 // If the thenable doesn't have a status, set it to "pending" and attach
7745 // a listener that will update its status and result when it resolves.
7746
7747
7748 switch (thenable.status) {
7749 case 'fulfilled':
7750 {
7751 var fulfilledValue = thenable.value;
7752 return fulfilledValue;
7753 }
7754
7755 case 'rejected':
7756 {
7757 var rejectedError = thenable.reason;
7758 throw rejectedError;
7759 }
7760
7761 default:
7762 {
7763 if (typeof thenable.status === 'string') {
7764 // Only instrument the thenable if the status if not defined. If
7765 // it's defined, but an unknown value, assume it's been instrumented by
7766 // some custom userspace implementation. We treat it as "pending".
7767 // Attach a dummy listener, to ensure that any lazy initialization can
7768 // happen. Flight lazily parses JSON when the value is actually awaited.
7769 thenable.then(noop$2, noop$2);
7770 } else {
7771 var pendingThenable = thenable;
7772 pendingThenable.status = 'pending';
7773 pendingThenable.then(function (fulfilledValue) {
7774 if (thenable.status === 'pending') {
7775 var fulfilledThenable = thenable;
7776 fulfilledThenable.status = 'fulfilled';
7777 fulfilledThenable.value = fulfilledValue;
7778 }
7779 }, function (error) {
7780 if (thenable.status === 'pending') {
7781 var rejectedThenable = thenable;
7782 rejectedThenable.status = 'rejected';
7783 rejectedThenable.reason = error;
7784 }
7785 });
7786 } // Check one more time in case the thenable resolved synchronously
7787
7788
7789 switch (thenable.status) {
7790 case 'fulfilled':
7791 {
7792 var fulfilledThenable = thenable;
7793 return fulfilledThenable.value;
7794 }
7795
7796 case 'rejected':
7797 {
7798 var rejectedThenable = thenable;
7799 throw rejectedThenable.reason;
7800 }
7801 } // Suspend.
7802 //
7803 // Throwing here is an implementation detail that allows us to unwind the
7804 // call stack. But we shouldn't allow it to leak into userspace. Throw an
7805 // opaque placeholder value instead of the actual thenable. If it doesn't
7806 // get captured by the work loop, log a warning, because that means
7807 // something in userspace must have caught it.
7808
7809
7810 suspendedThenable = thenable;
7811 throw SuspenseException;
7812 }
7813 }
7814}
7815// passed to the rest of the Suspense implementation — which, for historical
7816// reasons, expects to receive a thenable.
7817
7818var suspendedThenable = null;
7819function getSuspendedThenable() {
7820 // This is called right after `use` suspends by throwing an exception. `use`
7821 // throws an opaque value instead of the thenable itself so that it can't be
7822 // caught in userspace. Then the work loop accesses the actual thenable using
7823 // this function.
7824 if (suspendedThenable === null) {
7825 throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.');
7826 }
7827
7828 var thenable = suspendedThenable;
7829 suspendedThenable = null;
7830 return thenable;
7831}
7832
7833/**
7834 * inlined Object.is polyfill to avoid requiring consumers ship their own
7835 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
7836 */
7837function is(x, y) {
7838 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
7839 ;
7840}
7841
7842var objectIs = // $FlowFixMe[method-unbinding]
7843typeof Object.is === 'function' ? Object.is : is;
7844
7845var currentlyRenderingComponent = null;
7846var currentlyRenderingTask = null;
7847var currentlyRenderingRequest = null;
7848var currentlyRenderingKeyPath = null;
7849var firstWorkInProgressHook = null;
7850var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook
7851
7852var isReRender = false; // Whether an update was scheduled during the currently executing render pass.
7853
7854var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component
7855
7856var localIdCounter = 0; // Chunks that should be pushed to the stream once the component
7857// finishes rendering.
7858// Counts the number of useActionState calls in this component
7859
7860var actionStateCounter = 0; // The index of the useActionState hook that matches the one passed in at the
7861// root during an MPA navigation, if any.
7862
7863var actionStateMatchingIndex = -1; // Counts the number of use(thenable) calls in this component
7864
7865var thenableIndexCounter = 0;
7866var thenableState = null; // Lazily created map of render-phase updates
7867
7868var renderPhaseUpdates = null; // Counter to prevent infinite loops.
7869
7870var numberOfReRenders = 0;
7871var RE_RENDER_LIMIT = 25;
7872var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook
7873
7874var currentHookNameInDev;
7875
7876function resolveCurrentlyRenderingComponent() {
7877 if (currentlyRenderingComponent === null) {
7878 throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.');
7879 }
7880
7881 {
7882 if (isInHookUserCodeInDev) {
7883 error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://react.dev/link/rules-of-hooks');
7884 }
7885 }
7886
7887 return currentlyRenderingComponent;
7888}
7889
7890function areHookInputsEqual(nextDeps, prevDeps) {
7891 if (prevDeps === null) {
7892 {
7893 error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
7894 }
7895
7896 return false;
7897 }
7898
7899 {
7900 // Don't bother comparing lengths in prod because these arrays should be
7901 // passed inline.
7902 if (nextDeps.length !== prevDeps.length) {
7903 error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]");
7904 }
7905 } // $FlowFixMe[incompatible-use] found when upgrading Flow
7906
7907
7908 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
7909 // $FlowFixMe[incompatible-use] found when upgrading Flow
7910 if (objectIs(nextDeps[i], prevDeps[i])) {
7911 continue;
7912 }
7913
7914 return false;
7915 }
7916
7917 return true;
7918}
7919
7920function createHook() {
7921 if (numberOfReRenders > 0) {
7922 throw new Error('Rendered more hooks than during the previous render');
7923 }
7924
7925 return {
7926 memoizedState: null,
7927 queue: null,
7928 next: null
7929 };
7930}
7931
7932function createWorkInProgressHook() {
7933 if (workInProgressHook === null) {
7934 // This is the first hook in the list
7935 if (firstWorkInProgressHook === null) {
7936 isReRender = false;
7937 firstWorkInProgressHook = workInProgressHook = createHook();
7938 } else {
7939 // There's already a work-in-progress. Reuse it.
7940 isReRender = true;
7941 workInProgressHook = firstWorkInProgressHook;
7942 }
7943 } else {
7944 if (workInProgressHook.next === null) {
7945 isReRender = false; // Append to the end of the list
7946
7947 workInProgressHook = workInProgressHook.next = createHook();
7948 } else {
7949 // There's already a work-in-progress. Reuse it.
7950 isReRender = true;
7951 workInProgressHook = workInProgressHook.next;
7952 }
7953 }
7954
7955 return workInProgressHook;
7956}
7957
7958function prepareToUseHooks(request, task, keyPath, componentIdentity, prevThenableState) {
7959 currentlyRenderingComponent = componentIdentity;
7960 currentlyRenderingTask = task;
7961 currentlyRenderingRequest = request;
7962 currentlyRenderingKeyPath = keyPath;
7963
7964 {
7965 isInHookUserCodeInDev = false;
7966 } // The following should have already been reset
7967 // didScheduleRenderPhaseUpdate = false;
7968 // firstWorkInProgressHook = null;
7969 // numberOfReRenders = 0;
7970 // renderPhaseUpdates = null;
7971 // workInProgressHook = null;
7972
7973
7974 localIdCounter = 0;
7975 actionStateCounter = 0;
7976 actionStateMatchingIndex = -1;
7977 thenableIndexCounter = 0;
7978 thenableState = prevThenableState;
7979}
7980function finishHooks(Component, props, children, refOrContext) {
7981 // This must be called after every function component to prevent hooks from
7982 // being used in classes.
7983 while (didScheduleRenderPhaseUpdate) {
7984 // Updates were scheduled during the render phase. They are stored in
7985 // the `renderPhaseUpdates` map. Call the component again, reusing the
7986 // work-in-progress hooks and applying the additional updates on top. Keep
7987 // restarting until no more updates are scheduled.
7988 didScheduleRenderPhaseUpdate = false;
7989 localIdCounter = 0;
7990 actionStateCounter = 0;
7991 actionStateMatchingIndex = -1;
7992 thenableIndexCounter = 0;
7993 numberOfReRenders += 1; // Start over from the beginning of the list
7994
7995 workInProgressHook = null;
7996 children = Component(props, refOrContext);
7997 }
7998
7999 resetHooksState();
8000 return children;
8001}
8002function getThenableStateAfterSuspending() {
8003 var state = thenableState;
8004 thenableState = null;
8005 return state;
8006}
8007function checkDidRenderIdHook() {
8008 // This should be called immediately after every finishHooks call.
8009 // Conceptually, it's part of the return value of finishHooks; it's only a
8010 // separate function to avoid using an array tuple.
8011 var didRenderIdHook = localIdCounter !== 0;
8012 return didRenderIdHook;
8013}
8014function getActionStateCount() {
8015 // This should be called immediately after every finishHooks call.
8016 // Conceptually, it's part of the return value of finishHooks; it's only a
8017 // separate function to avoid using an array tuple.
8018 return actionStateCounter;
8019}
8020function getActionStateMatchingIndex() {
8021 // This should be called immediately after every finishHooks call.
8022 // Conceptually, it's part of the return value of finishHooks; it's only a
8023 // separate function to avoid using an array tuple.
8024 return actionStateMatchingIndex;
8025} // Reset the internal hooks state if an error occurs while rendering a component
8026
8027function resetHooksState() {
8028 {
8029 isInHookUserCodeInDev = false;
8030 }
8031
8032 currentlyRenderingComponent = null;
8033 currentlyRenderingTask = null;
8034 currentlyRenderingRequest = null;
8035 currentlyRenderingKeyPath = null;
8036 didScheduleRenderPhaseUpdate = false;
8037 firstWorkInProgressHook = null;
8038 numberOfReRenders = 0;
8039 renderPhaseUpdates = null;
8040 workInProgressHook = null;
8041}
8042
8043function readContext(context) {
8044 {
8045 if (isInHookUserCodeInDev) {
8046 error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
8047 }
8048 }
8049
8050 return readContext$1(context);
8051}
8052
8053function useContext(context) {
8054 {
8055 currentHookNameInDev = 'useContext';
8056 }
8057
8058 resolveCurrentlyRenderingComponent();
8059 return readContext$1(context);
8060}
8061
8062function basicStateReducer(state, action) {
8063 // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types
8064 return typeof action === 'function' ? action(state) : action;
8065}
8066
8067function useState(initialState) {
8068 {
8069 currentHookNameInDev = 'useState';
8070 }
8071
8072 return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers
8073 initialState);
8074}
8075function useReducer(reducer, initialArg, init) {
8076 {
8077 if (reducer !== basicStateReducer) {
8078 currentHookNameInDev = 'useReducer';
8079 }
8080 }
8081
8082 currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
8083 workInProgressHook = createWorkInProgressHook();
8084
8085 if (isReRender) {
8086 // This is a re-render. Apply the new render phase updates to the previous
8087 // current hook.
8088 var queue = workInProgressHook.queue;
8089 var dispatch = queue.dispatch;
8090
8091 if (renderPhaseUpdates !== null) {
8092 // Render phase updates are stored in a map of queue -> linked list
8093 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
8094
8095 if (firstRenderPhaseUpdate !== undefined) {
8096 // $FlowFixMe[incompatible-use] found when upgrading Flow
8097 renderPhaseUpdates.delete(queue); // $FlowFixMe[incompatible-use] found when upgrading Flow
8098
8099 var newState = workInProgressHook.memoizedState;
8100 var update = firstRenderPhaseUpdate;
8101
8102 do {
8103 // Process this render phase update. We don't have to check the
8104 // priority because it will always be the same as the current
8105 // render's.
8106 var action = update.action;
8107
8108 {
8109 isInHookUserCodeInDev = true;
8110 }
8111
8112 newState = reducer(newState, action);
8113
8114 {
8115 isInHookUserCodeInDev = false;
8116 } // $FlowFixMe[incompatible-type] we bail out when we get a null
8117
8118
8119 update = update.next;
8120 } while (update !== null); // $FlowFixMe[incompatible-use] found when upgrading Flow
8121
8122
8123 workInProgressHook.memoizedState = newState;
8124 return [newState, dispatch];
8125 }
8126 } // $FlowFixMe[incompatible-use] found when upgrading Flow
8127
8128
8129 return [workInProgressHook.memoizedState, dispatch];
8130 } else {
8131 {
8132 isInHookUserCodeInDev = true;
8133 }
8134
8135 var initialState;
8136
8137 if (reducer === basicStateReducer) {
8138 // Special case for `useState`.
8139 initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
8140 } else {
8141 initialState = init !== undefined ? init(initialArg) : initialArg;
8142 }
8143
8144 {
8145 isInHookUserCodeInDev = false;
8146 } // $FlowFixMe[incompatible-use] found when upgrading Flow
8147
8148
8149 workInProgressHook.memoizedState = initialState; // $FlowFixMe[incompatible-use] found when upgrading Flow
8150
8151 var _queue = workInProgressHook.queue = {
8152 last: null,
8153 dispatch: null
8154 };
8155
8156 var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue); // $FlowFixMe[incompatible-use] found when upgrading Flow
8157
8158
8159 return [workInProgressHook.memoizedState, _dispatch];
8160 }
8161}
8162
8163function useMemo(nextCreate, deps) {
8164 currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
8165 workInProgressHook = createWorkInProgressHook();
8166 var nextDeps = deps === undefined ? null : deps;
8167
8168 if (workInProgressHook !== null) {
8169 var prevState = workInProgressHook.memoizedState;
8170
8171 if (prevState !== null) {
8172 if (nextDeps !== null) {
8173 var prevDeps = prevState[1];
8174
8175 if (areHookInputsEqual(nextDeps, prevDeps)) {
8176 return prevState[0];
8177 }
8178 }
8179 }
8180 }
8181
8182 {
8183 isInHookUserCodeInDev = true;
8184 }
8185
8186 var nextValue = nextCreate();
8187
8188 {
8189 isInHookUserCodeInDev = false;
8190 } // $FlowFixMe[incompatible-use] found when upgrading Flow
8191
8192
8193 workInProgressHook.memoizedState = [nextValue, nextDeps];
8194 return nextValue;
8195}
8196
8197function useRef(initialValue) {
8198 currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
8199 workInProgressHook = createWorkInProgressHook();
8200 var previousRef = workInProgressHook.memoizedState;
8201
8202 if (previousRef === null) {
8203 var ref = {
8204 current: initialValue
8205 };
8206
8207 {
8208 Object.seal(ref);
8209 } // $FlowFixMe[incompatible-use] found when upgrading Flow
8210
8211
8212 workInProgressHook.memoizedState = ref;
8213 return ref;
8214 } else {
8215 return previousRef;
8216 }
8217}
8218
8219function dispatchAction(componentIdentity, queue, action) {
8220 if (numberOfReRenders >= RE_RENDER_LIMIT) {
8221 throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
8222 }
8223
8224 if (componentIdentity === currentlyRenderingComponent) {
8225 // This is a render phase update. Stash it in a lazily-created map of
8226 // queue -> linked list of updates. After this render pass, we'll restart
8227 // and apply the stashed updates on top of the work-in-progress hook.
8228 didScheduleRenderPhaseUpdate = true;
8229 var update = {
8230 action: action,
8231 next: null
8232 };
8233
8234 if (renderPhaseUpdates === null) {
8235 renderPhaseUpdates = new Map();
8236 }
8237
8238 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
8239
8240 if (firstRenderPhaseUpdate === undefined) {
8241 // $FlowFixMe[incompatible-use] found when upgrading Flow
8242 renderPhaseUpdates.set(queue, update);
8243 } else {
8244 // Append the update to the end of the list.
8245 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
8246
8247 while (lastRenderPhaseUpdate.next !== null) {
8248 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
8249 }
8250
8251 lastRenderPhaseUpdate.next = update;
8252 }
8253 }
8254}
8255
8256function useCallback(callback, deps) {
8257 return useMemo(function () {
8258 return callback;
8259 }, deps);
8260}
8261
8262function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
8263 if (getServerSnapshot === undefined) {
8264 throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
8265 }
8266
8267 return getServerSnapshot();
8268}
8269
8270function useDeferredValue(value, initialValue) {
8271 resolveCurrentlyRenderingComponent();
8272
8273 {
8274 return initialValue !== undefined ? initialValue : value;
8275 }
8276}
8277
8278function unsupportedStartTransition() {
8279 throw new Error('startTransition cannot be called during server rendering.');
8280}
8281
8282function useTransition() {
8283 resolveCurrentlyRenderingComponent();
8284 return [false, unsupportedStartTransition];
8285}
8286
8287function useHostTransitionStatus() {
8288 resolveCurrentlyRenderingComponent();
8289 return NotPendingTransition;
8290}
8291
8292function unsupportedSetOptimisticState() {
8293 throw new Error('Cannot update optimistic state while rendering.');
8294}
8295
8296function useOptimistic(passthrough, reducer) {
8297 resolveCurrentlyRenderingComponent();
8298 return [passthrough, unsupportedSetOptimisticState];
8299}
8300
8301function createPostbackActionStateKey(permalink, componentKeyPath, hookIndex) {
8302 if (permalink !== undefined) {
8303 // Don't bother to hash a permalink-based key since it's already short.
8304 return 'p' + permalink;
8305 } else {
8306 // Append a node to the key path that represents the form state hook.
8307 var keyPath = [componentKeyPath, null, hookIndex]; // Key paths are hashed to reduce the size. It does not need to be secure,
8308 // and it's more important that it's fast than that it's completely
8309 // collision-free.
8310
8311 var keyPathHash = createFastHashJS(JSON.stringify(keyPath));
8312 return 'k' + keyPathHash;
8313 }
8314}
8315
8316function useActionState(action, initialState, permalink) {
8317 resolveCurrentlyRenderingComponent(); // Count the number of useActionState hooks per component. We also use this to
8318 // track the position of this useActionState hook relative to the other ones in
8319 // this component, so we can generate a unique key for each one.
8320
8321 var actionStateHookIndex = actionStateCounter++;
8322 var request = currentlyRenderingRequest; // $FlowIgnore[prop-missing]
8323
8324 var formAction = action.$$FORM_ACTION;
8325
8326 if (typeof formAction === 'function') {
8327 // This is a server action. These have additional features to enable
8328 // MPA-style form submissions with progressive enhancement.
8329 // TODO: If the same permalink is passed to multiple useActionStates, and
8330 // they all have the same action signature, Fizz will pass the postback
8331 // state to all of them. We should probably only pass it to the first one,
8332 // and/or warn.
8333 // The key is lazily generated and deduped so the that the keypath doesn't
8334 // get JSON.stringify-ed unnecessarily, and at most once.
8335 var nextPostbackStateKey = null; // Determine the current form state. If we received state during an MPA form
8336 // submission, then we will reuse that, if the action identity matches.
8337 // Otherwise, we'll use the initial state argument. We will emit a comment
8338 // marker into the stream that indicates whether the state was reused.
8339
8340 var state = initialState;
8341 var componentKeyPath = currentlyRenderingKeyPath;
8342 var postbackActionState = getFormState(request); // $FlowIgnore[prop-missing]
8343
8344 var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL;
8345
8346 if (postbackActionState !== null && typeof isSignatureEqual === 'function') {
8347 var postbackKey = postbackActionState[1];
8348 var postbackReferenceId = postbackActionState[2];
8349 var postbackBoundArity = postbackActionState[3];
8350
8351 if (isSignatureEqual.call(action, postbackReferenceId, postbackBoundArity)) {
8352 nextPostbackStateKey = createPostbackActionStateKey(permalink, componentKeyPath, actionStateHookIndex);
8353
8354 if (postbackKey === nextPostbackStateKey) {
8355 // This was a match
8356 actionStateMatchingIndex = actionStateHookIndex; // Reuse the state that was submitted by the form.
8357
8358 state = postbackActionState[0];
8359 }
8360 }
8361 } // Bind the state to the first argument of the action.
8362
8363
8364 var boundAction = action.bind(null, state); // Wrap the action so the return value is void.
8365
8366 var dispatch = function (payload) {
8367 boundAction(payload);
8368 }; // $FlowIgnore[prop-missing]
8369
8370
8371 if (typeof boundAction.$$FORM_ACTION === 'function') {
8372 // $FlowIgnore[prop-missing]
8373 dispatch.$$FORM_ACTION = function (prefix) {
8374 var metadata = boundAction.$$FORM_ACTION(prefix); // Override the action URL
8375
8376 if (permalink !== undefined) {
8377 {
8378 checkAttributeStringCoercion(permalink, 'target');
8379 }
8380
8381 permalink += '';
8382 metadata.action = permalink;
8383 }
8384
8385 var formData = metadata.data;
8386
8387 if (formData) {
8388 if (nextPostbackStateKey === null) {
8389 nextPostbackStateKey = createPostbackActionStateKey(permalink, componentKeyPath, actionStateHookIndex);
8390 }
8391
8392 formData.append('$ACTION_KEY', nextPostbackStateKey);
8393 }
8394
8395 return metadata;
8396 };
8397 }
8398
8399 return [state, dispatch, false];
8400 } else {
8401 // This is not a server action, so the implementation is much simpler.
8402 // Bind the state to the first argument of the action.
8403 var _boundAction = action.bind(null, initialState); // Wrap the action so the return value is void.
8404
8405
8406 var _dispatch2 = function (payload) {
8407 _boundAction(payload);
8408 };
8409
8410 return [initialState, _dispatch2, false];
8411 }
8412}
8413
8414function useId() {
8415 var task = currentlyRenderingTask;
8416 var treeId = getTreeId(task.treeContext);
8417 var resumableState = currentResumableState;
8418
8419 if (resumableState === null) {
8420 throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');
8421 }
8422
8423 var localId = localIdCounter++;
8424 return makeId(resumableState, treeId, localId);
8425}
8426
8427function use(usable) {
8428 if (usable !== null && typeof usable === 'object') {
8429 // $FlowFixMe[method-unbinding]
8430 if (typeof usable.then === 'function') {
8431 // This is a thenable.
8432 var thenable = usable;
8433 return unwrapThenable(thenable);
8434 } else if (usable.$$typeof === REACT_CONTEXT_TYPE) {
8435 var context = usable;
8436 return readContext(context);
8437 }
8438 } // eslint-disable-next-line react-internal/safe-string-coercion
8439
8440
8441 throw new Error('An unsupported type was passed to use(): ' + String(usable));
8442}
8443
8444function unwrapThenable(thenable) {
8445 var index = thenableIndexCounter;
8446 thenableIndexCounter += 1;
8447
8448 if (thenableState === null) {
8449 thenableState = createThenableState();
8450 }
8451
8452 return trackUsedThenable(thenableState, thenable, index);
8453}
8454
8455function unsupportedRefresh() {
8456 throw new Error('Cache cannot be refreshed during server rendering.');
8457}
8458
8459function useCacheRefresh() {
8460 return unsupportedRefresh;
8461}
8462
8463function noop$1() {}
8464
8465var HooksDispatcher = {
8466 readContext: readContext,
8467 use: use,
8468 useContext: useContext,
8469 useMemo: useMemo,
8470 useReducer: useReducer,
8471 useRef: useRef,
8472 useState: useState,
8473 useInsertionEffect: noop$1,
8474 useLayoutEffect: noop$1,
8475 useCallback: useCallback,
8476 // useImperativeHandle is not run in the server environment
8477 useImperativeHandle: noop$1,
8478 // Effects are not run in the server environment.
8479 useEffect: noop$1,
8480 // Debugging effect
8481 useDebugValue: noop$1,
8482 useDeferredValue: useDeferredValue,
8483 useTransition: useTransition,
8484 useId: useId,
8485 // Subscriptions are not setup in a server environment.
8486 useSyncExternalStore: useSyncExternalStore
8487};
8488
8489{
8490 HooksDispatcher.useCacheRefresh = useCacheRefresh;
8491}
8492
8493{
8494 HooksDispatcher.useHostTransitionStatus = useHostTransitionStatus;
8495}
8496
8497{
8498 HooksDispatcher.useOptimistic = useOptimistic;
8499 HooksDispatcher.useFormState = useActionState;
8500 HooksDispatcher.useActionState = useActionState;
8501}
8502
8503var currentResumableState = null;
8504function setCurrentResumableState(resumableState) {
8505 currentResumableState = resumableState;
8506}
8507
8508function getCacheForType(resourceType) {
8509 throw new Error('Not implemented.');
8510}
8511
8512var DefaultAsyncDispatcher = {
8513 getCacheForType: getCacheForType
8514};
8515
8516{
8517 // Fizz never tracks owner but the JSX runtime looks for this.
8518 DefaultAsyncDispatcher.getOwner = function () {
8519 return null;
8520 };
8521}
8522
8523// Helpers to patch console.logs to avoid logging during side-effect free
8524// replaying on render function. This currently only patches the object
8525// lazily which won't cover if the log function was extracted eagerly.
8526// We could also eagerly patch the method.
8527var disabledDepth = 0;
8528var prevLog;
8529var prevInfo;
8530var prevWarn;
8531var prevError;
8532var prevGroup;
8533var prevGroupCollapsed;
8534var prevGroupEnd;
8535
8536function disabledLog() {}
8537
8538disabledLog.__reactDisabledLog = true;
8539function disableLogs() {
8540 {
8541 if (disabledDepth === 0) {
8542 /* eslint-disable react-internal/no-production-logging */
8543 prevLog = console.log;
8544 prevInfo = console.info;
8545 prevWarn = console.warn;
8546 prevError = console.error;
8547 prevGroup = console.group;
8548 prevGroupCollapsed = console.groupCollapsed;
8549 prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
8550
8551 var props = {
8552 configurable: true,
8553 enumerable: true,
8554 value: disabledLog,
8555 writable: true
8556 }; // $FlowFixMe[cannot-write] Flow thinks console is immutable.
8557
8558 Object.defineProperties(console, {
8559 info: props,
8560 log: props,
8561 warn: props,
8562 error: props,
8563 group: props,
8564 groupCollapsed: props,
8565 groupEnd: props
8566 });
8567 /* eslint-enable react-internal/no-production-logging */
8568 }
8569
8570 disabledDepth++;
8571 }
8572}
8573function reenableLogs() {
8574 {
8575 disabledDepth--;
8576
8577 if (disabledDepth === 0) {
8578 /* eslint-disable react-internal/no-production-logging */
8579 var props = {
8580 configurable: true,
8581 enumerable: true,
8582 writable: true
8583 }; // $FlowFixMe[cannot-write] Flow thinks console is immutable.
8584
8585 Object.defineProperties(console, {
8586 log: assign({}, props, {
8587 value: prevLog
8588 }),
8589 info: assign({}, props, {
8590 value: prevInfo
8591 }),
8592 warn: assign({}, props, {
8593 value: prevWarn
8594 }),
8595 error: assign({}, props, {
8596 value: prevError
8597 }),
8598 group: assign({}, props, {
8599 value: prevGroup
8600 }),
8601 groupCollapsed: assign({}, props, {
8602 value: prevGroupCollapsed
8603 }),
8604 groupEnd: assign({}, props, {
8605 value: prevGroupEnd
8606 })
8607 });
8608 /* eslint-enable react-internal/no-production-logging */
8609 }
8610
8611 if (disabledDepth < 0) {
8612 error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
8613 }
8614 }
8615}
8616
8617var prefix;
8618function describeBuiltInComponentFrame(name) {
8619 {
8620 if (prefix === undefined) {
8621 // Extract the VM specific prefix used by each line.
8622 try {
8623 throw Error();
8624 } catch (x) {
8625 var match = x.stack.trim().match(/\n( *(at )?)/);
8626 prefix = match && match[1] || '';
8627 }
8628 } // We use the prefix to ensure our stacks line up with native stack frames.
8629
8630
8631 return '\n' + prefix + name;
8632 }
8633}
8634var reentry = false;
8635var componentFrameCache;
8636
8637{
8638 var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
8639 componentFrameCache = new PossiblyWeakMap();
8640}
8641/**
8642 * Leverages native browser/VM stack frames to get proper details (e.g.
8643 * filename, line + col number) for a single component in a component stack. We
8644 * do this by:
8645 * (1) throwing and catching an error in the function - this will be our
8646 * control error.
8647 * (2) calling the component which will eventually throw an error that we'll
8648 * catch - this will be our sample error.
8649 * (3) diffing the control and sample error stacks to find the stack frame
8650 * which represents our component.
8651 */
8652
8653
8654function describeNativeComponentFrame(fn, construct) {
8655 // If something asked for a stack inside a fake render, it should get ignored.
8656 if (!fn || reentry) {
8657 return '';
8658 }
8659
8660 {
8661 var frame = componentFrameCache.get(fn);
8662
8663 if (frame !== undefined) {
8664 return frame;
8665 }
8666 }
8667
8668 reentry = true;
8669 var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe[incompatible-type] It does accept undefined.
8670
8671 Error.prepareStackTrace = undefined;
8672 var previousDispatcher = null;
8673
8674 {
8675 previousDispatcher = ReactSharedInternals.H; // Set the dispatcher in DEV because this might be call in the render function
8676 // for warnings.
8677
8678 ReactSharedInternals.H = null;
8679 disableLogs();
8680 }
8681 /**
8682 * Finding a common stack frame between sample and control errors can be
8683 * tricky given the different types and levels of stack trace truncation from
8684 * different JS VMs. So instead we'll attempt to control what that common
8685 * frame should be through this object method:
8686 * Having both the sample and control errors be in the function under the
8687 * `DescribeNativeComponentFrameRoot` property, + setting the `name` and
8688 * `displayName` properties of the function ensures that a stack
8689 * frame exists that has the method name `DescribeNativeComponentFrameRoot` in
8690 * it for both control and sample stacks.
8691 */
8692
8693
8694 var RunInRootFrame = {
8695 DetermineComponentFrameRoot: function () {
8696 var control;
8697
8698 try {
8699 // This should throw.
8700 if (construct) {
8701 // Something should be setting the props in the constructor.
8702 var Fake = function () {
8703 throw Error();
8704 }; // $FlowFixMe[prop-missing]
8705
8706
8707 Object.defineProperty(Fake.prototype, 'props', {
8708 set: function () {
8709 // We use a throwing setter instead of frozen or non-writable props
8710 // because that won't throw in a non-strict mode function.
8711 throw Error();
8712 }
8713 });
8714
8715 if (typeof Reflect === 'object' && Reflect.construct) {
8716 // We construct a different control for this case to include any extra
8717 // frames added by the construct call.
8718 try {
8719 Reflect.construct(Fake, []);
8720 } catch (x) {
8721 control = x;
8722 }
8723
8724 Reflect.construct(fn, [], Fake);
8725 } else {
8726 try {
8727 Fake.call();
8728 } catch (x) {
8729 control = x;
8730 } // $FlowFixMe[prop-missing] found when upgrading Flow
8731
8732
8733 fn.call(Fake.prototype);
8734 }
8735 } else {
8736 try {
8737 throw Error();
8738 } catch (x) {
8739 control = x;
8740 } // TODO(luna): This will currently only throw if the function component
8741 // tries to access React/ReactDOM/props. We should probably make this throw
8742 // in simple components too
8743
8744
8745 var maybePromise = fn(); // If the function component returns a promise, it's likely an async
8746 // component, which we don't yet support. Attach a noop catch handler to
8747 // silence the error.
8748 // TODO: Implement component stacks for async client components?
8749
8750 if (maybePromise && typeof maybePromise.catch === 'function') {
8751 maybePromise.catch(function () {});
8752 }
8753 }
8754 } catch (sample) {
8755 // This is inlined manually because closure doesn't do it for us.
8756 if (sample && control && typeof sample.stack === 'string') {
8757 return [sample.stack, control.stack];
8758 }
8759 }
8760
8761 return [null, null];
8762 }
8763 }; // $FlowFixMe[prop-missing]
8764
8765 RunInRootFrame.DetermineComponentFrameRoot.displayName = 'DetermineComponentFrameRoot';
8766 var namePropDescriptor = Object.getOwnPropertyDescriptor(RunInRootFrame.DetermineComponentFrameRoot, 'name'); // Before ES6, the `name` property was not configurable.
8767
8768 if (namePropDescriptor && namePropDescriptor.configurable) {
8769 // V8 utilizes a function's `name` property when generating a stack trace.
8770 Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot, // Configurable properties can be updated even if its writable descriptor
8771 // is set to `false`.
8772 // $FlowFixMe[cannot-write]
8773 'name', {
8774 value: 'DetermineComponentFrameRoot'
8775 });
8776 }
8777
8778 try {
8779 var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(),
8780 sampleStack = _RunInRootFrame$Deter[0],
8781 controlStack = _RunInRootFrame$Deter[1];
8782
8783 if (sampleStack && controlStack) {
8784 // This extracts the first frame from the sample that isn't also in the control.
8785 // Skipping one frame that we assume is the frame that calls the two.
8786 var sampleLines = sampleStack.split('\n');
8787 var controlLines = controlStack.split('\n');
8788 var s = 0;
8789 var c = 0;
8790
8791 while (s < sampleLines.length && !sampleLines[s].includes('DetermineComponentFrameRoot')) {
8792 s++;
8793 }
8794
8795 while (c < controlLines.length && !controlLines[c].includes('DetermineComponentFrameRoot')) {
8796 c++;
8797 } // We couldn't find our intentionally injected common root frame, attempt
8798 // to find another common root frame by search from the bottom of the
8799 // control stack...
8800
8801
8802 if (s === sampleLines.length || c === controlLines.length) {
8803 s = sampleLines.length - 1;
8804 c = controlLines.length - 1;
8805
8806 while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
8807 // We expect at least one stack frame to be shared.
8808 // Typically this will be the root most one. However, stack frames may be
8809 // cut off due to maximum stack limits. In this case, one maybe cut off
8810 // earlier than the other. We assume that the sample is longer or the same
8811 // and there for cut off earlier. So we should find the root most frame in
8812 // the sample somewhere in the control.
8813 c--;
8814 }
8815 }
8816
8817 for (; s >= 1 && c >= 0; s--, c--) {
8818 // Next we find the first one that isn't the same which should be the
8819 // frame that called our sample function and the control.
8820 if (sampleLines[s] !== controlLines[c]) {
8821 // In V8, the first line is describing the message but other VMs don't.
8822 // If we're about to return the first line, and the control is also on the same
8823 // line, that's a pretty good indicator that our sample threw at same line as
8824 // the control. I.e. before we entered the sample frame. So we ignore this result.
8825 // This can happen if you passed a class to function component, or non-function.
8826 if (s !== 1 || c !== 1) {
8827 do {
8828 s--;
8829 c--; // We may still have similar intermediate frames from the construct call.
8830 // The next one that isn't the same should be our match though.
8831
8832 if (c < 0 || sampleLines[s] !== controlLines[c]) {
8833 // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
8834 var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
8835 // but we have a user-provided "displayName"
8836 // splice it in to make the stack more readable.
8837
8838
8839 if (fn.displayName && _frame.includes('<anonymous>')) {
8840 _frame = _frame.replace('<anonymous>', fn.displayName);
8841 }
8842
8843 if (true) {
8844 if (typeof fn === 'function') {
8845 componentFrameCache.set(fn, _frame);
8846 }
8847 } // Return the line we found.
8848
8849
8850 return _frame;
8851 }
8852 } while (s >= 1 && c >= 0);
8853 }
8854
8855 break;
8856 }
8857 }
8858 }
8859 } finally {
8860 reentry = false;
8861
8862 {
8863 ReactSharedInternals.H = previousDispatcher;
8864 reenableLogs();
8865 }
8866
8867 Error.prepareStackTrace = previousPrepareStackTrace;
8868 } // Fallback to just using the name if we couldn't make it throw.
8869
8870
8871 var name = fn ? fn.displayName || fn.name : '';
8872 var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
8873
8874 {
8875 if (typeof fn === 'function') {
8876 componentFrameCache.set(fn, syntheticFrame);
8877 }
8878 }
8879
8880 return syntheticFrame;
8881}
8882
8883function describeClassComponentFrame(ctor) {
8884 {
8885 return describeNativeComponentFrame(ctor, true);
8886 }
8887}
8888function describeFunctionComponentFrame(fn) {
8889 {
8890 return describeNativeComponentFrame(fn, false);
8891 }
8892}
8893
8894function getStackByComponentStackNode(componentStack) {
8895 try {
8896 var info = '';
8897 var node = componentStack;
8898
8899 do {
8900 switch (node.tag) {
8901 case 0:
8902 info += describeBuiltInComponentFrame(node.type);
8903 break;
8904
8905 case 1:
8906 info += describeFunctionComponentFrame(node.type);
8907 break;
8908
8909 case 2:
8910 info += describeClassComponentFrame(node.type);
8911 break;
8912 } // $FlowFixMe[incompatible-type] we bail out when we get a null
8913
8914
8915 node = node.parent;
8916 } while (node);
8917
8918 return info;
8919 } catch (x) {
8920 return '\nError generating stack: ' + x.message + '\n' + x.stack;
8921 }
8922}
8923
8924// The name might be minified but we assume that it's going to be the same generated name. Typically
8925// because it's just the same compiled output in practice.
8926// resume with segmentID at the index
8927
8928var CLIENT_RENDERED = 4; // if it errors or infinitely suspends
8929
8930var PENDING = 0;
8931var COMPLETED = 1;
8932var FLUSHED = 2;
8933var ABORTED = 3;
8934var ERRORED = 4;
8935var POSTPONED = 5;
8936var OPEN = 0;
8937var CLOSING = 1;
8938var CLOSED = 2; // This is a default heuristic for how to split up the HTML content into progressive
8939// loading. Our goal is to be able to display additional new content about every 500ms.
8940// Faster than that is unnecessary and should be throttled on the client. It also
8941// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower
8942// end device but higher end suffer less from the overhead than lower end does from
8943// not getting small enough pieces. We error on the side of low end.
8944// We base this on low end 3G speeds which is about 500kbits per second. We assume
8945// that there can be a reasonable drop off from max bandwidth which leaves you with
8946// as little as 80%. We can receive half of that each 500ms - at best. In practice,
8947// a little bandwidth is lost to processing and contention - e.g. CSS and images that
8948// are downloaded along with the main content. So we estimate about half of that to be
8949// the lower end throughput. In other words, we expect that you can at least show
8950// about 12.5kb of content per 500ms. Not counting starting latency for the first
8951// paint.
8952// 500 * 1024 / 8 * .8 * 0.5 / 2
8953
8954var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;
8955
8956function defaultErrorHandler(error) {
8957 console['error'](error); // Don't transform to our wrapper
8958
8959 return null;
8960}
8961
8962function noop() {}
8963
8964function createRequest(children, resumableState, renderState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone, formState) {
8965 var pingedTasks = [];
8966 var abortSet = new Set();
8967 var request = {
8968 destination: null,
8969 flushScheduled: false,
8970 resumableState: resumableState,
8971 renderState: renderState,
8972 rootFormatContext: rootFormatContext,
8973 progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,
8974 status: OPEN,
8975 fatalError: null,
8976 nextSegmentId: 0,
8977 allPendingTasks: 0,
8978 pendingRootTasks: 0,
8979 completedRootSegment: null,
8980 abortableTasks: abortSet,
8981 pingedTasks: pingedTasks,
8982 clientRenderedBoundaries: [],
8983 completedBoundaries: [],
8984 partialBoundaries: [],
8985 trackedPostpones: null,
8986 onError: onError === undefined ? defaultErrorHandler : onError,
8987 onPostpone: onPostpone === undefined ? noop : onPostpone,
8988 onAllReady: onAllReady === undefined ? noop : onAllReady,
8989 onShellReady: onShellReady === undefined ? noop : onShellReady,
8990 onShellError: onShellError === undefined ? noop : onShellError,
8991 onFatalError: onFatalError === undefined ? noop : onFatalError,
8992 formState: formState === undefined ? null : formState
8993 }; // This segment represents the root fallback.
8994
8995 var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge
8996 false, false); // There is no parent so conceptually, we're unblocked to flush this segment.
8997
8998 rootSegment.parentFlushed = true;
8999 var rootTask = createRenderTask(request, null, children, -1, null, rootSegment, null, abortSet, null, rootFormatContext, emptyContextObject, rootContextSnapshot, emptyTreeContext, null, false);
9000 pingedTasks.push(rootTask);
9001 return request;
9002}
9003var currentRequest = null;
9004function resolveRequest() {
9005 if (currentRequest) return currentRequest;
9006
9007 return null;
9008}
9009
9010function pingTask(request, task) {
9011 var pingedTasks = request.pingedTasks;
9012 pingedTasks.push(task);
9013
9014 if (request.pingedTasks.length === 1) {
9015 request.flushScheduled = request.destination !== null;
9016 scheduleWork(function () {
9017 return performWork(request);
9018 });
9019 }
9020}
9021
9022function createSuspenseBoundary(request, fallbackAbortableTasks) {
9023 var boundary = {
9024 status: PENDING,
9025 rootSegmentID: -1,
9026 parentFlushed: false,
9027 pendingTasks: 0,
9028 completedSegments: [],
9029 byteSize: 0,
9030 fallbackAbortableTasks: fallbackAbortableTasks,
9031 errorDigest: null,
9032 contentState: createHoistableState(),
9033 fallbackState: createHoistableState(),
9034 trackedContentKeyPath: null,
9035 trackedFallbackNode: null
9036 };
9037
9038 {
9039 // DEV-only fields for hidden class
9040 boundary.errorMessage = null;
9041 boundary.errorStack = null;
9042 boundary.errorComponentStack = null;
9043 }
9044
9045 return boundary;
9046}
9047
9048function createRenderTask(request, thenableState, node, childIndex, blockedBoundary, blockedSegment, hoistableState, abortSet, keyPath, formatContext, legacyContext, context, treeContext, componentStack, isFallback) {
9049 request.allPendingTasks++;
9050
9051 if (blockedBoundary === null) {
9052 request.pendingRootTasks++;
9053 } else {
9054 blockedBoundary.pendingTasks++;
9055 }
9056
9057 var task = {
9058 replay: null,
9059 node: node,
9060 childIndex: childIndex,
9061 ping: function () {
9062 return pingTask(request, task);
9063 },
9064 blockedBoundary: blockedBoundary,
9065 blockedSegment: blockedSegment,
9066 hoistableState: hoistableState,
9067 abortSet: abortSet,
9068 keyPath: keyPath,
9069 formatContext: formatContext,
9070 legacyContext: legacyContext,
9071 context: context,
9072 treeContext: treeContext,
9073 componentStack: componentStack,
9074 thenableState: thenableState,
9075 isFallback: isFallback
9076 };
9077 abortSet.add(task);
9078 return task;
9079}
9080
9081function createReplayTask(request, thenableState, replay, node, childIndex, blockedBoundary, hoistableState, abortSet, keyPath, formatContext, legacyContext, context, treeContext, componentStack, isFallback) {
9082 request.allPendingTasks++;
9083
9084 if (blockedBoundary === null) {
9085 request.pendingRootTasks++;
9086 } else {
9087 blockedBoundary.pendingTasks++;
9088 }
9089
9090 replay.pendingTasks++;
9091 var task = {
9092 replay: replay,
9093 node: node,
9094 childIndex: childIndex,
9095 ping: function () {
9096 return pingTask(request, task);
9097 },
9098 blockedBoundary: blockedBoundary,
9099 blockedSegment: null,
9100 hoistableState: hoistableState,
9101 abortSet: abortSet,
9102 keyPath: keyPath,
9103 formatContext: formatContext,
9104 legacyContext: legacyContext,
9105 context: context,
9106 treeContext: treeContext,
9107 componentStack: componentStack,
9108 thenableState: thenableState,
9109 isFallback: isFallback
9110 };
9111 abortSet.add(task);
9112 return task;
9113}
9114
9115function createPendingSegment(request, index, boundary, parentFormatContext, lastPushedText, textEmbedded) {
9116 return {
9117 status: PENDING,
9118 id: -1,
9119 // lazily assigned later
9120 index: index,
9121 parentFlushed: false,
9122 chunks: [],
9123 children: [],
9124 parentFormatContext: parentFormatContext,
9125 boundary: boundary,
9126 lastPushedText: lastPushedText,
9127 textEmbedded: textEmbedded
9128 };
9129} // DEV-only global reference to the currently executing task
9130
9131
9132var currentTaskInDEV = null;
9133
9134function getCurrentStackInDEV() {
9135 {
9136 if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {
9137 return '';
9138 }
9139
9140 return getStackByComponentStackNode(currentTaskInDEV.componentStack);
9141 }
9142}
9143
9144function getStackFromNode(stackNode) {
9145 return getStackByComponentStackNode(stackNode);
9146}
9147
9148function createBuiltInComponentStack(task, type) {
9149 return {
9150 tag: 0,
9151 parent: task.componentStack,
9152 type: type
9153 };
9154}
9155
9156function createFunctionComponentStack(task, type) {
9157 return {
9158 tag: 1,
9159 parent: task.componentStack,
9160 type: type
9161 };
9162}
9163
9164function createClassComponentStack(task, type) {
9165 return {
9166 tag: 2,
9167 parent: task.componentStack,
9168 type: type
9169 };
9170} // While we track component stacks in prod all the time we only produce a reified stack in dev and
9171// during prerender in Prod. The reason for this is that the stack is useful for prerender where the timeliness
9172// of the request is less critical than the observability of the execution. For renders and resumes however we
9173// prioritize speed of the request.
9174
9175
9176function getThrownInfo(request, node) {
9177 if (node && ( // Always produce a stack in dev
9178 true )) {
9179 return {
9180 componentStack: getStackFromNode(node)
9181 };
9182 } else {
9183 return {};
9184 }
9185}
9186
9187function encodeErrorForBoundary(boundary, digest, error, thrownInfo, wasAborted) {
9188 boundary.errorDigest = digest;
9189
9190 {
9191 var message, stack; // In dev we additionally encode the error message and component stack on the boundary
9192
9193 if (error instanceof Error) {
9194 // eslint-disable-next-line react-internal/safe-string-coercion
9195 message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion
9196
9197 stack = String(error.stack);
9198 } else if (typeof error === 'object' && error !== null) {
9199 message = describeObjectForErrorMessage(error);
9200 stack = null;
9201 } else {
9202 // eslint-disable-next-line react-internal/safe-string-coercion
9203 message = String(error);
9204 stack = null;
9205 }
9206
9207 var prefix = wasAborted ? 'Switched to client rendering because the server rendering aborted due to:\n\n' : 'Switched to client rendering because the server rendering errored:\n\n';
9208 boundary.errorMessage = prefix + message;
9209 boundary.errorStack = stack !== null ? prefix + stack : null;
9210 boundary.errorComponentStack = thrownInfo.componentStack;
9211 }
9212}
9213
9214function logRecoverableError(request, error$1, errorInfo) {
9215 // If this callback errors, we intentionally let that error bubble up to become a fatal error
9216 // so that someone fixes the error reporting instead of hiding it.
9217 var errorDigest = request.onError(error$1, errorInfo);
9218
9219 if (errorDigest != null && typeof errorDigest !== 'string') {
9220 // We used to throw here but since this gets called from a variety of unprotected places it
9221 // seems better to just warn and discard the returned value.
9222 {
9223 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 "%s" instead', typeof errorDigest);
9224 }
9225
9226 return;
9227 }
9228
9229 return errorDigest;
9230}
9231
9232function fatalError(request, error) {
9233 // This is called outside error handling code such as if the root errors outside
9234 // a suspense boundary or if the root suspense boundary's fallback errors.
9235 // It's also called if React itself or its host configs errors.
9236 var onShellError = request.onShellError;
9237 onShellError(error);
9238 var onFatalError = request.onFatalError;
9239 onFatalError(error);
9240
9241 if (request.destination !== null) {
9242 request.status = CLOSED;
9243 closeWithError(request.destination, error);
9244 } else {
9245 request.status = CLOSING;
9246 request.fatalError = error;
9247 }
9248}
9249
9250function renderSuspenseBoundary(request, someTask, keyPath, props) {
9251 if (someTask.replay !== null) {
9252 // If we're replaying through this pass, it means we're replaying through
9253 // an already completed Suspense boundary. It's too late to do anything about it
9254 // so we can just render through it.
9255 var _prevKeyPath = someTask.keyPath;
9256 someTask.keyPath = keyPath;
9257 var _content = props.children;
9258
9259 try {
9260 renderNode(request, someTask, _content, -1);
9261 } finally {
9262 someTask.keyPath = _prevKeyPath;
9263 }
9264
9265 return;
9266 } // $FlowFixMe: Refined.
9267
9268
9269 var task = someTask;
9270 var previousComponentStack = task.componentStack; // If we end up creating the fallback task we need it to have the correct stack which is
9271 // the stack for the boundary itself. We stash it here so we can use it if needed later
9272
9273 var suspenseComponentStack = task.componentStack = createBuiltInComponentStack(task, 'Suspense');
9274 var prevKeyPath = task.keyPath;
9275 var parentBoundary = task.blockedBoundary;
9276 var parentHoistableState = task.hoistableState;
9277 var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for
9278 // the fallback so that we can later replace that segment with the content.
9279 // This also lets us split out the main content even if it doesn't suspend,
9280 // in case it ends up generating a large subtree of content.
9281
9282 var fallback = props.fallback;
9283 var content = props.children;
9284 var fallbackAbortSet = new Set();
9285 var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);
9286
9287 if (request.trackedPostpones !== null) {
9288 newBoundary.trackedContentKeyPath = keyPath;
9289 }
9290
9291 var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.
9292
9293 var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, task.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
9294 false, false);
9295 parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent
9296
9297 parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately.
9298
9299 var contentRootSegment = createPendingSegment(request, 0, null, task.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them
9300 false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is
9301 // no parent segment so there's nothing to wait on.
9302
9303 contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.
9304 // I suspect that there might be some efficiency benefits from not creating the suspended task
9305 // and instead just using the stack if possible.
9306 // TODO: Call this directly instead of messing with saving and restoring contexts.
9307 // We can reuse the current context and task to render the content immediately without
9308 // context switching. We just need to temporarily switch which boundary and which segment
9309 // we're writing to. If something suspends, it'll spawn new suspended task with that context.
9310
9311 task.blockedBoundary = newBoundary;
9312 task.hoistableState = newBoundary.contentState;
9313 task.blockedSegment = contentRootSegment;
9314 task.keyPath = keyPath;
9315
9316 try {
9317 // We use the safe form because we don't handle suspending here. Only error handling.
9318 renderNode(request, task, content, -1);
9319 pushSegmentFinale(contentRootSegment.chunks, request.renderState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded);
9320 contentRootSegment.status = COMPLETED;
9321 queueCompletedSegment(newBoundary, contentRootSegment);
9322
9323 if (newBoundary.pendingTasks === 0 && newBoundary.status === PENDING) {
9324 // This must have been the last segment we were waiting on. This boundary is now complete.
9325 // Therefore we won't need the fallback. We early return so that we don't have to create
9326 // the fallback.
9327 newBoundary.status = COMPLETED; // We are returning early so we need to restore the
9328
9329 task.componentStack = previousComponentStack;
9330 return;
9331 }
9332 } catch (error) {
9333 contentRootSegment.status = ERRORED;
9334 newBoundary.status = CLIENT_RENDERED;
9335 var thrownInfo = getThrownInfo(request, task.componentStack);
9336 var errorDigest;
9337
9338 {
9339 errorDigest = logRecoverableError(request, error, thrownInfo);
9340 }
9341
9342 encodeErrorForBoundary(newBoundary, errorDigest, error, thrownInfo, false);
9343 untrackBoundary(request, newBoundary); // We don't need to decrement any task numbers because we didn't spawn any new task.
9344 // We don't need to schedule any task because we know the parent has written yet.
9345 // We do need to fallthrough to create the fallback though.
9346 } finally {
9347 task.blockedBoundary = parentBoundary;
9348 task.hoistableState = parentHoistableState;
9349 task.blockedSegment = parentSegment;
9350 task.keyPath = prevKeyPath;
9351 task.componentStack = previousComponentStack;
9352 }
9353
9354 var fallbackKeyPath = [keyPath[0], 'Suspense Fallback', keyPath[2]];
9355 var trackedPostpones = request.trackedPostpones;
9356
9357 if (trackedPostpones !== null) {
9358 // We create a detached replay node to track any postpones inside the fallback.
9359 var fallbackReplayNode = [fallbackKeyPath[1], fallbackKeyPath[2], [], null];
9360 trackedPostpones.workingMap.set(fallbackKeyPath, fallbackReplayNode);
9361
9362 if (newBoundary.status === POSTPONED) {
9363 // This must exist now.
9364 var boundaryReplayNode = trackedPostpones.workingMap.get(keyPath);
9365 boundaryReplayNode[4] = fallbackReplayNode;
9366 } else {
9367 // We might not inject it into the postponed tree, unless the content actually
9368 // postpones too. We need to keep track of it until that happpens.
9369 newBoundary.trackedFallbackNode = fallbackReplayNode;
9370 }
9371 } // We create suspended task for the fallback because we don't want to actually work
9372 // on it yet in case we finish the main content, so we queue for later.
9373
9374
9375 var suspendedFallbackTask = createRenderTask(request, null, fallback, -1, parentBoundary, boundarySegment, newBoundary.fallbackState, fallbackAbortSet, fallbackKeyPath, task.formatContext, task.legacyContext, task.context, task.treeContext, // This stack should be the Suspense boundary stack because while the fallback is actually a child segment
9376 // of the parent boundary from a component standpoint the fallback is a child of the Suspense boundary itself
9377 suspenseComponentStack, true); // TODO: This should be queued at a separate lower priority queue so that we only work
9378 // on preparing fallbacks if we don't have any more main content to task on.
9379
9380 request.pingedTasks.push(suspendedFallbackTask);
9381}
9382
9383function replaySuspenseBoundary(request, task, keyPath, props, id, childNodes, childSlots, fallbackNodes, fallbackSlots) {
9384 var previousComponentStack = task.componentStack; // If we end up creating the fallback task we need it to have the correct stack which is
9385 // the stack for the boundary itself. We stash it here so we can use it if needed later
9386
9387 var suspenseComponentStack = task.componentStack = createBuiltInComponentStack(task, 'Suspense');
9388 var prevKeyPath = task.keyPath;
9389 var previousReplaySet = task.replay;
9390 var parentBoundary = task.blockedBoundary;
9391 var parentHoistableState = task.hoistableState;
9392 var content = props.children;
9393 var fallback = props.fallback;
9394 var fallbackAbortSet = new Set();
9395 var resumedBoundary = createSuspenseBoundary(request, fallbackAbortSet);
9396 resumedBoundary.parentFlushed = true; // We restore the same id of this boundary as was used during prerender.
9397
9398 resumedBoundary.rootSegmentID = id; // We can reuse the current context and task to render the content immediately without
9399 // context switching. We just need to temporarily switch which boundary and replay node
9400 // we're writing to. If something suspends, it'll spawn new suspended task with that context.
9401
9402 task.blockedBoundary = resumedBoundary;
9403 task.hoistableState = resumedBoundary.contentState;
9404 task.replay = {
9405 nodes: childNodes,
9406 slots: childSlots,
9407 pendingTasks: 1
9408 };
9409
9410 try {
9411 // We use the safe form because we don't handle suspending here. Only error handling.
9412 renderNode(request, task, content, -1);
9413
9414 if (task.replay.pendingTasks === 1 && task.replay.nodes.length > 0) {
9415 throw new Error("Couldn't find all resumable slots by key/index during replaying. " + "The tree doesn't match so React will fallback to client rendering.");
9416 }
9417
9418 task.replay.pendingTasks--;
9419
9420 if (resumedBoundary.pendingTasks === 0 && resumedBoundary.status === PENDING) {
9421 // This must have been the last segment we were waiting on. This boundary is now complete.
9422 // Therefore we won't need the fallback. We early return so that we don't have to create
9423 // the fallback.
9424 resumedBoundary.status = COMPLETED;
9425 request.completedBoundaries.push(resumedBoundary); // We restore the parent componentStack. Semantically this is the same as
9426 // popComponentStack(task) but we do this instead because it should be slightly
9427 // faster
9428
9429 return;
9430 }
9431 } catch (error) {
9432 resumedBoundary.status = CLIENT_RENDERED;
9433 var thrownInfo = getThrownInfo(request, task.componentStack);
9434 var errorDigest;
9435
9436 {
9437 errorDigest = logRecoverableError(request, error, thrownInfo);
9438 }
9439
9440 encodeErrorForBoundary(resumedBoundary, errorDigest, error, thrownInfo, false);
9441 task.replay.pendingTasks--; // The parent already flushed in the prerender so we need to schedule this to be emitted.
9442
9443 request.clientRenderedBoundaries.push(resumedBoundary); // We don't need to decrement any task numbers because we didn't spawn any new task.
9444 // We don't need to schedule any task because we know the parent has written yet.
9445 // We do need to fallthrough to create the fallback though.
9446 } finally {
9447 task.blockedBoundary = parentBoundary;
9448 task.hoistableState = parentHoistableState;
9449 task.replay = previousReplaySet;
9450 task.keyPath = prevKeyPath;
9451 task.componentStack = previousComponentStack;
9452 }
9453
9454 var fallbackKeyPath = [keyPath[0], 'Suspense Fallback', keyPath[2]]; // We create suspended task for the fallback because we don't want to actually work
9455 // on it yet in case we finish the main content, so we queue for later.
9456
9457 var fallbackReplay = {
9458 nodes: fallbackNodes,
9459 slots: fallbackSlots,
9460 pendingTasks: 0
9461 };
9462 var suspendedFallbackTask = createReplayTask(request, null, fallbackReplay, fallback, -1, parentBoundary, resumedBoundary.fallbackState, fallbackAbortSet, fallbackKeyPath, task.formatContext, task.legacyContext, task.context, task.treeContext, // This stack should be the Suspense boundary stack because while the fallback is actually a child segment
9463 // of the parent boundary from a component standpoint the fallback is a child of the Suspense boundary itself
9464 suspenseComponentStack, true); // TODO: This should be queued at a separate lower priority queue so that we only work
9465 // on preparing fallbacks if we don't have any more main content to task on.
9466
9467 request.pingedTasks.push(suspendedFallbackTask);
9468}
9469
9470function renderHostElement(request, task, keyPath, type, props) {
9471 var previousComponentStack = task.componentStack;
9472 task.componentStack = createBuiltInComponentStack(task, type);
9473 var segment = task.blockedSegment;
9474
9475 if (segment === null) {
9476 // Replay
9477 var children = props.children; // TODO: Make this a Config for replaying.
9478
9479 var prevContext = task.formatContext;
9480 var prevKeyPath = task.keyPath;
9481 task.formatContext = getChildFormatContext(prevContext, type, props);
9482 task.keyPath = keyPath; // We use the non-destructive form because if something suspends, we still
9483 // need to pop back up and finish this subtree of HTML.
9484
9485 renderNode(request, task, children, -1); // We expect that errors will fatal the whole task and that we don't need
9486 // the correct context. Therefore this is not in a finally.
9487
9488 task.formatContext = prevContext;
9489 task.keyPath = prevKeyPath;
9490 } else {
9491 // Render
9492 var _children = pushStartInstance(segment.chunks, type, props, request.resumableState, request.renderState, task.hoistableState, task.formatContext, segment.lastPushedText, task.isFallback);
9493
9494 segment.lastPushedText = false;
9495 var _prevContext = task.formatContext;
9496 var _prevKeyPath2 = task.keyPath;
9497 task.formatContext = getChildFormatContext(_prevContext, type, props);
9498 task.keyPath = keyPath; // We use the non-destructive form because if something suspends, we still
9499 // need to pop back up and finish this subtree of HTML.
9500
9501 renderNode(request, task, _children, -1); // We expect that errors will fatal the whole task and that we don't need
9502 // the correct context. Therefore this is not in a finally.
9503
9504 task.formatContext = _prevContext;
9505 task.keyPath = _prevKeyPath2;
9506 pushEndInstance(segment.chunks, type, props, request.resumableState, _prevContext);
9507 segment.lastPushedText = false;
9508 }
9509
9510 task.componentStack = previousComponentStack;
9511}
9512
9513function shouldConstruct(Component) {
9514 return Component.prototype && Component.prototype.isReactComponent;
9515}
9516
9517function renderWithHooks(request, task, keyPath, Component, props, secondArg) {
9518 // Reset the task's thenable state before continuing, so that if a later
9519 // component suspends we can reuse the same task object. If the same
9520 // component suspends again, the thenable state will be restored.
9521 var prevThenableState = task.thenableState;
9522 task.thenableState = null;
9523 var componentIdentity = {};
9524 prepareToUseHooks(request, task, keyPath, componentIdentity, prevThenableState);
9525 var result = Component(props, secondArg);
9526 return finishHooks(Component, props, result, secondArg);
9527}
9528
9529function finishClassComponent(request, task, keyPath, instance, Component, props) {
9530 var nextChildren = instance.render();
9531
9532 {
9533 if (instance.props !== props) {
9534 if (!didWarnAboutReassigningProps) {
9535 error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');
9536 }
9537
9538 didWarnAboutReassigningProps = true;
9539 }
9540 }
9541
9542 var prevKeyPath = task.keyPath;
9543 task.keyPath = keyPath;
9544 renderNodeDestructive(request, task, nextChildren, -1);
9545 task.keyPath = prevKeyPath;
9546}
9547
9548function resolveClassComponentProps(Component, baseProps) {
9549 var newProps = baseProps;
9550
9551 {
9552 // Remove ref from the props object, if it exists.
9553 if ('ref' in baseProps) {
9554 newProps = {};
9555
9556 for (var propName in baseProps) {
9557 if (propName !== 'ref') {
9558 newProps[propName] = baseProps[propName];
9559 }
9560 }
9561 }
9562 } // Resolve default props.
9563
9564
9565 var defaultProps = Component.defaultProps;
9566
9567 if (defaultProps && // If disableDefaultPropsExceptForClasses is true, we always resolve
9568 // default props here, rather than in the JSX runtime.
9569 disableDefaultPropsExceptForClasses) {
9570 // We may have already copied the props object above to remove ref. If so,
9571 // we can modify that. Otherwise, copy the props object with Object.assign.
9572 if (newProps === baseProps) {
9573 newProps = assign({}, newProps, baseProps);
9574 } // Taken from old JSX runtime, where this used to live.
9575
9576
9577 for (var _propName in defaultProps) {
9578 if (newProps[_propName] === undefined) {
9579 newProps[_propName] = defaultProps[_propName];
9580 }
9581 }
9582 }
9583
9584 return newProps;
9585}
9586
9587function renderClassComponent(request, task, keyPath, Component, props) {
9588 var resolvedProps = resolveClassComponentProps(Component, props);
9589 var previousComponentStack = task.componentStack;
9590 task.componentStack = createClassComponentStack(task, Component);
9591 var maskedContext = undefined;
9592 var instance = constructClassInstance(Component, resolvedProps);
9593 mountClassInstance(instance, Component, resolvedProps, maskedContext);
9594 finishClassComponent(request, task, keyPath, instance, Component, resolvedProps);
9595 task.componentStack = previousComponentStack;
9596}
9597
9598var didWarnAboutBadClass = {};
9599var didWarnAboutContextTypeOnFunctionComponent = {};
9600var didWarnAboutGetDerivedStateOnFunctionComponent = {};
9601var didWarnAboutReassigningProps = false;
9602var didWarnAboutGenerators = false;
9603var didWarnAboutMaps = false;
9604
9605function renderFunctionComponent(request, task, keyPath, Component, props) {
9606 var legacyContext;
9607
9608 var previousComponentStack = task.componentStack;
9609 task.componentStack = createFunctionComponentStack(task, Component);
9610
9611 {
9612 if (Component.prototype && typeof Component.prototype.render === 'function') {
9613 var componentName = getComponentNameFromType(Component) || 'Unknown';
9614
9615 if (!didWarnAboutBadClass[componentName]) {
9616 error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
9617
9618 didWarnAboutBadClass[componentName] = true;
9619 }
9620 }
9621 }
9622
9623 var value = renderWithHooks(request, task, keyPath, Component, props, legacyContext);
9624 var hasId = checkDidRenderIdHook();
9625 var actionStateCount = getActionStateCount();
9626 var actionStateMatchingIndex = getActionStateMatchingIndex();
9627
9628 {
9629 if (Component.contextTypes) {
9630 error('%s uses the legacy contextTypes API which was removed in React 19. ' + 'Use React.createContext() with React.useContext() instead.', getComponentNameFromType(Component) || 'Unknown');
9631 }
9632 }
9633
9634 {
9635 validateFunctionComponentInDev(Component);
9636 }
9637
9638 finishFunctionComponent(request, task, keyPath, value, hasId, actionStateCount, actionStateMatchingIndex);
9639 task.componentStack = previousComponentStack;
9640}
9641
9642function finishFunctionComponent(request, task, keyPath, children, hasId, actionStateCount, actionStateMatchingIndex) {
9643 var didEmitActionStateMarkers = false;
9644
9645 if (actionStateCount !== 0 && request.formState !== null) {
9646 // For each useActionState hook, emit a marker that indicates whether we
9647 // rendered using the form state passed at the root. We only emit these
9648 // markers if form state is passed at the root.
9649 var segment = task.blockedSegment;
9650
9651 if (segment === null) ; else {
9652 didEmitActionStateMarkers = true;
9653 var target = segment.chunks;
9654
9655 for (var i = 0; i < actionStateCount; i++) {
9656 if (i === actionStateMatchingIndex) {
9657 pushFormStateMarkerIsMatching(target);
9658 } else {
9659 pushFormStateMarkerIsNotMatching(target);
9660 }
9661 }
9662 }
9663 }
9664
9665 var prevKeyPath = task.keyPath;
9666 task.keyPath = keyPath;
9667
9668 if (hasId) {
9669 // This component materialized an id. We treat this as its own level, with
9670 // a single "child" slot.
9671 var prevTreeContext = task.treeContext;
9672 var totalChildren = 1;
9673 var index = 0; // Modify the id context. Because we'll need to reset this if something
9674 // suspends or errors, we'll use the non-destructive render path.
9675
9676 task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);
9677 renderNode(request, task, children, -1); // Like the other contexts, this does not need to be in a finally block
9678 // because renderNode takes care of unwinding the stack.
9679
9680 task.treeContext = prevTreeContext;
9681 } else if (didEmitActionStateMarkers) {
9682 // If there were useActionState hooks, we must use the non-destructive path
9683 // because this component is not a pure indirection; we emitted markers
9684 // to the stream.
9685 renderNode(request, task, children, -1);
9686 } else {
9687 // We're now successfully past this task, and we haven't modified the
9688 // context stack. We don't have to pop back to the previous task every
9689 // again, so we can use the destructive recursive form.
9690 renderNodeDestructive(request, task, children, -1);
9691 }
9692
9693 task.keyPath = prevKeyPath;
9694}
9695
9696function validateFunctionComponentInDev(Component) {
9697 {
9698 if (Component) {
9699 if (Component.childContextTypes) {
9700 error('childContextTypes cannot be defined on a function component.\n' + ' %s.childContextTypes = ...', Component.displayName || Component.name || 'Component');
9701 }
9702 }
9703
9704 if (typeof Component.getDerivedStateFromProps === 'function') {
9705 var _componentName = getComponentNameFromType(Component) || 'Unknown';
9706
9707 if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName]) {
9708 error('%s: Function components do not support getDerivedStateFromProps.', _componentName);
9709
9710 didWarnAboutGetDerivedStateOnFunctionComponent[_componentName] = true;
9711 }
9712 }
9713
9714 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
9715 var _componentName2 = getComponentNameFromType(Component) || 'Unknown';
9716
9717 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName2]) {
9718 error('%s: Function components do not support contextType.', _componentName2);
9719
9720 didWarnAboutContextTypeOnFunctionComponent[_componentName2] = true;
9721 }
9722 }
9723 }
9724}
9725
9726function resolveDefaultPropsOnNonClassComponent(Component, baseProps) {
9727 {
9728 // Support for defaultProps is removed in React 19 for all types
9729 // except classes.
9730 return baseProps;
9731 }
9732}
9733
9734function renderForwardRef(request, task, keyPath, type, props, ref) {
9735 var previousComponentStack = task.componentStack;
9736 task.componentStack = createFunctionComponentStack(task, type.render);
9737 var propsWithoutRef;
9738
9739 if ('ref' in props) {
9740 // `ref` is just a prop now, but `forwardRef` expects it to not appear in
9741 // the props object. This used to happen in the JSX runtime, but now we do
9742 // it here.
9743 propsWithoutRef = {};
9744
9745 for (var key in props) {
9746 // Since `ref` should only appear in props via the JSX transform, we can
9747 // assume that this is a plain object. So we don't need a
9748 // hasOwnProperty check.
9749 if (key !== 'ref') {
9750 propsWithoutRef[key] = props[key];
9751 }
9752 }
9753 } else {
9754 propsWithoutRef = props;
9755 }
9756
9757 var children = renderWithHooks(request, task, keyPath, type.render, propsWithoutRef, ref);
9758 var hasId = checkDidRenderIdHook();
9759 var actionStateCount = getActionStateCount();
9760 var actionStateMatchingIndex = getActionStateMatchingIndex();
9761 finishFunctionComponent(request, task, keyPath, children, hasId, actionStateCount, actionStateMatchingIndex);
9762 task.componentStack = previousComponentStack;
9763}
9764
9765function renderMemo(request, task, keyPath, type, props, ref) {
9766 var innerType = type.type;
9767 var resolvedProps = resolveDefaultPropsOnNonClassComponent(innerType, props);
9768 renderElement(request, task, keyPath, innerType, resolvedProps, ref);
9769}
9770
9771function renderContextConsumer(request, task, keyPath, context, props) {
9772 var render = props.children;
9773
9774 {
9775 if (typeof render !== 'function') {
9776 error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
9777 }
9778 }
9779
9780 var newValue = readContext$1(context);
9781 var newChildren = render(newValue);
9782 var prevKeyPath = task.keyPath;
9783 task.keyPath = keyPath;
9784 renderNodeDestructive(request, task, newChildren, -1);
9785 task.keyPath = prevKeyPath;
9786}
9787
9788function renderContextProvider(request, task, keyPath, context, props) {
9789 var value = props.value;
9790 var children = props.children;
9791 var prevSnapshot;
9792
9793 {
9794 prevSnapshot = task.context;
9795 }
9796
9797 var prevKeyPath = task.keyPath;
9798 task.context = pushProvider(context, value);
9799 task.keyPath = keyPath;
9800 renderNodeDestructive(request, task, children, -1);
9801 task.context = popProvider(context);
9802 task.keyPath = prevKeyPath;
9803
9804 {
9805 if (prevSnapshot !== task.context) {
9806 error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');
9807 }
9808 }
9809}
9810
9811function renderLazyComponent(request, task, keyPath, lazyComponent, props, ref) {
9812 var previousComponentStack = task.componentStack;
9813 task.componentStack = createBuiltInComponentStack(task, 'Lazy');
9814 var payload = lazyComponent._payload;
9815 var init = lazyComponent._init;
9816 var Component = init(payload);
9817 var resolvedProps = resolveDefaultPropsOnNonClassComponent(Component, props);
9818 renderElement(request, task, keyPath, Component, resolvedProps, ref);
9819 task.componentStack = previousComponentStack;
9820}
9821
9822function renderOffscreen(request, task, keyPath, props) {
9823 var mode = props.mode;
9824
9825 if (mode === 'hidden') ; else {
9826 // A visible Offscreen boundary is treated exactly like a fragment: a
9827 // pure indirection.
9828 var prevKeyPath = task.keyPath;
9829 task.keyPath = keyPath;
9830 renderNodeDestructive(request, task, props.children, -1);
9831 task.keyPath = prevKeyPath;
9832 }
9833}
9834
9835function renderElement(request, task, keyPath, type, props, ref) {
9836 if (typeof type === 'function') {
9837 if (shouldConstruct(type)) {
9838 renderClassComponent(request, task, keyPath, type, props);
9839 return;
9840 } else {
9841 renderFunctionComponent(request, task, keyPath, type, props);
9842 return;
9843 }
9844 }
9845
9846 if (typeof type === 'string') {
9847 renderHostElement(request, task, keyPath, type, props);
9848 return;
9849 }
9850
9851 switch (type) {
9852 // LegacyHidden acts the same as a fragment. This only works because we
9853 // currently assume that every instance of LegacyHidden is accompanied by a
9854 // host component wrapper. In the hidden mode, the host component is given a
9855 // `hidden` attribute, which ensures that the initial HTML is not visible.
9856 // To support the use of LegacyHidden as a true fragment, without an extra
9857 // DOM node, we would have to hide the initial HTML in some other way.
9858 // TODO: Delete in LegacyHidden. It's an unstable API only used in the
9859 // www build. As a migration step, we could add a special prop to Offscreen
9860 // that simulates the old behavior (no hiding, no change to effects).
9861 case REACT_LEGACY_HIDDEN_TYPE:
9862 case REACT_DEBUG_TRACING_MODE_TYPE:
9863 case REACT_STRICT_MODE_TYPE:
9864 case REACT_PROFILER_TYPE:
9865 case REACT_FRAGMENT_TYPE:
9866 {
9867 var prevKeyPath = task.keyPath;
9868 task.keyPath = keyPath;
9869 renderNodeDestructive(request, task, props.children, -1);
9870 task.keyPath = prevKeyPath;
9871 return;
9872 }
9873
9874 case REACT_OFFSCREEN_TYPE:
9875 {
9876 renderOffscreen(request, task, keyPath, props);
9877 return;
9878 }
9879
9880 case REACT_SUSPENSE_LIST_TYPE:
9881 {
9882 var preiousComponentStack = task.componentStack;
9883 task.componentStack = createBuiltInComponentStack(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.
9884
9885 var _prevKeyPath3 = task.keyPath;
9886 task.keyPath = keyPath;
9887 renderNodeDestructive(request, task, props.children, -1);
9888 task.keyPath = _prevKeyPath3;
9889 task.componentStack = preiousComponentStack;
9890 return;
9891 }
9892
9893 case REACT_SCOPE_TYPE:
9894 {
9895
9896 throw new Error('ReactDOMServer does not yet support scope components.');
9897 }
9898
9899 case REACT_SUSPENSE_TYPE:
9900 {
9901 {
9902 renderSuspenseBoundary(request, task, keyPath, props);
9903 }
9904
9905 return;
9906 }
9907 }
9908
9909 if (typeof type === 'object' && type !== null) {
9910 switch (type.$$typeof) {
9911 case REACT_FORWARD_REF_TYPE:
9912 {
9913 renderForwardRef(request, task, keyPath, type, props, ref);
9914 return;
9915 }
9916
9917 case REACT_MEMO_TYPE:
9918 {
9919 renderMemo(request, task, keyPath, type, props, ref);
9920 return;
9921 }
9922
9923 case REACT_PROVIDER_TYPE:
9924
9925 case REACT_CONTEXT_TYPE:
9926 {
9927 {
9928 var _context = type;
9929 renderContextProvider(request, task, keyPath, _context, props);
9930 return;
9931 }
9932 }
9933
9934 case REACT_CONSUMER_TYPE:
9935 {
9936 {
9937 var _context3 = type._context;
9938 renderContextConsumer(request, task, keyPath, _context3, props);
9939 return;
9940 } // Fall through
9941
9942 }
9943
9944 case REACT_LAZY_TYPE:
9945 {
9946 renderLazyComponent(request, task, keyPath, type, props);
9947 return;
9948 }
9949 }
9950 }
9951
9952 var info = '';
9953
9954 {
9955 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
9956 info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
9957 }
9958 }
9959
9960 throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
9961}
9962
9963function resumeNode(request, task, segmentId, node, childIndex) {
9964 var prevReplay = task.replay;
9965 var blockedBoundary = task.blockedBoundary;
9966 var resumedSegment = createPendingSegment(request, 0, null, task.formatContext, false, false);
9967 resumedSegment.id = segmentId;
9968 resumedSegment.parentFlushed = true;
9969
9970 try {
9971 // Convert the current ReplayTask to a RenderTask.
9972 var renderTask = task;
9973 renderTask.replay = null;
9974 renderTask.blockedSegment = resumedSegment;
9975 renderNode(request, task, node, childIndex);
9976 resumedSegment.status = COMPLETED;
9977
9978 if (blockedBoundary === null) {
9979 request.completedRootSegment = resumedSegment;
9980 } else {
9981 queueCompletedSegment(blockedBoundary, resumedSegment);
9982
9983 if (blockedBoundary.parentFlushed) {
9984 request.partialBoundaries.push(blockedBoundary);
9985 }
9986 }
9987 } finally {
9988 // Restore to a ReplayTask.
9989 task.replay = prevReplay;
9990 task.blockedSegment = null;
9991 }
9992}
9993
9994function replayElement(request, task, keyPath, name, keyOrIndex, childIndex, type, props, ref, replay) {
9995 // We're replaying. Find the path to follow.
9996 var replayNodes = replay.nodes;
9997
9998 for (var i = 0; i < replayNodes.length; i++) {
9999 // Flow doesn't support refinement on tuples so we do it manually here.
10000 var node = replayNodes[i];
10001
10002 if (keyOrIndex !== node[1]) {
10003 continue;
10004 }
10005
10006 if (node.length === 4) {
10007 // Matched a replayable path.
10008 // Let's double check that the component name matches as a precaution.
10009 if (name !== null && name !== node[0]) {
10010 throw new Error('Expected the resume to render <' + node[0] + '> in this slot but instead it rendered <' + name + '>. ' + "The tree doesn't match so React will fallback to client rendering.");
10011 }
10012
10013 var childNodes = node[2];
10014 var childSlots = node[3];
10015 var currentNode = task.node;
10016 task.replay = {
10017 nodes: childNodes,
10018 slots: childSlots,
10019 pendingTasks: 1
10020 };
10021
10022 try {
10023 renderElement(request, task, keyPath, type, props, ref);
10024
10025 if (task.replay.pendingTasks === 1 && task.replay.nodes.length > 0 // TODO check remaining slots
10026 ) {
10027 throw new Error("Couldn't find all resumable slots by key/index during replaying. " + "The tree doesn't match so React will fallback to client rendering.");
10028 }
10029
10030 task.replay.pendingTasks--;
10031 } catch (x) {
10032 if (typeof x === 'object' && x !== null && (x === SuspenseException || typeof x.then === 'function')) {
10033 // Suspend
10034 if (task.node === currentNode) {
10035 // This same element suspended so we need to pop the replay we just added.
10036 task.replay = replay;
10037 }
10038
10039 throw x;
10040 }
10041
10042 task.replay.pendingTasks--; // Unlike regular render, we don't terminate the siblings if we error
10043 // during a replay. That's because this component didn't actually error
10044 // in the original prerender. What's unable to complete is the child
10045 // replay nodes which might be Suspense boundaries which are able to
10046 // absorb the error and we can still continue with siblings.
10047
10048 var thrownInfo = getThrownInfo(request, task.componentStack);
10049 erroredReplay(request, task.blockedBoundary, x, thrownInfo, childNodes, childSlots);
10050 }
10051
10052 task.replay = replay;
10053 } else {
10054 // Let's double check that the component type matches.
10055 if (type !== REACT_SUSPENSE_TYPE) {
10056 var expectedType = 'Suspense';
10057 throw new Error('Expected the resume to render <' + expectedType + '> in this slot but instead it rendered <' + (getComponentNameFromType(type) || 'Unknown') + '>. ' + "The tree doesn't match so React will fallback to client rendering.");
10058 } // Matched a replayable path.
10059
10060
10061 replaySuspenseBoundary(request, task, keyPath, props, node[5], node[2], node[3], node[4] === null ? [] : node[4][2], node[4] === null ? null : node[4][3]);
10062 } // We finished rendering this node, so now we can consume this
10063 // slot. This must happen after in case we rerender this task.
10064
10065
10066 replayNodes.splice(i, 1);
10067 return;
10068 } // We didn't find any matching nodes. We assume that this element was already
10069 // rendered in the prelude and skip it.
10070
10071}
10072
10073function validateIterable(task, iterable, childIndex, iterator, iteratorFn) {
10074 {
10075 if (iterator === iterable) {
10076 // We don't support rendering Generators as props because it's a mutation.
10077 // See https://github.com/facebook/react/issues/12995
10078 // We do support generators if they were created by a GeneratorFunction component
10079 // as its direct child since we can recreate those by rerendering the component
10080 // as needed.
10081 var isGeneratorComponent = childIndex === -1 && // Only the root child is valid
10082 task.componentStack !== null && task.componentStack.tag === 1 && // FunctionComponent
10083 // $FlowFixMe[method-unbinding]
10084 Object.prototype.toString.call(task.componentStack.type) === '[object GeneratorFunction]' && // $FlowFixMe[method-unbinding]
10085 Object.prototype.toString.call(iterator) === '[object Generator]';
10086
10087 if (!isGeneratorComponent) {
10088 if (!didWarnAboutGenerators) {
10089 error('Using Iterators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. You can also use an ' + 'Iterable that can iterate multiple times over the same items.');
10090 }
10091
10092 didWarnAboutGenerators = true;
10093 }
10094 } else if (iterable.entries === iteratorFn) {
10095 // Warn about using Maps as children
10096 if (!didWarnAboutMaps) {
10097 error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
10098
10099 didWarnAboutMaps = true;
10100 }
10101 }
10102 }
10103}
10104
10105function warnOnFunctionType(invalidChild) {
10106 {
10107 var name = invalidChild.displayName || invalidChild.name || 'Component';
10108
10109 error('Functions are not valid as a React child. This may happen if ' + 'you return %s instead of <%s /> from render. ' + 'Or maybe you meant to call this function rather than return it.', name, name);
10110 }
10111}
10112
10113function warnOnSymbolType(invalidChild) {
10114 {
10115 // eslint-disable-next-line react-internal/safe-string-coercion
10116 var name = String(invalidChild);
10117
10118 error('Symbols are not valid as a React child.\n' + ' %s', name);
10119 }
10120} // This function by it self renders a node and consumes the task by mutating it
10121// to update the current execution state.
10122
10123
10124function renderNodeDestructive(request, task, node, childIndex) {
10125 if (task.replay !== null && typeof task.replay.slots === 'number') {
10126 // TODO: Figure out a cheaper place than this hot path to do this check.
10127 var resumeSegmentID = task.replay.slots;
10128 resumeNode(request, task, resumeSegmentID, node, childIndex);
10129 return;
10130 } // Stash the node we're working on. We'll pick up from this task in case
10131 // something suspends.
10132
10133
10134 task.node = node;
10135 task.childIndex = childIndex;
10136
10137 if (node === null) {
10138 return;
10139 } // Handle object types
10140
10141
10142 if (typeof node === 'object') {
10143 switch (node.$$typeof) {
10144 case REACT_ELEMENT_TYPE:
10145 {
10146 var element = node;
10147 var type = element.type;
10148 var key = element.key;
10149 var props = element.props;
10150 var ref;
10151
10152 {
10153 // TODO: This is a temporary, intermediate step. Once the feature
10154 // flag is removed, we should get the ref off the props object right
10155 // before using it.
10156 var refProp = props.ref;
10157 ref = refProp !== undefined ? refProp : null;
10158 }
10159
10160 var name = getComponentNameFromType(type);
10161 var keyOrIndex = key == null ? childIndex === -1 ? 0 : childIndex : key;
10162 var keyPath = [task.keyPath, name, keyOrIndex];
10163
10164 if (task.replay !== null) {
10165 replayElement(request, task, keyPath, name, keyOrIndex, childIndex, type, props, ref, task.replay); // No matches found for this node. We assume it's already emitted in the
10166 // prelude and skip it during the replay.
10167 } else {
10168 // We're doing a plain render.
10169 renderElement(request, task, keyPath, type, props, ref);
10170 }
10171
10172 return;
10173 }
10174
10175 case REACT_PORTAL_TYPE:
10176 throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');
10177
10178 case REACT_LAZY_TYPE:
10179 {
10180 var previousComponentStack = task.componentStack;
10181 task.componentStack = createBuiltInComponentStack(task, 'Lazy');
10182 var lazyNode = node;
10183 var payload = lazyNode._payload;
10184 var init = lazyNode._init;
10185 var resolvedNode = init(payload); // We restore the stack before rendering the resolved node because once the Lazy
10186 // has resolved any future errors
10187
10188 task.componentStack = previousComponentStack; // Now we render the resolved node
10189
10190 renderNodeDestructive(request, task, resolvedNode, childIndex);
10191 return;
10192 }
10193 }
10194
10195 if (isArray(node)) {
10196 renderChildrenArray(request, task, node, childIndex);
10197 return;
10198 }
10199
10200 var iteratorFn = getIteratorFn(node);
10201
10202 if (iteratorFn) {
10203 var iterator = iteratorFn.call(node);
10204
10205 if (iterator) {
10206 {
10207 validateIterable(task, node, childIndex, iterator, iteratorFn);
10208 } // We need to know how many total children are in this set, so that we
10209 // can allocate enough id slots to acommodate them. So we must exhaust
10210 // the iterator before we start recursively rendering the children.
10211 // TODO: This is not great but I think it's inherent to the id
10212 // generation algorithm.
10213
10214
10215 var step = iterator.next();
10216
10217 if (!step.done) {
10218 var children = [];
10219
10220 do {
10221 children.push(step.value);
10222 step = iterator.next();
10223 } while (!step.done);
10224
10225 renderChildrenArray(request, task, children, childIndex);
10226 }
10227
10228 return;
10229 }
10230 }
10231 // a child position, it unwraps it using the same algorithm as `use`. For
10232 // example, for promises, React will throw an exception to unwind the
10233 // stack, then replay the component once the promise resolves.
10234 //
10235 // A difference from `use` is that React will keep unwrapping the value
10236 // until it reaches a non-Usable type.
10237 //
10238 // e.g. Usable<Usable<Usable<T>>> should resolve to T
10239
10240
10241 var maybeUsable = node;
10242
10243 if (typeof maybeUsable.then === 'function') {
10244 // Clear any previous thenable state that was created by the unwrapping.
10245 task.thenableState = null;
10246 var thenable = maybeUsable;
10247 return renderNodeDestructive(request, task, unwrapThenable(thenable), childIndex);
10248 }
10249
10250 if (maybeUsable.$$typeof === REACT_CONTEXT_TYPE) {
10251 var context = maybeUsable;
10252 return renderNodeDestructive(request, task, readContext$1(context), childIndex);
10253 } // $FlowFixMe[method-unbinding]
10254
10255
10256 var childString = Object.prototype.toString.call(node);
10257 throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
10258 }
10259
10260 if (typeof node === 'string') {
10261 var segment = task.blockedSegment;
10262
10263 if (segment === null) ; else {
10264 segment.lastPushedText = pushTextInstance(segment.chunks, node, request.renderState, segment.lastPushedText);
10265 }
10266
10267 return;
10268 }
10269
10270 if (typeof node === 'number' || typeof node === 'bigint') {
10271 var _segment = task.blockedSegment;
10272
10273 if (_segment === null) ; else {
10274 _segment.lastPushedText = pushTextInstance(_segment.chunks, '' + node, request.renderState, _segment.lastPushedText);
10275 }
10276
10277 return;
10278 }
10279
10280 {
10281 if (typeof node === 'function') {
10282 warnOnFunctionType(node);
10283 }
10284
10285 if (typeof node === 'symbol') {
10286 warnOnSymbolType(node);
10287 }
10288 }
10289}
10290
10291function replayFragment(request, task, children, childIndex) {
10292 // If we're supposed follow this array, we'd expect to see a ReplayNode matching
10293 // this fragment.
10294 var replay = task.replay;
10295 var replayNodes = replay.nodes;
10296
10297 for (var j = 0; j < replayNodes.length; j++) {
10298 var node = replayNodes[j];
10299
10300 if (node[1] !== childIndex) {
10301 continue;
10302 } // Matched a replayable path.
10303
10304
10305 var childNodes = node[2];
10306 var childSlots = node[3];
10307 task.replay = {
10308 nodes: childNodes,
10309 slots: childSlots,
10310 pendingTasks: 1
10311 };
10312
10313 try {
10314 renderChildrenArray(request, task, children, -1);
10315
10316 if (task.replay.pendingTasks === 1 && task.replay.nodes.length > 0) {
10317 throw new Error("Couldn't find all resumable slots by key/index during replaying. " + "The tree doesn't match so React will fallback to client rendering.");
10318 }
10319
10320 task.replay.pendingTasks--;
10321 } catch (x) {
10322 if (typeof x === 'object' && x !== null && (x === SuspenseException || typeof x.then === 'function')) {
10323 // Suspend
10324 throw x;
10325 }
10326
10327 task.replay.pendingTasks--; // Unlike regular render, we don't terminate the siblings if we error
10328 // during a replay. That's because this component didn't actually error
10329 // in the original prerender. What's unable to complete is the child
10330 // replay nodes which might be Suspense boundaries which are able to
10331 // absorb the error and we can still continue with siblings.
10332 // This is an error, stash the component stack if it is null.
10333
10334 var thrownInfo = getThrownInfo(request, task.componentStack);
10335 erroredReplay(request, task.blockedBoundary, x, thrownInfo, childNodes, childSlots);
10336 }
10337
10338 task.replay = replay; // We finished rendering this node, so now we can consume this
10339 // slot. This must happen after in case we rerender this task.
10340
10341 replayNodes.splice(j, 1);
10342 break;
10343 }
10344}
10345
10346function renderChildrenArray(request, task, children, childIndex) {
10347 var prevKeyPath = task.keyPath;
10348
10349 if (childIndex !== -1) {
10350 task.keyPath = [task.keyPath, 'Fragment', childIndex];
10351
10352 if (task.replay !== null) {
10353 replayFragment(request, // $FlowFixMe: Refined.
10354 task, children, childIndex);
10355 task.keyPath = prevKeyPath;
10356 return;
10357 }
10358 }
10359
10360 var prevTreeContext = task.treeContext;
10361 var totalChildren = children.length;
10362
10363 if (task.replay !== null) {
10364 // Replay
10365 // First we need to check if we have any resume slots at this level.
10366 var resumeSlots = task.replay.slots;
10367
10368 if (resumeSlots !== null && typeof resumeSlots === 'object') {
10369 for (var i = 0; i < totalChildren; i++) {
10370 var node = children[i];
10371 task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i); // We need to use the non-destructive form so that we can safely pop back
10372 // up and render the sibling if something suspends.
10373
10374 var resumeSegmentID = resumeSlots[i]; // TODO: If this errors we should still continue with the next sibling.
10375
10376 if (typeof resumeSegmentID === 'number') {
10377 resumeNode(request, task, resumeSegmentID, node, i); // We finished rendering this node, so now we can consume this
10378 // slot. This must happen after in case we rerender this task.
10379
10380 delete resumeSlots[i];
10381 } else {
10382 renderNode(request, task, node, i);
10383 }
10384 }
10385
10386 task.treeContext = prevTreeContext;
10387 task.keyPath = prevKeyPath;
10388 return;
10389 }
10390 }
10391
10392 for (var _i = 0; _i < totalChildren; _i++) {
10393 var _node = children[_i];
10394 task.treeContext = pushTreeContext(prevTreeContext, totalChildren, _i); // We need to use the non-destructive form so that we can safely pop back
10395 // up and render the sibling if something suspends.
10396
10397 renderNode(request, task, _node, _i);
10398 } // Because this context is always set right before rendering every child, we
10399 // only need to reset it to the previous value at the very end.
10400
10401
10402 task.treeContext = prevTreeContext;
10403 task.keyPath = prevKeyPath;
10404}
10405// resume it.
10406
10407
10408function untrackBoundary(request, boundary) {
10409 var trackedPostpones = request.trackedPostpones;
10410
10411 if (trackedPostpones === null) {
10412 return;
10413 }
10414
10415 var boundaryKeyPath = boundary.trackedContentKeyPath;
10416
10417 if (boundaryKeyPath === null) {
10418 return;
10419 }
10420
10421 var boundaryNode = trackedPostpones.workingMap.get(boundaryKeyPath);
10422
10423 if (boundaryNode === undefined) {
10424 return;
10425 } // Downgrade to plain ReplayNode since we won't replay through it.
10426 // $FlowFixMe[cannot-write]: We intentionally downgrade this to the other tuple.
10427
10428
10429 boundaryNode.length = 4; // Remove any resumable slots.
10430
10431 boundaryNode[2] = [];
10432 boundaryNode[3] = null; // TODO: We should really just remove the boundary from all parent paths too so
10433 // we don't replay the path to it.
10434}
10435
10436function spawnNewSuspendedReplayTask(request, task, thenableState, x) {
10437 var newTask = createReplayTask(request, thenableState, task.replay, task.node, task.childIndex, task.blockedBoundary, task.hoistableState, task.abortSet, task.keyPath, task.formatContext, task.legacyContext, task.context, task.treeContext, // We pop one task off the stack because the node that suspended will be tried again,
10438 // which will add it back onto the stack.
10439 task.componentStack !== null ? task.componentStack.parent : null, task.isFallback);
10440 var ping = newTask.ping;
10441 x.then(ping, ping);
10442}
10443
10444function spawnNewSuspendedRenderTask(request, task, thenableState, x) {
10445 // Something suspended, we'll need to create a new segment and resolve it later.
10446 var segment = task.blockedSegment;
10447 var insertionIndex = segment.chunks.length;
10448 var newSegment = createPendingSegment(request, insertionIndex, null, task.formatContext, // Adopt the parent segment's leading text embed
10449 segment.lastPushedText, // Assume we are text embedded at the trailing edge
10450 true);
10451 segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it
10452
10453 segment.lastPushedText = false;
10454 var newTask = createRenderTask(request, thenableState, task.node, task.childIndex, task.blockedBoundary, newSegment, task.hoistableState, task.abortSet, task.keyPath, task.formatContext, task.legacyContext, task.context, task.treeContext, // We pop one task off the stack because the node that suspended will be tried again,
10455 // which will add it back onto the stack.
10456 task.componentStack !== null ? task.componentStack.parent : null, task.isFallback);
10457 var ping = newTask.ping;
10458 x.then(ping, ping);
10459} // This is a non-destructive form of rendering a node. If it suspends it spawns
10460// a new task and restores the context of this task to what it was before.
10461
10462
10463function renderNode(request, task, node, childIndex) {
10464 // Snapshot the current context in case something throws to interrupt the
10465 // process.
10466 var previousFormatContext = task.formatContext;
10467 var previousLegacyContext = task.legacyContext;
10468 var previousContext = task.context;
10469 var previousKeyPath = task.keyPath;
10470 var previousTreeContext = task.treeContext;
10471 var previousComponentStack = task.componentStack;
10472 var x; // Store how much we've pushed at this point so we can reset it in case something
10473 // suspended partially through writing something.
10474
10475 var segment = task.blockedSegment;
10476
10477 if (segment === null) {
10478 // Replay
10479 try {
10480 return renderNodeDestructive(request, task, node, childIndex);
10481 } catch (thrownValue) {
10482 resetHooksState();
10483 x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
10484 // reasons, the rest of the Suspense implementation expects the thrown
10485 // value to be a thenable, because before `use` existed that was the
10486 // (unstable) API for suspending. This implementation detail can change
10487 // later, once we deprecate the old API in favor of `use`.
10488 getSuspendedThenable() : thrownValue;
10489
10490 if (typeof x === 'object' && x !== null) {
10491 // $FlowFixMe[method-unbinding]
10492 if (typeof x.then === 'function') {
10493 var wakeable = x;
10494 var thenableState = getThenableStateAfterSuspending();
10495 spawnNewSuspendedReplayTask(request, // $FlowFixMe: Refined.
10496 task, thenableState, wakeable); // Restore the context. We assume that this will be restored by the inner
10497 // functions in case nothing throws so we don't use "finally" here.
10498
10499 task.formatContext = previousFormatContext;
10500 task.legacyContext = previousLegacyContext;
10501 task.context = previousContext;
10502 task.keyPath = previousKeyPath;
10503 task.treeContext = previousTreeContext;
10504 task.componentStack = previousComponentStack; // Restore all active ReactContexts to what they were before.
10505
10506 switchContext(previousContext);
10507 return;
10508 }
10509 } // TODO: Abort any undiscovered Suspense boundaries in the ReplayNode.
10510
10511 }
10512 } else {
10513 // Render
10514 var childrenLength = segment.children.length;
10515 var chunkLength = segment.chunks.length;
10516
10517 try {
10518 return renderNodeDestructive(request, task, node, childIndex);
10519 } catch (thrownValue) {
10520 resetHooksState(); // Reset the write pointers to where we started.
10521
10522 segment.children.length = childrenLength;
10523 segment.chunks.length = chunkLength;
10524 x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
10525 // reasons, the rest of the Suspense implementation expects the thrown
10526 // value to be a thenable, because before `use` existed that was the
10527 // (unstable) API for suspending. This implementation detail can change
10528 // later, once we deprecate the old API in favor of `use`.
10529 getSuspendedThenable() : thrownValue;
10530
10531 if (typeof x === 'object' && x !== null) {
10532 // $FlowFixMe[method-unbinding]
10533 if (typeof x.then === 'function') {
10534 var _wakeable = x;
10535
10536 var _thenableState = getThenableStateAfterSuspending();
10537
10538 spawnNewSuspendedRenderTask(request, // $FlowFixMe: Refined.
10539 task, _thenableState, _wakeable); // Restore the context. We assume that this will be restored by the inner
10540 // functions in case nothing throws so we don't use "finally" here.
10541
10542 task.formatContext = previousFormatContext;
10543 task.legacyContext = previousLegacyContext;
10544 task.context = previousContext;
10545 task.keyPath = previousKeyPath;
10546 task.treeContext = previousTreeContext;
10547 task.componentStack = previousComponentStack; // Restore all active ReactContexts to what they were before.
10548
10549 switchContext(previousContext);
10550 return;
10551 }
10552 }
10553 }
10554 } // Restore the context. We assume that this will be restored by the inner
10555 // functions in case nothing throws so we don't use "finally" here.
10556
10557
10558 task.formatContext = previousFormatContext;
10559 task.legacyContext = previousLegacyContext;
10560 task.context = previousContext;
10561 task.keyPath = previousKeyPath;
10562 task.treeContext = previousTreeContext; // We intentionally do not restore the component stack on the error pathway
10563 // Whatever handles the error needs to use this stack which is the location of the
10564 // error. We must restore the stack wherever we handle this
10565 // Restore all active ReactContexts to what they were before.
10566
10567 switchContext(previousContext);
10568 throw x;
10569}
10570
10571function erroredReplay(request, boundary, error, errorInfo, replayNodes, resumeSlots) {
10572 // Erroring during a replay doesn't actually cause an error by itself because
10573 // that component has already rendered. What causes the error is the resumable
10574 // points that we did not yet finish which will be below the point of the reset.
10575 // For example, if we're replaying a path to a Suspense boundary that is not done
10576 // that doesn't error the parent Suspense boundary.
10577 // This might be a bit strange that the error in a parent gets thrown at a child.
10578 // We log it only once and reuse the digest.
10579 var errorDigest;
10580
10581 {
10582 errorDigest = logRecoverableError(request, error, errorInfo);
10583 }
10584
10585 abortRemainingReplayNodes(request, boundary, replayNodes, resumeSlots, error, errorDigest, errorInfo, false);
10586}
10587
10588function erroredTask(request, boundary, error, errorInfo) {
10589 // Report the error to a global handler.
10590 var errorDigest;
10591
10592 {
10593 errorDigest = logRecoverableError(request, error, errorInfo);
10594 }
10595
10596 if (boundary === null) {
10597 fatalError(request, error);
10598 } else {
10599 boundary.pendingTasks--;
10600
10601 if (boundary.status !== CLIENT_RENDERED) {
10602 boundary.status = CLIENT_RENDERED;
10603 encodeErrorForBoundary(boundary, errorDigest, error, errorInfo, false);
10604 untrackBoundary(request, boundary); // Regardless of what happens next, this boundary won't be displayed,
10605 // so we can flush it, if the parent already flushed.
10606
10607 if (boundary.parentFlushed) {
10608 // We don't have a preference where in the queue this goes since it's likely
10609 // to error on the client anyway. However, intentionally client-rendered
10610 // boundaries should be flushed earlier so that they can start on the client.
10611 // We reuse the same queue for errors.
10612 request.clientRenderedBoundaries.push(boundary);
10613 }
10614 }
10615 }
10616
10617 request.allPendingTasks--;
10618
10619 if (request.allPendingTasks === 0) {
10620 completeAll(request);
10621 }
10622}
10623
10624function abortTaskSoft(task) {
10625 // This aborts task without aborting the parent boundary that it blocks.
10626 // It's used for when we didn't need this task to complete the tree.
10627 // If task was needed, then it should use abortTask instead.
10628 var request = this;
10629 var boundary = task.blockedBoundary;
10630 var segment = task.blockedSegment;
10631
10632 if (segment !== null) {
10633 segment.status = ABORTED;
10634 finishedTask(request, boundary, segment);
10635 }
10636}
10637
10638function abortRemainingSuspenseBoundary(request, rootSegmentID, error, errorDigest, errorInfo, wasAborted) {
10639 var resumedBoundary = createSuspenseBoundary(request, new Set());
10640 resumedBoundary.parentFlushed = true; // We restore the same id of this boundary as was used during prerender.
10641
10642 resumedBoundary.rootSegmentID = rootSegmentID;
10643 resumedBoundary.status = CLIENT_RENDERED;
10644 encodeErrorForBoundary(resumedBoundary, errorDigest, error, errorInfo, wasAborted);
10645
10646 if (resumedBoundary.parentFlushed) {
10647 request.clientRenderedBoundaries.push(resumedBoundary);
10648 }
10649}
10650
10651function abortRemainingReplayNodes(request, boundary, nodes, slots, error, errorDigest, errorInfo, aborted) {
10652 for (var i = 0; i < nodes.length; i++) {
10653 var node = nodes[i];
10654
10655 if (node.length === 4) {
10656 abortRemainingReplayNodes(request, boundary, node[2], node[3], error, errorDigest, errorInfo, aborted);
10657 } else {
10658 var boundaryNode = node;
10659 var rootSegmentID = boundaryNode[5];
10660 abortRemainingSuspenseBoundary(request, rootSegmentID, error, errorDigest, errorInfo, aborted);
10661 }
10662 } // Empty the set, since we've cleared it now.
10663
10664
10665 nodes.length = 0;
10666
10667 if (slots !== null) {
10668 // We had something still to resume in the parent boundary. We must trigger
10669 // the error on the parent boundary since it's not able to complete.
10670 if (boundary === null) {
10671 throw new Error('We should not have any resumable nodes in the shell. ' + 'This is a bug in React.');
10672 } else if (boundary.status !== CLIENT_RENDERED) {
10673 boundary.status = CLIENT_RENDERED;
10674 encodeErrorForBoundary(boundary, errorDigest, error, errorInfo, aborted);
10675
10676 if (boundary.parentFlushed) {
10677 request.clientRenderedBoundaries.push(boundary);
10678 }
10679 } // Empty the set
10680
10681
10682 if (typeof slots === 'object') {
10683 for (var index in slots) {
10684 delete slots[index];
10685 }
10686 }
10687 }
10688}
10689
10690function abortTask(task, request, error) {
10691 // This aborts the task and aborts the parent that it blocks, putting it into
10692 // client rendered mode.
10693 var boundary = task.blockedBoundary;
10694 var segment = task.blockedSegment;
10695
10696 if (segment !== null) {
10697 segment.status = ABORTED;
10698 }
10699
10700 if (boundary === null) {
10701 var errorInfo = {};
10702
10703 if (request.status !== CLOSING && request.status !== CLOSED) {
10704 var replay = task.replay;
10705
10706 if (replay === null) {
10707 // We didn't complete the root so we have nothing to show. We can close
10708 // the request;
10709 {
10710 logRecoverableError(request, error, errorInfo);
10711 fatalError(request, error);
10712 }
10713
10714 return;
10715 } else {
10716 // If the shell aborts during a replay, that's not a fatal error. Instead
10717 // we should be able to recover by client rendering all the root boundaries in
10718 // the ReplaySet.
10719 replay.pendingTasks--;
10720
10721 if (replay.pendingTasks === 0 && replay.nodes.length > 0) {
10722 var errorDigest;
10723
10724 {
10725 errorDigest = logRecoverableError(request, error, errorInfo);
10726 }
10727
10728 abortRemainingReplayNodes(request, null, replay.nodes, replay.slots, error, errorDigest, errorInfo, true);
10729 }
10730
10731 request.pendingRootTasks--;
10732
10733 if (request.pendingRootTasks === 0) {
10734 completeShell(request);
10735 }
10736 }
10737 }
10738 } else {
10739 boundary.pendingTasks--;
10740
10741 if (boundary.status !== CLIENT_RENDERED) {
10742 boundary.status = CLIENT_RENDERED; // We construct an errorInfo from the boundary's componentStack so the error in dev will indicate which
10743 // boundary the message is referring to
10744
10745 var _errorInfo = getThrownInfo(request, task.componentStack);
10746
10747 var _errorDigest;
10748
10749 {
10750 _errorDigest = logRecoverableError(request, error, _errorInfo);
10751 }
10752
10753 encodeErrorForBoundary(boundary, _errorDigest, error, _errorInfo, true);
10754 untrackBoundary(request, boundary);
10755
10756 if (boundary.parentFlushed) {
10757 request.clientRenderedBoundaries.push(boundary);
10758 }
10759 } // If this boundary was still pending then we haven't already cancelled its fallbacks.
10760 // We'll need to abort the fallbacks, which will also error that parent boundary.
10761
10762
10763 boundary.fallbackAbortableTasks.forEach(function (fallbackTask) {
10764 return abortTask(fallbackTask, request, error);
10765 });
10766 boundary.fallbackAbortableTasks.clear();
10767 }
10768
10769 request.allPendingTasks--;
10770
10771 if (request.allPendingTasks === 0) {
10772 completeAll(request);
10773 }
10774}
10775
10776function safelyEmitEarlyPreloads(request, shellComplete) {
10777 try {
10778 emitEarlyPreloads(request.renderState, request.resumableState, shellComplete);
10779 } catch (error) {
10780 // We assume preloads are optimistic and thus non-fatal if errored.
10781 var errorInfo = {};
10782 logRecoverableError(request, error, errorInfo);
10783 }
10784} // I extracted this function out because we want to ensure we consistently emit preloads before
10785// transitioning to the next request stage and this transition can happen in multiple places in this
10786// implementation.
10787
10788
10789function completeShell(request) {
10790 if (request.trackedPostpones === null) {
10791 // We only emit early preloads on shell completion for renders. For prerenders
10792 // we wait for the entire Request to finish because we are not responding to a
10793 // live request and can wait for as much data as possible.
10794 // we should only be calling completeShell when the shell is complete so we
10795 // just use a literal here
10796 var shellComplete = true;
10797 safelyEmitEarlyPreloads(request, shellComplete);
10798 } // We have completed the shell so the shell can't error anymore.
10799
10800
10801 request.onShellError = noop;
10802 var onShellReady = request.onShellReady;
10803 onShellReady();
10804} // I extracted this function out because we want to ensure we consistently emit preloads before
10805// transitioning to the next request stage and this transition can happen in multiple places in this
10806// implementation.
10807
10808
10809function completeAll(request) {
10810 // During a render the shell must be complete if the entire request is finished
10811 // however during a Prerender it is possible that the shell is incomplete because
10812 // it postponed. We cannot use rootPendingTasks in the prerender case because
10813 // those hit zero even when the shell postpones. Instead we look at the completedRootSegment
10814 var shellComplete = request.trackedPostpones === null ? // Render, we assume it is completed
10815 true : // Prerender Request, we use the state of the root segment
10816 request.completedRootSegment === null || request.completedRootSegment.status !== POSTPONED;
10817 safelyEmitEarlyPreloads(request, shellComplete);
10818 var onAllReady = request.onAllReady;
10819 onAllReady();
10820}
10821
10822function queueCompletedSegment(boundary, segment) {
10823 if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null && segment.children[0].id === -1) {
10824 // This is an empty segment. There's nothing to write, so we can instead transfer the ID
10825 // to the child. That way any existing references point to the child.
10826 var childSegment = segment.children[0];
10827 childSegment.id = segment.id;
10828 childSegment.parentFlushed = true;
10829
10830 if (childSegment.status === COMPLETED) {
10831 queueCompletedSegment(boundary, childSegment);
10832 }
10833 } else {
10834 var completedSegments = boundary.completedSegments;
10835 completedSegments.push(segment);
10836 }
10837}
10838
10839function finishedTask(request, boundary, segment) {
10840 if (boundary === null) {
10841 if (segment !== null && segment.parentFlushed) {
10842 if (request.completedRootSegment !== null) {
10843 throw new Error('There can only be one root segment. This is a bug in React.');
10844 }
10845
10846 request.completedRootSegment = segment;
10847 }
10848
10849 request.pendingRootTasks--;
10850
10851 if (request.pendingRootTasks === 0) {
10852 completeShell(request);
10853 }
10854 } else {
10855 boundary.pendingTasks--;
10856
10857 if (boundary.status === CLIENT_RENDERED) ; else if (boundary.pendingTasks === 0) {
10858 if (boundary.status === PENDING) {
10859 boundary.status = COMPLETED;
10860 } // This must have been the last segment we were waiting on. This boundary is now complete.
10861
10862
10863 if (segment !== null && segment.parentFlushed) {
10864 // Our parent segment already flushed, so we need to schedule this segment to be emitted.
10865 // If it is a segment that was aborted, we'll write other content instead so we don't need
10866 // to emit it.
10867 if (segment.status === COMPLETED) {
10868 queueCompletedSegment(boundary, segment);
10869 }
10870 }
10871
10872 if (boundary.parentFlushed) {
10873 // The segment might be part of a segment that didn't flush yet, but if the boundary's
10874 // parent flushed, we need to schedule the boundary to be emitted.
10875 request.completedBoundaries.push(boundary);
10876 } // We can now cancel any pending task on the fallback since we won't need to show it anymore.
10877 // This needs to happen after we read the parentFlushed flags because aborting can finish
10878 // work which can trigger user code, which can start flushing, which can change those flags.
10879 // If the boundary was POSTPONED, we still need to finish the fallback first.
10880
10881
10882 if (boundary.status === COMPLETED) {
10883 boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);
10884 boundary.fallbackAbortableTasks.clear();
10885 }
10886 } else {
10887 if (segment !== null && segment.parentFlushed) {
10888 // Our parent already flushed, so we need to schedule this segment to be emitted.
10889 // If it is a segment that was aborted, we'll write other content instead so we don't need
10890 // to emit it.
10891 if (segment.status === COMPLETED) {
10892 queueCompletedSegment(boundary, segment);
10893 var completedSegments = boundary.completedSegments;
10894
10895 if (completedSegments.length === 1) {
10896 // This is the first time since we last flushed that we completed anything.
10897 // We can schedule this boundary to emit its partially completed segments early
10898 // in case the parent has already been flushed.
10899 if (boundary.parentFlushed) {
10900 request.partialBoundaries.push(boundary);
10901 }
10902 }
10903 }
10904 }
10905 }
10906 }
10907
10908 request.allPendingTasks--;
10909
10910 if (request.allPendingTasks === 0) {
10911 completeAll(request);
10912 }
10913}
10914
10915function retryTask(request, task) {
10916 var segment = task.blockedSegment;
10917
10918 if (segment === null) {
10919 retryReplayTask(request, // $FlowFixMe: Refined.
10920 task);
10921 } else {
10922 retryRenderTask(request, // $FlowFixMe: Refined.
10923 task, segment);
10924 }
10925}
10926
10927function retryRenderTask(request, task, segment) {
10928 if (segment.status !== PENDING) {
10929 // We completed this by other means before we had a chance to retry it.
10930 return;
10931 } // We restore the context to what it was when we suspended.
10932 // We don't restore it after we leave because it's likely that we'll end up
10933 // needing a very similar context soon again.
10934
10935
10936 switchContext(task.context);
10937 var prevTaskInDEV = null;
10938
10939 {
10940 prevTaskInDEV = currentTaskInDEV;
10941 currentTaskInDEV = task;
10942 }
10943
10944 var childrenLength = segment.children.length;
10945 var chunkLength = segment.chunks.length;
10946
10947 try {
10948 // We call the destructive form that mutates this task. That way if something
10949 // suspends again, we can reuse the same task instead of spawning a new one.
10950 renderNodeDestructive(request, task, task.node, task.childIndex);
10951 pushSegmentFinale(segment.chunks, request.renderState, segment.lastPushedText, segment.textEmbedded);
10952 task.abortSet.delete(task);
10953 segment.status = COMPLETED;
10954 finishedTask(request, task.blockedBoundary, segment);
10955 } catch (thrownValue) {
10956 resetHooksState(); // Reset the write pointers to where we started.
10957
10958 segment.children.length = childrenLength;
10959 segment.chunks.length = chunkLength;
10960 var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
10961 // reasons, the rest of the Suspense implementation expects the thrown
10962 // value to be a thenable, because before `use` existed that was the
10963 // (unstable) API for suspending. This implementation detail can change
10964 // later, once we deprecate the old API in favor of `use`.
10965 getSuspendedThenable() : thrownValue;
10966
10967 if (typeof x === 'object' && x !== null) {
10968 // $FlowFixMe[method-unbinding]
10969 if (typeof x.then === 'function') {
10970 // Something suspended again, let's pick it back up later.
10971 var ping = task.ping;
10972 x.then(ping, ping);
10973 task.thenableState = getThenableStateAfterSuspending(); // We pop one task off the stack because the node that suspended will be tried again,
10974 // which will add it back onto the stack.
10975
10976 if (task.componentStack !== null) {
10977 task.componentStack = task.componentStack.parent;
10978 }
10979
10980 return;
10981 }
10982 }
10983
10984 var errorInfo = getThrownInfo(request, task.componentStack);
10985 task.abortSet.delete(task);
10986 segment.status = ERRORED;
10987 erroredTask(request, task.blockedBoundary, x, errorInfo);
10988 return;
10989 } finally {
10990 {
10991 currentTaskInDEV = prevTaskInDEV;
10992 }
10993 }
10994}
10995
10996function retryReplayTask(request, task) {
10997 if (task.replay.pendingTasks === 0) {
10998 // There are no pending tasks working on this set, so we must have aborted.
10999 return;
11000 } // We restore the context to what it was when we suspended.
11001 // We don't restore it after we leave because it's likely that we'll end up
11002 // needing a very similar context soon again.
11003
11004
11005 switchContext(task.context);
11006 var prevTaskInDEV = null;
11007
11008 {
11009 prevTaskInDEV = currentTaskInDEV;
11010 currentTaskInDEV = task;
11011 }
11012
11013 try {
11014 // We call the destructive form that mutates this task. That way if something
11015 // suspends again, we can reuse the same task instead of spawning a new one.
11016 renderNodeDestructive(request, task, task.node, task.childIndex);
11017
11018 if (task.replay.pendingTasks === 1 && task.replay.nodes.length > 0) {
11019 throw new Error("Couldn't find all resumable slots by key/index during replaying. " + "The tree doesn't match so React will fallback to client rendering.");
11020 }
11021
11022 task.replay.pendingTasks--;
11023 task.abortSet.delete(task);
11024 finishedTask(request, task.blockedBoundary, null);
11025 } catch (thrownValue) {
11026 resetHooksState();
11027 var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical
11028 // reasons, the rest of the Suspense implementation expects the thrown
11029 // value to be a thenable, because before `use` existed that was the
11030 // (unstable) API for suspending. This implementation detail can change
11031 // later, once we deprecate the old API in favor of `use`.
11032 getSuspendedThenable() : thrownValue;
11033
11034 if (typeof x === 'object' && x !== null) {
11035 // $FlowFixMe[method-unbinding]
11036 if (typeof x.then === 'function') {
11037 // Something suspended again, let's pick it back up later.
11038 var ping = task.ping;
11039 x.then(ping, ping);
11040 task.thenableState = getThenableStateAfterSuspending(); // We pop one task off the stack because the node that suspended will be tried again,
11041 // which will add it back onto the stack.
11042
11043 if (task.componentStack !== null) {
11044 task.componentStack = task.componentStack.parent;
11045 }
11046
11047 return;
11048 }
11049 }
11050
11051 task.replay.pendingTasks--;
11052 task.abortSet.delete(task);
11053 var errorInfo = getThrownInfo(request, task.componentStack);
11054 erroredReplay(request, task.blockedBoundary, x, errorInfo, task.replay.nodes, task.replay.slots);
11055 request.pendingRootTasks--;
11056
11057 if (request.pendingRootTasks === 0) {
11058 completeShell(request);
11059 }
11060
11061 request.allPendingTasks--;
11062
11063 if (request.allPendingTasks === 0) {
11064 completeAll(request);
11065 }
11066
11067 return;
11068 } finally {
11069 {
11070 currentTaskInDEV = prevTaskInDEV;
11071 }
11072 }
11073}
11074
11075function performWork(request) {
11076 if (request.status === CLOSED) {
11077 return;
11078 }
11079
11080 var prevContext = getActiveContext();
11081 var prevDispatcher = ReactSharedInternals.H;
11082 ReactSharedInternals.H = HooksDispatcher;
11083 var prevAsyncDispatcher = null;
11084
11085 {
11086 prevAsyncDispatcher = ReactSharedInternals.A;
11087 ReactSharedInternals.A = DefaultAsyncDispatcher;
11088 }
11089
11090 var prevRequest = currentRequest;
11091 currentRequest = request;
11092 var prevGetCurrentStackImpl = null;
11093
11094 {
11095 prevGetCurrentStackImpl = ReactSharedInternals.getCurrentStack;
11096 ReactSharedInternals.getCurrentStack = getCurrentStackInDEV;
11097 }
11098
11099 var prevResumableState = currentResumableState;
11100 setCurrentResumableState(request.resumableState);
11101
11102 try {
11103 var pingedTasks = request.pingedTasks;
11104 var i;
11105
11106 for (i = 0; i < pingedTasks.length; i++) {
11107 var task = pingedTasks[i];
11108 retryTask(request, task);
11109 }
11110
11111 pingedTasks.splice(0, i);
11112
11113 if (request.destination !== null) {
11114 flushCompletedQueues(request, request.destination);
11115 }
11116 } catch (error) {
11117 var errorInfo = {};
11118 logRecoverableError(request, error, errorInfo);
11119 fatalError(request, error);
11120 } finally {
11121 setCurrentResumableState(prevResumableState);
11122 ReactSharedInternals.H = prevDispatcher;
11123
11124 {
11125 ReactSharedInternals.A = prevAsyncDispatcher;
11126 }
11127
11128 {
11129 ReactSharedInternals.getCurrentStack = prevGetCurrentStackImpl;
11130 }
11131
11132 if (prevDispatcher === HooksDispatcher) {
11133 // This means that we were in a reentrant work loop. This could happen
11134 // in a renderer that supports synchronous work like renderToString,
11135 // when it's called from within another renderer.
11136 // Normally we don't bother switching the contexts to their root/default
11137 // values when leaving because we'll likely need the same or similar
11138 // context again. However, when we're inside a synchronous loop like this
11139 // we'll to restore the context to what it was before returning.
11140 switchContext(prevContext);
11141 }
11142
11143 currentRequest = prevRequest;
11144 }
11145}
11146
11147function flushPreamble(request, destination, rootSegment) {
11148 writePreamble(destination, request.resumableState, request.renderState);
11149}
11150
11151function flushSubtree(request, destination, segment, hoistableState) {
11152 segment.parentFlushed = true;
11153
11154 switch (segment.status) {
11155 case PENDING:
11156 {
11157 // We're emitting a placeholder for this segment to be filled in later.
11158 // Therefore we'll need to assign it an ID - to refer to it by.
11159 segment.id = request.nextSegmentId++; // Fallthrough
11160 }
11161
11162 case POSTPONED:
11163 {
11164 var segmentID = segment.id; // When this segment finally completes it won't be embedded in text since it will flush separately
11165
11166 segment.lastPushedText = false;
11167 segment.textEmbedded = false;
11168 return writePlaceholder(destination, request.renderState, segmentID);
11169 }
11170
11171 case COMPLETED:
11172 {
11173 segment.status = FLUSHED;
11174 var r = true;
11175 var chunks = segment.chunks;
11176 var chunkIdx = 0;
11177 var children = segment.children;
11178
11179 for (var childIdx = 0; childIdx < children.length; childIdx++) {
11180 var nextChild = children[childIdx]; // Write all the chunks up until the next child.
11181
11182 for (; chunkIdx < nextChild.index; chunkIdx++) {
11183 writeChunk(destination, chunks[chunkIdx]);
11184 }
11185
11186 r = flushSegment(request, destination, nextChild, hoistableState);
11187 } // Finally just write all the remaining chunks
11188
11189
11190 for (; chunkIdx < chunks.length - 1; chunkIdx++) {
11191 writeChunk(destination, chunks[chunkIdx]);
11192 }
11193
11194 if (chunkIdx < chunks.length) {
11195 r = writeChunkAndReturn(destination, chunks[chunkIdx]);
11196 }
11197
11198 return r;
11199 }
11200
11201 default:
11202 {
11203 throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');
11204 }
11205 }
11206}
11207
11208function flushSegment(request, destination, segment, hoistableState) {
11209 var boundary = segment.boundary;
11210
11211 if (boundary === null) {
11212 // Not a suspense boundary.
11213 return flushSubtree(request, destination, segment, hoistableState);
11214 }
11215
11216 boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to
11217 // emit the content or the fallback now.
11218
11219 if (boundary.status === CLIENT_RENDERED) {
11220 // Emit a client rendered suspense boundary wrapper.
11221 // We never queue the inner boundary so we'll never emit its content or partial segments.
11222 {
11223 writeStartClientRenderedSuspenseBoundary(destination, request.renderState, boundary.errorDigest, boundary.errorMessage, boundary.errorStack, boundary.errorComponentStack);
11224 } // Flush the fallback.
11225
11226
11227 flushSubtree(request, destination, segment, hoistableState);
11228 return writeEndClientRenderedSuspenseBoundary(destination);
11229 } else if (boundary.status !== COMPLETED) {
11230 if (boundary.status === PENDING) {
11231 // For pending boundaries we lazily assign an ID to the boundary
11232 // and root segment.
11233 boundary.rootSegmentID = request.nextSegmentId++;
11234 }
11235
11236 if (boundary.completedSegments.length > 0) {
11237 // If this is at least partially complete, we can queue it to be partially emitted early.
11238 request.partialBoundaries.push(boundary);
11239 } // This boundary is still loading. Emit a pending suspense boundary wrapper.
11240
11241
11242 var id = boundary.rootSegmentID;
11243 writeStartPendingSuspenseBoundary(destination, request.renderState, id);
11244
11245 if (hoistableState) {
11246 hoistHoistables(hoistableState, boundary.fallbackState);
11247 } // Flush the fallback.
11248
11249
11250 flushSubtree(request, destination, segment, hoistableState);
11251 return writeEndPendingSuspenseBoundary(destination);
11252 } else if (boundary.byteSize > request.progressiveChunkSize) {
11253 // This boundary is large and will be emitted separately so that we can progressively show
11254 // other content. We add it to the queue during the flush because we have to ensure that
11255 // the parent flushes first so that there's something to inject it into.
11256 // We also have to make sure that it's emitted into the queue in a deterministic slot.
11257 // I.e. we can't insert it here when it completes.
11258 // Assign an ID to refer to the future content by.
11259 boundary.rootSegmentID = request.nextSegmentId++;
11260 request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.
11261
11262 writeStartPendingSuspenseBoundary(destination, request.renderState, boundary.rootSegmentID); // While we are going to flush the fallback we are going to follow it up with
11263 // the completed boundary immediately so we make the choice to omit fallback
11264 // boundary state from the parent since it will be replaced when the boundary
11265 // flushes later in this pass or in a future flush
11266 // Flush the fallback.
11267
11268 flushSubtree(request, destination, segment, hoistableState);
11269 return writeEndPendingSuspenseBoundary(destination);
11270 } else {
11271 if (hoistableState) {
11272 hoistHoistables(hoistableState, boundary.contentState);
11273 } // We can inline this boundary's content as a complete boundary.
11274
11275
11276 writeStartCompletedSuspenseBoundary(destination);
11277 var completedSegments = boundary.completedSegments;
11278
11279 if (completedSegments.length !== 1) {
11280 throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');
11281 }
11282
11283 var contentSegment = completedSegments[0];
11284 flushSegment(request, destination, contentSegment, hoistableState);
11285 return writeEndCompletedSuspenseBoundary(destination);
11286 }
11287}
11288
11289function flushClientRenderedBoundary(request, destination, boundary) {
11290 {
11291 return writeClientRenderBoundaryInstruction(destination, request.resumableState, request.renderState, boundary.rootSegmentID, boundary.errorDigest, boundary.errorMessage, boundary.errorStack, boundary.errorComponentStack);
11292 }
11293}
11294
11295function flushSegmentContainer(request, destination, segment, hoistableState) {
11296 writeStartSegment(destination, request.renderState, segment.parentFormatContext, segment.id);
11297 flushSegment(request, destination, segment, hoistableState);
11298 return writeEndSegment(destination, segment.parentFormatContext);
11299}
11300
11301function flushCompletedBoundary(request, destination, boundary) {
11302 var completedSegments = boundary.completedSegments;
11303 var i = 0;
11304
11305 for (; i < completedSegments.length; i++) {
11306 var segment = completedSegments[i];
11307 flushPartiallyCompletedSegment(request, destination, boundary, segment);
11308 }
11309
11310 completedSegments.length = 0;
11311 writeHoistablesForBoundary(destination, boundary.contentState, request.renderState);
11312 return writeCompletedBoundaryInstruction(destination, request.resumableState, request.renderState, boundary.rootSegmentID, boundary.contentState);
11313}
11314
11315function flushPartialBoundary(request, destination, boundary) {
11316 var completedSegments = boundary.completedSegments;
11317 var i = 0;
11318
11319 for (; i < completedSegments.length; i++) {
11320 var segment = completedSegments[i];
11321
11322 if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {
11323 i++;
11324 completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority
11325 // might want to write later.
11326
11327 return false;
11328 }
11329 }
11330
11331 completedSegments.splice(0, i);
11332 return writeHoistablesForBoundary(destination, boundary.contentState, request.renderState);
11333}
11334
11335function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
11336 if (segment.status === FLUSHED) {
11337 // We've already flushed this inline.
11338 return true;
11339 }
11340
11341 var hoistableState = boundary.contentState;
11342 var segmentID = segment.id;
11343
11344 if (segmentID === -1) {
11345 // This segment wasn't previously referred to. This happens at the root of
11346 // a boundary. We make kind of a leap here and assume this is the root.
11347 var rootSegmentID = segment.id = boundary.rootSegmentID;
11348
11349 if (rootSegmentID === -1) {
11350 throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');
11351 }
11352
11353 return flushSegmentContainer(request, destination, segment, hoistableState);
11354 } else if (segmentID === boundary.rootSegmentID) {
11355 // When we emit postponed boundaries, we might have assigned the ID already
11356 // but it's still the root segment so we can't inject it into the parent yet.
11357 return flushSegmentContainer(request, destination, segment, hoistableState);
11358 } else {
11359 flushSegmentContainer(request, destination, segment, hoistableState);
11360 return writeCompletedSegmentInstruction(destination, request.resumableState, request.renderState, segmentID);
11361 }
11362}
11363
11364function flushCompletedQueues(request, destination) {
11365 beginWriting();
11366
11367 try {
11368 // The structure of this is to go through each queue one by one and write
11369 // until the sink tells us to stop. When we should stop, we still finish writing
11370 // that item fully and then yield. At that point we remove the already completed
11371 // items up until the point we completed them.
11372 if (request.pendingRootTasks > 0) {
11373 // When there are pending root tasks we don't want to flush anything
11374 return;
11375 }
11376
11377 var i;
11378 var completedRootSegment = request.completedRootSegment;
11379
11380 if (completedRootSegment !== null) {
11381 if (completedRootSegment.status === POSTPONED) {
11382 // We postponed the root, so we write nothing.
11383 return;
11384 }
11385
11386 flushPreamble(request, destination, completedRootSegment);
11387 flushSegment(request, destination, completedRootSegment, null);
11388 request.completedRootSegment = null;
11389 writeCompletedRoot(destination, request.renderState);
11390 }
11391
11392 writeHoistables(destination, request.resumableState, request.renderState); // We emit client rendering instructions for already emitted boundaries first.
11393 // This is so that we can signal to the client to start client rendering them as
11394 // soon as possible.
11395
11396 var clientRenderedBoundaries = request.clientRenderedBoundaries;
11397
11398 for (i = 0; i < clientRenderedBoundaries.length; i++) {
11399 var boundary = clientRenderedBoundaries[i];
11400
11401 if (!flushClientRenderedBoundary(request, destination, boundary)) {
11402 request.destination = null;
11403 i++;
11404 clientRenderedBoundaries.splice(0, i);
11405 return;
11406 }
11407 }
11408
11409 clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries
11410 // that are completely done since we can actually show them, than it is to emit
11411 // any individual segments from a partially complete boundary.
11412
11413 var completedBoundaries = request.completedBoundaries;
11414
11415 for (i = 0; i < completedBoundaries.length; i++) {
11416 var _boundary = completedBoundaries[i];
11417
11418 if (!flushCompletedBoundary(request, destination, _boundary)) {
11419 request.destination = null;
11420 i++;
11421 completedBoundaries.splice(0, i);
11422 return;
11423 }
11424 }
11425
11426 completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before
11427 // we continue with lower priorities.
11428
11429 completeWriting(destination);
11430 beginWriting(destination); // TODO: Here we'll emit data used by hydration.
11431 // Next we emit any segments of any boundaries that are partially complete
11432 // but not deeply complete.
11433
11434 var partialBoundaries = request.partialBoundaries;
11435
11436 for (i = 0; i < partialBoundaries.length; i++) {
11437 var _boundary2 = partialBoundaries[i];
11438
11439 if (!flushPartialBoundary(request, destination, _boundary2)) {
11440 request.destination = null;
11441 i++;
11442 partialBoundaries.splice(0, i);
11443 return;
11444 }
11445 }
11446
11447 partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had
11448 // boundaries added to it in case they were too larged to be inlined.
11449 // New ones might be added in this loop.
11450
11451 var largeBoundaries = request.completedBoundaries;
11452
11453 for (i = 0; i < largeBoundaries.length; i++) {
11454 var _boundary3 = largeBoundaries[i];
11455
11456 if (!flushCompletedBoundary(request, destination, _boundary3)) {
11457 request.destination = null;
11458 i++;
11459 largeBoundaries.splice(0, i);
11460 return;
11461 }
11462 }
11463
11464 largeBoundaries.splice(0, i);
11465 } finally {
11466 if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because
11467 // either they have pending task or they're complete.
11468 ) {
11469 request.flushScheduled = false; // We write the trailing tags but only if don't have any data to resume.
11470 // If we need to resume we'll write the postamble in the resume instead.
11471
11472 {
11473 writePostamble(destination, request.resumableState);
11474 }
11475
11476 completeWriting(destination);
11477
11478 {
11479 if (request.abortableTasks.size !== 0) {
11480 error('There was still abortable task at the root when we closed. This is a bug in React.');
11481 }
11482 } // We're done.
11483
11484
11485 close(destination); // We need to stop flowing now because we do not want any async contexts which might call
11486 // float methods to initiate any flushes after this point
11487
11488 stopFlowing(request);
11489 } else {
11490 completeWriting(destination);
11491 }
11492 }
11493}
11494
11495function startWork(request) {
11496 request.flushScheduled = request.destination !== null;
11497
11498 {
11499 scheduleWork(function () {
11500 return performWork(request);
11501 });
11502 }
11503
11504 if (request.trackedPostpones === null) {
11505 // this is either a regular render or a resume. For regular render we want
11506 // to call emitEarlyPreloads after the first performWork because we want
11507 // are responding to a live request and need to balance sending something early
11508 // (i.e. don't want for the shell to finish) but we need something to send.
11509 // The only implementation of this is for DOM at the moment and during resumes nothing
11510 // actually emits but the code paths here are the same.
11511 // During a prerender we don't want to be too aggressive in emitting early preloads
11512 // because we aren't responding to a live request and we can wait for the prerender to
11513 // postpone before we emit anything.
11514 {
11515 scheduleWork(function () {
11516 return enqueueEarlyPreloadsAfterInitialWork(request);
11517 });
11518 }
11519 }
11520}
11521
11522function enqueueEarlyPreloadsAfterInitialWork(request) {
11523 var shellComplete = request.pendingRootTasks === 0;
11524 safelyEmitEarlyPreloads(request, shellComplete);
11525}
11526
11527function enqueueFlush(request) {
11528 if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes
11529 request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will
11530 // happen when we start flowing again
11531 request.destination !== null) {
11532 request.flushScheduled = true;
11533 scheduleWork(function () {
11534 // We need to existence check destination again here because it might go away
11535 // in between the enqueueFlush call and the work execution
11536 var destination = request.destination;
11537
11538 if (destination) {
11539 flushCompletedQueues(request, destination);
11540 } else {
11541 request.flushScheduled = false;
11542 }
11543 });
11544 }
11545} // This function is intented to only be called during the pipe function for the Node builds.
11546function startFlowing(request, destination) {
11547 if (request.status === CLOSING) {
11548 request.status = CLOSED;
11549 closeWithError(destination, request.fatalError);
11550 return;
11551 }
11552
11553 if (request.status === CLOSED) {
11554 return;
11555 }
11556
11557 if (request.destination !== null) {
11558 // We're already flowing.
11559 return;
11560 }
11561
11562 request.destination = destination;
11563
11564 try {
11565 flushCompletedQueues(request, destination);
11566 } catch (error) {
11567 var errorInfo = {};
11568 logRecoverableError(request, error, errorInfo);
11569 fatalError(request, error);
11570 }
11571}
11572function stopFlowing(request) {
11573 request.destination = null;
11574} // This is called to early terminate a request. It puts all pending boundaries in client rendered state.
11575
11576function abort(request, reason) {
11577 try {
11578 var abortableTasks = request.abortableTasks;
11579
11580 if (abortableTasks.size > 0) {
11581 var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
11582 abortableTasks.forEach(function (task) {
11583 return abortTask(task, request, error);
11584 });
11585 abortableTasks.clear();
11586 }
11587
11588 if (request.destination !== null) {
11589 flushCompletedQueues(request, request.destination);
11590 }
11591 } catch (error) {
11592 var errorInfo = {};
11593 logRecoverableError(request, error, errorInfo);
11594 fatalError(request, error);
11595 }
11596}
11597function flushResources(request) {
11598 enqueueFlush(request);
11599}
11600function getFormState(request) {
11601 return request.formState;
11602}
11603function getResumableState(request) {
11604 return request.resumableState;
11605}
11606function getRenderState(request) {
11607 return request.renderState;
11608}
11609
11610function renderToReadableStream(children, options) {
11611 return new Promise(function (resolve, reject) {
11612 var onFatalError;
11613 var onAllReady;
11614 var allReady = new Promise(function (res, rej) {
11615 onAllReady = res;
11616 onFatalError = rej;
11617 });
11618
11619 function onShellReady() {
11620 var stream = new ReadableStream({
11621 type: 'bytes',
11622 pull: function (controller) {
11623 startFlowing(request, controller);
11624 },
11625 cancel: function (reason) {
11626 stopFlowing(request);
11627 abort(request, reason);
11628 }
11629 }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams.
11630 {
11631 highWaterMark: 0
11632 }); // TODO: Move to sub-classing ReadableStream.
11633
11634 stream.allReady = allReady;
11635 resolve(stream);
11636 }
11637
11638 function onShellError(error) {
11639 // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`.
11640 // However, `allReady` will be rejected by `onFatalError` as well.
11641 // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`.
11642 allReady.catch(function () {});
11643 reject(error);
11644 }
11645
11646 var onHeaders = options ? options.onHeaders : undefined;
11647 var onHeadersImpl;
11648
11649 if (onHeaders) {
11650 onHeadersImpl = function (headersDescriptor) {
11651 onHeaders(new Headers(headersDescriptor));
11652 };
11653 }
11654
11655 var resumableState = createResumableState(options ? options.identifierPrefix : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.bootstrapScriptContent : undefined, options ? options.bootstrapScripts : undefined, options ? options.bootstrapModules : undefined);
11656 var request = createRequest(children, resumableState, createRenderState(resumableState, options ? options.nonce : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.importMap : undefined, onHeadersImpl, options ? options.maxHeadersLength : undefined), createRootFormatContext(options ? options.namespaceURI : undefined), options ? options.progressiveChunkSize : undefined, options ? options.onError : undefined, onAllReady, onShellReady, onShellError, onFatalError, options ? options.onPostpone : undefined, options ? options.formState : undefined);
11657
11658 if (options && options.signal) {
11659 var signal = options.signal;
11660
11661 if (signal.aborted) {
11662 abort(request, signal.reason);
11663 } else {
11664 var listener = function () {
11665 abort(request, signal.reason);
11666 signal.removeEventListener('abort', listener);
11667 };
11668
11669 signal.addEventListener('abort', listener);
11670 }
11671 }
11672
11673 startWork(request);
11674 });
11675}
11676
11677exports.renderToReadableStream = renderToReadableStream;
11678exports.version = ReactVersion;
11679 })();
11680}