Commit Graph

177 Commits

Author SHA1 Message Date
Colin McDonnell 56ffca8b9e
Add Bun streaming server renderer (#25597)
Add support for Bun server renderer
2022-11-17 13:15:56 -08:00
Andrew Clark f284d9fafa Track ThenableState alongside other hooks
Now that hook state is preserved while the work loop is suspended, we
don't need to track the thenable state in the work loop. We can track
it alongside the rest of the hook state.

This is a nice simplification and also aligns better with how it works
in Fizz and Flight.

The promises will still be cleared when the component finishes rendering
(either complete or unwind). In the future, we could stash the promises
on the fiber and reuse them during an update. However, this would only
work for `use` calls that occur before an prop/state/context is
processed, because `use` calls can only be assumed to execute in the
same order if no other props/state/context have changed. So it might not
be worth doing until we have finer grained memoization.
2022-11-17 14:48:42 -05:00
Andrew Clark 44c4e6f4dd
Force unwind work loop during selective hydration (#25695)
When an update flows into a dehydrated boundary, React cannot apply the
update until the boundary has finished hydrating. The way this currently
works is by scheduling a slightly higher priority task on the boundary,
using a special lane that's reserved only for this purpose. Because the
task is slightly higher priority, on the next turn of the work loop, the
Scheduler will force the work loop to yield (i.e. shouldYield starts
returning `true` because there's a higher priority task).

The downside of this approach is that it only works when time slicing is
enabled. It doesn't work for synchronous updates, because the
synchronous work loop does not consult the Scheduler on each iteration.

We plan to add support for selective hydration during synchronous
updates, too, so we need to model this some other way.

I've added a special internal exception that can be thrown to force the
work loop to interrupt the work-in-progress tree. Because it's thrown
from a React-only execution stack, throwing isn't strictly necessary —
we could instead modify some internal work loop state. But using an
exception means we don't need to check for this case on every iteration
of the work loop. So doing it this way moves the check out of the fast
path.

The ideal implementation wouldn't need to unwind the stack at all — we
should be able to hydrate the subtree and then apply the update all
within a single render phase. This is how we intend to implement it in
the future, but this requires a refactor to how we handle "stack"
variables, which are currently pushed to a per-render array. We need to
make this stack resumable, like how context works in Flight and Fizz.
2022-11-17 13:51:33 -05:00
Andrew Clark d2a0176a13
Detect and warn if use(promise) is wrapped with try/catch block (#25543)
The old (unstable) mechanism for suspending was to throw a promise. The
purpose of throwing is to interrupt the component's execution, and also
to signal to React that the interruption was caused by Suspense as
opposed to some other error.

A flaw is that throwing is meant to be an implementation detail — if
code in userspace catches the promise, it can lead to unexpected
behavior.

With `use`, userspace code does not throw promises directly, but `use`
itself still needs to throw something to interrupt the component and
unwind the stack.

The solution is to throw an internal error. In development, we can
detect whether the error was caught by a userspace try/catch block and
log a warning — though it's not foolproof, since a clever user could
catch the object and rethrow it later.

The error message includes advice to move `use` outside of the try/catch
block.

I did not yet implement the warning in Flight.
2022-10-28 17:46:03 -04:00
Sebastian Markbåge cce18e3504
[Flight] Use AsyncLocalStorage to extend the scope of the cache to micro tasks (#25542)
This extends the scope of the cache and fetch instrumentation using
AsyncLocalStorage for microtasks. This is an intermediate step. It sets
up the dispatcher only once. This is unique to RSC because it uses the
react.shared-subset module for its shared state.

Ideally we should support multiple renderers. We should also have this
take over from an outer SSR's instrumented fetch. We should also be able
to have a fallback to global state per request where AsyncLocalStorage
doesn't exist and then the whole client-side solutions. I'm still
figuring out the right wiring for that so this is a temporary hack.
2022-10-23 01:06:58 -04:00
Josh Story 973b90bdf6
[Float] support meta tags as Resources (#25514)
Stacked on #25508

This PR adds meta tags as a resource type.

metas are classified in the following priority

1. charset
2. http-equiv
3. property
4. name
5. itemprop

when using property, there is special logic for og type properties where
a `property="og:image:height"` following a `property="og:image"` will
inherit the key of the previous tag. this relies on timing effects to
stay consistent so when mounting new metas it is important that if
structured properties are being used all members of a structure mount
together. This is similarly true for arrays where the implicit
sequential order defines the array structure. if you need an array you
need to mount all array members in the same pass.
2022-10-21 15:21:29 -07:00
Andrew Clark 9cdf8a99ed
[Codemod] Update copyright header to Meta (#25315)
* Facebook -> Meta in copyright

rg --files | xargs sed -i 's#Copyright (c) Facebook, Inc. and its affiliates.#Copyright (c) Meta Platforms, Inc. and affiliates.#g'

* Manual tweaks
2022-10-18 11:19:24 -04:00
Samuel Susla 14072ce648
Add detach to Offscreen component (#25265) 2022-10-18 15:56:41 +01:00
Sebastian Markbåge bc358362a6
[Flight] Improve Error Messages when Invalid Object is Passed to Client/Host Components (#25492)
* Print built-in specific error message for toJSON

This is a better message for Date.

Also, format the message to highlight the affected prop.

* Describe error messages using JSX elements in DEV

We don't have access to the grand parent objects on the stack so we stash
them on weakmaps so we can access them while printing error messages.

Might be a bit slow.

* Capitalize Server/Client Component

* Special case errror messages for children of host components

These are likely meant to be text content if they're not a supported object.

* Update error messages
2022-10-16 21:49:17 -04:00
Sebastian Markbåge a8c16a0040
Split Cache into its own Dispatcher (#25474)
* Missing Hooks

* Remove www forks. These can use __SECRET... instead.

* Move cache to separate dispatcher

These will be available in more contexts than just render.
2022-10-12 23:13:39 -04:00
Josh Story 2cf4352e1c
Implement HostSingleton Fiber type (#25426) 2022-10-11 08:42:42 -07:00
Josh Story aa9988e5e6
Server render fork for react-dom (#25436)
Publish an aliasable entry for `react-dom` top level package exports for use in server environments. This is a stub containing only the exports that we expect to retain in the top level once 19 is released
2022-10-10 11:06:22 -07:00
Josh Story 2872a26e14
track resources in different roots separately (#25388)
* track resources in different roots separately

* flow types

* add test demonstrating portals deep into shadowRoots

* revert hostcontext changes

* lints

* funge style cache key a la ReactDOMComponentTree

* hide hacks in componentTree
2022-10-04 16:11:15 -07:00
Josh Story 7b25b961df
[Fizz/Float] Float for stylesheet resources (#25243)
* [Fizz/Float] Float for stylesheet resources

This commit implements Float in Fizz and on the Client. The initial set of supported APIs is roughly

1. Convert certain stylesheets into style Resources when opting in with precedence prop
2. Emit preloads for stylesheets and explicit preload tags
3. Dedupe all Resources by href
4. Implement ReactDOM.preload() to allow for imperative preloading
5. Implement ReactDOM.preinit() to allow for imperative preinitialization

Currently supports
1. style Resources (link rel "stylesheet")
2. font Resources (preload as "font")

later updates will include support for scripts and modules
2022-09-30 16:14:04 -07:00
dan 3de9264496
[Fizz] experimental_useEvent (#25325)
* [Fizz] useEvent

* Use same message on client and server
2022-09-27 20:42:16 +01:00
Josh Story efc6a08e98
[Flight] Implement error digests for Flight runtime and expose errorInfo in getDerivedStateFromError (#25302)
Similar to Fizz, Flight now supports a return value from the user provided onError option. If a value is returned from onError it will be serialized and provided to the client.

The digest is stashed on the constructed Error on the client as .digest
2022-09-23 13:19:29 -07:00
Lauren Tan c91a1e03be
experimental_useEvent (#25229)
This commit adds a new hook `useEvent` per the RFC [here](https://github.com/reactjs/rfcs/pull/220), gated as experimental. 

Co-authored-by: Rick Hanlon <rickhanlonii@gmail.com>
Co-authored-by: Rick Hanlon <rickhanlonii@fb.com>
Co-authored-by: Lauren Tan <poteto@users.noreply.github.com>
2022-09-14 11:39:06 -07:00
Sebastian Markbåge 8d1b057ec1
[Flight] Minor error handling fixes (#25151)
* Fix error handling when the Flight client itself errors

* Serialize references to errors in the error priority queue

It doesn't make sense to emit references to future values at higher pri
than the value that they're referencing.

This ensures that we don't emit hard forward references to values that
don't yet exist.
2022-08-31 18:40:17 -04:00
Andrew Clark b6978bc38f
experimental_use(promise) (#25084)
* Internal `act`: Unwrapping resolved promises

This update our internal implementation of `act` to support React's new
behavior for unwrapping promises. Like we did with Scheduler, when 
something suspends, it will yield to the main thread so the microtasks
can run, then continue in a new task.

I need to implement the same behavior in the public version of `act`,
but there are some additional considerations so I'll do that in a
separate commit.

* Move throwException to after work loop resumes

throwException is the function that finds the nearest boundary and
schedules it for a second render pass. We should only call it right 
before we unwind the stack — not if we receive an immediate ping and
render the fiber again.

This was an oversight in 8ef3a7c that I didn't notice because it happens
to mostly work, anyway. What made me notice the mistake is that
throwException also marks the entire render phase as suspended
(RootDidSuspend or RootDidSuspendWithDelay), which is only supposed to
be happen if we show a fallback. One consequence was that, in the 
RootDidSuspendWithDelay case, the entire commit phase was blocked,
because that's the exit status we use to block a bad fallback
from appearing.

* Use expando to check whether promise has resolved

Add a `status` expando to a thrown thenable to track when its value has
resolved.

In a later step, we'll also use `value` and `reason` expandos to track
the resolved value.

This is not part of the official JavaScript spec — think of
it as an extension of the Promise API, or a custom interface that is a
superset of Thenable. However, it's inspired by the terminology used
by `Promise.allSettled`.

The intent is that this will be a public API — Suspense implementations
can set these expandos to allow React to unwrap the value synchronously
without waiting a microtask.

* Scaffolding for `experimental_use` hook

Sets up a new experimental hook behind a feature flag, but does not
implement it yet.

* use(promise)

Adds experimental support to Fiber for unwrapping the value of a promise
inside a component. It is not yet implemented for Server Components, 
but that is planned.

If promise has already resolved, the value can be unwrapped
"immediately" without showing a fallback. The trick we use to implement
this is to yield to the main thread (literally suspending the work
loop), wait for the microtask queue to drain, then check if the promise
resolved in the meantime. If so, we can resume the last attempted fiber
without unwinding the stack. This functionality was implemented in 
previous commits.

Another feature is that the promises do not need to be cached between
attempts. Because we assume idempotent execution of components, React
will track the promises that were used during the previous attempt and
reuse the result. You shouldn't rely on this property, but during
initial render it mostly just works. Updates are trickier, though,
because if you used an uncached promise, we have no way of knowing 
whether the underlying data has changed, so we have to unwrap the
promise every time. It will still work, but it's inefficient and can
lead to unnecessary fallbacks if it happens during a discrete update.

When we implement this for Server Components, this will be less of an
issue because there are no updates in that environment. However, it's
still better for performance to cache data requests, so the same
principles largely apply.

The intention is that this will eventually be the only supported way to
suspend on arbitrary promises. Throwing a promise directly will
be deprecated.
2022-08-25 14:12:07 -04:00
Josh Story 6ef466c681
make preamble and postamble types explicit and fix typo (#25102) 2022-08-16 12:17:49 +01:00
Josh Story 796d31809b
Implement basic stylesheet Resources for react-dom (#25060)
Implement basic support for "Resources". In the context of this commit, the only thing that is currently a Resource are

<link rel="stylesheet" precedence="some-value" ...>

Resources can be rendered anywhere in the react tree, even outside of normal parenting rules, for instance you can render a resource before you have rendered the <html><head> tags for your application. In the stream we reorder this so the browser always receives valid HTML and resources are emitted either in place (normal circumstances) or at the top of the <head> (when you render them above or before the <head> in your react tree)

On the client, resources opt into an entirely different hydration path. Instead of matching the location within the Document these resources are queried for in the entire document. It is an error to have more than one resource with the same href attribute.

The use of precedence here as an opt-in signal for resourcifying the link is in preparation for a more complete Resource implementation which will dedupe resource references (multiple will be valid), hoist to the appropriate container (body, head, or elsewhere), order (according to precedence) and Suspend boundaries that depend on them. More details will come in the coming weeks on this plan.

This feature is gated by an experimental flag and will only be made available in experimental builds until some future time.
2022-08-12 13:27:53 -07:00
Andrew Clark 82e9e99098
Suspending inside a hidden tree should not cause fallbacks to appear (#24699)
* [FORKED] Hidden trees should capture Suspense

If something suspends inside a hidden tree, it should not affect
anything in the visible part of the UI. This means that Offscreen acts
like a Suspense boundary whenever it's in its hidden state.

* Add previous commit to forked revisions
2022-07-05 17:51:27 -04:00
Josh Story 9e3b772b8c
Update error transform to allow excluding errors inside subexpressions like ternaries (#24693)
* Update error transform to allow excluding errors inside subexpressions like ternaries

* make leadingcomments aggregation walk the expression stack
2022-06-08 16:59:49 -07:00
Josh Story b345523528
[Fizz] Support abort reasons (#24680)
* [Fizz] Support abort reasons

Fizz supports aborting the render but does not currently accept a reason. The various render functions that use Fizz have some automatic and some user-controlled abort semantics that can be useful to communicate with the running program and users about why an Abort happened.

This change implements abort reasons for renderToReadableStream and renderToPipeable stream as well as legacy renderers such as renderToString and related implementations.

For AbortController implementations the reason passed to the abort method is forwarded to Fizz and sent to the onError handler. If no reason is provided the AbortController should construct an AbortError DOMException and as a fallback Fizz will generate a similar error in the absence of a reason

For pipeable  streams, an abort function is returned alongside pipe which already accepted a reason. That reason is now forwarded to Fizz and the implementation described above.

For legacy renderers there is no exposed abort functionality but it is used internally and the reasons provided give useful context to, for instance to the fact that Suspense is not supported in renderToString-like renderers
2022-06-07 22:36:09 -07:00
Josh Story bcbeb52bf3
[Fizz] Disallow complex children in <title> elements (#24679)
* [Fizz] Disallow complex children in <title> elements

<title> Elements in the DOM can only have Text content. In Fizz if more than one text node is emitted an HTML comment node is used as a text separator. Unfortunately because of the content restriction of the DOM representation of the title element this separator is displayed as escaped text which is not what the component author intended.

This commit special cases title handling, primarily to issue warnings if you pass complex children to <title>. At the moment title expects to receive a single child or an array of length 1. In both cases the type of that child must be string or number. If anything more complex is provided a warning will be logged to the console explaining why this is problematic.

There is no runtime behavior change so broken things are still broken (e.g. returning two text nodes which will cause a separator or using Suspense inside title children) but they should at least be accompanied by warnings that are useful.

One edge case that will now warn but won't technically break an application is if you use a Component that returns a single string as a child of title. This is a form of indirection that works but becasue we cannot discriminate between a Component that will follow the rules and one that violates them the warning is issued regardless.

* fixup dev warning conditional logic

* lints

* fix bugs
2022-06-07 00:33:36 -07:00
Josh Story 4f29ba1cc5
support errorInfo in onRecoverableError (#24591)
* extend onRecoverableError API to support errorInfo

errorInfo has been used in Error Boundaries wiht componentDidCatch for a while now. To date this metadata only contained a componentStack. onRecoverableError only receives an error (type mixed) argument and thus providing additional error metadata was not possible without mutating user created mixed objects.

This change modifies rootConcurrentErrors rootRecoverableErrors, and hydrationErrors so all expect CapturedValue types. additionally a new factory function allows the creation of CapturedValues from a value plus a hash and stack.

In general, client derived CapturedValues will be created using the original function which derives a componentStack from a fiber and server originated CapturedValues will be created using with a passed in hash and optional componentStack.
2022-06-06 14:23:32 -07:00
Josh Story dd4950c90e
[Flight] Implement useId hook (#24172)
* Implements useId hook for Flight server.

The approach for ids for Flight is different from Fizz/Client where there is a need for determinancy. Flight rendered elements will not be rendered on the client and as such the ids generated in a request only need to be unique. However since FLight does support refetching subtrees it is possible a client will need to patch up a part of the tree rather than replacing the entire thing so it is not safe to use a simple incrementing counter. To solve for this we allow the caller to specify a prefix. On an initial fetch it is likely this will be empty but on refetches or subtrees we expect to have a client `useId` provide the prefix since it will guaranteed be unique for that subtree and thus for the entire tree. It is also possible that we will automatically provide prefixes based on a client/Fizz useId on refetches

in addition to the core change I also modified the structure of options for renderToReadableStream where `onError`, `context`, and the new `identifierPrefix` are properties of an Options object argument to avoid the clumsiness of a growing list of optional function arguments.

* defend against useId call outside of rendering

* switch to S from F for Server Component ids

* default to empty string identifier prefix

* Add a test demonstrating that there is no warning when double rendering on the client a server component that used useId

* lints and gates
2022-05-31 14:53:32 -07:00
Josh Story aec575914a
[Fizz] Send errors down to client (#24551)
* use return from onError

* export getSuspenseInstanceFallbackError

* stringToChunk

* return string from onError in downstream type signatures

* 1 more type

* support encoding errors in html stream and escape user input

This commit adds another way to get errors to the suspense instance by encoding them as dataset properties of a template element at the head of the boundary. Previously if there was an error before the boundary flushed there was no way to stream the error to the client because there would never be a client render instruction.

Additionally the error is sent in 3 parts

1) error hash - this is always sent (dev or prod) if one is provided
2) error message - Dev only
3) error component stack - Dev only, this now captures the stack at the point of error

Another item addressed in this commit is the escaping of potentially unsafe data. all error components are escaped as test for browers when written into the html and as javascript strings when written into a client render instruction.

* nits

Co-authored-by: Marco Salazar <salazarm@fb.com>
2022-05-29 23:07:10 -07:00
salazarm d5f1b067c8
[ServerContext] Flight support for ServerContext (#23244)
* Flight side of server context

* 1 more test

* rm unused function

* flow+prettier

* flow again =)

* duplicate ReactServerContext across packages

* store default value when lazily initializing server context

* .

* better comment

* derp... missing import

* rm optional chaining

* missed feature flag

* React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED ??

* add warning if non ServerContext passed into useServerContext

* pass context in as array of arrays

* make importServerContext nott pollute the global context state

* merge main

* remove useServerContext

* dont rely on object getters in ReactServerContext and disallow JSX

* add symbols to devtools + rename globalServerContextRegistry to just ContextRegistry

* gate test case as experimental

* feedback

* remove unions

* Lint

* fix oopsies (tests/lint/mismatching arguments/signatures

* lint again

* replace-fork

* remove extraneous change

* rebase

* 1 more test

* rm unused function

* flow+prettier

* flow again =)

* duplicate ReactServerContext across packages

* store default value when lazily initializing server context

* .

* better comment

* derp... missing import

* rm optional chaining

* missed feature flag

* React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED ??

* add warning if non ServerContext passed into useServerContext

* pass context in as array of arrays

* make importServerContext nott pollute the global context state

* merge main

* remove useServerContext

* dont rely on object getters in ReactServerContext and disallow JSX

* add symbols to devtools + rename globalServerContextRegistry to just ContextRegistry

* gate test case as experimental

* feedback

* remove unions

* Lint

* fix oopsies (tests/lint/mismatching arguments/signatures

* lint again

* replace-fork

* remove extraneous change

* rebase

* reinline

* rebase

* add back changes lost due to rebase being hard

* emit chunk for provider

* remove case for React provider type

* update type for SomeChunk

* enable flag with experimental

* add missing types

* fix flow type

* missing type

* t: any

* revert extraneous type change

* better type

* better type

* feedback

* change import to type import

* test?

* test?

* remove react-dom

* remove react-native-renderer from react-server-native-relay/package.json

* gate change in FiberNewContext, getComponentNameFromType, use switch statement in FlightServer

* getComponentNameFromTpe: server context type gated and use displayName if available

* fallthrough

* lint....

* POP

* lint
2022-03-08 07:55:32 -05:00
Andrew Clark 3a60844a0f
Update error message for suspending at sync priority (#23361)
Instead of adding a new Suspense boundary, the default recommendation
is to wrap the suspending update with startTransition.
2022-02-24 21:02:06 -05:00
Andrew Clark 52c393b5d2
Revert to client render on text mismatch (#23354)
* Refactor warnForTextDifference

We're going to fork the behavior of this function between concurrent
roots and legacy roots.

The legacy behavior is to warn in dev when the text mismatches during
hydration. In concurrent roots, we'll log a recoverable error and revert
to client rendering. That means this is no longer a development-only
function — it affects the prod behavior, too.

I haven't changed any behavior in this commit. I only rearranged the
code slightly so that the dev environment check is inside the body
instead of around the function call. I also threaded through an
isConcurrentMode argument.

* Revert to client render on text content mismatch

Expands the behavior of enableClientRenderFallbackOnHydrationMismatch to
check text content, too.

If the text is different from what was rendered on the server, we will
recover the UI by falling back to client rendering, up to the nearest
Suspense boundary.
2022-02-24 00:23:56 -05:00
Andrew Clark 51c8411d9d
Log a recoverable error whenever hydration fails (#23319)
There are several cases where hydration fails, server-rendered HTML is
discarded, and we fall back to client rendering. Whenever this happens,
we will now log an error with onRecoverableError, with a message
explaining why.

In some of these scenarios, this is not the only recoverable error that
is logged. For example, an error during hydration will cause hydration
to fail, which is itself an error. So we end up logging two separate
errors: the original error, and one that explains why hydration failed.

I've made sure that the original error always gets logged first, to
preserve the causal sequence.

Another thing we could do is aggregate the errors with the Error "cause"
feature and AggregateError. Since these are new-ish features in
JavaScript, we'd need a fallback behavior. I'll leave this for a
follow up.
2022-02-17 15:16:17 -05:00
salazarm 0ddd69d122
Throw on hydration mismatch and force client rendering if boundary hasn't suspended within concurrent root (#22629)
* Throw on hydration mismatch

* remove debugger

* update error message

* update error message part2...

* fix test?

* test? :(

* tests 4real

* remove useRefAccessWarning gating

* split markSuspenseBoundary and getNearestBoundary

* also assert html is correct

* replace-fork

* also remove client render flag on suspend

* replace-fork

* fix mismerge????
2021-11-09 13:40:50 -05:00
Andrew Clark 75f3ddebfa
Remove experimental useOpaqueIdentifier API (#22672)
useId is the updated version of this API.
2021-11-01 15:02:39 -07:00
Andrew Clark 7034408ff7
Follow-up improvements to error code extraction infra (#22516)
* Output FIXME during build for unminified errors

The invariant Babel transform used to output a FIXME comment if it
could not find a matching error code. This could happen if there were
a configuration mistake that caused an unminified message to
slip through.

Linting the compiled bundles is the most reliable way to do it because
there's not a one-to-one mapping between source modules and bundles. For
example, the same source module may appear in multiple bundles, some
which are minified and others which aren't.

This updates the transform to output the same messages for Error calls.

The source lint rule is still useful for catching mistakes during
development, to prompt you to update the error codes map before pushing
the PR to CI.

* Don't run error transform in development

We used to run the error transform in both production and development,
because in development it was used to convert `invariant` calls into
throw statements.

Now that don't use `invariant` anymore, we only have to run the
transform for production builds.

* Add ! to FIXME comment so Closure doesn't strip it

Don't love this solution because Closure could change this heuristic,
or we could switch to a differnt compiler that doesn't support it. But
it works.

Could add a bundle that contains an unminified error solely for the
purpose of testing it, but that seems like overkill.

* Alternate extract-errors that scrapes artifacts

The build script outputs a special FIXME comment when it fails to minify
an error message. CI will detect these comments and fail the workflow.

The comments also include the expected error message. So I added an
alternate extract-errors that scrapes unminified messages from the
build artifacts and updates `codes.json`.

This is nice because it works on partial builds. And you can also run it
after the fact, instead of needing build all over again.

* Disable error minification in more bundles

Not worth it because the number of errors does not outweight the size
of the formatProdErrorMessage runtime.

* Run extract-errors script in CI

The lint_build job already checks for unminified errors, but the output
isn't super helpful.

Instead I've added a new job that runs the extract-errors script and
fails the build if `codes.json` changes. It also outputs the expected
diff so you can easily see which messages were missing from the map.

* Replace old extract-errors script with new one

Deletes the old extract-errors in favor of extract-errors2
2021-10-31 15:37:32 -07:00
Sebastian Markbåge 579c008a75
[Fizz/Flight] pipeToNodeWritable(..., writable).startWriting() -> renderToPipeableStream(...).pipe(writable) (#22450)
* Rename pipeToNodeWritable to renderToNodePipe

* Add startWriting API to Flight

We don't really need it in this case because there's way less reason to
delay the stream in Flight.

* Pass the destination to startWriting instead of renderToNode

* Rename startWriting to pipe

This mirrors the ReadableStream API in Node

* Error codes

* Rename to renderToPipeableStream

This mimics the renderToReadableStream API for the browser.
2021-10-06 00:31:06 -04:00
Sebastian Markbåge 6485ef7472
Remove duplicate error code (#22513) 2021-10-05 19:59:46 -07:00
Andrew Clark a724a3b578
[RFC] Codemod invariant -> throw new Error (#22435)
* Hoist error codes import to module scope

When this code was written, the error codes map (`codes.json`) was
created on-the-fly, so we had to lazily require from inside the visitor.

Because `codes.json` is now checked into source, we can import it a
single time in module scope.

* Minify error constructors in production

We use a script to minify our error messages in production. Each message
is assigned an error code, defined in `scripts/error-codes/codes.json`.
Then our build script replaces the messages with a link to our
error decoder page, e.g. https://reactjs.org/docs/error-decoder.html/?invariant=92

This enables us to write helpful error messages without increasing the
bundle size.

Right now, the script only works for `invariant` calls. It does not work
if you throw an Error object. This is an old Facebookism that we don't
really need, other than the fact that our error minification script
relies on it.

So, I've updated the script to minify error constructors, too:

Input:
  Error(`A ${adj} message that contains ${noun}`);
Output:
  Error(formatProdErrorMessage(ERR_CODE, adj, noun));

It only works for constructors that are literally named Error, though we
could add support for other names, too.

As a next step, I will add a lint rule to enforce that errors written
this way must have a corresponding error code.

* Minify "no fallback UI specified" error in prod

This error message wasn't being minified because it doesn't use
invariant. The reason it didn't use invariant is because this particular
error is created without begin thrown — it doesn't need to be thrown
because it's located inside the error handling part of the runtime.

Now that the error minification script supports Error constructors, we
can minify it by assigning it a production error code in
`scripts/error-codes/codes.json`.

To support the use of Error constructors more generally, I will add a
lint rule that enforces each message has a corresponding error code.

* Lint rule to detect unminified errors

Adds a lint rule that detects when an Error constructor is used without
a corresponding production error code.

We already have this for `invariant`, but not for regular errors, i.e.
`throw new Error(msg)`. There's also nothing that enforces the use of
`invariant` besides convention.

There are some packages where we don't care to minify errors. These are
packages that run in environments where bundle size is not a concern,
like react-pg. I added an override in the ESLint config to ignore these.

* Temporarily add invariant codemod script

I'm adding this codemod to the repo temporarily, but I'll revert it
in the same PR. That way we don't have to check it in but it's still
accessible (via the PR) if we need it later.

* [Automated] Codemod invariant -> Error

This commit contains only automated changes:

npx jscodeshift -t scripts/codemod-invariant.js packages --ignore-pattern="node_modules/**/*"
yarn linc --fix
yarn prettier

I will do any manual touch ups in separate commits so they're easier
to review.

* Remove temporary codemod script

This reverts the codemod script and ESLint config I added temporarily
in order to perform the invariant codemod.

* Manual touch ups

A few manual changes I made after the codemod ran.

* Enable error code transform per package

Currently we're not consistent about which packages should have their
errors minified in production and which ones should.

This adds a field to the bundle configuration to control whether to
apply the transform. We should decide what the criteria is going
forward. I think it's probably a good idea to minify any package that
gets sent over the network. So yes to modules that run in the browser,
and no to modules that run on the server and during development only.
2021-09-30 12:01:28 -07:00
Andrew Clark d3e0869324
Make root.unmount() synchronous (#22444)
* Move flushSync warning to React DOM

When you call in `flushSync` from an effect, React fires a warning. I've
moved the implementation of this warning out of the reconciler and into
React DOM.

`flushSync` is a renderer API, not an isomorphic API, because it has
behavior that was designed specifically for the constraints of React
DOM. The equivalent API in a different renderer may not be the same.
For example, React Native has a different threading model than the
browser, so it might not make sense to expose a `flushSync` API to the
JavaScript thread.

* Make root.unmount() synchronous

When you unmount a root, the internal state that React stores on the
DOM node is immediately cleared. So, we should also synchronously
delete the React tree. You should be able to create a new root using
the same container.
2021-09-27 14:04:39 -07:00
Andrew Clark 79b8fc6670
Implement getServerSnapshot in userspace shim (#22359)
* Convert useSES shim tests to use React DOM

Idea is that eventually we'll run these tests against an actual build of
React DOM 17 to test backwards compatibility.

* Implement getServerSnapshot in userspace shim

If the DOM is not present, we assume that we are running in a server
environment and return the result of `getServerSnapshot`.

This heuristic doesn't work in React Native, so we'll need to provide
a separate native build (using the `.native` extension). I've left this
for a follow-up.

We can't call `getServerSnapshot` on the client, because in versions of
React before 18, there's no built-in mechanism to detect whether we're
hydrating. To avoid a server mismatch warning, users must account for
this themselves and return the correct value inside `getSnapshot`.

Note that none of this is relevant to the built-in API that is being
added in 18. This only affects the userspace shim that is provided
for backwards compatibility with versions 16 and 17.
2021-09-20 08:32:13 -07:00
Andrew Clark 86b3e2461d
Implement useSyncExternalStore on server (#22347)
Adds a third argument called `getServerSnapshot`.

On the server, React calls this one instead of the normal `getSnapshot`.
We also call it during hydration.

So it represents the snapshot that is used to generate the initial,
server-rendered HTML. The purpose is to avoid server-client mismatches.
What we render during hydration needs to match up exactly with what we
render on the server.

The pattern is for the server to send down a serialized copy of the
store that was used to generate the initial HTML. On the client, React
will call either `getSnapshot` or `getServerSnapshot` on the client as
appropriate, depending on whether it's currently hydrating.

The argument is optional for fully client rendered use cases. If the
user does attempt to omit `getServerSnapshot`, and the hook is called
on the server, React will abort that subtree on the server and
revert to client rendering, up to the nearest Suspense boundary.

For the userspace shim, we will need to use a heuristic (canUseDOM)
to determine whether we are in a server environment. I'll do that in
a follow up.
2021-09-20 08:31:02 -07:00
Shubham Pandey 6f3fcbd6fa
Some remaining instances of master to main (#21982)
Co-authored-by: Shubham Pandey <shubham.pandey@mfine.co>
2021-07-30 08:56:55 -04:00
Sebastian Markbåge 321087d134
[Fizz] Don't add aborted segments to the completedSegments list (#21976)
* Don't add aborted segments to the completedSegments list

* Update error message to include aborted status
2021-07-27 21:53:37 -04:00
Brian Vaughn d483463bc8
Updated scripts and config to replace "master" with "main" branch (#21768) 2021-06-29 14:26:24 -04:00
Andrew Clark bd0a963445
Throw when `act` is used in production (#21686)
Upgrades the deprecation warning to a runtime error.

I did it this way instead of removing the export so the type is the same
in both builds. It will get dead code eliminated regardless.
2021-06-16 16:29:51 -04:00
Sebastian Markbåge 7ec4c55971
createRoot(..., {hydrate:true}) -> hydrateRoot(...) (#21687)
This adds a new top level API for hydrating a root. It takes the initial
children as part of its constructor. These are unlike other render calls
in that they have to represent what the server sent and they can't be
batched with other updates.

I also changed the options to move the hydrationOptions to the top level
since now these options are all hydration options.

I kept the createRoot one just temporarily to make it easier to codemod
internally but I'm doing a follow up to delete.

As part of this I un-dried a couple of paths. ReactDOMLegacy was intended
to be built on top of the new API but it didn't actually use those root
APIs because there are special paths. It also doesn't actually use most of
the commmon paths since all the options are ignored. It also made it hard
to add only warnings for legacy only or new only code paths.

I also forked the create/hydrate paths because they're subtly different
since now the options are different. The containers are also different
because I now error for comment nodes during hydration which just doesn't
work at all but eventually we'll error for all createRoot calls.

After some iteration it might make sense to break out some common paths but
for now it's easier to iterate on the duplicates.
2021-06-15 13:37:53 -07:00
Sebastian Markbåge f4d7a0f1ea
Implement useOpaqueIdentifier (#21260)
The format of this ID is specific to the format.
2021-04-14 14:25:42 -07:00
Sebastian Markbåge 4f76a28c93
[Fizz] Implement New Context (#21255)
* Add NewContext module

This implements a reverse linked list tree containing the previous
contexts.

* Implement recursive algorithm

This algorithm pops the contexts back to a shared ancestor on the way down
the stack and then pushes new contexts in reverse order up the stack.

* Move isPrimaryRenderer to ServerFormatConfig

This is primarily intended to be used to support renderToString with a
separate build than the main one. This allows them to be nested.

* Wire up more element type matchers

* Wire up Context Provider type

* Wire up Context Consumer

* Test

* Implement reader in class

* Update error codez
2021-04-14 11:45:42 -07:00
Sebastian Markbåge b9e4c10e99
[Fizz] Implement all the DOM attributes and special cases (#21153)
* Implement DOM format config structure

* Styles

* Input warnings

* Textarea special cases

* Select special cases

* Option special cases

We read the currently selected value from the FormatContext.

* Warning for non-lower case HTML

We don't change to lower case at runtime anymore but keep the warning.

* Pre tags innerHTML needs to be prefixed

This is because if you do the equivalent on the client using innerHTML,
this is the effect you'd get.

* Extract errors
2021-03-31 17:39:38 -07:00
Sebastian Markbåge 32d6f39edd
[Fizz] Support special HTML/SVG/MathML tags to suspend (#21113)
* Encode tables as a special insertion mode

The table modes are special in that its children can't be created outside
a table context so we need the segment container to be wrapped in a table.

* Move formatContext from Task to Segment

It works the same otherwise. It's just that this context needs to outlive
the task so that I can use it when writing the segment.

* Use template tag for placeholders and inserted dummy nodes with IDs

These can be used in any parent. At least outside IE11. Not sure yet what
happens in IE11 to these.

Not sure if these are bad for perf since they're special nodes.

* Add special wrappers around inserted segments depending on their insertion mode

* Allow the root namespace to be configured

This allows us to insert the correct wrappers when streaming into an
existing non-HTML tree.

* Add comment
2021-03-27 10:50:38 -07:00