Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(react-router): add SerializesTo brand type #12264

Merged
merged 8 commits into from
Feb 12, 2025

Conversation

phryneas
Copy link
Contributor

Apart from the turbo-stream support for ReadableStream, this is the only other change that we would need to add support for preloading Apollo Client data during SSR in loader functions.

The problem here is that Apollo Client uses a branded type QueryRef<TData, TVariables> that looks like this:

export interface QueryRef<TData = unknown, TVariables = unknown> {
  /** @internal */
  [QUERY_REF_BRAND]?(variables: TVariables): TData;
}

We are using an "imaginary" function here to preserve variance when passing around the type - TVariables should be contravariant, so it is referenced as a method argument, while TData is covariant, so it is passed as a method return value.

This function doesn't really exist on the transport object and no other properties on it are typed, since the user should never interact with the object apart from passing it into a consuming useReadQuery(queryRef) hook in the browser.

Unfortunately, currently that QueryRef above is turned into { [QUERY_REF_BRAND]?: undefined }, since Serialize removes all functions.

This SerializesTo type would be an escape hatch to allow it for e.g. library authors to pass around branded values like this by specifying what the "serialized" result type should be.

So the preloadQuery function that we provide for loaders would return something of the type SerializesTo<QueryRef<TData, TVariables>>.

Copy link

changeset-bot bot commented Nov 12, 2024

🦋 Changeset detected

Latest commit: 0e5eecd

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
react-router Patch
@react-router/architect Patch
@react-router/cloudflare Patch
@react-router/dev Patch
react-router-dom Patch
@react-router/express Patch
@react-router/node Patch
@react-router/serve Patch
@react-router/fs-routes Patch
@react-router/remix-routes-option-adapter Patch
create-react-router Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@remix-cla-bot
Copy link
Contributor

remix-cla-bot bot commented Nov 12, 2024

Hi @phryneas,

Welcome, and thank you for contributing to React Router!

Before we consider your pull request, we ask that you sign our Contributor License Agreement (CLA). We require this only once.

You may review the CLA and sign it by adding your name to contributors.yml.

Once the CLA is signed, the CLA Signed label will be added to the pull request.

If you have already signed the CLA and received this response in error, or if you have any questions, please contact us at hello@remix.run.

Thanks!

- The Remix team

@remix-cla-bot
Copy link
Contributor

remix-cla-bot bot commented Nov 12, 2024

Thank you for signing the Contributor License Agreement. Let's get this merged! 🥳

@MichaelDeBoey MichaelDeBoey changed the title Add SerializesTo brand type. feat(react-router): add SerializesTo brand type Nov 13, 2024
Co-authored-by: Michaël De Boey <info@michaeldeboey.be>
@phryneas
Copy link
Contributor Author

phryneas commented Nov 25, 2024

Okay, seems like a lot of things moved in the last two weeks, did some merging and reorganizing.

