Skip to content

Commit

Permalink
Merge branch 'canary' into shu/f1c3
Browse files Browse the repository at this point in the history
  • Loading branch information
shuding authored Aug 30, 2023
2 parents e7e6530 + d3a1079 commit 619f113
Show file tree
Hide file tree
Showing 44 changed files with 239 additions and 407 deletions.
2 changes: 1 addition & 1 deletion packages/next-codemod/bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ const TRANSFORMER_INQUIRER_CHOICES = [
value: 'cra-to-next',
},
{
name: 'new-link: Ensures your <Link> usage is backwards compatible. Used in combination with experimental newNextLinkBehavior',
name: 'new-link: Ensures your <Link> usage is backwards compatible.',
value: 'new-link',
},
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
// @ts-expect-error
process.env.__NEXT_NEW_LINK_BEHAVIOR = true

// eslint-disable-next-line no-undef
self.__next_require__ = __turbopack_require__

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import { IncrementalCache } from 'next/dist/server/lib/incremental-cache'

installRequireAndChunkLoad()

process.env.__NEXT_NEW_LINK_BEHAVIOR = 'true'

const MIME_TEXT_HTML_UTF8 = 'text/html; charset=utf-8'

startOperationStreamHandler(async (renderData: RenderData, respond) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ globalThis.__next_require__ = (data) => {
}
globalThis.__next_chunk_load__ = __turbopack_load__

process.env.__NEXT_NEW_LINK_BEHAVIOR = 'true'

const appElement = document

const getCacheKey = () => {
Expand Down
9 changes: 2 additions & 7 deletions packages/next/src/build/jest/jest.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { loadEnvConfig } from '@next/env'
import { resolve, join } from 'path'
import loadConfig from '../../server/config'
import type { NextConfigComplete } from '../../server/config-shared'
import { PHASE_TEST } from '../../shared/lib/constants'
import loadJsConfig from '../load-jsconfig'
import * as Log from '../output/log'
Expand Down Expand Up @@ -31,13 +30,9 @@ function loadClosestPackageJson(dir: string, attempts = 1): any {
}

/** Loads dotenv files and sets environment variables based on next config. */
function setUpEnv(dir: string, nextConfig: NextConfigComplete) {
function setUpEnv(dir: string) {
const dev = false
loadEnvConfig(dir, dev, Log)

if (nextConfig.experimental.newNextLinkBehavior) {
process.env.__NEXT_NEW_LINK_BEHAVIOR = 'true'
}
}

/*
Expand Down Expand Up @@ -82,7 +77,7 @@ export default function nextJest(options: { dir?: string } = {}) {
const findPagesDirResult = findPagesDir(resolvedDir, isAppDirEnabled)
hasServerComponents = !!findPagesDirResult.appDir
pagesDir = findPagesDirResult.pagesDir
setUpEnv(resolvedDir, nextConfig)
setUpEnv(resolvedDir)
// TODO: revisit when bug in SWC is fixed that strips `.css`
const result = await loadJsConfig(resolvedDir, nextConfig)
jsConfig = result.jsConfig
Expand Down
11 changes: 3 additions & 8 deletions packages/next/src/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2067,8 +2067,7 @@ export class NestedMiddlewareError extends Error {

export function getSupportedBrowsers(
dir: string,
isDevelopment: boolean,
config: NextConfigComplete
isDevelopment: boolean
): string[] | undefined {
let browsers: any
try {
Expand All @@ -2087,10 +2086,6 @@ export function getSupportedBrowsers(
return browsers
}

// When the user sets `legacyBrowsers: true`, we pass undefined
// to SWC which is basically ES5 and matches the default behavior
// prior to Next.js 13
return config.experimental.legacyBrowsers
? undefined
: MODERN_BROWSERSLIST_TARGET
// Uses modern browsers as the default.
return MODERN_BROWSERSLIST_TARGET
}
99 changes: 1 addition & 98 deletions packages/next/src/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,9 +280,6 @@ export function getDefineEnv({
'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH': JSON.stringify(
config.experimental.manualClientBasePath
),
'process.env.__NEXT_NEW_LINK_BEHAVIOR': JSON.stringify(
config.experimental.newNextLinkBehavior
),
'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED': JSON.stringify(
config.experimental.clientRouterFilter
),
Expand Down Expand Up @@ -739,7 +736,7 @@ export async function loadProjectInfo({
dev: boolean
}) {
const { jsConfig, resolvedBaseUrl } = await loadJsConfig(dir, config)
const supportedBrowsers = await getSupportedBrowsers(dir, dev, config)
const supportedBrowsers = await getSupportedBrowsers(dir, dev)
return {
jsConfig,
resolvedBaseUrl,
Expand Down Expand Up @@ -911,7 +908,6 @@ export default async function getBaseWebpackConfig(
appDir,
hasReactRefresh: dev && isClient,
hasServerComponents: true,
fileReading: config.experimental.swcFileReading,
nextConfig: config,
jsConfig,
supportedBrowsers,
Expand Down Expand Up @@ -2768,7 +2764,6 @@ export default async function getBaseWebpackConfig(
relay: config.compiler?.relay,
emotion: config.compiler?.emotion,
modularizeImports: config.modularizeImports,
legacyBrowsers: config.experimental?.legacyBrowsers,
imageLoaderFile: config.images.loaderFile,
})

Expand Down Expand Up @@ -3145,98 +3140,6 @@ export default async function getBaseWebpackConfig(
}
}

// Patch `@zeit/next-sass`, `@zeit/next-less`, `@zeit/next-stylus` for compatibility
if (webpackConfig.module && Array.isArray(webpackConfig.module.rules)) {
;[].forEach.call(
webpackConfig.module.rules,
function (rule: webpack.RuleSetRule) {
if (!(rule.test instanceof RegExp && Array.isArray(rule.use))) {
return
}

const isSass =
rule.test.source === '\\.scss$' || rule.test.source === '\\.sass$'
const isLess = rule.test.source === '\\.less$'
const isCss = rule.test.source === '\\.css$'
const isStylus = rule.test.source === '\\.styl$'

// Check if the rule we're iterating over applies to Sass, Less, or CSS
if (!(isSass || isLess || isCss || isStylus)) {
return
}

;[].forEach.call(rule.use, function (use: webpack.RuleSetUseItem) {
if (
!(
use &&
typeof use === 'object' &&
// Identify use statements only pertaining to `css-loader`
(use.loader === 'css-loader' ||
use.loader === 'css-loader/locals') &&
use.options &&
typeof use.options === 'object' &&
// The `minimize` property is a good heuristic that we need to
// perform this hack. The `minimize` property was only valid on
// old `css-loader` versions. Custom setups (that aren't next-sass,
// next-less or next-stylus) likely have the newer version.
// We still handle this gracefully below.
(Object.prototype.hasOwnProperty.call(use.options, 'minimize') ||
Object.prototype.hasOwnProperty.call(
use.options,
'exportOnlyLocals'
))
)
) {
return
}

// Try to monkey patch within a try-catch. We shouldn't fail the build
// if we cannot pull this off.
// The user may not even be using the `next-sass` or `next-less` or
// `next-stylus` plugins.
// If it does work, great!
try {
// Resolve the version of `@zeit/next-css` as depended on by the Sass,
// Less or Stylus plugin.
const correctNextCss = require.resolve('@zeit/next-css', {
paths: [
isCss
? // Resolve `@zeit/next-css` from the base directory
dir
: // Else, resolve it from the specific plugins
require.resolve(
isSass
? '@zeit/next-sass'
: isLess
? '@zeit/next-less'
: isStylus
? '@zeit/next-stylus'
: 'next'
),
],
})

// If we found `@zeit/next-css` ...
if (correctNextCss) {
// ... resolve the version of `css-loader` shipped with that
// package instead of whichever was hoisted highest in your
// `node_modules` tree.
const correctCssLoader = require.resolve(use.loader, {
paths: [correctNextCss],
})
if (correctCssLoader) {
// We saved the user from a failed build!
use.loader = correctCssLoader
}
}
} catch (_) {
// The error is not required to be handled.
}
})
}
)
}

// Backwards compat for `main.js` entry key
// and setup of dependencies between entries
// we can't do that in the initial entry for
Expand Down
5 changes: 1 addition & 4 deletions packages/next/src/build/webpack/loaders/next-app-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { MiddlewareConfig } from '../../analysis/get-page-static-info'
import { getFilenameAndExtension } from './next-metadata-route-loader'
import { isAppBuiltinNotFoundPage } from '../../utils'
import { loadEntrypoint } from '../../load-entrypoint'
import { isGroupSegment } from '../../../shared/lib/segment'

export type AppLoaderOptions = {
name: string
Expand Down Expand Up @@ -76,10 +77,6 @@ export type ComponentsType = {
readonly defaultPage?: ModuleReference
}

function isGroupSegment(segment: string) {
return segment.startsWith('(') && segment.endsWith(')')
}

async function createAppRouteCode({
name,
page,
Expand Down
2 changes: 0 additions & 2 deletions packages/next/src/build/webpack/loaders/next-swc-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,9 @@ const EXCLUDED_PATHS =
export function pitch(this: any) {
const callback = this.async()
;(async () => {
let loaderOptions = this.getOptions() || {}
if (
// TODO: investigate swc file reading in PnP mode?
!process.versions.pnp &&
loaderOptions.fileReading &&
!EXCLUDED_PATHS.test(this.resourcePath) &&
this.loaders.length - 1 === this.loaderIndex &&
isAbsolute(this.resourcePath) &&
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { FlightRouterState, Segment } from '../../../server/app-render/types'
import { INTERCEPTION_ROUTE_MARKERS } from '../../../server/future/helpers/interception-routes'
import { isGroupSegment } from '../../../shared/lib/segment'
import { matchSegment } from '../match-segments'

const removeLeadingSlash = (segment: string): string => {
return segment[0] === '/' ? segment.slice(1) : segment
}

const segmentToPathname = (segment: Segment): string => {
if (typeof segment === 'string') {
return segment
Expand All @@ -10,13 +15,11 @@ const segmentToPathname = (segment: Segment): string => {
return segment[1]
}

function normalizePathname(pathname: string): string {
function normalizeSegments(segments: string[]): string {
return (
pathname.split('/').reduce((acc, segment) => {
if (
segment === '' ||
(segment.startsWith('(') && segment.endsWith(')'))
) {
segments.reduce((acc, segment) => {
segment = removeLeadingSlash(segment)
if (segment === '' || isGroupSegment(segment)) {
return acc
}

Expand All @@ -40,30 +43,28 @@ export function extractPathFromFlightRouterState(

if (segment.startsWith('__PAGE__')) return ''

const path = [segment]

const segments = [segment]
const parallelRoutes = flightRouterState[1] ?? {}

const childrenPath = parallelRoutes.children
? extractPathFromFlightRouterState(parallelRoutes.children)
: undefined

if (childrenPath !== undefined) {
path.push(childrenPath)
segments.push(childrenPath)
} else {
for (const [key, value] of Object.entries(parallelRoutes)) {
if (key === 'children') continue

const childPath = extractPathFromFlightRouterState(value)

if (childPath !== undefined) {
path.push(childPath)
segments.push(childPath)
}
}
}

// TODO-APP: optimise this, it's not ideal to join and split
return normalizePathname(path.join('/'))
return normalizeSegments(segments)
}

function computeChangedPathImpl(
Expand Down Expand Up @@ -116,5 +117,5 @@ export function computeChangedPath(
}

// lightweight normalization to remove route groups
return normalizePathname(changedPath)
return normalizeSegments(changedPath.split('/'))
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ async function fetchServerAction(
}

const redirectLocation = location
? new URL(addBasePath(location), window.location.origin)
? new URL(
addBasePath(location),
// Ensure relative redirects in Server Actions work, e.g. redirect('./somewhere-else')
new URL(state.canonicalUrl, window.location.href)
)
: undefined

let isFlightResponse =
Expand Down
3 changes: 1 addition & 2 deletions packages/next/src/client/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
onClick,
onMouseEnter: onMouseEnterProp,
onTouchStart: onTouchStartProp,
// @ts-expect-error this is inlined as a literal boolean not a string
legacyBehavior = process.env.__NEXT_NEW_LINK_BEHAVIOR === false,
legacyBehavior = false,
...restProps
} = props

Expand Down
1 change: 0 additions & 1 deletion packages/next/src/lib/turbopack-warning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ const supportedTurbopackNextConfigOptions = [
'experimental.serverComponentsExternalPackages',
'experimental.turbo',
'experimental.mdxRs',
'experimental.swcFileReading',
'experimental.forceSwcTransforms',
// options below are not really supported, but ignored
'webpack',
Expand Down
4 changes: 4 additions & 0 deletions packages/next/src/server/base-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1614,6 +1614,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
!(is404Page || pathname === '/_error')
) {
res.setHeader('x-middleware-skip', '1')
res.setHeader(
'cache-control',
'private, no-cache, no-store, max-age=0, must-revalidate'
)
res.body('{}').send()
return null
}
Expand Down
9 changes: 0 additions & 9 deletions packages/next/src/server/config-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,9 +350,6 @@ const configSchema = {
largePageDataBytes: {
type: 'number',
},
legacyBrowsers: {
type: 'boolean',
},
manualClientBasePath: {
type: 'boolean',
},
Expand All @@ -361,9 +358,6 @@ const configSchema = {
enum: ['strict', 'flexible'] as any,
type: 'string',
},
newNextLinkBehavior: {
type: 'boolean',
},
nextScriptWorkers: {
type: 'boolean',
},
Expand Down Expand Up @@ -424,9 +418,6 @@ const configSchema = {
strictNextHead: {
type: 'boolean',
},
swcFileReading: {
type: 'boolean',
},
swcMinify: {
type: 'boolean',
},
Expand Down
Loading

0 comments on commit 619f113

Please sign in to comment.