Unverified Commit b877de14 authored by Sebastian Markbåge's avatar Sebastian Markbåge Committed by GitHub

Enable progressive enhanced form actions through decodeAction (#49187)

This uses the new built-in progressive enhancement features of React.
These always use `multipart/form-data` atm. When one comes in that's not
a fetch, we can use `decodeAction` to get a resolved function.

This also ensures that we can test this by passing disableJavaScript to
tests. This disables JS for the context.
parent 83b774ee
...@@ -596,7 +596,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -596,7 +596,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
export * as serverHooks from 'next/dist/client/components/hooks-server-context' export * as serverHooks from 'next/dist/client/components/hooks-server-context'
export { renderToReadableStream, decodeReply } from 'react-server-dom-webpack/server.edge' export { renderToReadableStream, decodeReply, decodeAction } from 'react-server-dom-webpack/server.edge'
export const __next_app_webpack_require__ = __webpack_require__ export const __next_app_webpack_require__ = __webpack_require__
export { preloadStyle, preloadFont, preconnect } from 'next/dist/server/app-render/rsc/preloads' export { preloadStyle, preloadFont, preconnect } from 'next/dist/server/app-render/rsc/preloads'
......
...@@ -171,7 +171,7 @@ export async function handleAction({ ...@@ -171,7 +171,7 @@ export async function handleAction({
}): Promise<undefined | RenderResult | 'not-found'> { }): Promise<undefined | RenderResult | 'not-found'> {
let actionId = req.headers[ACTION.toLowerCase()] as string let actionId = req.headers[ACTION.toLowerCase()] as string
const contentType = req.headers['content-type'] const contentType = req.headers['content-type']
const isFormAction = const isURLEncodedAction =
req.method === 'POST' && contentType === 'application/x-www-form-urlencoded' req.method === 'POST' && contentType === 'application/x-www-form-urlencoded'
const isMultipartAction = const isMultipartAction =
req.method === 'POST' && contentType?.startsWith('multipart/form-data') req.method === 'POST' && contentType?.startsWith('multipart/form-data')
...@@ -181,7 +181,7 @@ export async function handleAction({ ...@@ -181,7 +181,7 @@ export async function handleAction({
typeof actionId === 'string' && typeof actionId === 'string' &&
req.method === 'POST' req.method === 'POST'
if (isFetchAction || isFormAction || isMultipartAction) { if (isFetchAction || isURLEncodedAction || isMultipartAction) {
let bound = [] let bound = []
const workerName = 'app' + pathname const workerName = 'app' + pathname
...@@ -210,7 +210,7 @@ export async function handleAction({ ...@@ -210,7 +210,7 @@ export async function handleAction({
await actionAsyncStorage.run({ isAction: true }, async () => { await actionAsyncStorage.run({ isAction: true }, async () => {
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
// Use react-server-dom-webpack/server.edge // Use react-server-dom-webpack/server.edge
const { decodeReply } = ComponentMod const { decodeReply, decodeAction } = ComponentMod
const webRequest = req as unknown as WebNextRequest const webRequest = req as unknown as WebNextRequest
if (!webRequest.body) { if (!webRequest.body) {
...@@ -220,7 +220,14 @@ export async function handleAction({ ...@@ -220,7 +220,14 @@ export async function handleAction({
if (isMultipartAction) { if (isMultipartAction) {
// TODO-APP: Add streaming support // TODO-APP: Add streaming support
const formData = await webRequest.request.formData() const formData = await webRequest.request.formData()
bound = await decodeReply(formData, serverModuleMap) if (isFetchAction) {
bound = await decodeReply(formData, serverModuleMap)
} else {
const action = await decodeAction(formData, serverModuleMap)
await action()
// Skip the fetch path
return
}
} else { } else {
let actionData = '' let actionData = ''
...@@ -234,16 +241,9 @@ export async function handleAction({ ...@@ -234,16 +241,9 @@ export async function handleAction({
actionData += new TextDecoder().decode(value) actionData += new TextDecoder().decode(value)
} }
if (isFormAction) { if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData) const formData = formDataFromSearchQueryString(actionData)
actionId = formData.get('$$id') as string bound = await decodeReply(formData, serverModuleMap)
if (!actionId) {
// Return if no action ID is found, it could be a regular POST request
return
}
formData.delete('$$id')
bound = [formData]
} else { } else {
bound = await decodeReply(actionData, serverModuleMap) bound = await decodeReply(actionData, serverModuleMap)
} }
...@@ -253,28 +253,41 @@ export async function handleAction({ ...@@ -253,28 +253,41 @@ export async function handleAction({
const { const {
decodeReply, decodeReply,
decodeReplyFromBusboy, decodeReplyFromBusboy,
decodeAction,
} = require(`react-server-dom-webpack/server.node`) } = require(`react-server-dom-webpack/server.node`)
if (isMultipartAction) { if (isMultipartAction) {
const busboy = require('busboy') if (isFetchAction) {
const bb = busboy({ headers: req.headers }) const busboy = require('busboy')
req.pipe(bb) const bb = busboy({ headers: req.headers })
req.pipe(bb)
bound = await decodeReplyFromBusboy(bb, serverModuleMap) bound = await decodeReplyFromBusboy(bb, serverModuleMap)
} else {
// React doesn't yet publish a busboy version of decodeAction
// so we polyfill the parsing of FormData.
const { Readable } = require('stream')
const UndiciRequest = require('next/dist/compiled/undici').Request
const fakeRequest = new UndiciRequest('http://localhost', {
method: 'POST',
headers: { 'Content-Type': req.headers['content-type'] },
body: Readable.toWeb(req),
duplex: 'half',
})
const formData = await fakeRequest.formData()
const action = await decodeAction(formData, serverModuleMap)
await action()
// Skip the fetch path
return
}
} else { } else {
const { parseBody } = const { parseBody } =
require('../api-utils/node') as typeof import('../api-utils/node') require('../api-utils/node') as typeof import('../api-utils/node')
const actionData = (await parseBody(req, '1mb')) || '' const actionData = (await parseBody(req, '1mb')) || ''
if (isFormAction) { if (isURLEncodedAction) {
actionId = actionData.$$id as string
if (!actionId) {
// Return if no action ID is found, it could be a regular POST request
return
}
const formData = formDataFromSearchQueryString(actionData) const formData = formDataFromSearchQueryString(actionData)
formData.delete('$$id') bound = await decodeReply(formData, serverModuleMap)
bound = [formData]
} else { } else {
bound = await decodeReply(actionData, serverModuleMap) bound = await decodeReply(actionData, serverModuleMap)
} }
...@@ -302,9 +315,7 @@ export async function handleAction({ ...@@ -302,9 +315,7 @@ export async function handleAction({
} }
}) })
if (actionResult) { return actionResult
return actionResult
}
} catch (err) { } catch (err) {
if (isRedirectError(err)) { if (isRedirectError(err)) {
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
......
...@@ -80,7 +80,10 @@ createNextDescribe( ...@@ -80,7 +80,10 @@ createNextDescribe(
}) })
it('should support notFound', async () => { it('should support notFound', async () => {
const browser = await next.browser('/server') const browser = await next.browser('/server', {
// TODO we should also test this with javascript on but not-found is not implemented yet.
disableJavaScript: true,
})
await browser.elementByCss('#nowhere').click() await browser.elementByCss('#nowhere').click()
......
...@@ -15,6 +15,11 @@ async function nowhere() { ...@@ -15,6 +15,11 @@ async function nowhere() {
notFound() notFound()
} }
async function here() {
'use server'
// nothing
}
async function file(formData) { async function file(formData) {
'use server' 'use server'
const file = formData.get('file') const file = formData.get('file')
...@@ -25,19 +30,20 @@ export default function Form() { ...@@ -25,19 +30,20 @@ export default function Form() {
return ( return (
<> <>
<hr /> <hr />
<form method="POST" action=""> <form action={action}>
<input type="text" name="$$id" value={action.$$id} hidden readOnly />
<input type="text" name="name" id="name" required /> <input type="text" name="name" id="name" required />
<button type="submit" id="submit"> <button type="submit" id="submit">
Submit Submit
</button> </button>
</form> </form>
<hr /> <hr />
<form method="POST" action=""> <form>
<input type="text" name="$$id" value={nowhere.$$id} hidden readOnly /> <button formAction={nowhere} type="submit" id="nowhere">
<button type="submit" id="nowhere">
Go nowhere Go nowhere
</button> </button>
<button formAction={here} type="submit" id="here">
Go here
</button>
</form> </form>
<hr /> <hr />
<form action={file}> <form action={file}>
......
...@@ -43,7 +43,11 @@ export class BrowserInterface implements PromiseLike<any> { ...@@ -43,7 +43,11 @@ export class BrowserInterface implements PromiseLike<any> {
}) })
} }
async setup(browserName: string, locale?: string): Promise<void> {} async setup(
browserName: string,
locale: string,
javaScriptEnabled: boolean
): Promise<void> {}
async close(): Promise<void> {} async close(): Promise<void> {}
async quit(): Promise<void> {} async quit(): Promise<void> {}
......
...@@ -15,6 +15,7 @@ import path from 'path' ...@@ -15,6 +15,7 @@ import path from 'path'
let page: Page let page: Page
let browser: Browser let browser: Browser
let context: BrowserContext let context: BrowserContext
let contextHasJSEnabled: boolean = true
let pageLogs: Array<{ source: string; message: string }> = [] let pageLogs: Array<{ source: string; message: string }> = []
let websocketFrames: Array<{ payload: string | Buffer }> = [] let websocketFrames: Array<{ payload: string | Buffer }> = []
...@@ -47,8 +48,7 @@ export class Playwright extends BrowserInterface { ...@@ -47,8 +48,7 @@ export class Playwright extends BrowserInterface {
this.eventCallbacks[event]?.delete(cb) this.eventCallbacks[event]?.delete(cb)
} }
async setup(browserName: string, locale?: string) { async setup(browserName: string, locale: string, javaScriptEnabled: boolean) {
if (browser) return
const headless = !!process.env.HEADLESS const headless = !!process.env.HEADLESS
let device let device
...@@ -62,8 +62,23 @@ export class Playwright extends BrowserInterface { ...@@ -62,8 +62,23 @@ export class Playwright extends BrowserInterface {
} }
} }
if (browser) {
if (contextHasJSEnabled !== javaScriptEnabled) {
// If we have switched from having JS enable/disabled we need to recreate the context.
await context?.close()
context = await browser.newContext({
locale,
javaScriptEnabled,
...device,
})
contextHasJSEnabled = javaScriptEnabled
}
return
}
browser = await this.launchBrowser(browserName, { headless }) browser = await this.launchBrowser(browserName, { headless })
context = await browser.newContext({ locale, ...device }) context = await browser.newContext({ locale, javaScriptEnabled, ...device })
contextHasJSEnabled = javaScriptEnabled
} }
async launchBrowser(browserName: string, launchOptions: Record<string, any>) { async launchBrowser(browserName: string, launchOptions: Record<string, any>) {
......
...@@ -46,7 +46,7 @@ export class Selenium extends BrowserInterface { ...@@ -46,7 +46,7 @@ export class Selenium extends BrowserInterface {
private browserName: string private browserName: string
// TODO: support setting locale // TODO: support setting locale
async setup(browserName: string, locale?: string) { async setup(browserName: string, locale: string, javaScriptEnabled: boolean) {
if (browser) return if (browser) return
this.browserName = browserName this.browserName = browserName
......
...@@ -61,6 +61,7 @@ export default async function webdriver( ...@@ -61,6 +61,7 @@ export default async function webdriver(
disableCache?: boolean disableCache?: boolean
beforePageLoad?: (page: any) => void beforePageLoad?: (page: any) => void
locale?: string locale?: string
disableJavaScript?: boolean
} }
): Promise<BrowserInterface> { ): Promise<BrowserInterface> {
let CurrentInterface: typeof BrowserInterface let CurrentInterface: typeof BrowserInterface
...@@ -77,6 +78,7 @@ export default async function webdriver( ...@@ -77,6 +78,7 @@ export default async function webdriver(
disableCache, disableCache,
beforePageLoad, beforePageLoad,
locale, locale,
disableJavaScript,
} = options } = options
// we import only the needed interface // we import only the needed interface
...@@ -96,7 +98,7 @@ export default async function webdriver( ...@@ -96,7 +98,7 @@ export default async function webdriver(
const browser = new CurrentInterface() const browser = new CurrentInterface()
const browserName = process.env.BROWSER_NAME || 'chrome' const browserName = process.env.BROWSER_NAME || 'chrome'
await browser.setup(browserName, locale) await browser.setup(browserName, locale, !disableJavaScript)
;(global as any).browserName = browserName ;(global as any).browserName = browserName
const fullUrl = getFullUrl( const fullUrl = getFullUrl(
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment