-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathadvanced-api-routes.ts
188 lines (161 loc) · 5.01 KB
/
advanced-api-routes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { existsSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import type { PluginContext } from './plugin-context.js'
interface FunctionsConfigManifest {
version: number
functions: Record<string, Record<string, string | number>>
}
// eslint-disable-next-line no-shadow
export const enum ApiRouteType {
SCHEDULED = 'experimental-scheduled',
BACKGROUND = 'experimental-background',
}
interface ApiStandardConfig {
type?: never
runtime?: 'nodejs' | 'experimental-edge' | 'edge'
schedule?: never
}
interface ApiScheduledConfig {
type: ApiRouteType.SCHEDULED
runtime?: 'nodejs'
schedule: string
}
interface ApiBackgroundConfig {
type: ApiRouteType.BACKGROUND
runtime?: 'nodejs'
schedule?: never
}
type ApiConfig = ApiStandardConfig | ApiScheduledConfig | ApiBackgroundConfig
// Next.js already defines a default `pageExtensions` array in its `required-server-files.json` file
// In case it gets `undefined`, this is a fallback
const SOURCE_FILE_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx']
/**
* Find the source file for a given page route
*/
const getSourceFileForPage = (
page: string,
roots: string[],
pageExtensions = SOURCE_FILE_EXTENSIONS,
) => {
for (const root of roots) {
for (const extension of pageExtensions) {
const file = join(root, `${page}.${extension}`)
if (existsSync(file)) {
return file
}
const fileAtFolderIndex = join(root, page, `index.${extension}`)
if (existsSync(fileAtFolderIndex)) {
return fileAtFolderIndex
}
}
}
}
/**
* Given an array of base paths and candidate modules, return the first one that exists
*/
const findModuleFromBase = ({
paths,
candidates,
}: {
paths: string[]
candidates: string[]
}): string | null => {
for (const candidate of candidates) {
try {
const modulePath = require.resolve(candidate, { paths })
if (modulePath) {
return modulePath
}
} catch {
// Ignore the error
}
}
// if we couldn't find a module from paths, let's try to resolve from here
for (const candidate of candidates) {
try {
const modulePath = require.resolve(candidate)
if (modulePath) {
return modulePath
}
} catch {
// Ignore the error
}
}
return null
}
let extractConstValue: typeof import('next/dist/build/analysis/extract-const-value.js')
let parseModule: typeof import('next/dist/build/analysis/parse-module.js').parseModule
const extractConfigFromFile = async (apiFilePath: string, appDir: string): Promise<ApiConfig> => {
if (!apiFilePath || !existsSync(apiFilePath)) {
return {}
}
const extractConstValueModulePath = findModuleFromBase({
paths: [appDir],
candidates: ['next/dist/build/analysis/extract-const-value'],
})
const parseModulePath = findModuleFromBase({
paths: [appDir],
candidates: ['next/dist/build/analysis/parse-module'],
})
if (!extractConstValueModulePath || !parseModulePath) {
// Old Next.js version
return {}
}
if (!extractConstValue && extractConstValueModulePath) {
// eslint-disable-next-line import/no-dynamic-require, n/global-require
extractConstValue = require(extractConstValueModulePath)
}
if (!parseModule && parseModulePath) {
// eslint-disable-next-line prefer-destructuring, @typescript-eslint/no-var-requires, import/no-dynamic-require, n/global-require
parseModule = require(parseModulePath).parseModule
}
const { extractExportedConstValue } = extractConstValue
const fileContent = await readFile(apiFilePath, 'utf8')
// No need to parse if there's no "config"
if (!fileContent.includes('config')) {
return {}
}
const ast = await parseModule(apiFilePath, fileContent)
try {
return extractExportedConstValue(ast, 'config') as ApiConfig
} catch {
return {}
}
}
export async function getAPIRoutesConfigs(ctx: PluginContext) {
const functionsConfigManifestPath = join(
ctx.publishDir,
'server',
'functions-config-manifest.json',
)
if (!existsSync(functionsConfigManifestPath)) {
// before https://github.com/vercel/next.js/pull/60163 this file might not have been produced if there were no API routes at all
return []
}
const functionsConfigManifest = JSON.parse(
await readFile(functionsConfigManifestPath, 'utf-8'),
) as FunctionsConfigManifest
const appDir = ctx.resolveFromSiteDir('.')
const pagesDir = join(appDir, 'pages')
const srcPagesDir = join(appDir, 'src', 'pages')
const { pageExtensions } = ctx.requiredServerFiles.config
return Promise.all(
Object.keys(functionsConfigManifest.functions).map(async (apiRoute) => {
const filePath = getSourceFileForPage(apiRoute, [pagesDir, srcPagesDir], pageExtensions)
const sharedFields = {
apiRoute,
filePath,
config: {} as ApiConfig,
}
if (filePath) {
const config = await extractConfigFromFile(filePath, appDir)
return {
...sharedFields,
config,
}
}
return sharedFields
}),
)
}