UNPKG

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