Skip to content

Commit ba66880

Browse files
committed
fix: testing something new
1 parent 548a482 commit ba66880

File tree

5 files changed

+26
-42
lines changed

5 files changed

+26
-42
lines changed

packages/runtime/src/helpers/functions.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { getResolverForPages, getResolverForSourceFiles } from '../templates/get
2828
import { ApiConfig, extractConfigFromFile, isEdgeConfig } from './analysis'
2929
import { getRequiredServerFiles } from './config'
3030
import { getDependenciesOfFile, getServerFile, getSourceFileForPage } from './files'
31-
import { writeFunctionConfiguration } from './functionsMetaData'
31+
import { writeFunctionConfiguration, nextVersionNum } from './functionsMetaData'
3232
import { pack } from './pack'
3333
import { ApiRouteType } from './types'
3434
import { getFunctionNameForPage } from './utils'
@@ -132,11 +132,13 @@ export const generateFunctions = async (
132132
}
133133

134134
const writeHandler = async (functionName: string, functionTitle: string, isODB: boolean) => {
135+
const useHooks = await nextVersionNum()
135136
const handlerSource = getHandler({
136137
isODB,
137138
publishDir,
138139
appDir: relative(functionDir, appDir),
139140
nextServerModuleRelativeLocation,
141+
useHooks,
140142
})
141143
await ensureDir(join(functionsDir, functionName))
142144

packages/runtime/src/helpers/functionsMetaData.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { existsSync, readJSON, writeFile } from 'fs-extra'
22
import { join } from 'pathe'
3+
import { satisfies } from 'semver'
34

45
import { NEXT_PLUGIN, NEXT_PLUGIN_NAME } from '../constants'
56

@@ -17,8 +18,8 @@ const getNextRuntimeVersion = async (packageJsonPath: string, useNodeModulesPath
1718

1819
const PLUGIN_PACKAGE_PATH = '.netlify/plugins/package.json'
1920

20-
const nextPluginVersion = async () => {
21-
const moduleRoot = resolveModuleRoot(NEXT_PLUGIN)
21+
const nextPluginVersion = async (module?: string) => {
22+
const moduleRoot = resolveModuleRoot(module || NEXT_PLUGIN)
2223
const nodeModulesPath = moduleRoot ? join(moduleRoot, 'package.json') : null
2324

2425
return (
@@ -31,6 +32,8 @@ const nextPluginVersion = async () => {
3132

3233
export const getPluginVersion = async () => `${NEXT_PLUGIN_NAME}@${await nextPluginVersion()}`
3334

35+
export const nextVersionNum = async () => satisfies(await nextPluginVersion('next'), '13.3.3 - 13.4.9')
36+
3437
// The information needed to create a function configuration file
3538
export interface FunctionInfo {
3639
// The name of the function, e.g. `___netlify-handler`

packages/runtime/src/templates/getHandler.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,13 @@ const path = require('path')
1717
const { URLSearchParams, URL } = require('url')
1818

1919
const { Bridge } = require('@vercel/node-bridge/bridge')
20-
const { satisfies } = require('semver')
2120

2221
const {
2322
augmentFsModule,
2423
getMaxAge,
2524
getMultiValueHeaders,
2625
getPrefetchResponse,
2726
normalizePath,
28-
nextVersionNum,
2927
} = require('./handlerUtils')
3028
const { overrideRequireHooks, applyRequireHooks } = require('./requireHooks')
3129
const { getNetlifyNextServer } = require('./server')
@@ -42,11 +40,20 @@ type MakeHandlerParams = {
4240
NextServer: NextServerType
4341
staticManifest: Array<[string, string]>
4442
mode: 'ssr' | 'odb'
43+
useHooks: boolean
4544
}
4645

4746
// We return a function and then call `toString()` on it to serialise it as the launcher function
4847
// eslint-disable-next-line max-lines-per-function
49-
const makeHandler = ({ conf, app, pageRoot, NextServer, staticManifest = [], mode = 'ssr' }: MakeHandlerParams) => {
48+
const makeHandler = ({
49+
conf,
50+
app,
51+
pageRoot,
52+
NextServer,
53+
staticManifest = [],
54+
mode = 'ssr',
55+
useHooks,
56+
}: MakeHandlerParams) => {
5057
// Change working directory into the site root, unless using Nx, which moves the
5158
// dist directory and handles this itself
5259
const dir = path.resolve(__dirname, app)
@@ -63,15 +70,10 @@ const makeHandler = ({ conf, app, pageRoot, NextServer, staticManifest = [], mod
6370
const { appDir }: ExperimentalConfigWithLegacy = conf.experimental
6471
// Next 13.4 conditionally uses different React versions and we need to make sure we use the same one
6572
// With the release of 13.5 experimental.appDir is no longer used.
66-
// we will need to check if appDir is set and Next version before running requireHooks
67-
const runRequireHooks = async (hook) =>
68-
await nextVersionNum(satisfies)
69-
.then((version) => (appDir && version ? hook : null))
70-
.catch(() => ({}))
71-
72-
runRequireHooks(overrideRequireHooks(conf.experimental))
73+
// we will need to check if appDir is set and Next version before running requireHook
74+
if (appDir && useHooks) return overrideRequireHooks(conf.experimental)
7375
const NetlifyNextServer: NetlifyNextServerType = getNetlifyNextServer(NextServer)
74-
runRequireHooks(applyRequireHooks())
76+
if (appDir && useHooks) return applyRequireHooks()
7577

7678
const ONE_YEAR_IN_SECONDS = 31536000
7779

@@ -216,6 +218,7 @@ export const getHandler = ({
216218
publishDir = '../../../.next',
217219
appDir = '../../..',
218220
nextServerModuleRelativeLocation,
221+
useHooks,
219222
}): string =>
220223
// This is a string, but if you have the right editor plugin it should format as js (e.g. bierner.comment-tagged-templates in VS Code)
221224
javascript/* javascript */ `
@@ -227,7 +230,6 @@ export const getHandler = ({
227230
228231
const { Server } = require("http");
229232
const { promises } = require("fs");
230-
const { satisfies } = require('semver')
231233
// We copy the file here rather than requiring from the node module
232234
const { Bridge } = require("./bridge");
233235
const { augmentFsModule, getMaxAge, getMultiValueHeaders, getPrefetchResponse, normalizePath, nextVersionNum } = require('./handlerUtils')
@@ -244,7 +246,7 @@ export const getHandler = ({
244246
const pageRoot = path.resolve(path.join(__dirname, "${publishDir}", "server"));
245247
exports.handler = ${
246248
isODB
247-
? `builder((${makeHandler.toString()})({ conf: config, app: "${appDir}", pageRoot, NextServer, staticManifest, mode: 'odb' }));`
248-
: `(${makeHandler.toString()})({ conf: config, app: "${appDir}", pageRoot, NextServer, staticManifest, mode: 'ssr' });`
249+
? `builder((${makeHandler.toString()})({ conf: config, app: "${appDir}", pageRoot, NextServer, staticManifest, mode: 'odb', useHooks: ${useHooks} }));`
250+
: `(${makeHandler.toString()})({ conf: config, app: "${appDir}", pageRoot, NextServer, staticManifest, mode: 'ssr', useHooks: ${useHooks} });`
249251
}
250252
`

packages/runtime/src/templates/handlerUtils.ts

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
import fs, { createWriteStream, existsSync } from 'fs'
22
import { ServerResponse } from 'http'
33
import { tmpdir } from 'os'
4-
import path, { dirname, join, relative } from 'path'
4+
import path from 'path'
55
import { pipeline } from 'stream'
66
import { promisify } from 'util'
77

88
import { HandlerEvent, HandlerResponse } from '@netlify/functions'
99
import { http, https } from 'follow-redirects'
1010
import NextNodeServer from 'next/dist/server/next-server'
11-
import { satisfies } from 'semver'
1211

1312
import type { StaticRoute } from '../helpers/types'
1413

@@ -275,26 +274,6 @@ export const localizeDataRoute = (dataRoute: string, localizedRoute: string): st
275274
.replace(/\/index\.json$/, '.json')
276275
}
277276

278-
export const resolveModuleRoot = (moduleName) => {
279-
try {
280-
return dirname(relative(process.cwd(), require.resolve(`${moduleName}/package.json`, { paths: [process.cwd()] })))
281-
} catch {
282-
return null
283-
}
284-
}
285-
// Had to copy nextPluginVersion logic from functionsMetaData for it to work within server.ts and getHandler.ts
286-
const nextPluginVersion = async () => {
287-
const moduleRoot = resolveModuleRoot('next')
288-
if (!existsSync(moduleRoot)) {
289-
return
290-
}
291-
const packagePath = join(moduleRoot, 'package.json')
292-
const packagePlugin = await fs.promises.readFile(packagePath, 'utf-8').then((contents) => JSON.parse(contents))
293-
return packagePlugin?.version
294-
}
295-
296-
export const nextVersionNum = async (sem?) => (sem ?? satisfies)(await nextPluginVersion(), '13.3.3 - 13.4.9')
297-
298277
export const getMatchedRoute = (
299278
paths: string,
300279
routesManifest: Array<StaticRoute>,

packages/runtime/src/templates/server.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import {
1717
localizeDataRoute,
1818
unlocalizeRoute,
1919
getMatchedRoute,
20-
nextVersionNum,
2120
} from './handlerUtils'
2221

2322
interface NetlifyConfig {
@@ -67,8 +66,7 @@ const getNetlifyNextServer = (NextServer: NextServerType) => {
6766
// conditionally use the prebundled React module
6867
// PrebundledReact should only apply when appDir is set it falls between the specified Next versions
6968
const { experimental }: NextConfigWithAppDir = this.nextConfig
70-
const version = await nextVersionNum()
71-
if (experimental?.appDir && version) this.netlifyPrebundleReact(url, this.nextConfig, parsedUrl)
69+
if (experimental?.appDir) this.netlifyPrebundleReact(url, this.nextConfig, parsedUrl)
7270

7371
// intercept on-demand revalidation requests and handle with the Netlify API
7472
if (headers['x-prerender-revalidate'] && this.netlifyConfig.revalidateToken) {

0 commit comments

Comments
 (0)