Skip to content

Commit

Permalink
Merge branch 'canary' into fix-png-decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
kodiakhq[bot] authored Apr 1, 2021
2 parents d31f71b + 65c2216 commit 46eb823
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 21 deletions.
1 change: 0 additions & 1 deletion examples/using-preact/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
},
"devDependencies": {},
"dependencies": {
"@prefresh/next": "^1.3.0",
"next": "^10.0.0",
"next-plugin-preact": "^3.0.3",
"preact": "^10.5.5",
Expand Down
34 changes: 32 additions & 2 deletions packages/next/lib/load-custom-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from '../next-server/lib/constants'
import { execOnce } from '../next-server/lib/utils'
import * as Log from '../build/output/log'
import { getSafeParamName } from '../next-server/lib/router/utils/prepare-destination'

export type RouteHas =
| {
Expand Down Expand Up @@ -325,6 +326,34 @@ function checkCustomRoutes(
}
sourceTokens = tokens
}
const hasSegments = new Set<string>()

if (route.has) {
for (const hasItem of route.has) {
if (!hasItem.value && hasItem.key) {
hasSegments.add(hasItem.key)
}

if (hasItem.value) {
const matcher = new RegExp(`^${hasItem.value}$`)
const matches = matcher.exec('')

if (matches) {
if (matches.groups) {
Object.keys(matches.groups).forEach((groupKey) => {
const safeKey = getSafeParamName(groupKey)

if (safeKey && matches.groups![groupKey]) {
hasSegments.add(safeKey)
}
})
} else {
hasSegments.add(hasItem.key || 'host')
}
}
}
}
}

// make sure no unnamed patterns are attempted to be used in the
// destination as this can cause confusion and is not allowed
Expand Down Expand Up @@ -369,15 +398,16 @@ function checkCustomRoutes(
for (const token of destTokens!) {
if (
typeof token === 'object' &&
!sourceSegments.has(token.name)
!sourceSegments.has(token.name) &&
!hasSegments.has(token.name as string)
) {
invalidDestSegments.add(token.name)
}
}

if (invalidDestSegments.size) {
invalidParts.push(
`\`destination\` has segments not in \`source\` (${[
`\`destination\` has segments not in \`source\` or \`has\` (${[
...invalidDestSegments,
].join(', ')})`
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type Params = { [param: string]: any }

// ensure only a-zA-Z are used for param names for proper interpolating
// with path-to-regexp
const getSafeParamName = (paramName: string) => {
export const getSafeParamName = (paramName: string) => {
let newParamName = ''

for (let i = 0; i < paramName.length; i++) {
Expand Down
6 changes: 4 additions & 2 deletions packages/next/next-server/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import isAnimated from 'next/dist/compiled/is-animated'
import { join } from 'path'
import Stream from 'stream'
import nodeUrl, { UrlWithParsedQuery } from 'url'
import { NextConfig } from '../../next-server/server/config-shared'
import { fileExists } from '../../lib/file-exists'
import { ImageConfig, imageConfigDefault } from './image-config'
import { processBuffer, Operation } from './lib/squoosh/main'
Expand All @@ -30,9 +31,10 @@ export async function imageOptimizer(
server: Server,
req: IncomingMessage,
res: ServerResponse,
parsedUrl: UrlWithParsedQuery
parsedUrl: UrlWithParsedQuery,
nextConfig: NextConfig,
distDir: string
) {
const { nextConfig, distDir } = server
const imageData: ImageConfig = nextConfig.images || imageConfigDefault
const { deviceSizes = [], imageSizes = [], domains = [], loader } = imageData

Expand Down
35 changes: 21 additions & 14 deletions packages/next/next-server/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,18 +124,18 @@ export type ServerConstructor = {
}

export default class Server {
dir: string
quiet: boolean
nextConfig: NextConfig
distDir: string
pagesDir?: string
publicDir: string
hasStaticDir: boolean
serverBuildDir: string
pagesManifest?: PagesManifest
buildId: string
minimalMode: boolean
renderOpts: {
protected dir: string
protected quiet: boolean
protected nextConfig: NextConfig
protected distDir: string
protected pagesDir?: string
protected publicDir: string
protected hasStaticDir: boolean
protected serverBuildDir: string
protected pagesManifest?: PagesManifest
protected buildId: string
protected minimalMode: boolean
protected renderOpts: {
poweredByHeader: boolean
buildId: string
generateEtags: boolean
Expand All @@ -161,7 +161,7 @@ export default class Server {
private compression?: Middleware
private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void>
private incrementalCache: IncrementalCache
router: Router
protected router: Router
protected dynamicRoutes?: DynamicRoutes
protected customRoutes: CustomRoutes

Expand Down Expand Up @@ -784,7 +784,14 @@ export default class Server {
type: 'route',
name: '_next/image catchall',
fn: (req, res, _params, parsedUrl) =>
imageOptimizer(server, req, res, parsedUrl),
imageOptimizer(
server,
req,
res,
parsedUrl,
server.nextConfig,
server.distDir
),
},
{
match: route('/_next/:path*'),
Expand Down
10 changes: 10 additions & 0 deletions test/integration/custom-routes/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,16 @@ module.exports = {
],
destination: '/with-params?host=1',
},
{
source: '/has-rewrite-5',
has: [
{
type: 'query',
key: 'hasParam',
},
],
destination: '/:hasParam',
},
],
beforeFiles: [
{
Expand Down
27 changes: 27 additions & 0 deletions test/integration/custom-routes/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,22 @@ const runTests = (isDev = false) => {
expect(res2.status).toBe(404)
})

it('should pass has segment for rewrite correctly', async () => {
const res1 = await fetchViaHTTP(appPort, '/has-rewrite-5')
expect(res1.status).toBe(404)

const res = await fetchViaHTTP(appPort, '/has-rewrite-5', {
hasParam: 'with-params',
})

expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())

expect(JSON.parse($('#query').text())).toEqual({
hasParam: 'with-params',
})
})

it('should match has rewrite correctly before files', async () => {
const res1 = await fetchViaHTTP(appPort, '/hello')
expect(res1.status).toBe(200)
Expand Down Expand Up @@ -1509,6 +1525,17 @@ const runTests = (isDev = false) => {
regex: '^\\/has-rewrite-4$',
source: '/has-rewrite-4',
},
{
destination: '/:hasParam',
has: [
{
key: 'hasParam',
type: 'query',
},
],
regex: normalizeRegEx('^\\/has-rewrite-5$'),
source: '/has-rewrite-5',
},
],
fallback: [],
},
Expand Down
2 changes: 1 addition & 1 deletion test/integration/invalid-custom-routes/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ const runTests = () => {
const stderr = await getStderr()

expect(stderr).toContain(
`\`destination\` has segments not in \`source\` (id) for route {"source":"/feedback/:type","destination":"/feedback/:id"}`
`\`destination\` has segments not in \`source\` or \`has\` (id) for route {"source":"/feedback/:type","destination":"/feedback/:id"}`
)
})
}
Expand Down

0 comments on commit 46eb823

Please sign in to comment.