Unverified Commit 886dc9f3 authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

feat: add support for the src folder for the instrumentation hook (#46529)

parent 7a9047a7
...@@ -206,7 +206,7 @@ export function getEdgeServerEntry(opts: { ...@@ -206,7 +206,7 @@ export function getEdgeServerEntry(opts: {
if (isInstrumentationHookFile(opts.page)) { if (isInstrumentationHookFile(opts.page)) {
return { return {
import: opts.page, import: opts.absolutePagePath,
filename: `edge-${INSTRUMENTATION_HOOK_FILENAME}.js`, filename: `edge-${INSTRUMENTATION_HOOK_FILENAME}.js`,
} }
} }
...@@ -447,7 +447,15 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -447,7 +447,15 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
}) })
} else { } else {
server[serverBundlePath] = [mappings[page]] if (isInstrumentationHookFile(page) && pagesType === 'root') {
server[serverBundlePath.replace('src/', '')] = {
import: mappings[page],
// the '../' is needed to make sure the file is not chunked
filename: `../${INSTRUMENTATION_HOOK_FILENAME}.js`,
}
} else {
server[serverBundlePath] = [mappings[page]]
}
} }
}, },
onEdgeServer: () => { onEdgeServer: () => {
...@@ -463,8 +471,11 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -463,8 +471,11 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
}).import }).import
} }
const normalizedServerBundlePath =
edgeServer[serverBundlePath] = getEdgeServerEntry({ isInstrumentationHookFile(page) && pagesType === 'root'
? serverBundlePath.replace('src/', '')
: serverBundlePath
edgeServer[normalizedServerBundlePath] = getEdgeServerEntry({
...params, ...params,
rootDir, rootDir,
absolutePagePath: mappings[page], absolutePagePath: mappings[page],
......
...@@ -1877,9 +1877,15 @@ export function getPossibleInstrumentationHookFilenames( ...@@ -1877,9 +1877,15 @@ export function getPossibleInstrumentationHookFilenames(
folder: string, folder: string,
extensions: string[] extensions: string[]
) { ) {
return extensions.map((extension) => const files = []
path.join(folder, `${INSTRUMENTATION_HOOK_FILENAME}.${extension}`) for (const extension of extensions) {
) files.push(
path.join(folder, `${INSTRUMENTATION_HOOK_FILENAME}.${extension}`),
path.join(folder, `src`, `${INSTRUMENTATION_HOOK_FILENAME}.${extension}`)
)
}
return files
} }
export function getPossibleMiddlewareFilenames( export function getPossibleMiddlewareFilenames(
......
...@@ -625,27 +625,20 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit ...@@ -625,27 +625,20 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit
? getPossibleInstrumentationHookFilenames(dir, config.pageExtensions!) ? getPossibleInstrumentationHookFilenames(dir, config.pageExtensions!)
: [] : []
const wp = new Watchpack({ const instrumentationFileWatcher = new Watchpack({})
ignored: (entry: string) => {
return ( instrumentationFileWatcher.watch({
!(entry.split('/').length <= watchedEntryLength) && files: instrumentationFilePaths,
!instrumentationFilePaths.includes(entry) startTime: 0,
)
},
}) })
wp.watch({ directories: [parentDir], startTime: 0 })
let instrumentationFileLastHash: string | undefined = undefined let instrumentationFileLastHash: string | undefined = undefined
const previousInstrumentationFiles = new Set<string>()
wp.on('aggregated', async () => { instrumentationFileWatcher.on('aggregated', async () => {
const knownFiles = wp.getTimeInfoEntries() const knownFiles = instrumentationFileWatcher.getTimeInfoEntries()
const newFiles: string[] = [] const instrumentationFile = [...knownFiles.entries()].find(
let hasPagesApp = false ([key, value]) => instrumentationFilePaths.includes(key) && value
// check if the `instrumentation.js` has changed )?.[0]
// if it has we need to restart the server
const instrumentationFile = [...knownFiles.keys()].find((key) =>
instrumentationFilePaths.includes(key)
)
if (instrumentationFile) { if (instrumentationFile) {
const fs = require('fs') as typeof import('fs') const fs = require('fs') as typeof import('fs')
...@@ -665,16 +658,19 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit ...@@ -665,16 +658,19 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit
) )
return setupFork() return setupFork()
} else { } else {
if (!instrumentationFileLastHash && previousItems.size !== 0) { if (
!instrumentationFileLastHash &&
previousInstrumentationFiles.size !== 0
) {
warn( warn(
'An instrumentation file was added, restarting the server to apply changes.' 'The instrumentation file was added, restarting the server to apply changes.'
) )
return setupFork() return setupFork()
} }
instrumentationFileLastHash = instrumentationFileHash instrumentationFileLastHash = instrumentationFileHash
} }
} else if ( } else if (
[...previousItems.keys()].find((key) => [...previousInstrumentationFiles.keys()].find((key) =>
instrumentationFilePaths.includes(key) instrumentationFilePaths.includes(key)
) )
) { ) {
...@@ -685,6 +681,23 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit ...@@ -685,6 +681,23 @@ If you cannot make the changes above, but still want to try out\nNext.js v13 wit
return setupFork() return setupFork()
} }
previousInstrumentationFiles.clear()
knownFiles.forEach((_, key) => previousInstrumentationFiles.add(key))
})
const projectFolderWatcher = new Watchpack({
ignored: (entry: string) => {
return !(entry.split('/').length <= watchedEntryLength)
},
})
projectFolderWatcher.watch({ directories: [parentDir], startTime: 0 })
projectFolderWatcher.on('aggregated', async () => {
const knownFiles = projectFolderWatcher.getTimeInfoEntries()
const newFiles: string[] = []
let hasPagesApp = false
// if the dir still exists nothing to check // if the dir still exists nothing to check
try { try {
const result = findPagesDir(dir, !!config.experimental?.appDir) const result = findPagesDir(dir, !!config.experimental?.appDir)
......
...@@ -776,7 +776,6 @@ export default class HotReloader { ...@@ -776,7 +776,6 @@ export default class HotReloader {
) { ) {
relativeRequest = `./${relativeRequest}` relativeRequest = `./${relativeRequest}`
} }
entrypoints[bundlePath] = finalizeEntrypoint({ entrypoints[bundlePath] = finalizeEntrypoint({
compilerType: COMPILER_NAMES.server, compilerType: COMPILER_NAMES.server,
name: bundlePath, name: bundlePath,
...@@ -806,7 +805,6 @@ export default class HotReloader { ...@@ -806,7 +805,6 @@ export default class HotReloader {
}) })
}) })
) )
return entrypoints return entrypoints
} }
} }
......
...@@ -301,10 +301,8 @@ async function findPagePathData( ...@@ -301,10 +301,8 @@ async function findPagePathData(
const normalizedPagePath = tryToNormalizePagePath(page) const normalizedPagePath = tryToNormalizePagePath(page)
let pagePath: string | null = null let pagePath: string | null = null
if ( const isInstrumentation = isInstrumentationHookFile(normalizedPagePath)
isMiddlewareFile(normalizedPagePath) || if (isMiddlewareFile(normalizedPagePath) || isInstrumentation) {
isInstrumentationHookFile(normalizedPagePath)
) {
pagePath = await findPageFile( pagePath = await findPageFile(
rootDir, rootDir,
normalizedPagePath, normalizedPagePath,
...@@ -322,10 +320,18 @@ async function findPagePathData( ...@@ -322,10 +320,18 @@ async function findPagePathData(
}) })
) )
let bundlePath = normalizedPagePath
let pageKey = posix.normalize(pageUrl)
if (isInstrumentation) {
bundlePath = bundlePath.replace('/src', '')
pageKey = page.replace('/src', '')
}
return { return {
absolutePagePath: join(rootDir, pagePath), absolutePagePath: join(rootDir, pagePath),
bundlePath: normalizedPagePath.slice(1), bundlePath: bundlePath.slice(1),
page: posix.normalize(pageUrl), page: pageKey,
} }
} }
...@@ -448,7 +454,6 @@ export function onDemandEntryHandler({ ...@@ -448,7 +454,6 @@ export function onDemandEntryHandler({
pagePaths.push(`${type}/${entrypoint.name}`) pagePaths.push(`${type}/${entrypoint.name}`)
} }
} }
return pagePaths return pagePaths
} }
......
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'instrumentation-hook-src',
{
files: __dirname,
nextConfig: {
experimental: {
instrumentationHook: true,
},
},
skipDeployment: true,
},
({ next, isNextDev }) => {
it('should run the instrumentation hook', async () => {
await next.render('/')
await check(() => next.cliOutput, /instrumentation hook/)
})
it('should not overlap with a instrumentation page', async () => {
const page = await next.render('/instrumentation')
expect(page).toContain('Hello')
})
it('should run the edge instrumentation compiled version with the edge runtime', async () => {
await next.render('/edge')
await check(() => next.cliOutput, /instrumentation hook on the edge/)
})
if (isNextDev) {
it('should reload the server when the instrumentation hook changes', async () => {
await next.render('/')
await next.patchFile(
'./src/instrumentation.js',
`export function register() {console.log('toast')}`
)
await check(() => next.cliOutput, /toast/)
await next.renameFile(
'./src/instrumentation.js',
'./src/instrumentation.js.bak'
)
await check(
() => next.cliOutput,
/The instrumentation file has been removed/
)
await next.patchFile(
'./src/instrumentation.js.bak',
`export function register() {console.log('bread')}`
)
await next.renameFile(
'./src/instrumentation.js.bak',
'./src/instrumentation.js'
)
await check(() => next.cliOutput, /The instrumentation file was added/)
await check(() => next.cliOutput, /bread/)
})
}
}
)
export function register() {
if (process.env.NEXT_RUNTIME === 'edge') {
console.log('instrumentation hook on the edge')
} else if (process.env.NEXT_RUNTIME === 'nodejs') {
console.log('instrumentation hook')
} else {
require('this should fail')
}
}
import React from 'react'
export default function EdgePage() {
return <div>Edge Page</div>
}
export const config = {
runtime: 'experimental-edge',
}
export function getServerSideProps() {
return {
props: {},
}
}
export default function Page() {
return <p>hello world</p>
}
export default function Hello() {
return <div>Hello</div>
}
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
...@@ -49,7 +49,7 @@ createNextDescribe( ...@@ -49,7 +49,7 @@ createNextDescribe(
'./instrumentation.js.bak', './instrumentation.js.bak',
'./instrumentation.js' './instrumentation.js'
) )
await check(() => next.cliOutput, /An instrumentation file was added/) await check(() => next.cliOutput, /The instrumentation file was added/)
await check(() => next.cliOutput, /bread/) await check(() => next.cliOutput, /bread/)
}) })
} }
......
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
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