Unverified Commit f507b0e6 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update types and more test coverage for adapters (#82919)

This tweaks the output structure a bit and makes types more
strong/specific for easier handling. Also adds additional test coverage.
parent da54d104
......@@ -391,8 +391,8 @@ export type ManifestHeaderRoute = ManifestBuiltRoute & Header
export type ManifestRoute = ManifestBuiltRoute & {
page: string
namedRegex?: string
routeKeys?: { [key: string]: string }
namedRegex: string
routeKeys: { [key: string]: string }
/**
* If true, this indicates that the route has fallback root params. This is
......@@ -4112,6 +4112,9 @@ export default async function build(
await handleBuildComplete({
dir,
distDir,
config,
staticPages,
nextVersion: process.env.__NEXT_VERSION as string,
tracingRoot: outputFileTracingRoot,
hasNodeMiddleware,
hasInstrumentationHook,
......
......@@ -55,6 +55,7 @@ export type Redirect = {
locale?: false
has?: RouteHas[]
missing?: RouteHas[]
priority?: boolean
/**
* @internal - used internally for routing
......@@ -740,6 +741,7 @@ export default async function loadCustomRoutes(
permanent: true,
locale: config.i18n ? false : undefined,
internal: true,
priority: true,
// don't run this redirect for _next/data requests
missing: [
{
......@@ -754,6 +756,7 @@ export default async function loadCustomRoutes(
permanent: true,
locale: config.i18n ? false : undefined,
internal: true,
priority: true,
}
)
if (config.basePath) {
......@@ -764,6 +767,7 @@ export default async function loadCustomRoutes(
basePath: false,
locale: config.i18n ? false : undefined,
internal: true,
priority: true,
})
}
} else {
......@@ -773,6 +777,7 @@ export default async function loadCustomRoutes(
permanent: true,
locale: config.i18n ? false : undefined,
internal: true,
priority: true,
})
if (config.basePath) {
redirects.unshift({
......@@ -782,6 +787,7 @@ export default async function loadCustomRoutes(
basePath: false,
locale: config.i18n ? false : undefined,
internal: true,
priority: true,
})
}
}
......
import os from 'os'
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type {
Header,
Redirect,
Rewrite,
RouteHas,
} from '../lib/load-custom-routes'
import type { Header, Redirect, Rewrite } from '../lib/load-custom-routes'
import { imageConfigDefault } from '../shared/lib/image-config'
import type {
ImageConfig,
......@@ -18,17 +13,7 @@ import type { SizeLimit } from '../types'
import type { SupportedTestRunners } from '../cli/next-test'
import type { ExperimentalPPRConfig } from './lib/experimental/ppr'
import { INFINITE_CACHE } from '../lib/constants'
import type {
ManifestRewriteRoute,
ManifestHeaderRoute,
ManifestRedirectRoute,
ManifestRoute,
} from '../build'
import { isStableBuild } from '../shared/lib/canary-only'
import type { RenderingMode } from '../build/rendering-mode'
import type { Revalidate } from './lib/cache-control'
import type { AdapterOutputType } from '../shared/lib/constants'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import type { FallbackRouteParam } from '../build/static-paths/types'
export type NextConfigComplete = Required<NextConfig> & {
......@@ -43,146 +28,6 @@ export type NextConfigComplete = Required<NextConfig> & {
experimental: Omit<ExperimentalConfig, 'turbo'>
}
export type AdapterOutputs = Array<{
/**
* id is a unique identifier for the output
*/
id: string
/**
* pathname is the URL path that the output is meant to
* be routable to at e.g. /blog/[slug] or /_next/static/chunks/chunk.js
*/
pathname: string
/**
* runtime for the route, this doesn't apply for prerender or static
*/
runtime?: 'nodejs' | 'edge'
/**
* config related to the route
*/
config?: {
/**
* maxDuration is a segment config to signal the max
* execution duration a route should be allowed before
* it's timed out
*/
maxDuration?: number
/**
* preferredRegion is a segment config to signal deployment
* region preferences to the provider being used
*/
preferredRegion?: string | string[]
/**
* allowQuery is the allowed query values to be passed
* to an ISR function and what should be considered for the cacheKey
* e.g. for /blog/[slug], "slug" is the only allowQuery
*/
allowQuery?: string[]
/**
* allowHeader is the allowed headers to be passed to an
* ISR function to prevent accidentally poisoning the cache
* from leaking additional information that can impact the render
*/
allowHeader?: string[]
/**
* bypass for is a list of has conditions the cache
* should be bypassed and invoked directly e.g. action header
*/
bypassFor?: RouteHas[]
/**
* renderingMode signals PPR or not for a prerender
*/
renderingMode?: RenderingMode
/**
* matchers are the configured matchers for middleware
*/
matchers?: MiddlewareMatcher[]
/**
* bypassToken is the generated token that signals a prerender cache
* should be bypassed
*/
bypassToken?: string
/**
* postponed is the PPR state when it postponed and is used for resuming
*/
postponed?: string
}
/**
* For prerenders the parent output is the originating
* page that the prerender is created from
*/
parentOutputId?: string
/**
* fallback is initial cache data generated during build for a prerender
*/
fallback?: {
/**
* path to the fallback file can be HTML/JSON/RSC
*/
filePath: string
/**
* initialStatus is the status code that should be applied
* when serving the fallback
*/
initialStatus?: number
/**
* initialHeaders are the headers that should be sent when
* serving the fallback
*/
initialHeaders?: Record<string, string | string[]>
/**
* initial expiration is how long until the fallback entry
* is considered expired and no longer valid to serve
*/
initialExpiration?: number
/**
* initial revalidate is how long until the fallback is
* considered stale and should be revalidated
*/
initialRevalidate?: Revalidate
}
/**
* assets are all necessary traced assets that could be
* loaded by the output to handle a request e.g. traced
* node_modules or necessary manifests for Next.js
*/
assets?: Record<string, string>
/**
* filePath is present for all cases except a Prerender
* which may or may not have a fallback (initial cache entry).
* The parent output will have a filePath for a prerender though
*/
filePath?: string
/**
* type of output
*/
type: AdapterOutputType
}>
export interface NextAdapter {
name: string
modifyConfig?: (
config: NextConfigComplete
) => Promise<NextConfigComplete> | NextConfigComplete
onBuildComplete?: (ctx: {
routes: {
headers: Array<ManifestHeaderRoute>
redirects: Array<ManifestRedirectRoute>
rewrites: {
beforeFiles: Array<ManifestRewriteRoute>
afterFiles: Array<ManifestRewriteRoute>
fallback: Array<ManifestRewriteRoute>
}
dynamicRoutes: ReadonlyArray<ManifestRoute>
}
outputs: AdapterOutputs
}) => Promise<void> | void
}
export type I18NDomains = readonly DomainLocale[]
export interface I18NConfig {
......
import { PHASE_PRODUCTION_BUILD } from '../api/constants'
describe('loadConfig', () => {
let loadConfig: typeof import('./config').default
......@@ -12,7 +14,7 @@ describe('loadConfig', () => {
})
describe('nextConfig.images defaults', () => {
it('should assign a `images.remotePatterns` when using assetPrefix', async () => {
const result = await loadConfig('', __dirname, {
const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
assetPrefix: 'https://cdn.example.com',
images: {
......@@ -33,7 +35,7 @@ describe('loadConfig', () => {
})
it('should not assign a duplicate `images.remotePatterns` value when using assetPrefix', async () => {
let result = await loadConfig('', __dirname, {
let result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
assetPrefix: 'https://cdn.example.com',
images: {
......@@ -51,7 +53,7 @@ describe('loadConfig', () => {
expect(result.images.remotePatterns.length).toBe(1)
result = await loadConfig('', __dirname, {
result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
assetPrefix: 'https://cdn.example.com/foobar',
images: {
......@@ -81,7 +83,7 @@ describe('loadConfig', () => {
})
it('should not print a stack trace when throwing an error', async () => {
const loadConfigPromise = loadConfig('', __dirname, {
const loadConfigPromise = loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
ppr: true,
......@@ -105,7 +107,7 @@ describe('loadConfig', () => {
it('errors when using PPR if not in canary', async () => {
await expect(
loadConfig('', __dirname, {
loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
ppr: true,
......@@ -119,7 +121,7 @@ describe('loadConfig', () => {
it('errors when using cacheComponents if not in canary', async () => {
await expect(
loadConfig('', __dirname, {
loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
cacheComponents: true,
......@@ -133,7 +135,7 @@ describe('loadConfig', () => {
it('errors when using persistentCaching if not in canary', async () => {
await expect(
loadConfig('', __dirname, {
loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
turbopackPersistentCaching: true,
......@@ -157,7 +159,7 @@ describe('loadConfig', () => {
it('errors when cacheComponents is enabled but PPR is disabled', async () => {
await expect(
loadConfig('', __dirname, {
loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
cacheComponents: true,
......@@ -172,7 +174,7 @@ describe('loadConfig', () => {
it('errors when rdcForNavigations is enabled but ppr is disabled', async () => {
await expect(
loadConfig('', __dirname, {
loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
rdcForNavigations: true,
......@@ -186,7 +188,7 @@ describe('loadConfig', () => {
})
it('defaults rdcForNavigations to true when ppr is enabled', async () => {
const result = await loadConfig('', __dirname, {
const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
ppr: true,
......@@ -198,7 +200,7 @@ describe('loadConfig', () => {
})
it('allows explicitly disabling rdcForNavigations when ppr is enabled', async () => {
const result = await loadConfig('', __dirname, {
const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
ppr: true,
......@@ -212,7 +214,7 @@ describe('loadConfig', () => {
it('errors when cacheComponents is enabled but PPR set to "incremental"', async () => {
await expect(
loadConfig('', __dirname, {
loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
cacheComponents: true,
......@@ -228,7 +230,7 @@ describe('loadConfig', () => {
it('migrates experimental.dynamicIO to experimental.cacheComponents', async () => {
process.env.__NEXT_VERSION = 'canary'
const result = await loadConfig('', __dirname, {
const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
dynamicIO: true,
......@@ -246,7 +248,7 @@ describe('loadConfig', () => {
it('preserves cacheComponents when both dynamicIO and cacheComponents are set', async () => {
process.env.__NEXT_VERSION = 'canary'
const result = await loadConfig('', __dirname, {
const result = await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
dynamicIO: true,
......@@ -267,7 +269,7 @@ describe('loadConfig', () => {
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation()
await loadConfig('', __dirname, {
await loadConfig(PHASE_PRODUCTION_BUILD, __dirname, {
customConfig: {
experimental: {
dynamicIO: true,
......
......@@ -9,7 +9,7 @@ import {
PHASE_DEVELOPMENT_SERVER,
PHASE_EXPORT,
PHASE_PRODUCTION_BUILD,
PHASE_PRODUCTION_SERVER,
type PHASE_TYPE,
} from '../shared/lib/constants'
import { defaultConfig, normalizeConfig } from './config-shared'
import type {
......@@ -17,7 +17,6 @@ import type {
NextConfigComplete,
NextConfig,
TurbopackLoaderItem,
NextAdapter,
} from './config-shared'
import { loadWebpackHook } from './config-utils'
......@@ -43,6 +42,7 @@ import { findDir } from '../lib/find-pages-dir'
import { CanaryOnlyError, isStableBuild } from '../shared/lib/canary-only'
import { interopDefault } from '../lib/interop-default'
import { djb2Hash } from '../shared/lib/hash'
import type { NextAdapter } from '../build/adapter/build-complete'
export { normalizeConfig } from './config-shared'
export type { DomainLocale, NextConfig } from './config-shared'
......@@ -1203,15 +1203,12 @@ function assignDefaultsAndValidate(
async function applyModifyConfig(
config: NextConfigComplete,
phase: string,
phase: PHASE_TYPE,
silent: boolean
): Promise<NextConfigComplete> {
if (
// TODO: should this be called for server start as
// adapters shouldn't be relying on "next start"
[PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_SERVER].includes(phase) &&
config.experimental?.adapterPath
) {
// we always call modify config and phase can be used to only
// modify for specific times
if (config.experimental?.adapterPath) {
const adapterMod = interopDefault(
await import(
pathToFileURL(require.resolve(config.experimental.adapterPath)).href
......@@ -1222,7 +1219,10 @@ async function applyModifyConfig(
if (!silent) {
Log.info(`Applying modifyConfig from ${adapterMod.name}`)
}
config = await adapterMod.modifyConfig(config)
config = await adapterMod.modifyConfig(config, {
phase,
})
}
}
return config
......@@ -1241,7 +1241,7 @@ const configCache = new Map<
// Generate cache key based on parameters that affect config output
// We need a unique key for cache because there can be multiple values
function getCacheKey(
phase: string,
phase: PHASE_TYPE,
dir: string,
customConfig?: object | null,
reactProductionProfiling?: boolean,
......@@ -1261,7 +1261,7 @@ function getCacheKey(
}
export default async function loadConfig(
phase: string,
phase: PHASE_TYPE,
dir: string,
{
customConfig,
......@@ -1656,7 +1656,7 @@ function enforceExperimentalFeatures(
isDefaultConfig: boolean
configuredExperimentalFeatures: ConfiguredExperimentalFeature[] | undefined
debugPrerender: boolean | undefined
phase: string
phase: PHASE_TYPE
}
) {
const {
......
......@@ -22,7 +22,10 @@ import { recursiveReadDir } from '../../../lib/recursive-readdir'
import { isDynamicRoute } from '../../../shared/lib/router/utils'
import { escapeStringRegexp } from '../../../shared/lib/escape-regexp'
import { getPathMatch } from '../../../shared/lib/router/utils/path-match'
import { getRouteRegex } from '../../../shared/lib/router/utils/route-regex'
import {
getNamedRouteRegex,
getRouteRegex,
} from '../../../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'
import { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
......@@ -255,10 +258,14 @@ export async function setupFsCheck(opts: {
for (const route of routesManifest.dataRoutes) {
if (isDynamicRoute(route.page)) {
const routeRegex = getRouteRegex(route.page)
const routeRegex = getNamedRouteRegex(route.page, {
prefixRouteKeys: true,
})
dynamicRoutes.push({
...route,
regex: routeRegex.re.toString(),
namedRegex: routeRegex.namedRegex,
routeKeys: routeRegex.routeKeys,
match: getRouteMatcher({
// TODO: fix this in the manifest itself, must also be fixed in
// upstream builder that relies on this
......
......@@ -37,7 +37,7 @@ import {
} from '../../../build/entries'
import { verifyTypeScriptSetup } from '../../../lib/verify-typescript-setup'
import { verifyPartytownSetup } from '../../../lib/verify-partytown-setup'
import { getRouteRegex } from '../../../shared/lib/router/utils/route-regex'
import { getNamedRouteRegex } from '../../../shared/lib/router/utils/route-regex'
import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths'
import { buildDataRoute } from './build-data-route'
import { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'
......@@ -970,9 +970,13 @@ async function startWatcher(
opts.fsChecker.dynamicRoutes = sortedRoutes.map(
(page): FilesystemDynamicRoute => {
const regex = getRouteRegex(page)
const regex = getNamedRouteRegex(page, {
prefixRouteKeys: true,
})
return {
regex: regex.re.toString(),
namedRegex: regex.namedRegex,
routeKeys: regex.routeKeys,
match: getRouteMatcher(regex),
page,
}
......@@ -983,10 +987,14 @@ async function startWatcher(
for (const page of sortedRoutes) {
const route = buildDataRoute(page, 'development')
const routeRegex = getRouteRegex(route.page)
const routeRegex = getNamedRouteRegex(route.page, {
prefixRouteKeys: true,
})
dataRoutes.push({
...route,
regex: routeRegex.re.toString(),
namedRegex: routeRegex.namedRegex,
routeKeys: routeRegex.routeKeys,
match: getRouteMatcher({
// TODO: fix this in the manifest itself, must also be fixed in
// upstream builder that relies on this
......
......@@ -12,6 +12,22 @@ export const COMPILER_NAMES = {
export type CompilerNameValues = ValueOf<typeof COMPILER_NAMES>
export const COMPILER_INDEXES: {
[compilerKey in CompilerNameValues]: number
} = {
[COMPILER_NAMES.client]: 0,
[COMPILER_NAMES.server]: 1,
[COMPILER_NAMES.edgeServer]: 2,
} as const
// Re-export entry constants for backward compatibility
export {
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
UNDERSCORE_GLOBAL_ERROR_ROUTE,
UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,
} from './entry-constants'
export enum AdapterOutputType {
/**
* `PAGES` represents all the React pages that are under `pages/`.
......@@ -51,28 +67,21 @@ export enum AdapterOutputType {
MIDDLEWARE = 'MIDDLEWARE',
}
export const COMPILER_INDEXES: {
[compilerKey in CompilerNameValues]: number
} = {
[COMPILER_NAMES.client]: 0,
[COMPILER_NAMES.server]: 1,
[COMPILER_NAMES.edgeServer]: 2,
} as const
// Re-export entry constants for backward compatibility
export {
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
UNDERSCORE_GLOBAL_ERROR_ROUTE,
UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,
} from './entry-constants'
export const PHASE_EXPORT = 'phase-export'
export const PHASE_PRODUCTION_BUILD = 'phase-production-build'
export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'
export const PHASE_TEST = 'phase-test'
export const PHASE_INFO = 'phase-info'
export type PHASE_TYPE =
| typeof PHASE_INFO
| typeof PHASE_TEST
| typeof PHASE_EXPORT
| typeof PHASE_PRODUCTION_BUILD
| typeof PHASE_PRODUCTION_SERVER
| typeof PHASE_DEVELOPMENT_SERVER
export const PAGES_MANIFEST = 'pages-manifest.json'
export const WEBPACK_STATS = 'webpack-stats.json'
export const APP_PATHS_MANIFEST = 'app-paths-manifest.json'
......
......@@ -29,7 +29,7 @@ export type ServerRuntime = 'nodejs' | 'experimental-edge' | 'edge' | undefined
// @ts-ignore This path is generated at build time and conflicts otherwise
export { NextConfig } from './server/config'
export type { NextAdapter } from './server/config-shared'
export type { NextAdapter, AdapterOutput } from './build/adapter/build-complete'
export type {
Metadata,
......
......@@ -1857,6 +1857,7 @@ const runTests = (isDev = false) => {
{
"destination": "/:path+",
"internal": true,
"priority": true,
"regex": "^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))\\/$",
"source": "/:path+/",
"statusCode": 308,
......
......@@ -1456,6 +1456,7 @@ function runTests({ dev }) {
{
"destination": "/:path+",
"internal": true,
"priority": true,
"regex": "^(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))/$",
"source": "/:path+/",
"statusCode": 308,
......
import fs from 'fs'
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
import { AdapterOutputType } from 'next/constants'
import type { AdapterOutput, NextAdapter } from 'next'
import { version as nextVersion } from 'next/package.json'
describe('adapter-config', () => {
const { next } = nextTestSetup({
......@@ -23,56 +23,64 @@ describe('adapter-config', () => {
it('should call onBuildComplete with correct context', async () => {
expect(next.cliOutput).toContain('onBuildComplete called')
const buildContext: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const {
outputs,
routes,
config,
...ctx
}: Parameters<NextAdapter['onBuildComplete']>[0] = await next.readJSON(
'build-complete.json'
)
const outputMap = new Map<string, (typeof buildContext.outputs)[0]>()
const prerenderOutputs: typeof buildContext.outputs = []
const staticOutputs: typeof buildContext.outputs = []
const nodeOutputs: typeof buildContext.outputs = []
const edgeOutputs: typeof buildContext.outputs = []
for (const field of ['distDir', 'projectDir', 'repoRoot']) {
expect(ctx[field]).toBeString()
for (const output of buildContext.outputs) {
if (outputMap.has(output.id)) {
if (!fs.existsSync(ctx[field])) {
throw new Error(
`multiple outputs with same ID ${JSON.stringify(
{
first: outputMap.get(output.id),
second: output,
},
null,
2
)}`
`Invalid dir value provided for ${field} value ${ctx[field]}`
)
}
}
switch (output.type) {
case AdapterOutputType.PRERENDER: {
prerenderOutputs.push(output)
break
}
case AdapterOutputType.STATIC_FILE: {
staticOutputs.push(output)
break
}
case AdapterOutputType.APP_PAGE:
case AdapterOutputType.APP_ROUTE:
case AdapterOutputType.PAGES:
case AdapterOutputType.PAGES_API: {
if (output.runtime === 'nodejs') {
nodeOutputs.push(output)
} else if (output.runtime === 'edge') {
edgeOutputs.push(output)
} else {
throw new Error(
`unrecognized runtime on ${JSON.stringify(output, null, 2)}`
)
}
break
}
default: {
throw new Error(`unrecognized output type ${output.type}`)
}
expect(ctx.nextVersion).toBe(nextVersion)
expect(config?.basePath).toBe('/docs')
const combinedRouteOutputs = [
...outputs.appPages,
...outputs.appRoutes,
...outputs.pages,
...outputs.pagesApi,
]
type PageRoutesType =
| AdapterOutput['APP_PAGE']
| AdapterOutput['APP_ROUTE']
| AdapterOutput['PAGES']
| AdapterOutput['PAGES_API']
const outputMap = new Map<string, PageRoutesType>()
const prerenderOutputs: AdapterOutput['PRERENDER'][] = outputs.prerenders
const staticOutputs: AdapterOutput['STATIC_FILE'][] = outputs.staticFiles
const nodeOutputs: PageRoutesType[] = []
const edgeOutputs: PageRoutesType[] = []
for (const routeOutput of combinedRouteOutputs) {
if (outputMap.has(routeOutput.id)) {
require('console').error({
existingOutput: outputMap.get(routeOutput.id),
newOutput: routeOutput,
})
throw new Error(`duplicate id on route outputs ${routeOutput.id}`)
}
outputMap.set(routeOutput.id, routeOutput)
if (routeOutput.runtime === 'edge') {
edgeOutputs.push(routeOutput)
} else if (routeOutput.runtime === 'nodejs') {
nodeOutputs.push(routeOutput)
} else {
require('console').error(routeOutput)
throw new Error(`Unexpected runtime on output ${routeOutput.runtime}`)
}
}
......@@ -83,17 +91,25 @@ describe('adapter-config', () => {
for (const output of staticOutputs) {
expect(output.id).toBeTruthy()
expect(output.pathname).toStartWith('/_next/static')
expect(fs.existsSync(output.filePath)).toBe(true)
if (output.filePath.endsWith('.html')) {
expect(output.pathname.endsWith('.html')).toBe(false)
} else {
expect(output.pathname).toStartWith('/_next/static')
}
const stats = await fs.promises.stat(output.filePath)
expect(stats.isFile()).toBe(true)
}
for (const prerenderOutput of prerenderOutputs) {
try {
expect(prerenderOutput.parentOutputId).toBeTruthy()
if (prerenderOutput.fallback) {
expect(await fs.existsSync(prerenderOutput.fallback.filePath)).toBe(
true
const stats = await fs.promises.stat(
prerenderOutput.fallback.filePath
)
expect(stats.isFile()).toBe(true)
expect(prerenderOutput.fallback.initialRevalidate).toBeDefined()
}
......@@ -106,7 +122,57 @@ describe('adapter-config', () => {
}
}
expect(buildContext.routes).toEqual({
for (const route of nodeOutputs) {
try {
expect(route.id).toBeString()
expect(route.config).toBeObject()
expect(route.pathname).toBeString()
expect(route.runtime).toBe('nodejs')
const stats = await fs.promises.stat(route.filePath)
expect(stats.isFile()).toBe(true)
const missingAssets: string[] = []
for (const filePath of Object.values(route.assets)) {
if (!fs.existsSync(filePath)) {
missingAssets.push(filePath)
}
}
expect(missingAssets).toEqual([])
} catch (err) {
require('console').error(`Invalid fields for ${route.id}`, route, err)
throw err
}
}
for (const route of edgeOutputs) {
try {
expect(route.id).toBeString()
expect(route.config).toBeObject()
expect(route.pathname).toBeString()
expect(route.runtime).toBe('edge')
const stats = await fs.promises.stat(route.filePath)
expect(stats.isFile()).toBe(true)
const missingAssets: string[] = []
for (const filePath of Object.values(route.assets)) {
if (!fs.existsSync(filePath)) {
missingAssets.push(filePath)
}
}
expect(missingAssets).toEqual([])
} catch (err) {
require('console').error(`Invalid fields for ${route.id}`, route, err)
throw err
}
}
expect(routes).toEqual({
dynamicRoutes: expect.toBeArray(),
rewrites: expect.toBeObject(),
redirects: expect.toBeArray(),
......
......@@ -4,8 +4,11 @@ import fs from 'fs'
/** @type {import('next').NextAdapter } */
const myAdapter = {
name: 'my-custom-adapter',
modifyConfig: (config) => {
console.log('called modify config in adapter')
modifyConfig: (config, { phase }) => {
if (typeof phase !== 'string') {
throw new Error(`invalid phase value provided to modifyConfig ${phase}`)
}
console.log('called modify config in adapter with phase', phase)
config.basePath = '/docs'
return config
},
......
export default function Pages() {
return <p>automatic-static-pages</p>
}
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