Unverified Commit 17e0dab0 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

test: Add test for ESM and CJS exports of `next/*` APIs (#98882)

Assert the shape of those across ESM and CJS to prevent regressions in
the future
parent 2861a364
'use client'
import compatRouter, * as compatRouterEsm from 'next/compat/router'
import cache, * as cacheEsm from 'next/cache'
import client, * as clientEsm from 'next/client'
import ErrorComponent, * as errorEsm from 'next/error'
import * as navigationEsm from 'next/navigation'
import offline, * as offlineEsm from 'next/offline'
import webVitals, * as webVitalsEsm from 'next/web-vitals'
import {
describeEntry,
describeNamespaceEntry,
} from '../../../lib/export-matches'
const compatRouterCjs = require('next/compat/router')
const cacheCjs = require('next/cache')
const clientCjs = require('next/client')
const errorCjs = require('next/error')
const navigationCjs = require('next/navigation')
const offlineCjs = require('next/offline')
const webVitalsCjs = require('next/web-vitals')
// The client layer does not get the `.react-server` aliases, so `next/error`
// keeps its Pages Router default export and `next/navigation` exposes the full
// client navigation surface. Asserting both here is what pins the difference
// between the two layers.
const checks = {
cache: describeEntry(cache, cacheEsm, cacheCjs, ['unstable_cache']),
client: describeEntry(client, clientEsm, clientCjs, ['emitter', 'router']),
'compat/router': describeEntry(
compatRouter,
compatRouterEsm,
compatRouterCjs,
['useRouter']
),
error: describeEntry(ErrorComponent, errorEsm, errorCjs, []),
// The client layer gets the full navigation surface, including the hooks that
// the react-server variant deliberately omits.
navigation: describeNamespaceEntry(navigationEsm, navigationCjs, [
'useRouter',
'usePathname',
'useSearchParams',
'useParams',
'redirect',
'notFound',
]),
offline: describeEntry(offline, offlineEsm, offlineCjs, ['useOffline']),
'web-vitals': describeEntry(webVitals, webVitalsEsm, webVitalsCjs, [
'useReportWebVitals',
]),
}
// `next/root-params` requires compiler replacement, a root dynamic segment, and
// its experimental flag, so it cannot be meaningfully exercised by this fixture.
// `next/font/google` and `next/font/local` are compile-time transformed APIs, so
// runtime import identity checks do not apply to them.
export function ClientApiExportChecks() {
return Object.entries(checks).map(([name, shape]) => (
<li key={name} data-layer="client" data-api={name} data-shape={shape} />
))
}
import * as errorEsm from 'next/error'
import * as headersEsm from 'next/headers'
import * as navigationEsm from 'next/navigation'
import { apiExportChecks, describeEntry } from '../../../lib/api-exports'
import { ClientApiExportChecks } from './client'
const headersCjs = require('next/headers')
const errorCjs = require('next/error')
const navigationCjs = require('next/navigation')
// In the react-server layer `next/error` is aliased to `error.react-server`,
// which only exposes `catchError`, and `next/navigation` is aliased to
// `navigation.react-server`, which has no default export. Neither entry can be
// default-imported here, so both pass `undefined` as the default binding.
const checks = {
...apiExportChecks,
error: describeEntry(undefined, errorEsm, errorCjs, ['catchError']),
headers: describeEntry(undefined, headersEsm, headersCjs, [
'cookies',
'headers',
'draftMode',
]),
// `redirect` and `notFound` come from `navigation.react-server`, while
// `useRouter` is client-only and must NOT be present in this layer. The
// absence assertion below is what pins the react-server alias.
navigation: describeEntry(undefined, navigationEsm, navigationCjs, [
'redirect',
'permanentRedirect',
'notFound',
'forbidden',
'unauthorized',
]),
}
const clientOnlyNavigationExports = [
'useRouter',
'usePathname',
'useSearchParams',
'useParams',
'useSelectedLayoutSegment',
]
// Hooks that only exist in `navigation`, not `navigation.react-server`. If this
// is ever non-empty, the react-server layer resolved the client entry.
const leakedClientNavigationExports = clientOnlyNavigationExports
.filter((name) => name in navigationEsm)
.join(',')
export default function Page() {
return (
<ul>
<li data-leaked-client-navigation={leakedClientNavigationExports} />
{Object.entries(checks).map(([name, shape]) => (
<li
key={name}
data-layer="react-server"
data-api={name}
data-shape={shape}
/>
))}
<ClientApiExportChecks />
</ul>
)
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
describe('app-dir - esm js extension', () => { describe('app-dir - esm js extension', () => {
const { next } = nextTestSetup({ const { next, isTurbopack } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
...@@ -23,6 +23,207 @@ describe('app-dir - esm js extension', () => { ...@@ -23,6 +23,207 @@ describe('app-dir - esm js extension', () => {
expect($('head link[href="/test.js"]').length).toBe(1) expect($('head link[href="/test.js"]').length).toBe(1)
}) })
// Each entry records which module a `next/*` entrypoint resolved to in a given
// layer, so a change in aliasing or in what an entry exports shows up as a
// diff rather than a silent pass. `default` is the `import x from` binding,
// `namespace-default` the namespace's `default`, `absent-markers` any expected
// export the entry is missing, and `missing-from-cjs` any named export the
// CommonJS form lacks.
async function getApiExportShapes(pathname: string, layer?: string) {
const $ = await next.render$(pathname)
const selector = layer ? `[data-layer="${layer}"]` : '[data-api]'
const entries = $(selector)
.map((_index, element) => ({
name: $(element).attr('data-api'),
shape: $(element).attr('data-shape'),
}))
.get()
expect(entries.length).toBeGreaterThan(0)
return Object.fromEntries(entries.map(({ name, shape }) => [name, shape]))
}
it('should not expose client-only navigation hooks in the react-server layer', async () => {
const $ = await next.render$('/app/api-exports')
const leaked = $('[data-leaked-client-navigation]')
expect(leaked.length).toBe(1)
// `next/navigation` must resolve to `navigation.react-server` here, which
// omits the client hooks entirely.
expect(leaked.attr('data-leaked-client-navigation')).toBe('')
})
it('should preserve Pages Router API exports for ESM and CommonJS imports', async () => {
const shapes = await getApiExportShapes('/api-exports')
if (isTurbopack) {
expect(shapes).toMatchInlineSnapshot(`
{
"app": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"cache": "default namespace-default",
"client": "default namespace-default",
"compat/router": "default namespace-default",
"constants": "default namespace-default",
"document": "default namespace-default default-callable",
"dynamic": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"error": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"form": "default namespace-default cjs-is-own-default",
"head": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"image": "default namespace-default",
"legacy/image": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"link": "default namespace-default cjs-is-own-default",
"navigation": "default namespace-default",
"offline": "default namespace-default",
"og": "default namespace-default",
"script": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"server": "default namespace-default",
"web-vitals": "default namespace-default",
}
`)
} else {
expect(shapes).toMatchInlineSnapshot(`
{
"app": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"cache": "default",
"client": "",
"compat/router": "",
"constants": "",
"document": "default namespace-default default-callable",
"dynamic": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"error": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"form": "default namespace-default cjs-is-own-default",
"head": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"image": "default namespace-default",
"legacy/image": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"link": "default namespace-default cjs-is-own-default",
"navigation": "",
"offline": "",
"og": "",
"script": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"server": "",
"web-vitals": "",
}
`)
}
})
it('should preserve react-server layer API exports for ESM and CommonJS imports', async () => {
const shapes = await getApiExportShapes('/app/api-exports', 'react-server')
if (isTurbopack) {
expect(shapes).toMatchInlineSnapshot(`
{
"cache": "default namespace-default",
"constants": "default namespace-default",
"dynamic": "default namespace-default default-callable cjs-callable cjs-is-own-default absent-markers:noSSR",
"error": "",
"form": "default namespace-default default-callable",
"head": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"headers": "namespace-default",
"image": "default namespace-default default-callable",
"legacy/image": "default namespace-default default-callable",
"link": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"navigation": "",
"og": "default namespace-default",
"script": "default namespace-default default-callable absent-markers:handleClientScriptLoad,initScriptLoader",
"server": "default namespace-default",
}
`)
} else {
expect(shapes).toMatchInlineSnapshot(`
{
"cache": "default",
"constants": "",
"dynamic": "default namespace-default default-callable absent-markers:noSSR",
"error": "",
"form": "default namespace-default default-callable",
"head": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"headers": "",
"image": "default namespace-default default-callable",
"legacy/image": "default namespace-default default-callable",
"link": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"navigation": "",
"og": "",
"script": "default namespace-default default-callable absent-markers:handleClientScriptLoad,initScriptLoader",
"server": "",
}
`)
}
})
it('should preserve client layer API exports for ESM and CommonJS imports', async () => {
const shapes = await getApiExportShapes('/app/api-exports', 'client')
if (isTurbopack) {
expect(shapes).toMatchInlineSnapshot(`
{
"cache": "default namespace-default",
"client": "default namespace-default",
"compat/router": "default namespace-default",
"error": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"navigation": "default namespace-default",
"offline": "default namespace-default",
"web-vitals": "default namespace-default",
}
`)
} else {
expect(shapes).toMatchInlineSnapshot(`
{
"cache": "default",
"client": "",
"compat/router": "",
"error": "default namespace-default default-callable",
"navigation": "",
"offline": "",
"web-vitals": "",
}
`)
}
})
it('should preserve browser API exports for ESM and CommonJS imports', async () => {
const browser = await next.browser('/app/api-exports')
const shapes = await browser.eval(() =>
Object.fromEntries(
Array.from(
document.querySelectorAll('[data-layer="client"]'),
(element) => [
element.getAttribute('data-api'),
element.getAttribute('data-shape'),
]
)
)
)
if (isTurbopack) {
expect(shapes).toMatchInlineSnapshot(`
{
"cache": "default namespace-default",
"client": "default namespace-default",
"compat/router": "default namespace-default",
"error": "default namespace-default default-callable cjs-callable cjs-is-own-default",
"navigation": "default namespace-default",
"offline": "default namespace-default",
"web-vitals": "default namespace-default",
}
`)
} else {
expect(shapes).toMatchInlineSnapshot(`
{
"cache": "default",
"client": "",
"compat/router": "",
"error": "default namespace-default default-callable",
"navigation": "",
"offline": "",
"web-vitals": "",
}
`)
}
})
it('should be able to use nextjs api in pages router', async () => { it('should be able to use nextjs api in pages router', async () => {
const $ = await next.render$('/pages') const $ = await next.render$('/pages')
......
import cache, * as cacheEsm from 'next/cache'
import * as constantsEsm from 'next/constants'
import dynamic, * as dynamicEsm from 'next/dynamic'
import Form, * as formEsm from 'next/form'
import Head, * as headEsm from 'next/head'
import Image, * as imageEsm from 'next/image'
import LegacyImage, * as legacyImageEsm from 'next/legacy/image'
import Link, * as linkEsm from 'next/link'
import * as ogEsm from 'next/og'
import Script, * as scriptEsm from 'next/script'
import * as serverEsm from 'next/server'
import { describeEntry, describeNamespaceEntry } from './export-matches'
export { describeEntry }
// `next/error` and `next/navigation` are intentionally absent here: they are
// aliased to `.react-server` variants in the react-server layer, so their shape
// differs per layer and each entrypoint asserts them separately.
//
// Read optional defaults from the namespace for entries that do not declare a
// default export. A syntactic default import makes webpack emit an export
// warning even though some bundlers synthesize a default at runtime.
export const apiExportChecks = {
cache: describeEntry(cache, cacheEsm, require('next/cache'), [
'unstable_cache',
'revalidateTag',
'cacheLife',
]),
constants: describeNamespaceEntry(constantsEsm, require('next/constants'), [
'PHASE_PRODUCTION_BUILD',
'PHASE_DEVELOPMENT_SERVER',
]),
dynamic: describeEntry(dynamic, dynamicEsm, require('next/dynamic'), [
'noSSR',
]),
form: describeEntry(Form, formEsm, require('next/form'), []),
head: describeEntry(Head, headEsm, require('next/head'), []),
image: describeEntry(Image, imageEsm, require('next/image'), [
'getImageProps',
]),
'legacy/image': describeEntry(
LegacyImage,
legacyImageEsm,
require('next/legacy/image'),
[]
),
link: describeEntry(Link, linkEsm, require('next/link'), ['useLinkStatus']),
og: describeNamespaceEntry(ogEsm, require('next/og'), ['ImageResponse']),
script: describeEntry(Script, scriptEsm, require('next/script'), [
'handleClientScriptLoad',
'initScriptLoader',
]),
server: describeNamespaceEntry(serverEsm, require('next/server'), [
'NextRequest',
'NextResponse',
'after',
'connection',
]),
}
// Next.js resolves its public entrypoints differently per bundler layer, so the
// *shape* of a given entry is not uniform. `next/navigation` has no default
// export, `next/error` collapses to just `catchError` in the react-server
// layer, and `next/link` resolves to a different component in the App Router
// than in the Pages Router. These helpers describe the observed surface of an
// entry so each layer can assert its own expected shape instead of assuming one
// shared contract.
// `default` is checked separately, `__esModule` is the CommonJS interop marker,
// and `then`/`catch`/`finally` are thenable members that client-reference
// proxies expose in the react-server layer. None of them are public API.
const NON_API_EXPORTS = new Set([
'default',
'__esModule',
'then',
'catch',
'finally',
])
// Returns the public named exports exposed by an ESM namespace.
function getNamedExports(esmNamespace) {
return Object.keys(esmNamespace).filter(
(exportName) => !NON_API_EXPORTS.has(exportName)
)
}
// Checks export presence without requiring a value to be defined. Some public
// exports, such as `next/client`'s router, are intentionally undefined early in
// the module lifecycle.
function hasExport(object, exportName) {
return object != null && exportName in Object(object)
}
// Describes which module an entrypoint resolved to, as a stable string.
//
// `markers` is a curated list of exports that identify the target module, so a
// change in aliasing (for example the react-server variant of `next/navigation`
// no longer being used) shows up as a diff. The full `Object.keys` listing is
// deliberately not snapshotted: it picks up incidental members such as a
// component's `displayName` in development, or `__nextScript` under one
// bundler, which would make the snapshot churn without describing the API.
//
// `defaultBinding` is the `import x from '...'` form. It is passed in (rather
// than read off the namespace) so the binding is genuinely used: an unused
// default import is elided by the bundler, which would silently drop the
// build-time coverage that default-importing a default-less entry is an error.
export function describeEntry(defaultBinding, esmNamespace, commonJs, markers) {
const named = getNamedExports(esmNamespace)
const absentMarkers = markers
.filter((marker) => !hasExport(esmNamespace, marker))
.join(',')
const missingFromCjs = named
.filter((exportName) => !hasExport(commonJs, exportName))
.join(',')
return [
defaultBinding !== undefined ? `default` : undefined,
// Both ESM import forms must agree on whether a default export exists.
esmNamespace.default !== undefined ? `namespace-default` : undefined,
// Whether the value itself is callable. Entries whose primary export is a
// function -- `next/dynamic`, `next/head`, `next/script` -- are callable
// directly off `require()`, so `const dynamic = require('next/dynamic')`
// followed by `dynamic(...)` works. Collapsing one of those to a plain
// `{ default }` object would break that call without removing any export,
// so presence checks alone cannot catch it.
typeof defaultBinding === 'function' ? `default-callable` : undefined,
typeof commonJs === 'function' ? `cjs-callable` : undefined,
// For those entries `module.exports` is the function *and* carries a
// self-referencing `.default`, which is what lets the same module serve
// `require()` and `import` callers.
commonJs !== undefined && commonJs === commonJs.default
? `cjs-is-own-default`
: undefined,
// Markers the entry is missing. Expected to be empty for every entry.
absentMarkers ? `absent-markers:${absentMarkers}` : undefined,
// Named exports ESM exposes but CommonJS does not. Expected to be empty:
// the two forms must agree on the surface even where the bundler hands out
// distinct wrapper objects.
missingFromCjs ? `missing-from-cjs:${missingFromCjs}` : undefined,
]
.filter(Boolean)
.join(' ')
}
// Use this for entrypoints that do not statically declare a default export.
// Accessing `namespace.default` at the import site makes webpack request that
// export and emit a warning. Looking it up through an ordinary function
// parameter still records a synthesized runtime default when one exists.
export function describeNamespaceEntry(esmNamespace, commonJs, markers) {
return describeEntry(esmNamespace.default, esmNamespace, commonJs, markers)
}
import App, * as appEsm from 'next/app'
import client, * as clientEsm from 'next/client'
import Document, * as documentEsm from 'next/document'
import ErrorComponent, * as errorEsm from 'next/error'
import navigation, * as navigationEsm from 'next/navigation'
import compatRouter, * as compatRouterEsm from 'next/compat/router'
import offline, * as offlineEsm from 'next/offline'
import webVitals, * as webVitalsEsm from 'next/web-vitals'
import { apiExportChecks, describeEntry } from '../lib/api-exports'
const appCjs = require('next/app')
const clientCjs = require('next/client')
const documentCjs = require('next/document')
const errorCjs = require('next/error')
const navigationCjs = require('next/navigation')
const compatRouterCjs = require('next/compat/router')
const offlineCjs = require('next/offline')
const webVitalsCjs = require('next/web-vitals')
// `next/router` is exercised in the browser check instead: its default export is
// a client-side singleton whose property access throws when read on the server.
export async function getServerSideProps() {
return {
props: {
checks: {
...apiExportChecks,
app: describeEntry(App, appEsm, appCjs, []),
client: describeEntry(client, clientEsm, clientCjs, [
'emitter',
'router',
]),
document: describeEntry(Document, documentEsm, documentCjs, [
'Html',
'Head',
'Main',
'NextScript',
]),
// The Pages Router never gets the `.react-server` aliases, so
// `next/error` keeps its `_error` default export here.
error: describeEntry(ErrorComponent, errorEsm, errorCjs, []),
navigation: describeEntry(navigation, navigationEsm, navigationCjs, [
'useRouter',
'usePathname',
'redirect',
'notFound',
]),
'compat/router': describeEntry(
compatRouter,
compatRouterEsm,
compatRouterCjs,
['useRouter']
),
offline: describeEntry(offline, offlineEsm, offlineCjs, ['useOffline']),
'web-vitals': describeEntry(webVitals, webVitalsEsm, webVitalsCjs, [
'useReportWebVitals',
]),
},
},
}
}
export default function Page({ checks }) {
return (
<ul>
{Object.entries(checks).map(([name, shape]) => (
<li key={name} data-api={name} data-shape={shape} />
))}
</ul>
)
}
...@@ -16,6 +16,7 @@ if (!(globalThis as any).isNextStart) { ...@@ -16,6 +16,7 @@ if (!(globalThis as any).isNextStart) {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: { files: {
app: new FileRef(path.join(__dirname, 'app')), app: new FileRef(path.join(__dirname, 'app')),
lib: new FileRef(path.join(__dirname, 'lib')),
pages: new FileRef(path.join(__dirname, 'pages')), pages: new FileRef(path.join(__dirname, 'pages')),
public: new FileRef(path.join(__dirname, 'public')), public: new FileRef(path.join(__dirname, 'public')),
'next.config.js': 'export default {"output": "standalone"}', 'next.config.js': 'export default {"output": "standalone"}',
......
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