react-server-dom-webpack-writer.browser.development.server.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084
  1. /**
  2. * @license React
  3. * react-server-dom-webpack-writer.browser.development.server.js
  4. *
  5. * Copyright (c) Facebook, Inc. and its 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. 'use strict';
  11. if (process.env.NODE_ENV !== "production") {
  12. (function() {
  13. 'use strict';
  14. var React = require('react');
  15. var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  16. function error(format) {
  17. {
  18. {
  19. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  20. args[_key2 - 1] = arguments[_key2];
  21. }
  22. printWarning('error', format, args);
  23. }
  24. }
  25. }
  26. function printWarning(level, format, args) {
  27. // When changing this logic, you might want to also
  28. // update consoleWithStackDev.www.js as well.
  29. {
  30. var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
  31. var stack = ReactDebugCurrentFrame.getStackAddendum();
  32. if (stack !== '') {
  33. format += '%s';
  34. args = args.concat([stack]);
  35. } // eslint-disable-next-line react-internal/safe-string-coercion
  36. var argsWithFormat = args.map(function (item) {
  37. return String(item);
  38. }); // Careful: RN currently depends on this prefix
  39. argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
  40. // breaks IE9: https://github.com/facebook/react/issues/13610
  41. // eslint-disable-next-line react-internal/no-production-logging
  42. Function.prototype.apply.call(console[level], console, argsWithFormat);
  43. }
  44. }
  45. function scheduleWork(callback) {
  46. callback();
  47. }
  48. var VIEW_SIZE = 512;
  49. var currentView = null;
  50. var writtenBytes = 0;
  51. function beginWriting(destination) {
  52. currentView = new Uint8Array(VIEW_SIZE);
  53. writtenBytes = 0;
  54. }
  55. function writeChunk(destination, chunk) {
  56. if (chunk.length === 0) {
  57. return;
  58. }
  59. if (chunk.length > VIEW_SIZE) {
  60. // this chunk may overflow a single view which implies it was not
  61. // one that is cached by the streaming renderer. We will enqueu
  62. // it directly and expect it is not re-used
  63. if (writtenBytes > 0) {
  64. destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
  65. currentView = new Uint8Array(VIEW_SIZE);
  66. writtenBytes = 0;
  67. }
  68. destination.enqueue(chunk);
  69. return;
  70. }
  71. var bytesToWrite = chunk;
  72. var allowableBytes = currentView.length - writtenBytes;
  73. if (allowableBytes < bytesToWrite.length) {
  74. // this chunk would overflow the current view. We enqueue a full view
  75. // and start a new view with the remaining chunk
  76. if (allowableBytes === 0) {
  77. // the current view is already full, send it
  78. destination.enqueue(currentView);
  79. } else {
  80. // fill up the current view and apply the remaining chunk bytes
  81. // to a new view.
  82. currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view
  83. destination.enqueue(currentView);
  84. bytesToWrite = bytesToWrite.subarray(allowableBytes);
  85. }
  86. currentView = new Uint8Array(VIEW_SIZE);
  87. writtenBytes = 0;
  88. }
  89. currentView.set(bytesToWrite, writtenBytes);
  90. writtenBytes += bytesToWrite.length;
  91. }
  92. function writeChunkAndReturn(destination, chunk) {
  93. writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more
  94. return true;
  95. }
  96. function completeWriting(destination) {
  97. if (currentView && writtenBytes > 0) {
  98. destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
  99. currentView = null;
  100. writtenBytes = 0;
  101. }
  102. }
  103. function close(destination) {
  104. destination.close();
  105. }
  106. var textEncoder = new TextEncoder();
  107. function stringToChunk(content) {
  108. return textEncoder.encode(content);
  109. }
  110. function stringToPrecomputedChunk(content) {
  111. return textEncoder.encode(content);
  112. }
  113. function closeWithError(destination, error) {
  114. if (typeof destination.error === 'function') {
  115. // $FlowFixMe: This is an Error object or the destination accepts other types.
  116. destination.error(error);
  117. } else {
  118. // Earlier implementations doesn't support this method. In that environment you're
  119. // supposed to throw from a promise returned but we don't return a promise in our
  120. // approach. We could fork this implementation but this is environment is an edge
  121. // case to begin with. It's even less common to run this in an older environment.
  122. // Even then, this is not where errors are supposed to happen and they get reported
  123. // to a global callback in addition to this anyway. So it's fine just to close this.
  124. destination.close();
  125. }
  126. }
  127. // This file is an intermediate layer to translate between Flight
  128. var stringify = JSON.stringify;
  129. function serializeRowHeader(tag, id) {
  130. return tag + id.toString(16) + ':';
  131. }
  132. function processErrorChunk(request, id, message, stack) {
  133. var errorInfo = {
  134. message: message,
  135. stack: stack
  136. };
  137. var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n';
  138. return stringToChunk(row);
  139. }
  140. function processModelChunk(request, id, model) {
  141. // $FlowFixMe: `json` might be `undefined` when model is a symbol.
  142. var json = stringify(model, request.toJSON);
  143. var row = serializeRowHeader('J', id) + json + '\n';
  144. return stringToChunk(row);
  145. }
  146. function processReferenceChunk(request, id, reference) {
  147. var json = stringify(reference);
  148. var row = serializeRowHeader('J', id) + json + '\n';
  149. return stringToChunk(row);
  150. }
  151. function processModuleChunk(request, id, moduleMetaData) {
  152. // $FlowFixMe: `json` might be `undefined` when moduleMetaData is a symbol.
  153. var json = stringify(moduleMetaData);
  154. var row = serializeRowHeader('M', id) + json + '\n';
  155. return stringToChunk(row);
  156. }
  157. function processProviderChunk(request, id, contextName) {
  158. var row = serializeRowHeader('P', id) + contextName + '\n';
  159. return stringToChunk(row);
  160. }
  161. function processSymbolChunk(request, id, name) {
  162. var json = stringify(name);
  163. var row = serializeRowHeader('S', id) + json + '\n';
  164. return stringToChunk(row);
  165. }
  166. // eslint-disable-next-line no-unused-vars
  167. var MODULE_TAG = Symbol.for('react.module.reference');
  168. function getModuleKey(reference) {
  169. return reference.filepath + '#' + reference.name + (reference.async ? '#async' : '');
  170. }
  171. function isModuleReference(reference) {
  172. return reference.$$typeof === MODULE_TAG;
  173. }
  174. function resolveModuleMetaData(config, moduleReference) {
  175. var resolvedModuleData = config[moduleReference.filepath][moduleReference.name];
  176. if (moduleReference.async) {
  177. return {
  178. id: resolvedModuleData.id,
  179. chunks: resolvedModuleData.chunks,
  180. name: resolvedModuleData.name,
  181. async: true
  182. };
  183. } else {
  184. return resolvedModuleData;
  185. }
  186. }
  187. // ATTENTION
  188. // When adding new symbols to this file,
  189. // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
  190. // The Symbol used to tag the ReactElement-like types.
  191. var REACT_ELEMENT_TYPE = Symbol.for('react.element');
  192. var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
  193. var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
  194. var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context');
  195. var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
  196. var REACT_MEMO_TYPE = Symbol.for('react.memo');
  197. var REACT_LAZY_TYPE = Symbol.for('react.lazy');
  198. var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
  199. // A reserved attribute.
  200. // It is handled by React separately and shouldn't be written to the DOM.
  201. var RESERVED = 0; // A simple string attribute.
  202. // Attributes that aren't in the filter are presumed to have this type.
  203. var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
  204. // "enumerated" attributes with "true" and "false" as possible values.
  205. // When true, it should be set to a "true" string.
  206. // When false, it should be set to a "false" string.
  207. var BOOLEANISH_STRING = 2; // A real boolean attribute.
  208. // When true, it should be present (set either to an empty string or its name).
  209. // When false, it should be omitted.
  210. var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
  211. // When true, it should be present (set either to an empty string or its name).
  212. // When false, it should be omitted.
  213. // For any other value, should be present with that value.
  214. var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
  215. // When falsy, it should be removed.
  216. var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
  217. // When falsy, it should be removed.
  218. var POSITIVE_NUMERIC = 6;
  219. function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
  220. this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
  221. this.attributeName = attributeName;
  222. this.attributeNamespace = attributeNamespace;
  223. this.mustUseProperty = mustUseProperty;
  224. this.propertyName = name;
  225. this.type = type;
  226. this.sanitizeURL = sanitizeURL;
  227. this.removeEmptyString = removeEmptyString;
  228. } // When adding attributes to this list, be sure to also add them to
  229. // the `possibleStandardNames` module to ensure casing and incorrect
  230. // name warnings.
  231. var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.
  232. var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
  233. // elements (not just inputs). Now that ReactDOMInput assigns to the
  234. // defaultValue property -- do we need this?
  235. 'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];
  236. {
  237. reservedProps.push('innerText', 'textContent');
  238. }
  239. reservedProps.forEach(function (name) {
  240. properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
  241. name, // attributeName
  242. null, // attributeNamespace
  243. false, // sanitizeURL
  244. false);
  245. }); // A few React string attributes have a different name.
  246. // This is a mapping from React prop names to the attribute names.
  247. [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
  248. var name = _ref[0],
  249. attributeName = _ref[1];
  250. properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  251. attributeName, // attributeName
  252. null, // attributeNamespace
  253. false, // sanitizeURL
  254. false);
  255. }); // These are "enumerated" HTML attributes that accept "true" and "false".
  256. // In React, we let users pass `true` and `false` even though technically
  257. // these aren't boolean attributes (they are coerced to strings).
  258. ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
  259. properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  260. name.toLowerCase(), // attributeName
  261. null, // attributeNamespace
  262. false, // sanitizeURL
  263. false);
  264. }); // These are "enumerated" SVG attributes that accept "true" and "false".
  265. // In React, we let users pass `true` and `false` even though technically
  266. // these aren't boolean attributes (they are coerced to strings).
  267. // Since these are SVG attributes, their attribute names are case-sensitive.
  268. ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
  269. properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
  270. name, // attributeName
  271. null, // attributeNamespace
  272. false, // sanitizeURL
  273. false);
  274. }); // These are HTML boolean attributes.
  275. ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
  276. // on the client side because the browsers are inconsistent. Instead we call focus().
  277. 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
  278. 'itemScope'].forEach(function (name) {
  279. properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
  280. name.toLowerCase(), // attributeName
  281. null, // attributeNamespace
  282. false, // sanitizeURL
  283. false);
  284. }); // These are the few React props that we set as DOM properties
  285. // rather than attributes. These are all booleans.
  286. ['checked', // Note: `option.selected` is not updated if `select.multiple` is
  287. // disabled with `removeAttribute`. We have special logic for handling this.
  288. 'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
  289. // you'll need to set attributeName to name.toLowerCase()
  290. // instead in the assignment below.
  291. ].forEach(function (name) {
  292. properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
  293. name, // attributeName
  294. null, // attributeNamespace
  295. false, // sanitizeURL
  296. false);
  297. }); // These are HTML attributes that are "overloaded booleans": they behave like
  298. // booleans, but can also accept a string value.
  299. ['capture', 'download' // NOTE: if you add a camelCased prop to this list,
  300. // you'll need to set attributeName to name.toLowerCase()
  301. // instead in the assignment below.
  302. ].forEach(function (name) {
  303. properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
  304. name, // attributeName
  305. null, // attributeNamespace
  306. false, // sanitizeURL
  307. false);
  308. }); // These are HTML attributes that must be positive numbers.
  309. ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
  310. // you'll need to set attributeName to name.toLowerCase()
  311. // instead in the assignment below.
  312. ].forEach(function (name) {
  313. properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
  314. name, // attributeName
  315. null, // attributeNamespace
  316. false, // sanitizeURL
  317. false);
  318. }); // These are HTML attributes that must be numbers.
  319. ['rowSpan', 'start'].forEach(function (name) {
  320. properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
  321. name.toLowerCase(), // attributeName
  322. null, // attributeNamespace
  323. false, // sanitizeURL
  324. false);
  325. });
  326. var CAMELIZE = /[\-\:]([a-z])/g;
  327. var capitalize = function (token) {
  328. return token[1].toUpperCase();
  329. }; // This is a list of all SVG attributes that need special casing, namespacing,
  330. // or boolean value assignment. Regular attributes that just accept strings
  331. // and have the same names are omitted, just like in the HTML attribute filter.
  332. // Some of these attributes can be hard to find. This list was created by
  333. // scraping the MDN documentation.
  334. ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
  335. // you'll need to set attributeName to name.toLowerCase()
  336. // instead in the assignment below.
  337. ].forEach(function (attributeName) {
  338. var name = attributeName.replace(CAMELIZE, capitalize);
  339. properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  340. attributeName, null, // attributeNamespace
  341. false, // sanitizeURL
  342. false);
  343. }); // String SVG attributes with the xlink namespace.
  344. ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
  345. // you'll need to set attributeName to name.toLowerCase()
  346. // instead in the assignment below.
  347. ].forEach(function (attributeName) {
  348. var name = attributeName.replace(CAMELIZE, capitalize);
  349. properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  350. attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
  351. false);
  352. }); // String SVG attributes with the xml namespace.
  353. ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
  354. // you'll need to set attributeName to name.toLowerCase()
  355. // instead in the assignment below.
  356. ].forEach(function (attributeName) {
  357. var name = attributeName.replace(CAMELIZE, capitalize);
  358. properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
  359. attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
  360. false);
  361. }); // These attribute exists both in HTML and SVG.
  362. // The attribute name is case-sensitive in SVG so we can't just use
  363. // the React name like we do for attributes that exist only in HTML.
  364. ['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
  365. properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  366. attributeName.toLowerCase(), // attributeName
  367. null, // attributeNamespace
  368. false, // sanitizeURL
  369. false);
  370. }); // These attributes accept URLs. These must not allow javascript: URLS.
  371. // These will also need to accept Trusted Types object in the future.
  372. var xlinkHref = 'xlinkHref';
  373. properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
  374. 'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
  375. false);
  376. ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
  377. properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
  378. attributeName.toLowerCase(), // attributeName
  379. null, // attributeNamespace
  380. true, // sanitizeURL
  381. true);
  382. });
  383. /**
  384. * CSS properties which accept numbers but are not in units of "px".
  385. */
  386. var isUnitlessNumber = {
  387. animationIterationCount: true,
  388. aspectRatio: true,
  389. borderImageOutset: true,
  390. borderImageSlice: true,
  391. borderImageWidth: true,
  392. boxFlex: true,
  393. boxFlexGroup: true,
  394. boxOrdinalGroup: true,
  395. columnCount: true,
  396. columns: true,
  397. flex: true,
  398. flexGrow: true,
  399. flexPositive: true,
  400. flexShrink: true,
  401. flexNegative: true,
  402. flexOrder: true,
  403. gridArea: true,
  404. gridRow: true,
  405. gridRowEnd: true,
  406. gridRowSpan: true,
  407. gridRowStart: true,
  408. gridColumn: true,
  409. gridColumnEnd: true,
  410. gridColumnSpan: true,
  411. gridColumnStart: true,
  412. fontWeight: true,
  413. lineClamp: true,
  414. lineHeight: true,
  415. opacity: true,
  416. order: true,
  417. orphans: true,
  418. tabSize: true,
  419. widows: true,
  420. zIndex: true,
  421. zoom: true,
  422. // SVG-related properties
  423. fillOpacity: true,
  424. floodOpacity: true,
  425. stopOpacity: true,
  426. strokeDasharray: true,
  427. strokeDashoffset: true,
  428. strokeMiterlimit: true,
  429. strokeOpacity: true,
  430. strokeWidth: true
  431. };
  432. /**
  433. * @param {string} prefix vendor-specific prefix, eg: Webkit
  434. * @param {string} key style name, eg: transitionDuration
  435. * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
  436. * WebkitTransitionDuration
  437. */
  438. function prefixKey(prefix, key) {
  439. return prefix + key.charAt(0).toUpperCase() + key.substring(1);
  440. }
  441. /**
  442. * Support style names that may come passed in prefixed by adding permutations
  443. * of vendor prefixes.
  444. */
  445. var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
  446. // infinite loop, because it iterates over the newly added props too.
  447. Object.keys(isUnitlessNumber).forEach(function (prop) {
  448. prefixes.forEach(function (prefix) {
  449. isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
  450. });
  451. });
  452. var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
  453. function isArray(a) {
  454. return isArrayImpl(a);
  455. }
  456. var startInlineScript = stringToPrecomputedChunk('<script>');
  457. var endInlineScript = stringToPrecomputedChunk('</script>');
  458. var startScriptSrc = stringToPrecomputedChunk('<script src="');
  459. var startModuleSrc = stringToPrecomputedChunk('<script type="module" src="');
  460. var scriptIntegirty = stringToPrecomputedChunk('" integrity="');
  461. var endAsyncScript = stringToPrecomputedChunk('" async=""></script>');
  462. var textSeparator = stringToPrecomputedChunk('<!-- -->');
  463. var styleAttributeStart = stringToPrecomputedChunk(' style="');
  464. var styleAssign = stringToPrecomputedChunk(':');
  465. var styleSeparator = stringToPrecomputedChunk(';');
  466. var attributeSeparator = stringToPrecomputedChunk(' ');
  467. var attributeAssign = stringToPrecomputedChunk('="');
  468. var attributeEnd = stringToPrecomputedChunk('"');
  469. var attributeEmptyString = stringToPrecomputedChunk('=""');
  470. var endOfStartTag = stringToPrecomputedChunk('>');
  471. var endOfStartTagSelfClosing = stringToPrecomputedChunk('/>');
  472. var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""');
  473. var leadingNewline = stringToPrecomputedChunk('\n');
  474. var DOCTYPE = stringToPrecomputedChunk('<!DOCTYPE html>');
  475. var endTag1 = stringToPrecomputedChunk('</');
  476. var endTag2 = stringToPrecomputedChunk('>');
  477. // A placeholder is a node inside a hidden partial tree that can be filled in later, but before
  478. // display. It's never visible to users. We use the template tag because it can be used in every
  479. // type of parent. <script> tags also work in every other tag except <colgroup>.
  480. var placeholder1 = stringToPrecomputedChunk('<template id="');
  481. var placeholder2 = stringToPrecomputedChunk('"></template>');
  482. var startCompletedSuspenseBoundary = stringToPrecomputedChunk('<!--$-->');
  483. var startPendingSuspenseBoundary1 = stringToPrecomputedChunk('<!--$?--><template id="');
  484. var startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>');
  485. var startClientRenderedSuspenseBoundary = stringToPrecomputedChunk('<!--$!-->');
  486. var endSuspenseBoundary = stringToPrecomputedChunk('<!--/$-->');
  487. var clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk('<template');
  488. var clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"');
  489. var clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="');
  490. var clientRenderedSuspenseBoundaryError1B = stringToPrecomputedChunk(' data-msg="');
  491. var clientRenderedSuspenseBoundaryError1C = stringToPrecomputedChunk(' data-stck="');
  492. var clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk('></template>');
  493. var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="');
  494. var startSegmentHTML2 = stringToPrecomputedChunk('">');
  495. var endSegmentHTML = stringToPrecomputedChunk('</div>');
  496. var startSegmentSVG = stringToPrecomputedChunk('<svg aria-hidden="true" style="display:none" id="');
  497. var startSegmentSVG2 = stringToPrecomputedChunk('">');
  498. var endSegmentSVG = stringToPrecomputedChunk('</svg>');
  499. var startSegmentMathML = stringToPrecomputedChunk('<math aria-hidden="true" style="display:none" id="');
  500. var startSegmentMathML2 = stringToPrecomputedChunk('">');
  501. var endSegmentMathML = stringToPrecomputedChunk('</math>');
  502. var startSegmentTable = stringToPrecomputedChunk('<table hidden id="');
  503. var startSegmentTable2 = stringToPrecomputedChunk('">');
  504. var endSegmentTable = stringToPrecomputedChunk('</table>');
  505. var startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="');
  506. var startSegmentTableBody2 = stringToPrecomputedChunk('">');
  507. var endSegmentTableBody = stringToPrecomputedChunk('</tbody></table>');
  508. var startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="');
  509. var startSegmentTableRow2 = stringToPrecomputedChunk('">');
  510. var endSegmentTableRow = stringToPrecomputedChunk('</tr></table>');
  511. var startSegmentColGroup = stringToPrecomputedChunk('<table hidden><colgroup id="');
  512. var startSegmentColGroup2 = stringToPrecomputedChunk('">');
  513. var endSegmentColGroup = stringToPrecomputedChunk('</colgroup></table>');
  514. // The following code is the source scripts that we then minify and inline below,
  515. // with renamed function names that we hope don't collide:
  516. // const COMMENT_NODE = 8;
  517. // const SUSPENSE_START_DATA = '$';
  518. // const SUSPENSE_END_DATA = '/$';
  519. // const SUSPENSE_PENDING_START_DATA = '$?';
  520. // const SUSPENSE_FALLBACK_START_DATA = '$!';
  521. //
  522. // function clientRenderBoundary(suspenseBoundaryID, errorDigest, errorMsg, errorComponentStack) {
  523. // // Find the fallback's first element.
  524. // const suspenseIdNode = document.getElementById(suspenseBoundaryID);
  525. // if (!suspenseIdNode) {
  526. // // The user must have already navigated away from this tree.
  527. // // E.g. because the parent was hydrated.
  528. // return;
  529. // }
  530. // // Find the boundary around the fallback. This is always the previous node.
  531. // const suspenseNode = suspenseIdNode.previousSibling;
  532. // // Tag it to be client rendered.
  533. // suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
  534. // // assign error metadata to first sibling
  535. // let dataset = suspenseIdNode.dataset;
  536. // if (errorDigest) dataset.dgst = errorDigest;
  537. // if (errorMsg) dataset.msg = errorMsg;
  538. // if (errorComponentStack) dataset.stck = errorComponentStack;
  539. // // Tell React to retry it if the parent already hydrated.
  540. // if (suspenseNode._reactRetry) {
  541. // suspenseNode._reactRetry();
  542. // }
  543. // }
  544. //
  545. // function completeBoundary(suspenseBoundaryID, contentID) {
  546. // // Find the fallback's first element.
  547. // const suspenseIdNode = document.getElementById(suspenseBoundaryID);
  548. // const contentNode = document.getElementById(contentID);
  549. // // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
  550. // // This might also help by not causing recalcing each time we move a child from here to the target.
  551. // contentNode.parentNode.removeChild(contentNode);
  552. // if (!suspenseIdNode) {
  553. // // The user must have already navigated away from this tree.
  554. // // E.g. because the parent was hydrated. That's fine there's nothing to do
  555. // // but we have to make sure that we already deleted the container node.
  556. // return;
  557. // }
  558. // // Find the boundary around the fallback. This is always the previous node.
  559. // const suspenseNode = suspenseIdNode.previousSibling;
  560. //
  561. // // Clear all the existing children. This is complicated because
  562. // // there can be embedded Suspense boundaries in the fallback.
  563. // // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
  564. // // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
  565. // // They never hydrate anyway. However, currently we support incrementally loading the fallback.
  566. // const parentInstance = suspenseNode.parentNode;
  567. // let node = suspenseNode.nextSibling;
  568. // let depth = 0;
  569. // do {
  570. // if (node && node.nodeType === COMMENT_NODE) {
  571. // const data = node.data;
  572. // if (data === SUSPENSE_END_DATA) {
  573. // if (depth === 0) {
  574. // break;
  575. // } else {
  576. // depth--;
  577. // }
  578. // } else if (
  579. // data === SUSPENSE_START_DATA ||
  580. // data === SUSPENSE_PENDING_START_DATA ||
  581. // data === SUSPENSE_FALLBACK_START_DATA
  582. // ) {
  583. // depth++;
  584. // }
  585. // }
  586. //
  587. // const nextNode = node.nextSibling;
  588. // parentInstance.removeChild(node);
  589. // node = nextNode;
  590. // } while (node);
  591. //
  592. // const endOfBoundary = node;
  593. //
  594. // // Insert all the children from the contentNode between the start and end of suspense boundary.
  595. // while (contentNode.firstChild) {
  596. // parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
  597. // }
  598. // suspenseNode.data = SUSPENSE_START_DATA;
  599. // if (suspenseNode._reactRetry) {
  600. // suspenseNode._reactRetry();
  601. // }
  602. // }
  603. //
  604. // function completeSegment(containerID, placeholderID) {
  605. // const segmentContainer = document.getElementById(containerID);
  606. // const placeholderNode = document.getElementById(placeholderID);
  607. // // We always expect both nodes to exist here because, while we might
  608. // // have navigated away from the main tree, we still expect the detached
  609. // // tree to exist.
  610. // segmentContainer.parentNode.removeChild(segmentContainer);
  611. // while (segmentContainer.firstChild) {
  612. // placeholderNode.parentNode.insertBefore(
  613. // segmentContainer.firstChild,
  614. // placeholderNode,
  615. // );
  616. // }
  617. // placeholderNode.parentNode.removeChild(placeholderNode);
  618. // }
  619. var completeSegmentFunction = 'function $RS(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)}';
  620. var completeBoundaryFunction = 'function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}}';
  621. var clientRenderFunction = 'function $RX(b,c,d,e){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),b._reactRetry&&b._reactRetry())}';
  622. var completeSegmentScript1Full = stringToPrecomputedChunk(completeSegmentFunction + ';$RS("');
  623. var completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("');
  624. var completeSegmentScript2 = stringToPrecomputedChunk('","');
  625. var completeSegmentScript3 = stringToPrecomputedChunk('")</script>');
  626. var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("');
  627. var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
  628. var completeBoundaryScript2 = stringToPrecomputedChunk('","');
  629. var completeBoundaryScript3 = stringToPrecomputedChunk('")</script>');
  630. var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("');
  631. var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("');
  632. var clientRenderScript1A = stringToPrecomputedChunk('"');
  633. var clientRenderScript2 = stringToPrecomputedChunk(')</script>');
  634. var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');
  635. var rendererSigil;
  636. {
  637. // Use this to detect multiple renderers using the same context
  638. rendererSigil = {};
  639. } // Used to store the parent path of all context overrides in a shared linked list.
  640. // Forming a reverse tree.
  641. var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
  642. // This global (actually thread local) state represents what state all those "current",
  643. // fields are currently in.
  644. var currentActiveSnapshot = null;
  645. function popNode(prev) {
  646. {
  647. prev.context._currentValue = prev.parentValue;
  648. }
  649. }
  650. function pushNode(next) {
  651. {
  652. next.context._currentValue = next.value;
  653. }
  654. }
  655. function popToNearestCommonAncestor(prev, next) {
  656. if (prev === next) ; else {
  657. popNode(prev);
  658. var parentPrev = prev.parent;
  659. var parentNext = next.parent;
  660. if (parentPrev === null) {
  661. if (parentNext !== null) {
  662. throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
  663. }
  664. } else {
  665. if (parentNext === null) {
  666. throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
  667. }
  668. popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common.
  669. pushNode(next);
  670. }
  671. }
  672. }
  673. function popAllPrevious(prev) {
  674. popNode(prev);
  675. var parentPrev = prev.parent;
  676. if (parentPrev !== null) {
  677. popAllPrevious(parentPrev);
  678. }
  679. }
  680. function pushAllNext(next) {
  681. var parentNext = next.parent;
  682. if (parentNext !== null) {
  683. pushAllNext(parentNext);
  684. }
  685. pushNode(next);
  686. }
  687. function popPreviousToCommonLevel(prev, next) {
  688. popNode(prev);
  689. var parentPrev = prev.parent;
  690. if (parentPrev === null) {
  691. throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  692. }
  693. if (parentPrev.depth === next.depth) {
  694. // We found the same level. Now we just need to find a shared ancestor.
  695. popToNearestCommonAncestor(parentPrev, next);
  696. } else {
  697. // We must still be deeper.
  698. popPreviousToCommonLevel(parentPrev, next);
  699. }
  700. }
  701. function popNextToCommonLevel(prev, next) {
  702. var parentNext = next.parent;
  703. if (parentNext === null) {
  704. throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
  705. }
  706. if (prev.depth === parentNext.depth) {
  707. // We found the same level. Now we just need to find a shared ancestor.
  708. popToNearestCommonAncestor(prev, parentNext);
  709. } else {
  710. // We must still be deeper.
  711. popNextToCommonLevel(prev, parentNext);
  712. }
  713. pushNode(next);
  714. } // Perform context switching to the new snapshot.
  715. // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
  716. // updating all the context's current values. That way reads, always just read the current value.
  717. // At the cost of updating contexts even if they're never read by this subtree.
  718. function switchContext(newSnapshot) {
  719. // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
  720. // We also need to update any new contexts that are now on the stack with the deepest value.
  721. // The easiest way to update new contexts is to just reapply them in reverse order from the
  722. // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
  723. // for that. Therefore this algorithm is recursive.
  724. // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
  725. // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
  726. // 3) Then we reapply new contexts on the way back up the stack.
  727. var prev = currentActiveSnapshot;
  728. var next = newSnapshot;
  729. if (prev !== next) {
  730. if (prev === null) {
  731. // $FlowFixMe: This has to be non-null since it's not equal to prev.
  732. pushAllNext(next);
  733. } else if (next === null) {
  734. popAllPrevious(prev);
  735. } else if (prev.depth === next.depth) {
  736. popToNearestCommonAncestor(prev, next);
  737. } else if (prev.depth > next.depth) {
  738. popPreviousToCommonLevel(prev, next);
  739. } else {
  740. popNextToCommonLevel(prev, next);
  741. }
  742. currentActiveSnapshot = next;
  743. }
  744. }
  745. function pushProvider(context, nextValue) {
  746. var prevValue;
  747. {
  748. prevValue = context._currentValue;
  749. context._currentValue = nextValue;
  750. {
  751. if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
  752. error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
  753. }
  754. context._currentRenderer = rendererSigil;
  755. }
  756. }
  757. var prevNode = currentActiveSnapshot;
  758. var newNode = {
  759. parent: prevNode,
  760. depth: prevNode === null ? 0 : prevNode.depth + 1,
  761. context: context,
  762. parentValue: prevValue,
  763. value: nextValue
  764. };
  765. currentActiveSnapshot = newNode;
  766. return newNode;
  767. }
  768. function popProvider() {
  769. var prevSnapshot = currentActiveSnapshot;
  770. if (prevSnapshot === null) {
  771. throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
  772. }
  773. {
  774. var value = prevSnapshot.parentValue;
  775. if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
  776. prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue;
  777. } else {
  778. prevSnapshot.context._currentValue = value;
  779. }
  780. }
  781. return currentActiveSnapshot = prevSnapshot.parent;
  782. }
  783. function getActiveContext() {
  784. return currentActiveSnapshot;
  785. }
  786. function readContext(context) {
  787. var value = context._currentValue ;
  788. return value;
  789. }
  790. // Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally,
  791. // changes to one module should be reflected in the others.
  792. // TODO: Rename this module and the corresponding Fiber one to "Thenable"
  793. // instead of "Wakeable". Or some other more appropriate name.
  794. // TODO: Sparse arrays are bad for performance.
  795. function createThenableState() {
  796. // The ThenableState is created the first time a component suspends. If it
  797. // suspends again, we'll reuse the same state.
  798. return [];
  799. }
  800. function trackSuspendedWakeable(wakeable) {
  801. // If this wakeable isn't already a thenable, turn it into one now. Then,
  802. // when we resume the work loop, we can check if its status is
  803. // still pending.
  804. // TODO: Get rid of the Wakeable type? It's superseded by UntrackedThenable.
  805. var thenable = wakeable; // We use an expando to track the status and result of a thenable so that we
  806. // can synchronously unwrap the value. Think of this as an extension of the
  807. // Promise API, or a custom interface that is a superset of Thenable.
  808. //
  809. // If the thenable doesn't have a status, set it to "pending" and attach
  810. // a listener that will update its status and result when it resolves.
  811. switch (thenable.status) {
  812. case 'fulfilled':
  813. case 'rejected':
  814. // A thenable that already resolved shouldn't have been thrown, so this is
  815. // unexpected. Suggests a mistake in a userspace data library. Don't track
  816. // this thenable, because if we keep trying it will likely infinite loop
  817. // without ever resolving.
  818. // TODO: Log a warning?
  819. break;
  820. default:
  821. {
  822. if (typeof thenable.status === 'string') {
  823. // Only instrument the thenable if the status if not defined. If
  824. // it's defined, but an unknown value, assume it's been instrumented by
  825. // some custom userspace implementation. We treat it as "pending".
  826. break;
  827. }
  828. var pendingThenable = thenable;
  829. pendingThenable.status = 'pending';
  830. pendingThenable.then(function (fulfilledValue) {
  831. if (thenable.status === 'pending') {
  832. var fulfilledThenable = thenable;
  833. fulfilledThenable.status = 'fulfilled';
  834. fulfilledThenable.value = fulfilledValue;
  835. }
  836. }, function (error) {
  837. if (thenable.status === 'pending') {
  838. var rejectedThenable = thenable;
  839. rejectedThenable.status = 'rejected';
  840. rejectedThenable.reason = error;
  841. }
  842. });
  843. break;
  844. }
  845. }
  846. }
  847. function trackUsedThenable(thenableState, thenable, index) {
  848. // This is only a separate function from trackSuspendedWakeable for symmetry
  849. // with Fiber.
  850. // TODO: Disallow throwing a thenable directly. It must go through `use` (or
  851. // some equivalent for internal Suspense implementations). We can't do this in
  852. // Fiber yet because it's a breaking change but we can do it in Server
  853. // Components because Server Components aren't released yet.
  854. thenableState[index] = thenable;
  855. }
  856. function getPreviouslyUsedThenableAtIndex(thenableState, index) {
  857. if (thenableState !== null) {
  858. var thenable = thenableState[index];
  859. if (thenable !== undefined) {
  860. return thenable;
  861. }
  862. }
  863. return null;
  864. }
  865. var currentRequest = null;
  866. var thenableIndexCounter = 0;
  867. var thenableState = null;
  868. function prepareToUseHooksForRequest(request) {
  869. currentRequest = request;
  870. }
  871. function resetHooksForRequest() {
  872. currentRequest = null;
  873. }
  874. function prepareToUseHooksForComponent(prevThenableState) {
  875. thenableIndexCounter = 0;
  876. thenableState = prevThenableState;
  877. }
  878. function getThenableStateAfterSuspending() {
  879. var state = thenableState;
  880. thenableState = null;
  881. return state;
  882. }
  883. function readContext$1(context) {
  884. {
  885. if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) {
  886. error('Only createServerContext is supported in Server Components.');
  887. }
  888. if (currentCache === null) {
  889. 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().');
  890. }
  891. }
  892. return readContext(context);
  893. }
  894. var Dispatcher = {
  895. useMemo: function (nextCreate) {
  896. return nextCreate();
  897. },
  898. useCallback: function (callback) {
  899. return callback;
  900. },
  901. useDebugValue: function () {},
  902. useDeferredValue: unsupportedHook,
  903. useTransition: unsupportedHook,
  904. getCacheForType: function (resourceType) {
  905. if (!currentCache) {
  906. throw new Error('Reading the cache is only supported while rendering.');
  907. }
  908. var entry = currentCache.get(resourceType);
  909. if (entry === undefined) {
  910. entry = resourceType(); // TODO: Warn if undefined?
  911. currentCache.set(resourceType, entry);
  912. }
  913. return entry;
  914. },
  915. readContext: readContext$1,
  916. useContext: readContext$1,
  917. useReducer: unsupportedHook,
  918. useRef: unsupportedHook,
  919. useState: unsupportedHook,
  920. useInsertionEffect: unsupportedHook,
  921. useLayoutEffect: unsupportedHook,
  922. useImperativeHandle: unsupportedHook,
  923. useEffect: unsupportedHook,
  924. useId: useId,
  925. useMutableSource: unsupportedHook,
  926. useSyncExternalStore: unsupportedHook,
  927. useCacheRefresh: function () {
  928. return unsupportedRefresh;
  929. },
  930. useMemoCache: function (size) {
  931. return new Array(size);
  932. },
  933. use: use
  934. };
  935. function unsupportedHook() {
  936. throw new Error('This Hook is not supported in Server Components.');
  937. }
  938. function unsupportedRefresh() {
  939. if (!currentCache) {
  940. throw new Error('Refreshing the cache is not supported in Server Components.');
  941. }
  942. }
  943. var currentCache = null;
  944. function setCurrentCache(cache) {
  945. currentCache = cache;
  946. return currentCache;
  947. }
  948. function getCurrentCache() {
  949. return currentCache;
  950. }
  951. function useId() {
  952. if (currentRequest === null) {
  953. throw new Error('useId can only be used while React is rendering');
  954. }
  955. var id = currentRequest.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client
  956. return ':' + currentRequest.identifierPrefix + 'S' + id.toString(32) + ':';
  957. }
  958. function use(usable) {
  959. if (usable !== null && typeof usable === 'object') {
  960. if (typeof usable.then === 'function') {
  961. // This is a thenable.
  962. var thenable = usable; // Track the position of the thenable within this fiber.
  963. var index = thenableIndexCounter;
  964. thenableIndexCounter += 1;
  965. switch (thenable.status) {
  966. case 'fulfilled':
  967. {
  968. var fulfilledValue = thenable.value;
  969. return fulfilledValue;
  970. }
  971. case 'rejected':
  972. {
  973. var rejectedError = thenable.reason;
  974. throw rejectedError;
  975. }
  976. default:
  977. {
  978. var prevThenableAtIndex = getPreviouslyUsedThenableAtIndex(thenableState, index);
  979. if (prevThenableAtIndex !== null) {
  980. switch (prevThenableAtIndex.status) {
  981. case 'fulfilled':
  982. {
  983. var _fulfilledValue = prevThenableAtIndex.value;
  984. return _fulfilledValue;
  985. }
  986. case 'rejected':
  987. {
  988. var _rejectedError = prevThenableAtIndex.reason;
  989. throw _rejectedError;
  990. }
  991. default:
  992. {
  993. // The thenable still hasn't resolved. Suspend with the same
  994. // thenable as last time to avoid redundant listeners.
  995. throw prevThenableAtIndex;
  996. }
  997. }
  998. } else {
  999. // This is the first time something has been used at this index.
  1000. // Stash the thenable at the current index so we can reuse it during
  1001. // the next attempt.
  1002. if (thenableState === null) {
  1003. thenableState = createThenableState();
  1004. }
  1005. trackUsedThenable(thenableState, thenable, index); // Suspend.
  1006. // TODO: Throwing here is an implementation detail that allows us to
  1007. // unwind the call stack. But we shouldn't allow it to leak into
  1008. // userspace. Throw an opaque placeholder value instead of the
  1009. // actual thenable. If it doesn't get captured by the work loop, log
  1010. // a warning, because that means something in userspace must have
  1011. // caught it.
  1012. throw thenable;
  1013. }
  1014. }
  1015. }
  1016. } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) {
  1017. var context = usable;
  1018. return readContext$1(context);
  1019. }
  1020. } // eslint-disable-next-line react-internal/safe-string-coercion
  1021. throw new Error('An unsupported type was passed to use(): ' + String(usable));
  1022. }
  1023. var ContextRegistry = ReactSharedInternals.ContextRegistry;
  1024. function getOrCreateServerContext(globalName) {
  1025. if (!ContextRegistry[globalName]) {
  1026. ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe function signature doesn't reflect the symbol value
  1027. REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED);
  1028. }
  1029. return ContextRegistry[globalName];
  1030. }
  1031. var PENDING = 0;
  1032. var COMPLETED = 1;
  1033. var ABORTED = 3;
  1034. var ERRORED = 4;
  1035. var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
  1036. function defaultErrorHandler(error) {
  1037. console['error'](error); // Don't transform to our wrapper
  1038. }
  1039. var OPEN = 0;
  1040. var CLOSING = 1;
  1041. var CLOSED = 2;
  1042. function createRequest(model, bundlerConfig, onError, context, identifierPrefix) {
  1043. var abortSet = new Set();
  1044. var pingedTasks = [];
  1045. var request = {
  1046. status: OPEN,
  1047. fatalError: null,
  1048. destination: null,
  1049. bundlerConfig: bundlerConfig,
  1050. cache: new Map(),
  1051. nextChunkId: 0,
  1052. pendingChunks: 0,
  1053. abortableTasks: abortSet,
  1054. pingedTasks: pingedTasks,
  1055. completedModuleChunks: [],
  1056. completedJSONChunks: [],
  1057. completedErrorChunks: [],
  1058. writtenSymbols: new Map(),
  1059. writtenModules: new Map(),
  1060. writtenProviders: new Map(),
  1061. identifierPrefix: identifierPrefix || '',
  1062. identifierCount: 1,
  1063. onError: onError === undefined ? defaultErrorHandler : onError,
  1064. toJSON: function (key, value) {
  1065. return resolveModelToJSON(request, this, key, value);
  1066. }
  1067. };
  1068. request.pendingChunks++;
  1069. var rootContext = createRootContext(context);
  1070. var rootTask = createTask(request, model, rootContext, abortSet);
  1071. pingedTasks.push(rootTask);
  1072. return request;
  1073. }
  1074. function createRootContext(reqContext) {
  1075. return importServerContexts(reqContext);
  1076. }
  1077. var POP = {};
  1078. function attemptResolveElement(type, key, ref, props, prevThenableState) {
  1079. if (ref !== null && ref !== undefined) {
  1080. // When the ref moves to the regular props object this will implicitly
  1081. // throw for functions. We could probably relax it to a DEV warning for other
  1082. // cases.
  1083. throw new Error('Refs cannot be used in server components, nor passed to client components.');
  1084. }
  1085. if (typeof type === 'function') {
  1086. if (isModuleReference(type)) {
  1087. // This is a reference to a client component.
  1088. return [REACT_ELEMENT_TYPE, type, key, props];
  1089. } // This is a server-side component.
  1090. prepareToUseHooksForComponent(prevThenableState);
  1091. return type(props);
  1092. } else if (typeof type === 'string') {
  1093. // This is a host element. E.g. HTML.
  1094. return [REACT_ELEMENT_TYPE, type, key, props];
  1095. } else if (typeof type === 'symbol') {
  1096. if (type === REACT_FRAGMENT_TYPE) {
  1097. // For key-less fragments, we add a small optimization to avoid serializing
  1098. // it as a wrapper.
  1099. // TODO: If a key is specified, we should propagate its key to any children.
  1100. // Same as if a server component has a key.
  1101. return props.children;
  1102. } // This might be a built-in React component. We'll let the client decide.
  1103. // Any built-in works as long as its props are serializable.
  1104. return [REACT_ELEMENT_TYPE, type, key, props];
  1105. } else if (type != null && typeof type === 'object') {
  1106. if (isModuleReference(type)) {
  1107. // This is a reference to a client component.
  1108. return [REACT_ELEMENT_TYPE, type, key, props];
  1109. }
  1110. switch (type.$$typeof) {
  1111. case REACT_LAZY_TYPE:
  1112. {
  1113. var payload = type._payload;
  1114. var init = type._init;
  1115. var wrappedType = init(payload);
  1116. return attemptResolveElement(wrappedType, key, ref, props, prevThenableState);
  1117. }
  1118. case REACT_FORWARD_REF_TYPE:
  1119. {
  1120. var render = type.render;
  1121. prepareToUseHooksForComponent(prevThenableState);
  1122. return render(props, undefined);
  1123. }
  1124. case REACT_MEMO_TYPE:
  1125. {
  1126. return attemptResolveElement(type.type, key, ref, props, prevThenableState);
  1127. }
  1128. case REACT_PROVIDER_TYPE:
  1129. {
  1130. pushProvider(type._context, props.value);
  1131. {
  1132. var extraKeys = Object.keys(props).filter(function (value) {
  1133. if (value === 'children' || value === 'value') {
  1134. return false;
  1135. }
  1136. return true;
  1137. });
  1138. if (extraKeys.length !== 0) {
  1139. error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys));
  1140. }
  1141. } // $FlowFixMe issue discovered when updating Flow
  1142. return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider.
  1143. {
  1144. value: props.value,
  1145. children: props.children,
  1146. __pop: POP
  1147. }];
  1148. }
  1149. }
  1150. }
  1151. throw new Error("Unsupported server component type: " + describeValueForErrorMessage(type));
  1152. }
  1153. function pingTask(request, task) {
  1154. var pingedTasks = request.pingedTasks;
  1155. pingedTasks.push(task);
  1156. if (pingedTasks.length === 1) {
  1157. scheduleWork(function () {
  1158. return performWork(request);
  1159. });
  1160. }
  1161. }
  1162. function createTask(request, model, context, abortSet) {
  1163. var id = request.nextChunkId++;
  1164. var task = {
  1165. id: id,
  1166. status: PENDING,
  1167. model: model,
  1168. context: context,
  1169. ping: function () {
  1170. return pingTask(request, task);
  1171. },
  1172. thenableState: null
  1173. };
  1174. abortSet.add(task);
  1175. return task;
  1176. }
  1177. function serializeByValueID(id) {
  1178. return '$' + id.toString(16);
  1179. }
  1180. function serializeByRefID(id) {
  1181. return '@' + id.toString(16);
  1182. }
  1183. function serializeModuleReference(request, parent, key, moduleReference) {
  1184. var moduleKey = getModuleKey(moduleReference);
  1185. var writtenModules = request.writtenModules;
  1186. var existingId = writtenModules.get(moduleKey);
  1187. if (existingId !== undefined) {
  1188. if (parent[0] === REACT_ELEMENT_TYPE && key === '1') {
  1189. // If we're encoding the "type" of an element, we can refer
  1190. // to that by a lazy reference instead of directly since React
  1191. // knows how to deal with lazy values. This lets us suspend
  1192. // on this component rather than its parent until the code has
  1193. // loaded.
  1194. return serializeByRefID(existingId);
  1195. }
  1196. return serializeByValueID(existingId);
  1197. }
  1198. try {
  1199. var moduleMetaData = resolveModuleMetaData(request.bundlerConfig, moduleReference);
  1200. request.pendingChunks++;
  1201. var moduleId = request.nextChunkId++;
  1202. emitModuleChunk(request, moduleId, moduleMetaData);
  1203. writtenModules.set(moduleKey, moduleId);
  1204. if (parent[0] === REACT_ELEMENT_TYPE && key === '1') {
  1205. // If we're encoding the "type" of an element, we can refer
  1206. // to that by a lazy reference instead of directly since React
  1207. // knows how to deal with lazy values. This lets us suspend
  1208. // on this component rather than its parent until the code has
  1209. // loaded.
  1210. return serializeByRefID(moduleId);
  1211. }
  1212. return serializeByValueID(moduleId);
  1213. } catch (x) {
  1214. request.pendingChunks++;
  1215. var errorId = request.nextChunkId++;
  1216. emitErrorChunk(request, errorId, x);
  1217. return serializeByValueID(errorId);
  1218. }
  1219. }
  1220. function escapeStringValue(value) {
  1221. if (value[0] === '$' || value[0] === '@') {
  1222. // We need to escape $ or @ prefixed strings since we use those to encode
  1223. // references to IDs and as special symbol values.
  1224. return '$' + value;
  1225. } else {
  1226. return value;
  1227. }
  1228. }
  1229. function isObjectPrototype(object) {
  1230. if (!object) {
  1231. return false;
  1232. }
  1233. var ObjectPrototype = Object.prototype;
  1234. if (object === ObjectPrototype) {
  1235. return true;
  1236. } // It might be an object from a different Realm which is
  1237. // still just a plain simple object.
  1238. if (Object.getPrototypeOf(object)) {
  1239. return false;
  1240. }
  1241. var names = Object.getOwnPropertyNames(object);
  1242. for (var i = 0; i < names.length; i++) {
  1243. if (!(names[i] in ObjectPrototype)) {
  1244. return false;
  1245. }
  1246. }
  1247. return true;
  1248. }
  1249. function isSimpleObject(object) {
  1250. if (!isObjectPrototype(Object.getPrototypeOf(object))) {
  1251. return false;
  1252. }
  1253. var names = Object.getOwnPropertyNames(object);
  1254. for (var i = 0; i < names.length; i++) {
  1255. var descriptor = Object.getOwnPropertyDescriptor(object, names[i]);
  1256. if (!descriptor) {
  1257. return false;
  1258. }
  1259. if (!descriptor.enumerable) {
  1260. if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') {
  1261. // React adds key and ref getters to props objects to issue warnings.
  1262. // Those getters will not be transferred to the client, but that's ok,
  1263. // so we'll special case them.
  1264. continue;
  1265. }
  1266. return false;
  1267. }
  1268. }
  1269. return true;
  1270. }
  1271. function objectName(object) {
  1272. var name = Object.prototype.toString.call(object);
  1273. return name.replace(/^\[object (.*)\]$/, function (m, p0) {
  1274. return p0;
  1275. });
  1276. }
  1277. function describeKeyForErrorMessage(key) {
  1278. var encodedKey = JSON.stringify(key);
  1279. return '"' + key + '"' === encodedKey ? key : encodedKey;
  1280. }
  1281. function describeValueForErrorMessage(value) {
  1282. switch (typeof value) {
  1283. case 'string':
  1284. {
  1285. return JSON.stringify(value.length <= 10 ? value : value.substr(0, 10) + '...');
  1286. }
  1287. case 'object':
  1288. {
  1289. if (isArray(value)) {
  1290. return '[...]';
  1291. }
  1292. var name = objectName(value);
  1293. if (name === 'Object') {
  1294. return '{...}';
  1295. }
  1296. return name;
  1297. }
  1298. case 'function':
  1299. return 'function';
  1300. default:
  1301. // eslint-disable-next-line react-internal/safe-string-coercion
  1302. return String(value);
  1303. }
  1304. }
  1305. function describeObjectForErrorMessage(objectOrArray, expandedName) {
  1306. if (isArray(objectOrArray)) {
  1307. var str = '[';
  1308. var array = objectOrArray;
  1309. for (var i = 0; i < array.length; i++) {
  1310. if (i > 0) {
  1311. str += ', ';
  1312. }
  1313. if (i > 6) {
  1314. str += '...';
  1315. break;
  1316. }
  1317. var _value = array[i];
  1318. if ('' + i === expandedName && typeof _value === 'object' && _value !== null) {
  1319. str += describeObjectForErrorMessage(_value);
  1320. } else {
  1321. str += describeValueForErrorMessage(_value);
  1322. }
  1323. }
  1324. str += ']';
  1325. return str;
  1326. } else {
  1327. var _str = '{';
  1328. var object = objectOrArray;
  1329. var names = Object.keys(object);
  1330. for (var _i = 0; _i < names.length; _i++) {
  1331. if (_i > 0) {
  1332. _str += ', ';
  1333. }
  1334. if (_i > 6) {
  1335. _str += '...';
  1336. break;
  1337. }
  1338. var name = names[_i];
  1339. _str += describeKeyForErrorMessage(name) + ': ';
  1340. var _value2 = object[name];
  1341. if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) {
  1342. _str += describeObjectForErrorMessage(_value2);
  1343. } else {
  1344. _str += describeValueForErrorMessage(_value2);
  1345. }
  1346. }
  1347. _str += '}';
  1348. return _str;
  1349. }
  1350. }
  1351. var insideContextProps = null;
  1352. var isInsideContextValue = false;
  1353. function resolveModelToJSON(request, parent, key, value) {
  1354. {
  1355. // $FlowFixMe
  1356. var originalValue = parent[key];
  1357. if (typeof originalValue === 'object' && originalValue !== value) {
  1358. error('Only plain objects can be passed to client components from server components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props. ' + 'Remove %s from these props: %s', describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent));
  1359. }
  1360. } // Special Symbols
  1361. switch (value) {
  1362. case REACT_ELEMENT_TYPE:
  1363. return '$';
  1364. }
  1365. {
  1366. if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') {
  1367. insideContextProps = value;
  1368. } else if (insideContextProps === parent && key === 'value') {
  1369. isInsideContextValue = true;
  1370. } else if (insideContextProps === parent && key === 'children') {
  1371. isInsideContextValue = false;
  1372. }
  1373. } // Resolve server components.
  1374. while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) {
  1375. {
  1376. if (isInsideContextValue) {
  1377. error('React elements are not allowed in ServerContext');
  1378. }
  1379. }
  1380. try {
  1381. switch (value.$$typeof) {
  1382. case REACT_ELEMENT_TYPE:
  1383. {
  1384. // TODO: Concatenate keys of parents onto children.
  1385. var element = value; // Attempt to render the server component.
  1386. value = attemptResolveElement(element.type, element.key, element.ref, element.props, null);
  1387. break;
  1388. }
  1389. case REACT_LAZY_TYPE:
  1390. {
  1391. var payload = value._payload;
  1392. var init = value._init;
  1393. value = init(payload);
  1394. break;
  1395. }
  1396. }
  1397. } catch (x) {
  1398. if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
  1399. // Something suspended, we'll need to create a new task and resolve it later.
  1400. request.pendingChunks++;
  1401. var newTask = createTask(request, value, getActiveContext(), request.abortableTasks);
  1402. var ping = newTask.ping;
  1403. x.then(ping, ping);
  1404. var wakeable = x;
  1405. trackSuspendedWakeable(wakeable);
  1406. newTask.thenableState = getThenableStateAfterSuspending();
  1407. return serializeByRefID(newTask.id);
  1408. } else {
  1409. logRecoverableError(request, x); // Something errored. We'll still send everything we have up until this point.
  1410. // We'll replace this element with a lazy reference that throws on the client
  1411. // once it gets rendered.
  1412. request.pendingChunks++;
  1413. var errorId = request.nextChunkId++;
  1414. emitErrorChunk(request, errorId, x);
  1415. return serializeByRefID(errorId);
  1416. }
  1417. }
  1418. }
  1419. if (value === null) {
  1420. return null;
  1421. }
  1422. if (typeof value === 'object') {
  1423. if (isModuleReference(value)) {
  1424. return serializeModuleReference(request, parent, key, value);
  1425. } else if (value.$$typeof === REACT_PROVIDER_TYPE) {
  1426. var providerKey = value._context._globalName;
  1427. var writtenProviders = request.writtenProviders;
  1428. var providerId = writtenProviders.get(key);
  1429. if (providerId === undefined) {
  1430. request.pendingChunks++;
  1431. providerId = request.nextChunkId++;
  1432. writtenProviders.set(providerKey, providerId);
  1433. emitProviderChunk(request, providerId, providerKey);
  1434. }
  1435. return serializeByValueID(providerId);
  1436. } else if (value === POP) {
  1437. popProvider();
  1438. {
  1439. insideContextProps = null;
  1440. isInsideContextValue = false;
  1441. }
  1442. return undefined;
  1443. }
  1444. {
  1445. if (value !== null && !isArray(value)) {
  1446. // Verify that this is a simple plain object.
  1447. if (objectName(value) !== 'Object') {
  1448. error('Only plain objects can be passed to client components from server components. ' + 'Built-ins like %s are not supported. ' + 'Remove %s from these props: %s', objectName(value), describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent));
  1449. } else if (!isSimpleObject(value)) {
  1450. error('Only plain objects can be passed to client components from server components. ' + 'Classes or other objects with methods are not supported. ' + 'Remove %s from these props: %s', describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent, key));
  1451. } else if (Object.getOwnPropertySymbols) {
  1452. var symbols = Object.getOwnPropertySymbols(value);
  1453. if (symbols.length > 0) {
  1454. error('Only plain objects can be passed to client components from server components. ' + 'Objects with symbol properties like %s are not supported. ' + 'Remove %s from these props: %s', symbols[0].description, describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent, key));
  1455. }
  1456. }
  1457. }
  1458. } // $FlowFixMe
  1459. return value;
  1460. }
  1461. if (typeof value === 'string') {
  1462. return escapeStringValue(value);
  1463. }
  1464. if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'undefined') {
  1465. return value;
  1466. }
  1467. if (typeof value === 'function') {
  1468. if (isModuleReference(value)) {
  1469. return serializeModuleReference(request, parent, key, value);
  1470. }
  1471. if (/^on[A-Z]/.test(key)) {
  1472. throw new Error('Event handlers cannot be passed to client component props. ' + ("Remove " + describeKeyForErrorMessage(key) + " from these props if possible: " + describeObjectForErrorMessage(parent) + "\n") + 'If you need interactivity, consider converting part of this to a client component.');
  1473. } else {
  1474. throw new Error('Functions cannot be passed directly to client components ' + "because they're not serializable. " + ("Remove " + describeKeyForErrorMessage(key) + " (" + (value.displayName || value.name || 'function') + ") from this object, or avoid the entire object: " + describeObjectForErrorMessage(parent)));
  1475. }
  1476. }
  1477. if (typeof value === 'symbol') {
  1478. var writtenSymbols = request.writtenSymbols;
  1479. var existingId = writtenSymbols.get(value);
  1480. if (existingId !== undefined) {
  1481. return serializeByValueID(existingId);
  1482. } // $FlowFixMe `description` might be undefined
  1483. var name = value.description; // $FlowFixMe `name` might be undefined
  1484. if (Symbol.for(name) !== value) {
  1485. throw new Error('Only global symbols received from Symbol.for(...) can be passed to client components. ' + ("The symbol Symbol.for(" + // $FlowFixMe `description` might be undefined
  1486. value.description + ") cannot be found among global symbols. ") + ("Remove " + describeKeyForErrorMessage(key) + " from this object, or avoid the entire object: " + describeObjectForErrorMessage(parent)));
  1487. }
  1488. request.pendingChunks++;
  1489. var symbolId = request.nextChunkId++;
  1490. emitSymbolChunk(request, symbolId, name);
  1491. writtenSymbols.set(value, symbolId);
  1492. return serializeByValueID(symbolId);
  1493. } // $FlowFixMe: bigint isn't added to Flow yet.
  1494. if (typeof value === 'bigint') {
  1495. throw new Error("BigInt (" + value + ") is not yet supported in client component props. " + ("Remove " + describeKeyForErrorMessage(key) + " from this object or use a plain number instead: " + describeObjectForErrorMessage(parent)));
  1496. }
  1497. throw new Error("Type " + typeof value + " is not supported in client component props. " + ("Remove " + describeKeyForErrorMessage(key) + " from this object, or avoid the entire object: " + describeObjectForErrorMessage(parent)));
  1498. }
  1499. function logRecoverableError(request, error) {
  1500. var onError = request.onError;
  1501. onError(error);
  1502. }
  1503. function fatalError(request, error) {
  1504. // This is called outside error handling code such as if an error happens in React internals.
  1505. if (request.destination !== null) {
  1506. request.status = CLOSED;
  1507. closeWithError(request.destination, error);
  1508. } else {
  1509. request.status = CLOSING;
  1510. request.fatalError = error;
  1511. }
  1512. }
  1513. function emitErrorChunk(request, id, error) {
  1514. // TODO: We should not leak error messages to the client in prod.
  1515. // Give this an error code instead and log on the server.
  1516. // We can serialize the error in DEV as a convenience.
  1517. var message;
  1518. var stack = '';
  1519. try {
  1520. if (error instanceof Error) {
  1521. // eslint-disable-next-line react-internal/safe-string-coercion
  1522. message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion
  1523. stack = String(error.stack);
  1524. } else {
  1525. message = 'Error: ' + error;
  1526. }
  1527. } catch (x) {
  1528. message = 'An error occurred but serializing the error message failed.';
  1529. }
  1530. var processedChunk = processErrorChunk(request, id, message, stack);
  1531. request.completedErrorChunks.push(processedChunk);
  1532. }
  1533. function emitModuleChunk(request, id, moduleMetaData) {
  1534. // $FlowFixMe ModuleMetaData is not a ReactModel
  1535. var processedChunk = processModuleChunk(request, id, moduleMetaData);
  1536. request.completedModuleChunks.push(processedChunk);
  1537. }
  1538. function emitSymbolChunk(request, id, name) {
  1539. var processedChunk = processSymbolChunk(request, id, name);
  1540. request.completedModuleChunks.push(processedChunk);
  1541. }
  1542. function emitProviderChunk(request, id, contextName) {
  1543. var processedChunk = processProviderChunk(request, id, contextName);
  1544. request.completedJSONChunks.push(processedChunk);
  1545. }
  1546. function retryTask(request, task) {
  1547. if (task.status !== PENDING) {
  1548. // We completed this by other means before we had a chance to retry it.
  1549. return;
  1550. }
  1551. switchContext(task.context);
  1552. try {
  1553. var _value3 = task.model;
  1554. if (typeof _value3 === 'object' && _value3 !== null && _value3.$$typeof === REACT_ELEMENT_TYPE) {
  1555. // TODO: Concatenate keys of parents onto children.
  1556. var element = _value3; // When retrying a component, reuse the thenableState from the
  1557. // previous attempt.
  1558. var prevThenableState = task.thenableState; // Attempt to render the server component.
  1559. // Doing this here lets us reuse this same task if the next component
  1560. // also suspends.
  1561. task.model = _value3;
  1562. _value3 = attemptResolveElement(element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering
  1563. // using the same task, but we reset its thenable state before continuing.
  1564. task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate
  1565. // from the render above because we don't need to reset the thenable state
  1566. // until the next time something suspends and retries.
  1567. while (typeof _value3 === 'object' && _value3 !== null && _value3.$$typeof === REACT_ELEMENT_TYPE) {
  1568. // TODO: Concatenate keys of parents onto children.
  1569. var nextElement = _value3;
  1570. task.model = _value3;
  1571. _value3 = attemptResolveElement(nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null);
  1572. }
  1573. }
  1574. var processedChunk = processModelChunk(request, task.id, _value3);
  1575. request.completedJSONChunks.push(processedChunk);
  1576. request.abortableTasks.delete(task);
  1577. task.status = COMPLETED;
  1578. } catch (x) {
  1579. if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
  1580. // Something suspended again, let's pick it back up later.
  1581. var ping = task.ping;
  1582. x.then(ping, ping);
  1583. var wakeable = x;
  1584. trackSuspendedWakeable(wakeable);
  1585. task.thenableState = getThenableStateAfterSuspending();
  1586. return;
  1587. } else {
  1588. request.abortableTasks.delete(task);
  1589. task.status = ERRORED;
  1590. logRecoverableError(request, x); // This errored, we need to serialize this error to the
  1591. emitErrorChunk(request, task.id, x);
  1592. }
  1593. }
  1594. }
  1595. function performWork(request) {
  1596. var prevDispatcher = ReactCurrentDispatcher.current;
  1597. var prevCache = getCurrentCache();
  1598. ReactCurrentDispatcher.current = Dispatcher;
  1599. setCurrentCache(request.cache);
  1600. prepareToUseHooksForRequest(request);
  1601. try {
  1602. var pingedTasks = request.pingedTasks;
  1603. request.pingedTasks = [];
  1604. for (var i = 0; i < pingedTasks.length; i++) {
  1605. var task = pingedTasks[i];
  1606. retryTask(request, task);
  1607. }
  1608. if (request.destination !== null) {
  1609. flushCompletedChunks(request, request.destination);
  1610. }
  1611. } catch (error) {
  1612. logRecoverableError(request, error);
  1613. fatalError(request, error);
  1614. } finally {
  1615. ReactCurrentDispatcher.current = prevDispatcher;
  1616. setCurrentCache(prevCache);
  1617. resetHooksForRequest();
  1618. }
  1619. }
  1620. function abortTask(task, request, errorId) {
  1621. task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only
  1622. // has a single value referencing the error.
  1623. var ref = serializeByValueID(errorId);
  1624. var processedChunk = processReferenceChunk(request, task.id, ref);
  1625. request.completedErrorChunks.push(processedChunk);
  1626. }
  1627. function flushCompletedChunks(request, destination) {
  1628. beginWriting();
  1629. try {
  1630. // We emit module chunks first in the stream so that
  1631. // they can be preloaded as early as possible.
  1632. var moduleChunks = request.completedModuleChunks;
  1633. var i = 0;
  1634. for (; i < moduleChunks.length; i++) {
  1635. request.pendingChunks--;
  1636. var chunk = moduleChunks[i];
  1637. var keepWriting = writeChunkAndReturn(destination, chunk);
  1638. if (!keepWriting) {
  1639. request.destination = null;
  1640. i++;
  1641. break;
  1642. }
  1643. }
  1644. moduleChunks.splice(0, i); // Next comes model data.
  1645. var jsonChunks = request.completedJSONChunks;
  1646. i = 0;
  1647. for (; i < jsonChunks.length; i++) {
  1648. request.pendingChunks--;
  1649. var _chunk = jsonChunks[i];
  1650. var _keepWriting = writeChunkAndReturn(destination, _chunk);
  1651. if (!_keepWriting) {
  1652. request.destination = null;
  1653. i++;
  1654. break;
  1655. }
  1656. }
  1657. jsonChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay
  1658. // any error messages and prioritize display of other parts of
  1659. // the page.
  1660. var errorChunks = request.completedErrorChunks;
  1661. i = 0;
  1662. for (; i < errorChunks.length; i++) {
  1663. request.pendingChunks--;
  1664. var _chunk2 = errorChunks[i];
  1665. var _keepWriting2 = writeChunkAndReturn(destination, _chunk2);
  1666. if (!_keepWriting2) {
  1667. request.destination = null;
  1668. i++;
  1669. break;
  1670. }
  1671. }
  1672. errorChunks.splice(0, i);
  1673. } finally {
  1674. completeWriting(destination);
  1675. }
  1676. if (request.pendingChunks === 0) {
  1677. // We're done.
  1678. close(destination);
  1679. }
  1680. }
  1681. function startWork(request) {
  1682. scheduleWork(function () {
  1683. return performWork(request);
  1684. });
  1685. }
  1686. function startFlowing(request, destination) {
  1687. if (request.status === CLOSING) {
  1688. request.status = CLOSED;
  1689. closeWithError(destination, request.fatalError);
  1690. return;
  1691. }
  1692. if (request.status === CLOSED) {
  1693. return;
  1694. }
  1695. if (request.destination !== null) {
  1696. // We're already flowing.
  1697. return;
  1698. }
  1699. request.destination = destination;
  1700. try {
  1701. flushCompletedChunks(request, destination);
  1702. } catch (error) {
  1703. logRecoverableError(request, error);
  1704. fatalError(request, error);
  1705. }
  1706. } // This is called to early terminate a request. It creates an error at all pending tasks.
  1707. function abort(request, reason) {
  1708. try {
  1709. var abortableTasks = request.abortableTasks;
  1710. if (abortableTasks.size > 0) {
  1711. // We have tasks to abort. We'll emit one error row and then emit a reference
  1712. // to that row from every row that's still remaining.
  1713. var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;
  1714. logRecoverableError(request, _error);
  1715. request.pendingChunks++;
  1716. var errorId = request.nextChunkId++;
  1717. emitErrorChunk(request, errorId, _error);
  1718. abortableTasks.forEach(function (task) {
  1719. return abortTask(task, request, errorId);
  1720. });
  1721. abortableTasks.clear();
  1722. }
  1723. if (request.destination !== null) {
  1724. flushCompletedChunks(request, request.destination);
  1725. }
  1726. } catch (error) {
  1727. logRecoverableError(request, error);
  1728. fatalError(request, error);
  1729. }
  1730. }
  1731. function importServerContexts(contexts) {
  1732. if (contexts) {
  1733. var prevContext = getActiveContext();
  1734. switchContext(rootContextSnapshot);
  1735. for (var i = 0; i < contexts.length; i++) {
  1736. var _contexts$i = contexts[i],
  1737. name = _contexts$i[0],
  1738. _value4 = _contexts$i[1];
  1739. var context = getOrCreateServerContext(name);
  1740. pushProvider(context, _value4);
  1741. }
  1742. var importedContext = getActiveContext();
  1743. switchContext(prevContext);
  1744. return importedContext;
  1745. }
  1746. return rootContextSnapshot;
  1747. }
  1748. function renderToReadableStream(model, webpackMap, options) {
  1749. var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined);
  1750. if (options && options.signal) {
  1751. var signal = options.signal;
  1752. if (signal.aborted) {
  1753. abort(request, signal.reason);
  1754. } else {
  1755. var listener = function () {
  1756. abort(request, signal.reason);
  1757. signal.removeEventListener('abort', listener);
  1758. };
  1759. signal.addEventListener('abort', listener);
  1760. }
  1761. }
  1762. var stream = new ReadableStream({
  1763. type: 'bytes',
  1764. start: function (controller) {
  1765. startWork(request);
  1766. },
  1767. pull: function (controller) {
  1768. startFlowing(request, controller);
  1769. },
  1770. cancel: function (reason) {}
  1771. }, // $FlowFixMe size() methods are not allowed on byte streams.
  1772. {
  1773. highWaterMark: 0
  1774. });
  1775. return stream;
  1776. }
  1777. exports.renderToReadableStream = renderToReadableStream;
  1778. })();
  1779. }