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

Fix client references extraction of CJS exports analysis #50059

Merged
merged 5 commits into from
May 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,26 @@ import type {
} from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack'

export function extractCjsExports(source: string) {
// In case the client entry is a CJS module, we need to parse all the exports
// to make sure that the flight manifest plugin can correctly generate the
// manifest.
// TODO: Currently SWC wraps CJS exports with `_export(exports, { ... })`,
// which is tricky to statically analyze. But since the shape is known, we
// use a regex to extract the exports as a workaround. See:
// https://github.com/swc-project/swc/blob/5629e6b5291b416c8316587b67b5e83d011a8c22/crates/swc_ecma_transforms_module/src/util.rs#L295

const matchExportObject = source.match(
/(?<=_export\(exports, {)(.*?)(?=}\);)/gs
)

if (matchExportObject) {
// Match the property name with format <property>: function() ...
return matchExportObject[0].match(/\b\w+(?=:)/g)
}
return null
}

/**
* A getter for module build info that casts to the type it should have.
* We also expose here types to make easier to use it.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getRSCModuleInformation } from '../../analysis/get-page-static-info'
import { getModuleBuildInfo } from './get-module-build-info'
import { getModuleBuildInfo, extractCjsExports } from './get-module-build-info'

export default async function transformSource(
this: any,
Expand All @@ -18,22 +18,8 @@ export default async function transformSource(
buildInfo.rsc = getRSCModuleInformation(source, false)

if (buildInfo.rsc.isClientRef) {
// In case the client entry is a CJS module, we need to parse all the exports
// to make sure that the flight manifest plugin can correctly generate the
// manifest.
// TODO: Currently SWC wraps CJS exports with `_export(exports, { ... })`,
// which is tricky to statically analyze. But since the shape is known, we
// use a regex to extract the exports as a workaround. See:
// https://github.com/swc-project/swc/blob/5629e6b5291b416c8316587b67b5e83d011a8c22/crates/swc_ecma_transforms_module/src/util.rs#L295
const matchExportObject = source.match(/\n_export\(exports, {([.\s\S]+)}/m)
if (matchExportObject) {
const matches: string[] = []
const matchExports = matchExportObject[1].matchAll(/([^\s]+):/g)
for (const match of matchExports) {
matches.push(match[1])
}
buildInfo.rsc.clientRefs = matches
}
const exportNames = extractCjsExports(source)
if (exportNames) buildInfo.rsc.clientRefs = exportNames
}

// This is a server action entry module in the client layer. We need to attach
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ export class ClientReferenceManifestPlugin {
].filter((name) => name !== null)

moduleExportedKeys.forEach((name) => {
const key = resource + '#' + name
const key = getClientReferenceModuleKey(resource, name)

// If the chunk is from `app/` chunkGroup, use it first.
// This make sure not to load the overlapped chunk from `pages/` chunkGroup
Expand Down
17 changes: 17 additions & 0 deletions test/e2e/app-dir/rsc-basic/rsc-basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,23 @@ createNextDescribe(
buildCommand: 'yarn build',
},
({ next, isNextDev, isNextStart }) => {
if (isNextDev) {
it('should have correct client references keys in manifest', async () => {
await next.render('/')
// Check that the client-side manifest is correct before any requests
const clientReferenceManifest = JSON.parse(
await next.readFile('.next/server/client-reference-manifest.json')
)
const clientModulesNames = Object.keys(
clientReferenceManifest.clientModules
)
clientModulesNames.every((name) => {
const [, key] = name.split('#')
return key === undefined || key === '' || key === 'default'
})
})
}

it('should correctly render page returning null', async () => {
const homeHTML = await next.render('/return-null/page')
const $ = cheerio.load(homeHTML)
Expand Down
30 changes: 30 additions & 0 deletions test/unit/get-module-build-info.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { extractCjsExports } from 'next/dist/build/webpack/loaders/get-module-build-info'

describe('extractCjsExports', () => {
it('should extract exports', () => {
const exportNames = extractCjsExports(`
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getServerActionDispatcher: function() {
return getServerActionDispatcher;
},
urlToUrlWithoutFlightMarker: function() {
return urlToUrlWithoutFlightMarker;
},
default: function() {
return AppRouter;
}
});
`)
expect(exportNames).toEqual([
'getServerActionDispatcher',
'urlToUrlWithoutFlightMarker',
'default',
])
})
})