Unverified Commit b4f74ee1 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Handle async module for client components (#39953)

### Problem

esm modules imports from client components will be compiled to `m = import('module-name')` when webpack bundles them for server components flight rendering. In this case, they will all become async modules since dyanmic imports will return a promise which react flight cannot handle it then results into module resolving error on server flight rendering.

### Solution

* React flight renderer supports handling async modules in https://github.com/facebook/react/pull/25138
* On next.js side leverage the module proxy change for each client reference, to make sure it always resolve the correct client module

The idea is wrapping each module with a module proxy, and if the module is async and accessed as thenable, it will return a new module reference with `async` label to tell react to handle it as async modules:

exported client reference `*` --> not async module (non thenable) --> original module reference `''`
exported client reference `*` --> it's async module (thenable) --> wrapped module reference `'*'` with `async` label

### Note

Since we need to check if user having incorrect gSSP/gSP specifying in layout client componet, so we still need to parse it and assign those info to the proxy (Does client module containing `ssr`, `ssg` exports). Otherwise the proxy will return the cached module reference
parent 1b61d1f5
...@@ -177,8 +177,8 @@ ...@@ -177,8 +177,8 @@
"react-17": "npm:react@17.0.2", "react-17": "npm:react@17.0.2",
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-dom-17": "npm:react-dom@17.0.2", "react-dom-17": "npm:react-dom@17.0.2",
"react-dom-exp": "npm:react-dom@0.0.0-experimental-6ef466c68-20220816", "react-dom-exp": "npm:react-dom@0.0.0-experimental-0de3ddf56-20220825",
"react-exp": "npm:react@0.0.0-experimental-6ef466c68-20220816", "react-exp": "npm:react@0.0.0-experimental-0de3ddf56-20220825",
"react-ssr-prepass": "1.0.8", "react-ssr-prepass": "1.0.8",
"react-virtualized": "9.22.3", "react-virtualized": "9.22.3",
"relay-compiler": "13.0.2", "relay-compiler": "13.0.2",
......
...@@ -28,7 +28,7 @@ export interface PageStaticInfo { ...@@ -28,7 +28,7 @@ export interface PageStaticInfo {
* - Modules with `export function getStaticProps | getServerSideProps` * - Modules with `export function getStaticProps | getServerSideProps`
* - Modules with `export { getStaticProps | getServerSideProps } <from ...>` * - Modules with `export { getStaticProps | getServerSideProps } <from ...>`
*/ */
function checkExports(swcAST: any) { export function checkExports(swcAST: any): { ssr: boolean; ssg: boolean } {
if (Array.isArray(swcAST?.body)) { if (Array.isArray(swcAST?.body)) {
try { try {
for (const node of swcAST.body) { for (const node of swcAST.body) {
......
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { promisify } from 'util'
import { parse } from '../../swc'
import { buildExports, isNextBuiltinClientComponent } from './utils'
function addExportNames(names: string[], node: any) {
if (!node) return
switch (node.type) {
case 'Identifier':
names.push(node.value)
return
case 'ObjectPattern':
for (let i = 0; i < node.properties.length; i++)
addExportNames(names, node.properties[i])
return
case 'ArrayPattern':
for (let i = 0; i < node.elements.length; i++) {
const element = node.elements[i]
if (element) addExportNames(names, element)
}
return
case 'Property':
addExportNames(names, node.value)
return
case 'AssignmentPattern':
addExportNames(names, node.left)
return
case 'RestElement':
addExportNames(names, node.argument)
return
case 'ParenthesizedExpression':
addExportNames(names, node.expression)
return
default:
return
}
}
async function collectExports(
resourcePath: string,
transformedSource: string,
{
resolve,
loadModule,
}: {
resolve: (request: string) => Promise<string>
loadModule: (request: string) => Promise<string>
}
) {
const names: string[] = []
// Next.js built-in client components
if (isNextBuiltinClientComponent(resourcePath)) {
names.push('default')
}
const { body } = await parse(transformedSource, {
filename: resourcePath,
isModule: 'unknown',
})
for (let i = 0; i < body.length; i++) {
const node = body[i]
switch (node.type) {
case 'ExportDefaultExpression':
case 'ExportDefaultDeclaration':
names.push('default')
break
case 'ExportNamedDeclaration':
if (node.declaration) {
if (node.declaration.type === 'VariableDeclaration') {
const declarations = node.declaration.declarations
for (let j = 0; j < declarations.length; j++) {
addExportNames(names, declarations[j].id)
}
} else {
addExportNames(names, node.declaration.id)
}
}
if (node.specifiers) {
const specifiers = node.specifiers
for (let j = 0; j < specifiers.length; j++) {
addExportNames(names, specifiers[j].exported)
}
}
break
case 'ExportDeclaration':
if (node.declaration?.identifier) {
addExportNames(names, node.declaration.identifier)
}
break
case 'ExpressionStatement': {
const {
expression: { left },
} = node
// exports.xxx = xxx
if (
left?.object &&
left.type === 'MemberExpression' &&
left.object.type === 'Identifier' &&
left.object.value === 'exports'
) {
addExportNames(names, left.property)
}
break
}
case 'ExportAllDeclaration':
if (node.exported) {
addExportNames(names, node.exported)
break
}
const reexportedFromResourcePath = await resolve(node.source.value)
const reexportedFromResourceSource = await loadModule(
reexportedFromResourcePath
)
names.push(
...(await collectExports(
reexportedFromResourcePath,
reexportedFromResourceSource,
{ resolve, loadModule }
))
)
continue
default:
break
}
}
return names
}
export default async function transformSource(
this: any,
source: string
): Promise<string> {
const { resourcePath, resolve, loadModule, context } = this
const transformedSource = source
if (typeof transformedSource !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
const names = await collectExports(resourcePath, transformedSource, {
resolve: (...args) => promisify(resolve)(context, ...args),
loadModule: promisify(loadModule),
})
const moduleRefDef =
"const MODULE_REFERENCE = Symbol.for('react.module.reference');\n"
const isNextClientBuiltIn = isNextBuiltinClientComponent(resourcePath)
const clientRefsExports = names.reduce((res: any, name) => {
const moduleRef =
'{ $$typeof: MODULE_REFERENCE, filepath: ' +
JSON.stringify(resourcePath) +
', name: ' +
JSON.stringify(name === 'default' && isNextClientBuiltIn ? '' : name) +
' };\n'
res[name] = moduleRef
return res
}, {})
// still generate module references in ESM
const output = moduleRefDef + buildExports(clientRefsExports, true)
return output
}
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { checkExports } from '../../../analysis/get-page-static-info'
import { parse } from '../../../swc'
export default async function transformSource(
this: any,
source: string
): Promise<string> {
const { resourcePath } = this
const transformedSource = source
if (typeof transformedSource !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
const swcAST = await parse(transformedSource, {
filename: resourcePath,
isModule: 'unknown',
})
const { ssg, ssr } = checkExports(swcAST)
const output = `
const { createProxy } = require("next/dist/build/webpack/loaders/next-flight-client-loader/module-proxy")\n
module.exports = createProxy(${JSON.stringify(
resourcePath
)}, { ssr: ${ssr}, ssg: ${ssg} })
`
return output
}
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Modified from https://github.com/facebook/react/blob/main/packages/react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js
const MODULE_REFERENCE = Symbol.for('react.module.reference')
const PROMISE_PROTOTYPE = Promise.prototype
const proxyHandlers: ProxyHandler<object> = {
get: function (target: any, name: string, _receiver: any) {
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 'filepath':
return target.filepath
case 'name':
return target.name
case 'async':
return target.async
// We need to special case this because createElement reads it if we pass this
// reference.
case 'defaultProps':
return undefined
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.
target.default = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
// This a placeholder value that tells the client to conditionally use the
// whole object or just the default export.
name: '',
async: target.async,
ssr: target.ssr,
ssg: target.ssg,
}
return true
case '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.
const then = function then(
resolve: (res: any) => void,
_reject: (err: any) => void
) {
const moduleReference: Record<string, any> = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
name: '*', // Represents the whole object instead of a particular import.
async: true,
ssr: target.ssr,
ssg: target.ssg,
}
return Promise.resolve(
resolve(new Proxy(moduleReference, proxyHandlers))
)
}
// 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.
then.$$typeof = MODULE_REFERENCE
then.filepath = target.filepath
// then.name is conveniently already "then" which is the export name we need.
// This will break if it's minified though.
return then
}
break
case 'ssg':
return target.ssg
case 'ssr':
return target.ssr
default:
break
}
let cachedReference = target[name]
if (!cachedReference) {
cachedReference = target[name] = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
name: name,
async: target.async,
}
}
return cachedReference
},
getPrototypeOf(_target: object) {
// 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.')
},
}
export function createProxy(
moduleId: string,
{ ssr, ssg }: { ssr: boolean; ssg: boolean }
) {
const moduleReference = {
$$typeof: MODULE_REFERENCE,
filepath: moduleId,
name: '*', // Represents the whole object instead of a particular import.
async: false,
ssr,
ssg,
}
return new Proxy(moduleReference, proxyHandlers)
}
...@@ -36,7 +36,18 @@ function parseModel(response, json) { ...@@ -36,7 +36,18 @@ function parseModel(response, json) {
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
function resolveModuleReference(bundlerConfig, moduleData) { function resolveModuleReference(bundlerConfig, moduleData) {
if (bundlerConfig) { if (bundlerConfig) {
return bundlerConfig[moduleData.id][moduleData.name]; var resolvedModuleData = bundlerConfig[moduleData.id][moduleData.name];
if (moduleData.async) {
return {
id: resolvedModuleData.id,
chunks: resolvedModuleData.chunks,
name: resolvedModuleData.name,
async: true
};
} else {
return resolvedModuleData;
}
} }
return moduleData; return moduleData;
...@@ -45,11 +56,13 @@ function resolveModuleReference(bundlerConfig, moduleData) { ...@@ -45,11 +56,13 @@ function resolveModuleReference(bundlerConfig, moduleData) {
// in Webpack but unfortunately it's not exposed so we have to // in Webpack but unfortunately it's not exposed so we have to
// replicate it in user space. null means that it has already loaded. // replicate it in user space. null means that it has already loaded.
var chunkCache = new Map(); // Start preloading the modules since we might need them soon. var chunkCache = new Map();
var asyncModuleCache = new Map(); // Start preloading the modules since we might need them soon.
// This function doesn't suspend. // This function doesn't suspend.
function preloadModule(moduleData) { function preloadModule(moduleData) {
var chunks = moduleData.chunks; var chunks = moduleData.chunks;
var promises = [];
for (var i = 0; i < chunks.length; i++) { for (var i = 0; i < chunks.length; i++) {
var chunkId = chunks[i]; var chunkId = chunks[i];
...@@ -58,31 +71,62 @@ function preloadModule(moduleData) { ...@@ -58,31 +71,62 @@ function preloadModule(moduleData) {
if (entry === undefined) { if (entry === undefined) {
var thenable = globalThis.__next_chunk_load__(chunkId); var thenable = globalThis.__next_chunk_load__(chunkId);
promises.push(thenable);
var resolve = chunkCache.set.bind(chunkCache, chunkId, null); var resolve = chunkCache.set.bind(chunkCache, chunkId, null);
var reject = chunkCache.set.bind(chunkCache, chunkId); var reject = chunkCache.set.bind(chunkCache, chunkId);
thenable.then(resolve, reject); thenable.then(resolve, reject);
chunkCache.set(chunkId, thenable); chunkCache.set(chunkId, thenable);
} }
} }
if (moduleData.async) {
var modulePromise = Promise.all(promises).then(function () {
return globalThis.__next_require__(moduleData.id);
});
modulePromise.then(function (value) {
modulePromise.status = 'fulfilled';
modulePromise.value = value;
}, function (reason) {
modulePromise.status = 'rejected';
modulePromise.reason = reason;
});
asyncModuleCache.set(moduleData.id, modulePromise);
}
} // Actually require the module or suspend if it's not yet ready. } // Actually require the module or suspend if it's not yet ready.
// Increase priority if necessary. // Increase priority if necessary.
function requireModule(moduleData) { function requireModule(moduleData) {
var chunks = moduleData.chunks; var moduleExports;
if (moduleData.async) {
// We assume that preloadModule has been called before, which
// should have added something to the module cache.
var promise = asyncModuleCache.get(moduleData.id);
if (promise.status === 'fulfilled') {
moduleExports = promise.value;
} else if (promise.status === 'rejected') {
throw promise.reason;
} else {
throw promise;
}
} else {
var chunks = moduleData.chunks;
for (var i = 0; i < chunks.length; i++) { for (var i = 0; i < chunks.length; i++) {
var chunkId = chunks[i]; var chunkId = chunks[i];
var entry = chunkCache.get(chunkId); var entry = chunkCache.get(chunkId);
if (entry !== null) { if (entry !== null) {
// We assume that preloadModule has been called before. // We assume that preloadModule has been called before.
// So we don't expect to see entry being undefined here, that's an error. // So we don't expect to see entry being undefined here, that's an error.
// Let's throw either an error or the Promise. // Let's throw either an error or the Promise.
throw entry; throw entry;
}
} }
}
var moduleExports = globalThis.__next_require__(moduleData.id); moduleExports = globalThis.__next_require__(moduleData.id);
}
if (moduleData.name === '*') { if (moduleData.name === '*') {
// This is a placeholder value that represents that the caller imported this // This is a placeholder value that represents that the caller imported this
......
...@@ -7,13 +7,14 @@ ...@@ -7,13 +7,14 @@
* This source code is licensed under the MIT license found in the * This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
'use strict';var k=require("react"),l={stream:!0},n=new Map,p=Symbol.for("react.element"),q=Symbol.for("react.lazy"),r=Symbol.for("react.default_value"),t=k.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ContextRegistry;function u(a){t[a]||(t[a]=k.createServerContext(a,r));return t[a]}function v(a,b,c){this._status=a;this._value=b;this._response=c}v.prototype.then=function(a){0===this._status?(null===this._value&&(this._value=[]),this._value.push(a)):a()}; 'use strict';var h=require("react"),l={stream:!0},m=new Map,p=new Map;function q(a){for(var b=a.chunks,c=[],d=0;d<b.length;d++){var e=b[d];if(void 0===m.get(e)){var f=globalThis.__next_chunk_load__(e);c.push(f);var F=m.set.bind(m,e,null),k=m.set.bind(m,e);f.then(F,k);m.set(e,f)}}if(a.async){var g=Promise.all(c).then(function(){return globalThis.__next_require__(a.id)});g.then(function(a){g.status="fulfilled";g.value=a},function(a){g.status="rejected";g.reason=a});p.set(a.id,g)}}
function w(a){switch(a._status){case 3:return a._value;case 1:var b=JSON.parse(a._value,a._response._fromJSON);a._status=3;return a._value=b;case 2:b=a._value;for(var c=b.chunks,d=0;d<c.length;d++){var e=n.get(c[d]);if(null!==e)throw e;}c=globalThis.__next_require__(b.id);b="*"===b.name?c:""===b.name?c.__esModule?c.default:c:c[b.name];a._status=3;return a._value=b;case 0:throw a;default:throw a._value;}}function x(){var a=y(this,0);return w(a)}function z(a,b){return new v(3,b,a)} var r=Symbol.for("react.element"),t=Symbol.for("react.lazy"),u=Symbol.for("react.default_value"),v=h.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ContextRegistry;function w(a){v[a]||(v[a]=h.createServerContext(a,u));return v[a]}function x(a,b,c){this._status=a;this._value=b;this._response=c}x.prototype.then=function(a){0===this._status?(null===this._value&&(this._value=[]),this._value.push(a)):a()};
function A(a){if(null!==a)for(var b=0;b<a.length;b++)(0,a[b])()}function C(a,b){if(0===a._status){var c=a._value;a._status=4;a._value=b;A(c)}}function D(a,b){a._chunks.forEach(function(a){C(a,b)})}function y(a,b){var c=a._chunks,d=c.get(b);d||(d=new v(0,null,a),c.set(b,d));return d} function y(a){switch(a._status){case 3:return a._value;case 1:var b=JSON.parse(a._value,a._response._fromJSON);a._status=3;return a._value=b;case 2:b=a._value;if(b.async){var c=p.get(b.id);if("fulfilled"===c.status)c=c.value;else{if("rejected"===c.status)throw c.reason;throw c;}}else{c=b.chunks;for(var d=0;d<c.length;d++){var e=m.get(c[d]);if(null!==e)throw e;}c=globalThis.__next_require__(b.id)}b="*"===b.name?c:""===b.name?c.__esModule?c.default:c:c[b.name];a._status=3;return a._value=b;case 0:throw a;default:throw a._value;
function E(a,b,c){switch(c[0]){case "$":if("$"===c)return p;if("$"===c[1]||"@"===c[1])return c.substring(1);b=parseInt(c.substring(1),16);a=y(a,b);return w(a);case "@":return b=parseInt(c.substring(1),16),a=y(a,b),{$$typeof:q,_payload:a,_init:w}}return c}function F(a){D(a,Error("Connection closed."))} }}function z(){var a=A(this,0);return y(a)}function B(a,b){return new x(3,b,a)}function C(a){if(null!==a)for(var b=0;b<a.length;b++)(0,a[b])()}function D(a,b){if(0===a._status){var c=a._value;a._status=4;a._value=b;C(c)}}function E(a,b){a._chunks.forEach(function(a){D(a,b)})}function A(a,b){var c=a._chunks,d=c.get(b);d||(d=new x(0,null,a),c.set(b,d));return d}
function G(a,b){if(""!==b){var c=b[0],d=b.indexOf(":",1),e=parseInt(b.substring(1,d),16);d=b.substring(d+1);switch(c){case "J":b=a._chunks;(c=b.get(e))?0===c._status&&(a=c._value,c._status=1,c._value=d,A(a)):b.set(e,new v(1,d,a));break;case "M":b=a._chunks;c=b.get(e);d=JSON.parse(d,a._fromJSON);var f=a._bundlerConfig;d=f?f[d.id][d.name]:d;f=d.chunks;for(var h=0;h<f.length;h++){var g=f[h];if(void 0===n.get(g)){var B=globalThis.__next_chunk_load__(g),m=n.set.bind(n,g,null),J=n.set.bind(n,g);B.then(m,J);n.set(g, function G(a,b,c){switch(c[0]){case "$":if("$"===c)return r;if("$"===c[1]||"@"===c[1])return c.substring(1);b=parseInt(c.substring(1),16);a=A(a,b);return y(a);case "@":return b=parseInt(c.substring(1),16),a=A(a,b),{$$typeof:t,_payload:a,_init:y}}return c}function H(a){E(a,Error("Connection closed."))}
B)}}c?0===c._status&&(a=c._value,c._status=2,c._value=d,A(a)):b.set(e,new v(2,d,a));break;case "P":a._chunks.set(e,z(a,u(d).Provider));break;case "S":c=JSON.parse(d);a._chunks.set(e,z(a,Symbol.for(c)));break;case "E":b=JSON.parse(d);c=Error(b.message);c.stack=b.stack;b=a._chunks;(d=b.get(e))?C(d,c):b.set(e,new v(4,c,a));break;default:throw Error("Error parsing the data. It's probably an error code or network corruption.");}}} function I(a,b){if(""!==b){var c=b[0],d=b.indexOf(":",1),e=parseInt(b.substring(1,d),16);d=b.substring(d+1);switch(c){case "J":b=a._chunks;(c=b.get(e))?0===c._status&&(a=c._value,c._status=1,c._value=d,C(a)):b.set(e,new x(1,d,a));break;case "M":b=a._chunks;c=b.get(e);d=JSON.parse(d,a._fromJSON);var f=a._bundlerConfig;f&&(f=f[d.id][d.name],d=d.async?{id:f.id,chunks:f.chunks,name:f.name,async:!0}:f);q(d);c?0===c._status&&(a=c._value,c._status=2,c._value=d,C(a)):b.set(e,new x(2,d,a));break;case "P":a._chunks.set(e,
function H(a){return function(b,c){return"string"===typeof c?E(a,this,c):"object"===typeof c&&null!==c?(b=c[0]===p?{$$typeof:p,type:c[1],key:c[2],ref:null,props:c[3],_owner:null}:c,b):c}}function I(a){var b=new TextDecoder,c=new Map;a={_bundlerConfig:a,_chunks:c,readRoot:x,_partialRow:"",_stringDecoder:b};a._fromJSON=H(a);return a} B(a,w(d).Provider));break;case "S":c=JSON.parse(d);a._chunks.set(e,B(a,Symbol.for(c)));break;case "E":b=JSON.parse(d);c=Error(b.message);c.stack=b.stack;b=a._chunks;(d=b.get(e))?D(d,c):b.set(e,new x(4,c,a));break;default:throw Error("Error parsing the data. It's probably an error code or network corruption.");}}}
function K(a,b){function c(b){var h=b.value;if(b.done)F(a);else{b=h;h=a._stringDecoder;for(var g=b.indexOf(10);-1<g;){var f=a._partialRow;var m=b.subarray(0,g);m=h.decode(m);G(a,f+m);a._partialRow="";b=b.subarray(g+1);g=b.indexOf(10)}a._partialRow+=h.decode(b,l);return e.read().then(c,d)}}function d(b){D(a,b)}var e=b.getReader();e.read().then(c,d)}exports.createFromFetch=function(a,b){var c=I(b&&b.moduleMap?b.moduleMap:null);a.then(function(a){K(c,a.body)},function(a){D(c,a)});return c}; function J(a){return function(b,c){return"string"===typeof c?G(a,this,c):"object"===typeof c&&null!==c?(b=c[0]===r?{$$typeof:r,type:c[1],key:c[2],ref:null,props:c[3],_owner:null}:c,b):c}}function K(a){var b=new TextDecoder,c=new Map;a={_bundlerConfig:a,_chunks:c,readRoot:z,_partialRow:"",_stringDecoder:b};a._fromJSON=J(a);return a}
exports.createFromReadableStream=function(a,b){b=I(b&&b.moduleMap?b.moduleMap:null);K(b,a);return b}; function L(a,b){function c(b){var f=b.value;if(b.done)H(a);else{b=f;f=a._stringDecoder;for(var k=b.indexOf(10);-1<k;){var g=a._partialRow;var n=b.subarray(0,k);n=f.decode(n);I(a,g+n);a._partialRow="";b=b.subarray(k+1);k=b.indexOf(10)}a._partialRow+=f.decode(b,l);return e.read().then(c,d)}}function d(b){E(a,b)}var e=b.getReader();e.read().then(c,d)}exports.createFromFetch=function(a,b){var c=K(b&&b.moduleMap?b.moduleMap:null);a.then(function(a){L(c,a.body)},function(a){E(c,a)});return c};
exports.createFromXHR=function(a,b){function c(){for(var b=a.responseText,c=f,d=b.indexOf("\n",c);-1<d;)c=e._partialRow+b.substring(c,d),G(e,c),e._partialRow="",c=d+1,d=b.indexOf("\n",c);e._partialRow+=b.substring(c);f=b.length}function d(){D(e,new TypeError("Network error"))}var e=I(b&&b.moduleMap?b.moduleMap:null),f=0;a.addEventListener("progress",c);a.addEventListener("load",function(){c();F(e)});a.addEventListener("error",d);a.addEventListener("abort",d);a.addEventListener("timeout",d);return e}; exports.createFromReadableStream=function(a,b){b=K(b&&b.moduleMap?b.moduleMap:null);L(b,a);return b};
exports.createFromXHR=function(a,b){function c(){for(var b=a.responseText,c=f,d=b.indexOf("\n",c);-1<d;)c=e._partialRow+b.substring(c,d),I(e,c),e._partialRow="",c=d+1,d=b.indexOf("\n",c);e._partialRow+=b.substring(c);f=b.length}function d(){E(e,new TypeError("Network error"))}var e=K(b&&b.moduleMap?b.moduleMap:null),f=0;a.addEventListener("progress",c);a.addEventListener("load",function(){c();H(e)});a.addEventListener("error",d);a.addEventListener("abort",d);a.addEventListener("timeout",d);return e};
...@@ -244,7 +244,7 @@ ...@@ -244,7 +244,7 @@
"raw-body": "2.4.1", "raw-body": "2.4.1",
"react-is": "17.0.2", "react-is": "17.0.2",
"react-refresh": "0.12.0", "react-refresh": "0.12.0",
"react-server-dom-webpack": "0.0.0-experimental-d2c9e834a-20220601", "react-server-dom-webpack": "0.0.0-experimental-0de3ddf56-20220825",
"regenerator-runtime": "0.13.4", "regenerator-runtime": "0.13.4",
"sass-loader": "12.4.0", "sass-loader": "12.4.0",
"schema-utils2": "npm:schema-utils@2.7.1", "schema-utils2": "npm:schema-utils@2.7.1",
......
...@@ -642,13 +642,13 @@ export async function renderToHTMLOrFlight( ...@@ -642,13 +642,13 @@ export async function renderToHTMLOrFlight(
// Only server components can have getServerSideProps / getStaticProps // Only server components can have getServerSideProps / getStaticProps
// TODO-APP: friendly error with correct stacktrace. Potentially this can be part of the compiler instead. // TODO-APP: friendly error with correct stacktrace. Potentially this can be part of the compiler instead.
if (isClientComponentModule) { if (isClientComponentModule) {
if (layoutOrPageMod.getServerSideProps) { if (layoutOrPageMod.ssr) {
throw new Error( throw new Error(
'getServerSideProps is not supported on Client Components' 'getServerSideProps is not supported on Client Components'
) )
} }
if (layoutOrPageMod.getStaticProps) { if (layoutOrPageMod.ssg) {
throw new Error('getStaticProps is not supported on Client Components') throw new Error('getStaticProps is not supported on Client Components')
} }
} }
...@@ -765,7 +765,7 @@ export async function renderToHTMLOrFlight( ...@@ -765,7 +765,7 @@ export async function renderToHTMLOrFlight(
} }
// TODO-APP: pass a shared cache from previous getStaticProps/getServerSideProps calls? // TODO-APP: pass a shared cache from previous getStaticProps/getServerSideProps calls?
if (layoutOrPageMod.getServerSideProps) { if (!isClientComponentModule && layoutOrPageMod.getServerSideProps) {
// TODO-APP: recommendation for i18n // TODO-APP: recommendation for i18n
// locales: (renderOpts as any).locales, // always the same // locales: (renderOpts as any).locales, // always the same
// locale: (renderOpts as any).locale, // /nl/something -> nl // locale: (renderOpts as any).locale, // /nl/something -> nl
...@@ -789,7 +789,7 @@ export async function renderToHTMLOrFlight( ...@@ -789,7 +789,7 @@ export async function renderToHTMLOrFlight(
) )
} }
// TODO-APP: implement layout specific caching for getStaticProps // TODO-APP: implement layout specific caching for getStaticProps
if (layoutOrPageMod.getStaticProps) { if (!isClientComponentModule && layoutOrPageMod.getStaticProps) {
const getStaticPropsContext: const getStaticPropsContext:
| GetStaticPropsContext | GetStaticPropsContext
| GetStaticPropContextPage = { | GetStaticPropContextPage = {
......
This diff is collapsed.
...@@ -269,27 +269,13 @@ describe('app dir - react server components', () => { ...@@ -269,27 +269,13 @@ describe('app dir - react server components', () => {
expect(imageTag.attr('src')).toContain('data:image') expect(imageTag.attr('src')).toContain('data:image')
}) })
// TODO: support esm import for RSC it('should handle external async module libraries correctly', async () => {
if (isNextDev) {
// For prod build, the directory contains the build ID so it's not deterministic.
// Only enable it for dev for now.
it.skip('should not bundle external imports into client builds for RSC', async () => {
const html = await renderViaHTTP(next.url, '/external-imports')
expect(html).toContain('date:')
const distServerDir = path.join(distDir, 'static', 'chunks', 'pages')
const bundle = fs
.readFileSync(path.join(distServerDir, 'external-imports.js'))
.toString()
expect(bundle).not.toContain('non-isomorphic-text')
})
}
// TODO: support esm import for RSC
it.skip('should not pick browser field from package.json for external libraries', async () => {
const html = await renderViaHTTP(next.url, '/external-imports') const html = await renderViaHTTP(next.url, '/external-imports')
expect(html).toContain('isomorphic-export') expect(html).toContain('module type:esm-export')
expect(html).toContain('export named:named')
expect(html).toContain('export value:123')
expect(html).toContain('export array:4,5,6')
expect(html).toContain('export object:{x:1}')
}) })
it('should handle various kinds of exports correctly', async () => { it('should handle various kinds of exports correctly', async () => {
......
import getType, { named, value, array, obj } from 'non-isomorphic-text'
export default function Page() {
return (
<div>
<div>{`module type:${getType()}`}</div>
<div>{`export named:${named}`}</div>
<div>{`export value:${value}`}</div>
<div>{`export array:${array.join(',')}`}</div>
<div>{`export object:{x:${obj.x}}`}</div>
</div>
)
}
import nonIsomorphicText from 'non-isomorphic-text'
export default function Page() {
return (
<div>
<div>date:{nonIsomorphicText()}</div>
</div>
)
}
export default () => 'browser-field-export' export default () => 'browser-export'
export const named = 'named'
export const value = 123
export default () => 'esm-export'
export const named = 'named'
export const value = 123
export const array = [4, 5, 6]
export const obj = { x: 1 }
{ {
"name": "non-isomorphic-text", "name": "non-isomorphic-text",
"type": "module", "type": "module",
"main": "./index.js", "exports": "./index.mjs",
"browser": "./browser.js" "browser": "./browser.js"
} }
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