-
-
Notifications
You must be signed in to change notification settings - Fork 263
feat(rsc): ability to register server function via plugins #1310
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
Merged
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
124f6ea
refactor(rsc): track server reference claims
hi-ogawa e459dd7
test(rsc): cover custom server function claims
hi-ogawa 0b27517
docs(rsc): document custom server function example
hi-ogawa bc00015
refactor(rsc): extract server references manager
hi-ogawa eabc0c8
nit
hi-ogawa a93de80
test(rsc): cover custom server function proxies
hi-ogawa a7c6815
test(rsc): cover server reference claim hmr
hi-ogawa c74f1e3
test(rsc): align custom example with starter
hi-ogawa 7ace06b
test(rsc): cover progressive custom server forms
hi-ogawa a5ceee0
refactor(rsc): simplify server reference claims
hi-ogawa c652ea1
refactor(rsc): derive server reference metadata
hi-ogawa f4ae4fa
refactor(rsc): normalize server reference import ids
hi-ogawa b7fa005
refactor(rsc): expose server reference metadata map
hi-ogawa 44d73a3
refactor(rsc): add server reference lookup helper
hi-ogawa f36fe28
refactor(rsc): separate server reference claim deletion
hi-ogawa cfc6789
refactor(rsc): simplify server reference claim replacement
hi-ogawa de91c9b
refactor(rsc): simplify server reference claim map
hi-ogawa 0757c63
refactor(rsc): clarify server reference aggregation
hi-ogawa 2733cee
refactor(rsc): use plugin names as claim owners
hi-ogawa 577c4a9
refactor(rsc): expose plugin manager type
hi-ogawa 1bf72c2
test(rsc): localize server-only type suppression
hi-ogawa 44cea03
test(rsc): reset custom server function state
hi-ogawa af9c022
Merge origin/main into server-reference-claims
hi-ogawa a963851
fix(rsc): preserve server reference claim ids
hi-ogawa 7637970
test(rsc): clarify custom action ownership flow
hi-ogawa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import { expect, test, type Page } from '@playwright/test' | ||
| import { useFixture } from './fixture' | ||
| import { | ||
| expectNoPageError, | ||
| expectNoReload, | ||
| testNoJs, | ||
| waitForHydration, | ||
| } from './helper' | ||
|
|
||
| test.describe('dev-custom-server-function', () => { | ||
| const f = useFixture({ | ||
| root: 'examples/custom-server-function', | ||
| mode: 'dev', | ||
| }) | ||
| defineTest(f) | ||
|
|
||
| test('moves an action between custom and built-in ownership', async ({ | ||
| page, | ||
| }) => { | ||
| using _ = expectNoPageError(page) | ||
| await page.goto(f.url()) | ||
| await waitForHydration(page) | ||
| await using _noReload = await expectNoReload(page) | ||
|
|
||
| const editor = f.createEditor('src/features/mixed-directives/actions.ts') | ||
| // Switch one export from the custom plugin to the built-in plugin. HMR | ||
| // must remove the custom claim while preserving the module's other claims. | ||
| editor.edit((source) => | ||
| source | ||
| .replace(`'use custom-server'`, `'use server'`) | ||
| .replace( | ||
| `customLabel = 'Custom'`, | ||
| `customLabel = 'Custom changed to built-in'`, | ||
| ) | ||
| .replace('customCount++', 'customCount += 10'), | ||
| ) | ||
|
|
||
| await expect( | ||
| page.getByRole('button', { name: 'Custom changed to built-in: 0' }), | ||
| ).toBeVisible() | ||
| await page.getByRole('button', { name: 'Built-in: 0', exact: true }).click() | ||
| await expect( | ||
| page.getByRole('button', { name: 'Built-in: 1', exact: true }), | ||
| ).toBeVisible() | ||
| await page | ||
| .getByRole('button', { name: 'Custom changed to built-in: 0' }) | ||
| .click() | ||
| await expect( | ||
| page.getByRole('button', { name: 'Custom changed to built-in: 10' }), | ||
| ).toBeVisible() | ||
|
|
||
| // Switch the export back and verify neither owner retained stale state. | ||
| editor.reset() | ||
| await expect(page.getByRole('button', { name: 'Custom: 0' })).toBeVisible() | ||
| await page.getByRole('button', { name: 'Built-in: 0', exact: true }).click() | ||
| await expect( | ||
| page.getByRole('button', { name: 'Built-in: 1', exact: true }), | ||
| ).toBeVisible() | ||
| await page.getByRole('button', { name: 'Custom: 0' }).click() | ||
| await expect(page.getByRole('button', { name: 'Custom: 1' })).toBeVisible() | ||
| }) | ||
| }) | ||
|
|
||
| test.describe('build-custom-server-function', () => { | ||
| const f = useFixture({ | ||
| root: 'examples/custom-server-function', | ||
| mode: 'build', | ||
| }) | ||
| defineTest(f) | ||
| }) | ||
|
|
||
| function defineTest(f: ReturnType<typeof useFixture>) { | ||
| test('built-in and custom server functions', async ({ page }) => { | ||
| using _ = expectNoPageError(page) | ||
| await page.goto(f.url()) | ||
| await waitForHydration(page) | ||
| await testActions(page) | ||
| }) | ||
|
|
||
| testNoJs('progressive forms', async ({ page }) => { | ||
| await page.goto(f.url()) | ||
| await testActions(page) | ||
| }) | ||
|
|
||
| async function testActions(page: Page) { | ||
| // The first two actions are inline functions in one RSC-reachable module. | ||
| await page.getByRole('button', { name: 'Built-in: 0' }).click() | ||
| await expect( | ||
| page.getByRole('button', { name: 'Built-in: 1' }), | ||
| ).toBeVisible() | ||
|
|
||
| await page.getByRole('button', { name: 'Custom: 0' }).click() | ||
| await expect(page.getByRole('button', { name: 'Custom: 1' })).toBeVisible() | ||
|
|
||
| // This module is only imported by a Client Component, so its implementation | ||
| // reaches the RSC build through the aggregated server reference manifest. | ||
| await page.getByRole('button', { name: 'From client: 0' }).click() | ||
| await expect( | ||
| page.getByRole('button', { name: 'From client: 1' }), | ||
| ).toBeVisible() | ||
|
|
||
| await page.getByRole('button', { name: 'Reset' }).click() | ||
| await expect( | ||
| page.getByRole('button', { name: 'Built-in: 0' }), | ||
| ).toBeVisible() | ||
| await expect(page.getByRole('button', { name: 'Custom: 0' })).toBeVisible() | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
packages/plugin-rsc/examples/custom-server-function/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| # Custom Server Function | ||
|
|
||
| This example demonstrates a third-party Vite plugin implementing a custom `"use custom-server"` directive alongside the built-in `"use server"` directive. | ||
|
|
||
| ## Background | ||
|
|
||
| Server Function extensibility has two separate concerns: | ||
|
|
||
| - The directive owner transforms its syntax and registers the function with the React runtime. | ||
| - `@vitejs/plugin-rsc` owns bundler-level module identity, graph visibility, manifests, and reference resolution. | ||
|
|
||
| The custom plugin in [`custom-server-function-plugin.ts`](./custom-server-function-plugin.ts) transforms `"use custom-server"` and reports its exports as server reference claims. The RSC plugin aggregates those claims with its built-in `"use server"` claim instead of requiring one transform to own the entire module. This keeps custom syntax and metadata policy outside the RSC plugin while preserving a single canonical reference identity for the bundler. | ||
|
|
||
| The example separates two import graph shapes under [`src/features`](./src/features): | ||
|
|
||
| - `mixed-directives` exports inline built-in and custom Server Functions from one RSC-reachable module. | ||
| - `action-from-client` imports a module-level custom Server Function only from a Client Component. The custom plugin creates its client and SSR proxies, while the server reference manifest brings its implementation into the RSC build. | ||
|
|
||
| This is a low-level integration example rather than a proposed high-level Server Function API. | ||
|
|
||
| ## Current E2E Coverage | ||
|
|
||
| [`../../e2e/custom-server-function.test.ts`](../../e2e/custom-server-function.test.ts) verifies in both development and production build modes that: | ||
|
|
||
| - a built-in Server Function and a custom Server Function can coexist in one module | ||
| - each function reaches the server and updates the rendered result | ||
| - a custom Server Function that is not statically imported by the RSC entry works through both the SSR and client proxy paths | ||
| - built-in, inline custom, and client-imported custom functions work as progressively enhanced forms without JavaScript | ||
| - in development, an export can move from the custom owner to the built-in owner and back without reloading, losing the built-in claim, or retaining a conflicting stale claim |
103 changes: 103 additions & 0 deletions
103
packages/plugin-rsc/examples/custom-server-function/custom-server-function-plugin.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| import { getPluginApi, type RscPluginManager } from '@vitejs/plugin-rsc' | ||
| import { | ||
| hasDirective, | ||
| transformDirectiveProxyExport, | ||
| transformHoistInlineDirective, | ||
| transformWrapExport, | ||
| } from '@vitejs/plugin-rsc/transforms' | ||
| import { parseAstAsync, type Plugin } from 'vite' | ||
|
|
||
| const directive = 'use custom-server' | ||
| const pluginName = 'example:custom-server-function' | ||
|
|
||
| // This intentionally mirrors the built-in "use server" pipeline through the | ||
| // public integration APIs, but uses a separate directive and plugin name and | ||
| // omits export-all expansion and action encryption. | ||
| // TODO: Give the custom directive observable runtime semantics so ownership | ||
| // swaps can assert the active registration path in addition to claim cleanup. | ||
| export function customServerFunctionPlugin(): Plugin { | ||
| let manager: RscPluginManager | ||
|
|
||
| return { | ||
| name: pluginName, | ||
| configResolved(config) { | ||
| manager = getPluginApi(config)!.manager | ||
| }, | ||
| async transform(code, id) { | ||
| const environmentName = this.environment.name | ||
| if (!code.includes(directive)) { | ||
| manager.serverReferences.deleteClaim(pluginName, id) | ||
| return | ||
| } | ||
|
|
||
| const reference = manager.serverReferences.resolve(id, 'rsc') | ||
| const ast = (await parseAstAsync(code)) as unknown as Parameters< | ||
| typeof transformHoistInlineDirective | ||
| >[1] | ||
|
|
||
| if (environmentName === 'rsc') { | ||
| const runtime = (value: string, name: string) => | ||
| `$$CustomReactServer.registerServerReference(${value}, ${JSON.stringify(reference.referenceKey)}, ${JSON.stringify(name)})` | ||
| const result = hasDirective(ast.body, directive) | ||
| ? transformWrapExport(code, ast, { | ||
| runtime, | ||
| rejectNonAsyncFunction: true, | ||
| }) | ||
| : transformHoistInlineDirective(code, ast, { | ||
| directive, | ||
| runtime, | ||
| rejectNonAsyncFunction: true, | ||
| }) | ||
| if (!result.output.hasChanged()) { | ||
| manager.serverReferences.deleteClaim(pluginName, id) | ||
| return | ||
| } | ||
|
|
||
| manager.serverReferences.replaceClaim(pluginName, id, { | ||
| ...reference, | ||
| exportNames: 'names' in result ? result.names : result.exportNames, | ||
| }) | ||
| result.output.prepend( | ||
| `import * as $$CustomReactServer from "@vitejs/plugin-rsc/react/rsc/server";\n`, | ||
| ) | ||
| return { | ||
| code: result.output.toString(), | ||
| map: result.output.generateMap({ hires: 'boundary' }), | ||
| } | ||
| } | ||
|
|
||
| const result = transformDirectiveProxyExport(ast, { | ||
| code, | ||
| directive, | ||
| rejectNonAsyncFunction: true, | ||
| runtime: (name) => | ||
| `$$CustomReactClient.createServerReference(` + | ||
| `${JSON.stringify(reference.referenceKey + '#' + name)},` + | ||
| `$$CustomReactClient.callServer,` + | ||
| `undefined,` + | ||
| (this.environment.mode === 'dev' | ||
| ? `$$CustomReactClient.findSourceMapURL,` | ||
| : `undefined,`) + | ||
| `${JSON.stringify(name)})`, | ||
| }) | ||
| if (!result?.output.hasChanged()) { | ||
| manager.serverReferences.deleteClaim(pluginName, id) | ||
| return | ||
| } | ||
|
|
||
| manager.serverReferences.replaceClaim(pluginName, id, { | ||
| ...reference, | ||
| exportNames: result.exportNames, | ||
| }) | ||
| const runtimeEnvironment = | ||
| environmentName === 'client' ? 'browser' : 'ssr' | ||
| result.output.prepend( | ||
| `import * as $$CustomReactClient from "@vitejs/plugin-rsc/react/${runtimeEnvironment}";\n`, | ||
| ) | ||
| return { | ||
| code: result.output.toString(), | ||
| map: result.output.generateMap({ hires: 'boundary' }), | ||
| } | ||
| }, | ||
| } | ||
| } | ||
24 changes: 24 additions & 0 deletions
24
packages/plugin-rsc/examples/custom-server-function/package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| { | ||
| "name": "@vitejs/plugin-rsc-examples-custom-server-function", | ||
| "version": "0.0.0", | ||
| "private": true, | ||
| "license": "MIT", | ||
| "type": "module", | ||
| "scripts": { | ||
| "dev": "vite", | ||
| "build": "vite build", | ||
| "preview": "vite preview" | ||
| }, | ||
| "dependencies": { | ||
| "react": "^19.2.8", | ||
| "react-dom": "^19.2.8" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/react": "^19.2.17", | ||
| "@types/react-dom": "^19.2.3", | ||
| "@vitejs/plugin-react": "latest", | ||
| "@vitejs/plugin-rsc": "latest", | ||
| "rsc-html-stream": "^0.0.7", | ||
| "vite": "^8.1.4" | ||
| } | ||
| } |
8 changes: 8 additions & 0 deletions
8
...ages/plugin-rsc/examples/custom-server-function/src/features/action-from-client/action.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| 'use custom-server' | ||
|
|
||
| // @ts-ignore -- virtualized by @vitejs/plugin-rsc | ||
| import 'server-only' | ||
|
|
||
| export async function incrementFromClient(previous: number) { | ||
| return previous + 1 | ||
| } |
13 changes: 13 additions & 0 deletions
13
...ges/plugin-rsc/examples/custom-server-function/src/features/action-from-client/client.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| 'use client' | ||
|
|
||
| import { useActionState } from 'react' | ||
| import { incrementFromClient } from './action.ts' | ||
|
|
||
| export function ActionFromClient() { | ||
| const [count, action] = useActionState(incrementFromClient, 0) | ||
| return ( | ||
| <form action={action}> | ||
| <button>From client: {count}</button> | ||
| </form> | ||
| ) | ||
| } |
24 changes: 24 additions & 0 deletions
24
packages/plugin-rsc/examples/custom-server-function/src/features/mixed-directives/actions.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| let builtinCount = 0 | ||
| let customCount = 0 | ||
|
|
||
| export const customLabel = 'Custom' | ||
|
|
||
| export function getCounts() { | ||
| return { builtinCount, customCount } | ||
| } | ||
|
|
||
| export async function incrementBuiltin() { | ||
| 'use server' | ||
| builtinCount++ | ||
| } | ||
|
|
||
| export async function incrementCustom() { | ||
| 'use custom-server' | ||
| customCount++ | ||
| } | ||
|
|
||
| export async function resetCounts() { | ||
| 'use server' | ||
| builtinCount = 0 | ||
| customCount = 0 | ||
| } |
26 changes: 26 additions & 0 deletions
26
packages/plugin-rsc/examples/custom-server-function/src/features/mixed-directives/server.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import { | ||
| customLabel, | ||
| getCounts, | ||
| incrementBuiltin, | ||
| incrementCustom, | ||
| resetCounts, | ||
| } from './actions.ts' | ||
|
|
||
| export function MixedDirectives() { | ||
| const { builtinCount, customCount } = getCounts() | ||
| return ( | ||
| <> | ||
| <form action={incrementBuiltin}> | ||
| <button>Built-in: {builtinCount}</button> | ||
| </form> | ||
| <form action={incrementCustom}> | ||
| <button> | ||
| {customLabel}: {customCount} | ||
| </button> | ||
| </form> | ||
| <form action={resetCounts}> | ||
| <button>Reset</button> | ||
| </form> | ||
| </> | ||
| ) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.