UNPKG

next

Version:

The React Framework

1,671 lines (1,386 loc) 105 kB
/** * @license React * react-server-dom-webpack-server.node.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; var React = require('react'); var util = require('util'); var async_hooks = require('async_hooks'); var ReactDOM = require('react-dom'); var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } // eslint-disable-next-line react-internal/safe-string-coercion var argsWithFormat = args.map(function (item) { return String(item); }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } function scheduleWork(callback) { setImmediate(callback); } function flushBuffered(destination) { // If we don't have any more data to send right now. // Flush whatever is in the buffer to the wire. if (typeof destination.flush === 'function') { // By convention the Zlib streams provide a flush function for this purpose. // For Express, compression middleware adds this method. destination.flush(); } } var VIEW_SIZE = 2048; var currentView = null; var writtenBytes = 0; var destinationHasCapacity = true; function beginWriting(destination) { currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; destinationHasCapacity = true; } function writeStringChunk(destination, stringChunk) { if (stringChunk.length === 0) { return; } // maximum possible view needed to encode entire string if (stringChunk.length * 3 > VIEW_SIZE) { if (writtenBytes > 0) { writeToDestination(destination, currentView.subarray(0, writtenBytes)); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } writeToDestination(destination, textEncoder.encode(stringChunk)); return; } var target = currentView; if (writtenBytes > 0) { target = currentView.subarray(writtenBytes); } var _textEncoder$encodeIn = textEncoder.encodeInto(stringChunk, target), read = _textEncoder$encodeIn.read, written = _textEncoder$encodeIn.written; writtenBytes += written; if (read < stringChunk.length) { writeToDestination(destination, currentView.subarray(0, writtenBytes)); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = textEncoder.encodeInto(stringChunk.slice(read), currentView).written; } if (writtenBytes === VIEW_SIZE) { writeToDestination(destination, currentView); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } } function writeViewChunk(destination, chunk) { if (chunk.byteLength === 0) { return; } if (chunk.byteLength > VIEW_SIZE) { { if (precomputedChunkSet && precomputedChunkSet.has(chunk)) { error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.'); } } // this chunk may overflow a single view which implies it was not // one that is cached by the streaming renderer. We will enqueu // it directly and expect it is not re-used if (writtenBytes > 0) { writeToDestination(destination, currentView.subarray(0, writtenBytes)); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } writeToDestination(destination, chunk); return; } var bytesToWrite = chunk; var allowableBytes = currentView.length - writtenBytes; if (allowableBytes < bytesToWrite.byteLength) { // this chunk would overflow the current view. We enqueue a full view // and start a new view with the remaining chunk if (allowableBytes === 0) { // the current view is already full, send it writeToDestination(destination, currentView); } else { // fill up the current view and apply the remaining chunk bytes // to a new view. currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); writtenBytes += allowableBytes; writeToDestination(destination, currentView); bytesToWrite = bytesToWrite.subarray(allowableBytes); } currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } currentView.set(bytesToWrite, writtenBytes); writtenBytes += bytesToWrite.byteLength; if (writtenBytes === VIEW_SIZE) { writeToDestination(destination, currentView); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } } function writeChunk(destination, chunk) { if (typeof chunk === 'string') { writeStringChunk(destination, chunk); } else { writeViewChunk(destination, chunk); } } function writeToDestination(destination, view) { var currentHasCapacity = destination.write(view); destinationHasCapacity = destinationHasCapacity && currentHasCapacity; } function writeChunkAndReturn(destination, chunk) { writeChunk(destination, chunk); return destinationHasCapacity; } function completeWriting(destination) { if (currentView && writtenBytes > 0) { destination.write(currentView.subarray(0, writtenBytes)); } currentView = null; writtenBytes = 0; destinationHasCapacity = true; } function close$1(destination) { destination.end(); } var textEncoder = new util.TextEncoder(); function stringToChunk(content) { return content; } var precomputedChunkSet = new Set() ; function byteLengthOfChunk(chunk) { return typeof chunk === 'string' ? Buffer.byteLength(chunk, 'utf8') : chunk.byteLength; } function closeWithError(destination, error) { // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. destination.destroy(error); } // eslint-disable-next-line no-unused-vars var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); function isClientReference(reference) { return reference.$$typeof === CLIENT_REFERENCE_TAG; } function isServerReference(reference) { return reference.$$typeof === SERVER_REFERENCE_TAG; } function registerClientReference(proxyImplementation, id, exportName) { return registerClientReferenceImpl(proxyImplementation, id + '#' + exportName, false); } function registerClientReferenceImpl(proxyImplementation, id, async) { return Object.defineProperties(proxyImplementation, { $$typeof: { value: CLIENT_REFERENCE_TAG }, $$id: { value: id }, $$async: { value: async } }); } // $FlowFixMe[method-unbinding] var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] var ArraySlice = Array.prototype.slice; function bind() { // $FlowFixMe[unsupported-syntax] var newFn = FunctionBind.apply(this, arguments); if (this.$$typeof === SERVER_REFERENCE_TAG) { var args = ArraySlice.call(arguments, 1); newFn.$$typeof = SERVER_REFERENCE_TAG; newFn.$$id = this.$$id; newFn.$$bound = this.$$bound ? this.$$bound.concat(args) : args; } return newFn; } function registerServerReference(reference, id, exportName) { return Object.defineProperties(reference, { $$typeof: { value: SERVER_REFERENCE_TAG }, $$id: { value: exportName === null ? id : id + '#' + exportName }, $$bound: { value: null }, bind: { value: bind } }); } var PROMISE_PROTOTYPE = Promise.prototype; var deepProxyHandlers = { get: function (target, name, receiver) { switch (name) { // These names are read by the Flight runtime if you end up using the exports object. case '$$typeof': // These names are a little too common. We should probably have a way to // have the Flight runtime extract the inner target instead. return target.$$typeof; case '$$id': return target.$$id; case '$$async': return target.$$async; case 'name': return target.name; case 'displayName': return undefined; // We need to special case this because createElement reads it if we pass this // reference. case 'defaultProps': return undefined; // Avoid this attempting to be serialized. case 'toJSON': return undefined; case Symbol.toPrimitive: // $FlowFixMe[prop-missing] return Object.prototype[Symbol.toPrimitive]; case 'Provider': throw new Error("Cannot render a Client Context Provider on the Server. " + "Instead, you can export a Client Component wrapper " + "that itself renders a Client Context Provider."); } // eslint-disable-next-line react-internal/safe-string-coercion var expression = String(target.name) + '.' + String(name); throw new Error("Cannot access " + expression + " on the server. " + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.'); }, set: function () { throw new Error('Cannot assign to a client module from a server module.'); } }; var proxyHandlers = { get: function (target, name, receiver) { switch (name) { // These names are read by the Flight runtime if you end up using the exports object. case '$$typeof': return target.$$typeof; case '$$id': return target.$$id; case '$$async': return target.$$async; case 'name': return target.name; // We need to special case this because createElement reads it if we pass this // reference. case 'defaultProps': return undefined; // Avoid this attempting to be serialized. case 'toJSON': return undefined; case Symbol.toPrimitive: // $FlowFixMe[prop-missing] return Object.prototype[Symbol.toPrimitive]; case '__esModule': // Something is conditionally checking which export to use. We'll pretend to be // an ESM compat module but then we'll check again on the client. var moduleId = target.$$id; target.default = registerClientReferenceImpl(function () { throw new Error("Attempted to call the default export of " + moduleId + " from the server " + "but it's on the client. It's not possible to invoke a client function from " + "the server, it can only be rendered as a Component or passed to props of a " + "Client Component."); }, target.$$id + '#', target.$$async); return true; case 'then': if (target.then) { // Use a cached value return target.then; } if (!target.$$async) { // If this module is expected to return a Promise (such as an AsyncModule) then // we should resolve that with a client reference that unwraps the Promise on // the client. var clientReference = registerClientReferenceImpl({}, target.$$id, true); var proxy = new Proxy(clientReference, proxyHandlers); // Treat this as a resolved Promise for React's use() target.status = 'fulfilled'; target.value = proxy; var then = target.then = registerClientReferenceImpl(function then(resolve, reject) { // Expose to React. return Promise.resolve(resolve(proxy)); }, // If this is not used as a Promise but is treated as a reference to a `.then` // export then we should treat it as a reference to that name. target.$$id + '#then', false); return then; } else { // Since typeof .then === 'function' is a feature test we'd continue recursing // indefinitely if we return a function. Instead, we return an object reference // if we check further. return undefined; } } var cachedReference = target[name]; if (!cachedReference) { var reference = registerClientReferenceImpl(function () { throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion "Attempted to call " + String(name) + "() from the server but " + String(name) + " is on the client. " + "It's not possible to invoke a client function from the server, it can " + "only be rendered as a Component or passed to props of a Client Component."); }, target.$$id + '#' + name, target.$$async); Object.defineProperty(reference, 'name', { value: name }); cachedReference = target[name] = new Proxy(reference, deepProxyHandlers); } return cachedReference; }, getPrototypeOf: function (target) { // Pretend to be a Promise in case anyone asks. return PROMISE_PROTOTYPE; }, set: function () { throw new Error('Cannot assign to a client module from a server module.'); } }; function createClientModuleProxy(moduleId) { var clientReference = registerClientReferenceImpl({}, // Represents the whole Module object instead of a particular import. moduleId, false); return new Proxy(clientReference, proxyHandlers); } function getClientReferenceKey(reference) { return reference.$$async ? reference.$$id + '#async' : reference.$$id; } function resolveClientReferenceMetadata(config, clientReference) { var modulePath = clientReference.$$id; var name = ''; var resolvedModuleData = config[modulePath]; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // We didn't find this specific export name but we might have the * export // which contains this name as well. // TODO: It's unfortunate that we now have to parse this string. We should // probably go back to encoding path and name separately on the client reference. var idx = modulePath.lastIndexOf('#'); if (idx !== -1) { name = modulePath.slice(idx + 1); resolvedModuleData = config[modulePath.slice(0, idx)]; } if (!resolvedModuleData) { throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); } } return { id: resolvedModuleData.id, chunks: resolvedModuleData.chunks, name: name, async: !!clientReference.$$async }; } function getServerReferenceId(config, serverReference) { return serverReference.$$id; } function getServerReferenceBoundArguments(config, serverReference) { return serverReference.$$bound; } var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var ReactDOMFlightServerDispatcher = { prefetchDNS: prefetchDNS, preconnect: preconnect, preload: preload, preinit: preinit }; function prefetchDNS(href, options) { { if (typeof href === 'string') { var request = resolveRequest(); if (request) { var hints = getHints(request); var key = 'D' + href; if (hints.has(key)) { // duplicate hint return; } hints.add(key); if (options) { emitHint(request, 'D', [href, options]); } else { emitHint(request, 'D', href); } } } } } function preconnect(href, options) { { if (typeof href === 'string') { var request = resolveRequest(); if (request) { var hints = getHints(request); var crossOrigin = options == null || typeof options.crossOrigin !== 'string' ? null : options.crossOrigin === 'use-credentials' ? 'use-credentials' : ''; var key = "C" + (crossOrigin === null ? 'null' : crossOrigin) + "|" + href; if (hints.has(key)) { // duplicate hint return; } hints.add(key); if (options) { emitHint(request, 'C', [href, options]); } else { emitHint(request, 'C', href); } } } } } function preload(href, options) { { if (typeof href === 'string') { var request = resolveRequest(); if (request) { var hints = getHints(request); var key = 'L' + href; if (hints.has(key)) { // duplicate hint return; } hints.add(key); emitHint(request, 'L', [href, options]); } } } } function preinit(href, options) { { if (typeof href === 'string') { var request = resolveRequest(); if (request) { var hints = getHints(request); var key = 'I' + href; if (hints.has(key)) { // duplicate hint return; } hints.add(key); emitHint(request, 'I', [href, options]); } } } } var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; function prepareHostDispatcher() { ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher; } // Used to distinguish these contexts from ones used in other renderers. function createHints() { return new Set(); } var requestStorage = new async_hooks.AsyncLocalStorage(); // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. var REACT_ELEMENT_TYPE = Symbol.for('react.element'); var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); var REACT_MEMO_TYPE = Symbol.for('react.memo'); var REACT_LAZY_TYPE = Symbol.for('react.lazy'); var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel'); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } var rendererSigil; { // Use this to detect multiple renderers using the same context rendererSigil = {}; } // Used to store the parent path of all context overrides in a shared linked list. // Forming a reverse tree. // The structure of a context snapshot is an implementation of this file. // Currently, it's implemented as tracking the current active node. var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. // This global (actually thread local) state represents what state all those "current", // fields are currently in. var currentActiveSnapshot = null; function popNode(prev) { { prev.context._currentValue = prev.parentValue; } } function pushNode(next) { { next.context._currentValue = next.value; } } function popToNearestCommonAncestor(prev, next) { if (prev === next) ; else { popNode(prev); var parentPrev = prev.parent; var parentNext = next.parent; if (parentPrev === null) { if (parentNext !== null) { throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); } } else { if (parentNext === null) { throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); } popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. pushNode(next); } } } function popAllPrevious(prev) { popNode(prev); var parentPrev = prev.parent; if (parentPrev !== null) { popAllPrevious(parentPrev); } } function pushAllNext(next) { var parentNext = next.parent; if (parentNext !== null) { pushAllNext(parentNext); } pushNode(next); } function popPreviousToCommonLevel(prev, next) { popNode(prev); var parentPrev = prev.parent; if (parentPrev === null) { throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); } if (parentPrev.depth === next.depth) { // We found the same level. Now we just need to find a shared ancestor. popToNearestCommonAncestor(parentPrev, next); } else { // We must still be deeper. popPreviousToCommonLevel(parentPrev, next); } } function popNextToCommonLevel(prev, next) { var parentNext = next.parent; if (parentNext === null) { throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); } if (prev.depth === parentNext.depth) { // We found the same level. Now we just need to find a shared ancestor. popToNearestCommonAncestor(prev, parentNext); } else { // We must still be deeper. popNextToCommonLevel(prev, parentNext); } pushNode(next); } // Perform context switching to the new snapshot. // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by // updating all the context's current values. That way reads, always just read the current value. // At the cost of updating contexts even if they're never read by this subtree. function switchContext(newSnapshot) { // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. // We also need to update any new contexts that are now on the stack with the deepest value. // The easiest way to update new contexts is to just reapply them in reverse order from the // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack // for that. Therefore this algorithm is recursive. // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. // 3) Then we reapply new contexts on the way back up the stack. var prev = currentActiveSnapshot; var next = newSnapshot; if (prev !== next) { if (prev === null) { // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. pushAllNext(next); } else if (next === null) { popAllPrevious(prev); } else if (prev.depth === next.depth) { popToNearestCommonAncestor(prev, next); } else if (prev.depth > next.depth) { popPreviousToCommonLevel(prev, next); } else { popNextToCommonLevel(prev, next); } currentActiveSnapshot = next; } } function pushProvider(context, nextValue) { var prevValue; { prevValue = context._currentValue; context._currentValue = nextValue; { if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); } context._currentRenderer = rendererSigil; } } var prevNode = currentActiveSnapshot; var newNode = { parent: prevNode, depth: prevNode === null ? 0 : prevNode.depth + 1, context: context, parentValue: prevValue, value: nextValue }; currentActiveSnapshot = newNode; return newNode; } function popProvider() { var prevSnapshot = currentActiveSnapshot; if (prevSnapshot === null) { throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); } { var value = prevSnapshot.parentValue; if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; } else { prevSnapshot.context._currentValue = value; } } return currentActiveSnapshot = prevSnapshot.parent; } function getActiveContext() { return currentActiveSnapshot; } function readContext$1(context) { var value = context._currentValue ; return value; } // Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally, // changes to one module should be reflected in the others. // TODO: Rename this module and the corresponding Fiber one to "Thenable" // instead of "Wakeable". Or some other more appropriate name. // An error that is thrown (e.g. by `use`) to trigger Suspense. If we // detect this is caught by userspace, we'll log a warning in development. var 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`"); function createThenableState() { // The ThenableState is created the first time a component suspends. If it // suspends again, we'll reuse the same state. return []; } function noop() {} function trackUsedThenable(thenableState, thenable, index) { var previous = thenableState[index]; if (previous === undefined) { thenableState.push(thenable); } else { if (previous !== thenable) { // Reuse the previous thenable, and drop the new one. We can assume // they represent the same value, because components are idempotent. // Avoid an unhandled rejection errors for the Promises that we'll // intentionally ignore. thenable.then(noop, noop); thenable = previous; } } // We use an expando to track the status and result of a thenable so that we // can synchronously unwrap the value. Think of this as an extension of the // Promise API, or a custom interface that is a superset of Thenable. // // If the thenable doesn't have a status, set it to "pending" and attach // a listener that will update its status and result when it resolves. switch (thenable.status) { case 'fulfilled': { var fulfilledValue = thenable.value; return fulfilledValue; } case 'rejected': { var rejectedError = thenable.reason; throw rejectedError; } default: { if (typeof thenable.status === 'string') ; else { var pendingThenable = thenable; pendingThenable.status = 'pending'; pendingThenable.then(function (fulfilledValue) { if (thenable.status === 'pending') { var fulfilledThenable = thenable; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = fulfilledValue; } }, function (error) { if (thenable.status === 'pending') { var rejectedThenable = thenable; rejectedThenable.status = 'rejected'; rejectedThenable.reason = error; } }); // Check one more time in case the thenable resolved synchronously switch (thenable.status) { case 'fulfilled': { var fulfilledThenable = thenable; return fulfilledThenable.value; } case 'rejected': { var rejectedThenable = thenable; throw rejectedThenable.reason; } } } // Suspend. // // Throwing here is an implementation detail that allows us to unwind the // call stack. But we shouldn't allow it to leak into userspace. Throw an // opaque placeholder value instead of the actual thenable. If it doesn't // get captured by the work loop, log a warning, because that means // something in userspace must have caught it. suspendedThenable = thenable; throw SuspenseException; } } } // This is used to track the actual thenable that suspended so it can be // passed to the rest of the Suspense implementation — which, for historical // reasons, expects to receive a thenable. var suspendedThenable = null; function getSuspendedThenable() { // This is called right after `use` suspends by throwing an exception. `use` // throws an opaque value instead of the thenable itself so that it can't be // caught in userspace. Then the work loop accesses the actual thenable using // this function. if (suspendedThenable === null) { throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.'); } var thenable = suspendedThenable; suspendedThenable = null; return thenable; } var currentRequest$1 = null; var thenableIndexCounter = 0; var thenableState = null; function prepareToUseHooksForRequest(request) { currentRequest$1 = request; } function resetHooksForRequest() { currentRequest$1 = null; } function prepareToUseHooksForComponent(prevThenableState) { thenableIndexCounter = 0; thenableState = prevThenableState; } function getThenableStateAfterSuspending() { var state = thenableState; thenableState = null; return state; } function readContext(context) { { if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) { if (isClientReference(context)) { error('Cannot read a Client Context from a Server Component.'); } else { error('Only createServerContext is supported in Server Components.'); } } if (currentRequest$1 === null) { 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().'); } } return readContext$1(context); } var HooksDispatcher = { useMemo: function (nextCreate) { return nextCreate(); }, useCallback: function (callback) { return callback; }, useDebugValue: function () {}, useDeferredValue: unsupportedHook, useTransition: unsupportedHook, readContext: readContext, useContext: readContext, useReducer: unsupportedHook, useRef: unsupportedHook, useState: unsupportedHook, useInsertionEffect: unsupportedHook, useLayoutEffect: unsupportedHook, useImperativeHandle: unsupportedHook, useEffect: unsupportedHook, useId: useId, useSyncExternalStore: unsupportedHook, useCacheRefresh: function () { return unsupportedRefresh; }, useMemoCache: function (size) { var data = new Array(size); for (var i = 0; i < size; i++) { data[i] = REACT_MEMO_CACHE_SENTINEL; } return data; }, use: use }; function unsupportedHook() { throw new Error('This Hook is not supported in Server Components.'); } function unsupportedRefresh() { throw new Error('Refreshing the cache is not supported in Server Components.'); } function useId() { if (currentRequest$1 === null) { throw new Error('useId can only be used while React is rendering'); } var id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':'; } function use(usable) { if (usable !== null && typeof usable === 'object' || typeof usable === 'function') { // $FlowFixMe[method-unbinding] if (typeof usable.then === 'function') { // This is a thenable. var thenable = usable; // Track the position of the thenable within this fiber. var index = thenableIndexCounter; thenableIndexCounter += 1; if (thenableState === null) { thenableState = createThenableState(); } return trackUsedThenable(thenableState, thenable, index); } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { var context = usable; return readContext(context); } } { if (isClientReference(usable)) { error('Cannot use() an already resolved Client Reference.'); } } // eslint-disable-next-line react-internal/safe-string-coercion throw new Error('An unsupported type was passed to use(): ' + String(usable)); } function createSignal() { return new AbortController().signal; } function resolveCache() { var request = resolveRequest(); if (request) { return getCache(request); } return new Map(); } var DefaultCacheDispatcher = { getCacheSignal: function () { var cache = resolveCache(); var entry = cache.get(createSignal); if (entry === undefined) { entry = createSignal(); cache.set(createSignal, entry); } return entry; }, getCacheForType: function (resourceType) { var cache = resolveCache(); var entry = cache.get(resourceType); if (entry === undefined) { entry = resourceType(); // TODO: Warn if undefined? cache.set(resourceType, entry); } return entry; } }; var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } // in case they error. var jsxPropsParents = new WeakMap(); var jsxChildrenParents = new WeakMap(); function isObjectPrototype(object) { if (!object) { return false; } var ObjectPrototype = Object.prototype; if (object === ObjectPrototype) { return true; } // It might be an object from a different Realm which is // still just a plain simple object. if (Object.getPrototypeOf(object)) { return false; } var names = Object.getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { if (!(names[i] in ObjectPrototype)) { return false; } } return true; } function isSimpleObject(object) { if (!isObjectPrototype(Object.getPrototypeOf(object))) { return false; } var names = Object.getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); if (!descriptor) { return false; } if (!descriptor.enumerable) { if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { // React adds key and ref getters to props objects to issue warnings. // Those getters will not be transferred to the client, but that's ok, // so we'll special case them. continue; } return false; } } return true; } function objectName(object) { // $FlowFixMe[method-unbinding] var name = Object.prototype.toString.call(object); return name.replace(/^\[object (.*)\]$/, function (m, p0) { return p0; }); } function describeKeyForErrorMessage(key) { var encodedKey = JSON.stringify(key); return '"' + key + '"' === encodedKey ? key : encodedKey; } function describeValueForErrorMessage(value) { switch (typeof value) { case 'string': { return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); } case 'object': { if (isArray(value)) { return '[...]'; } var name = objectName(value); if (name === 'Object') { return '{...}'; } return name; } case 'function': return 'function'; default: // eslint-disable-next-line react-internal/safe-string-coercion return String(value); } } function describeElementType(type) { if (typeof type === 'string') { return type; } switch (type) { case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeElementType(type.render); case REACT_MEMO_TYPE: return describeElementType(type.type); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeElementType(init(payload)); } catch (x) {} } } } return ''; } function describeObjectForErrorMessage(objectOrArray, expandedName) { var objKind = objectName(objectOrArray); if (objKind !== 'Object' && objKind !== 'Array') { return objKind; } var str = ''; var start = -1; var length = 0; if (isArray(objectOrArray)) { if (jsxChildrenParents.has(objectOrArray)) { // Print JSX Children var type = jsxChildrenParents.get(objectOrArray); str = '<' + describeElementType(type) + '>'; var array = objectOrArray; for (var i = 0; i < array.length; i++) { var value = array[i]; var substr = void 0; if (typeof value === 'string') { substr = value; } else if (typeof value === 'object' && value !== null) { substr = '{' + describeObjectForErrorMessage(value) + '}'; } else { substr = '{' + describeValueForErrorMessage(value) + '}'; } if ('' + i === expandedName) { start = str.length; length = substr.length; str += substr; } else if (substr.length < 15 && str.length + substr.length < 40) { str += substr; } else { str += '{...}'; } } str += '</' + describeElementType(type) + '>'; } else { // Print Array str = '['; var _array = objectOrArray; for (var _i = 0; _i < _array.length; _i++) { if (_i > 0) { str += ', '; } var _value = _array[_i]; var _substr = void 0; if (typeof _value === 'object' && _value !== null) { _substr = describeObjectForErrorMessage(_value); } else { _substr = describeValueForErrorMessage(_value); } if ('' + _i === expandedName) { start = str.length; length = _substr.length; str += _substr; } else if (_substr.length < 10 && str.length + _substr.length < 40) { str += _substr; } else { str += '...'; } } str += ']'; } } else { if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { str = '<' + describeElementType(objectOrArray.type) + '/>'; } else if (jsxPropsParents.has(objectOrArray)) { // Print JSX var _type = jsxPropsParents.get(objectOrArray); str = '<' + (describeElementType(_type) || '...'); var object = objectOrArray; var names = Object.keys(object); for (var _i2 = 0; _i2 < names.length; _i2++) { str += ' '; var name = names[_i2]; str += describeKeyForErrorMessage(name) + '='; var _value2 = object[name]; var _substr2 = void 0; if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { _substr2 = describeObjectForErrorMessage(_value2); } else { _substr2 = describeValueForErrorMessage(_value2); } if (typeof _value2 !== 'string') { _substr2 = '{' + _substr2 + '}'; } if (name === expandedName) { start = str.length; length = _substr2.length; str += _substr2; } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { str += _substr2; } else { str += '...'; } } str += '>'; } else { // Print Object str = '{'; var _object = objectOrArray; var _names = Object.keys(_object); for (var _i3 = 0; _i3 < _names.length; _i3++) { if (_i3 > 0) { str += ', '; } var _name = _names[_i3]; str += describeKeyForErrorMessage(_name) + ': '; var _value3 = _object[_name]; var _substr3 = void 0; if (typeof _value3 === 'object' && _value3 !== null) { _substr3 = describeObjectForErrorMessage(_value3); } else { _substr3 = describeValueForErrorMessage(_value3); } if (_name === expandedName) { start = str.length; length = _substr3.length; str += _substr3; } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { str += _substr3; } else { str += '...'; } } str += '}'; } } if (expandedName === undefined) { return str; } if (start > -1 && length > 0) { var highlight = ' '.repeat(start) + '^'.repeat(length); return '\n ' + str + '\n ' + highlight; } return '\n ' + str; } var ContextRegistry = ReactSharedInternals.ContextRegistry; function getOrCreateServerContext(globalName) { if (!ContextRegistry[globalName]) { ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED); } return ContextRegistry[globalName]; } var stringify = JSON.stringify; // Serializable values // Thenable<ReactClientValue> var PENDING$1 = 0; var COMPLETED = 1; var ABORTED = 3; var ERRORED$1 = 4; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; function defaultErrorHandler(error) { console['error'](error); // Don't transform to our wrapper } var OPEN = 0; var CLOSING = 1; var CLOSED = 2; function createRequest(model, bundlerConfig, onError, context, identifierPrefix) { if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) { throw new Error('Currently React only supports one RSC renderer at a time.'); } prepareHostDispatcher(); ReactCurrentCache.current = DefaultCacheDispatcher; var abortSet = new Set(); var pingedTasks = []; var hints = createHints(); var request = { status: OPEN, flushScheduled: false, fatalError: null, destination: null, bundlerConfig: bundlerConfig, cache: new Map(), nextChunkId: 0, pendingChunks: 0, hints: hints, abortableTasks: abortSet, pingedTasks: pingedTasks, completedImportChunks: [], completedHintChunks: [], completedRegularChunks: [], completedErrorChunks: [], writtenSymbols: new Map(), writtenClientReferences: new Map(), writtenServerReferences: new Map(), writtenProviders: new Map(), identifierPrefix: identifierPrefix || '', identifierCount: 1, onError: onError === undefined ? defaultErrorHandler : onError, // $FlowFixMe[missing-this-annot] toJSON: function (key, value) { return resolveModelToJSON(request, this, key, value); } }; request.pendingChunks++; var rootContext = createRootContext(context); var rootTask = createTask(request, model, rootContext, abortSet); pingedTasks.push(rootTask); return request; } var currentRequest = null; function resolveRequest() { if (currentRequest) return currentRequest; { var store = requestStorage.getStore(); if (store) return store; } return null; } function createRootContext(reqContext) { return importServerContexts(reqContext); } var POP = {}; function serializeThenable(request, thenable) { request.pendingChunks++; var newTask = createTask(request, null, getActiveContext(), request.abortableTasks); switch (thenable.status) { case 'fulfilled': { // We have the resolved value, we can go ahead and schedule it for serialization. newTask.model = thenable.value; pingTask(request, newTask); return newTask.id; } case 'rejected': { var x = thenable.reason; var digest = logRecoverableError(request, x); { var _getErrorMessageAndSt = getErrorMessageAndStackDev(x), message = _getErrorMessageAndSt.message, stack = _getErrorMessageAndSt.stack; emitErrorChunkDev(request, newTask.id, digest, message, stack); } return newTask.id; } default: { if (typeof thenable.status === 'string') { // Only instrument the thenable if the status if not defined. If // it's defined, but an unknown value, assume it's been instrumented by // some custom userspace implementation. We treat it as "pending". break; } var pendingThenable = thenable; pendingThenable.status = 'pending'; pendingThenable.then(function (fulfilledValue) { if (thenable.status === 'pending') { var fulfilledThenable = thenable; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = fulfilledValue; } }, function (error) { if (thenable.status === 'pending') { var rejectedThenable = thenable; rejectedThenable.status = 'rejected'; rejectedThenable.reason = error; } }); break; } } thenable.then(function (value) { newTask.model = value; pingTask(request, newTask); }, function (reason) { newTask.status = ERRORED$1; // TODO: We should ideally do this inside performWork so it's scheduled var digest = logRecoverableError(request, reason); { var _getErrorMessageAndSt2 = getErrorMessageAndStackDev(reason), _message = _getErrorMessageAndSt2.message, _stack = _getErrorMessageAndSt2.stack; emitErrorChunkDev(request, newTask.id, digest, _message, _stack); } if (request.destination !== null) { flushCompletedChunks(request, request.destination); } }); return newTask.id; } function emitHint(request, code, model) { emitHintChunk(request, code, model); enqueueFlush(request); } function getHints(request) { return request.hints; } function getCache(request) { return request.cache; } function readThenable(thenable) { if (thenable.status === 'fulfilled') { return thenable.value; } else if (thenable.status === 'rejected') { throw thenable.reason; } throw thenable; } function createLazyWrapperAroundWakeable(wakeable) { // This is a temporary fork of the `use` implementation until we accept // promises everywhere. var thenable = wakeable; switch (thenable.status) { case 'fulfilled': case 'rejected': break; default: { if (typeof thenable.status === 'string') { // Only instrument the thenable if the status if not defined. If // it's defined, but an unknown value, assume it's been instrumented by // some custom userspace implementation. We treat it as "pending". break; } var pendingThenable = thenable; pendingThenable.status = 'pending'; pendingThenable.then(function (fulfilledValue) { if (thenable.status === 'pending') { var fulfilledThenable = thenable; fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = fulfilledValue; } }, function (error) { if (thenable.status === 'pending') { var rejectedThenable = thenable; rejectedThenable.status = 'rejected'; rejectedThenable.reason = error; } }); break; } } var lazyType = { $$typeof: REACT_LAZY_TYPE, _payload: thenable, _init: readThenable }; return lazyType; } function attemptResolveElement(request, type, key, ref, props, prevThenableState) { if (ref !== null && ref !== undefined) { // When the ref moves to the regular props object this will implicitly // throw for functions. We could probably relax it to a DEV warning for other // cases. throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.'); } { jsxPropsParents.set(props, type); if (typeof props.children === 'object' && props.children !== null) { jsxChildrenParents.set(props.children, type); } } if (typeof type === 'function') { if (isClientReference(type)) { // This is a reference to a Client Component. return [REACT_ELEMENT_TYPE, type, key, props]; } // This is a server-side component. prepareToUseHooksForComponent(prevThenableState); var result = type(props); if (typeof result === 'object' && result !== null && typeof result.then === 'function') { // When the return value is in children position we can resolve it immediately, // to its value without a wrapper if it's synchronously available. var thenable = result; if (thenable.status === 'fulfilled') { return thenable.value; } // TODO: Once we accept Promises as children