Verified with a local build in apollographql/apollo-client-nextjs@2b56da6 (#394) that the type still works as expected.

@phryneas
Copy link
Contributor Author

phryneas commented Jan 9, 2025

At this time, this feature is ready on the Apollo side, so I would ask you to please give this a review, or at least some feedback, as this type change is the "missing piece" for us.

The whole PR can be seen here: apollographql/apollo-client-nextjs#394
This would be used in userland like this: https://github.com/apollographql/apollo-client-nextjs/blob/pr/react-router-7/integration-test/react-router/app/routes/home.tsx
You can see this "live" here: https://apolloc-git-ab15ba-apollo-client-next-package-integration-tests.vercel.app/ - a multipart graphql request is started during SSR in a loader, and both in SSR and in the browser, the results are merged into a normalized cache. You can see multiple chunks coming in slightly delayed, and as it is a client-side normalized cache, it can be live manipulated and refetched on the client without another server roundtrip (but navigation can merge more loader data in in the future).

@pcattori pcattori self-assigned this Jan 9, 2025
@timdorr timdorr removed the request for review from MichaelDeBoey January 9, 2025 19:02
@phryneas
Copy link
Contributor Author

@pcattori is there anything I can do from my side to help this move forward? Are there any open questions that you need answered?

* in your application.
*/
export type SerializesTo<T> = {
$__RR_SerializesTo?: [T];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@phryneas I was expecting $__RR_SerializesTo?: T without the wrapping []. Does wrapping in [] come with any benefits over unwrapped T?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's probably not a big deal, but It's slightly more safe around undefined:

{
  interface WithoutWrapping<T> {
    foo?: T;
  }

  type SerializesTo<T> = T extends WithoutWrapping<infer F> ? F : "other";

  type Test1 = SerializesTo<WithoutWrapping<number>>;
  //    ^?  type Test1 = number

  type Test2 = SerializesTo<WithoutWrapping<number|undefined>>;
  //    ^?  type Test2 = number | undefined

  // this could happen if for some reason the TS compiler inlines the `WithoutWrapping` type
  // when creating declarations for a third-party-package
  // an explicitly stated `undefined` would get lost
  type Test3 = SerializesTo<{ foo?: number|undefined }>;
  //    ^?  type Test3 = number
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you explain why the brand is optional in the first place?

Why not have:

export type SerializesTo<T> = {
  __ReactRouter_SerializesTo: T;
}

Copy link
Contributor Author

@phryneas phryneas Jan 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For assignability reasons - if it were non-optional you'd need an as any or as unknown when using it (example is obviously oversimplified):

type SerializesTo<T> = {
  __ReactRouter_SerializesTo?: [T];
};


const foo: number & SerializesTo<string> = 5

type SerializesToNonOptional<T> = {
  __ReactRouter_SerializesTo: [T];
};

// this errors
const bar: number & SerializesToNonOptional<string> = 5

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, just thinking of this - this is not actually there at runtime, so it keeps the type kinda "correct" in line with what you'd expect at runtime.

* in your application.
*/
export type SerializesTo<T> = {
$__RR_SerializesTo?: [T];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the $__ prefix a widely used convention? I was thinking of __ReactRouter_ prefix instead of $__RR_ just for increased clarity, but wasn't sure if there were conventions I'm unaware of

Copy link
Contributor Author

@phryneas phryneas Jan 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm perfectly fine with __ReactRouter_SerializesTo, too - I just hadn't seen any precedence and wanted to be extra sure :)

We use the $ (even with a space) in GraphQL because it's not allowed per spec for field names and we avoid collisions, but here it's not really necessary.

I'll fix this up to be __ReactRouter_SerializesTo later!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, made that change!

@phryneas phryneas requested a review from pcattori January 24, 2025 08:58
@pcattori
Copy link
Contributor

pcattori commented Feb 4, 2025

@phryneas just a quick update: I've been working on some type-safety improvements in #12752 . Just got to a good place there and will probably split up that PR into smaller PRs. The first of which will refactor the react-router/route-module package export to a new react-router/types package export. I think /types is probably a good home for the SerializesTo utility.

Once I have that in place, I'll push some commits to this PR to get it up-to-date with that; no need for you to do anything!

@phryneas
Copy link
Contributor Author

phryneas commented Feb 4, 2025

Okay, thank you for keeping me up to date @pcattori !

@pcattori
Copy link
Contributor

@phryneas ok I marked this API as unstable (with the unstable_ prefix) and moved the type util out of route-module (since that module is scoped solely towards type annotations for route module exports)

@pcattori pcattori merged commit 245cbd8 into remix-run:dev Feb 12, 2025
5 checks passed
@phryneas
Copy link
Contributor Author

Great, thank you!

Copy link
Contributor

🤖 Hello there,

We just published version 7.2.0-pre.2 which includes this pull request. If you'd like to take it for a test run please try it out and let us know what you think!

Thanks!

brophdawg11 pushed a commit that referenced this pull request Feb 17, 2025
* Add `SerializesTo` brand type.

* sign CLA

* Update .changeset/sour-avocados-lick.md

Co-authored-by: Michaël De Boey <info@michaeldeboey.be>

* change `__RR_SerializesTo` to `__ReactRouter_SerializesTo`

* mark `SerializesTo` as unstable

---------

Co-authored-by: Michaël De Boey <info@michaeldeboey.be>
Co-authored-by: Tim Dorr <timdorr@users.noreply.github.com>
Co-authored-by: Pedro Cattori <pcattori@gmail.com>
Copy link
Contributor

🤖 Hello there,

We just published version 7.2.0-pre.5 which includes this pull request. If you'd like to take it for a test run please try it out and let us know what you think!

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants