-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathindex.js
242 lines (201 loc) · 7.83 KB
/
index.js
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
const { writeJSON, unlink, existsSync, readFileSync, copy, ensureDir } = require('fs-extra')
const path = require('path')
const process = require('process')
const os = require('os')
const cpy = require('cpy')
const { dir: getTmpDir } = require('tmp-promise')
const plugin = require('../src')
const { HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME } = require('../src/constants')
const FIXTURES_DIR = `${__dirname}/fixtures`
const SAMPLE_PROJECT_DIR = `${__dirname}/../demo`
const constants = {
INTERNAL_FUNCTIONS_SRC: '.netlify/internal-functions',
PUBLISH_DIR: '.next',
}
const utils = {
build: {
failBuild(message) {
throw new Error(message)
},
},
run: async () => void 0,
cache: {
save: jest.fn(),
restore: jest.fn(),
},
}
// Temporary switch cwd
const changeCwd = function (cwd) {
const originalCwd = process.cwd()
process.chdir(cwd)
return () => {
process.chdir(originalCwd)
}
}
const onBuildHasRun = (netlifyConfig) =>
Boolean(netlifyConfig.functions[HANDLER_FUNCTION_NAME]?.included_files?.some((file) => file.includes('BUILD_ID')))
// Move .next from sample project to current directory
const moveNextDist = async function () {
await stubModules(['next', 'react', 'react-dom', 'sharp'])
await copy(path.join(SAMPLE_PROJECT_DIR, '.next'), path.join(process.cwd(), '.next'))
}
const stubModules = async function (modules) {
for (const mod of modules) {
const dir = path.join(process.cwd(), 'node_modules', mod)
await ensureDir(dir)
await writeJSON(path.join(dir, 'package.json'), { name: mod })
}
}
// Copy fixture files to the current directory
const useFixture = async function (fixtureName) {
const fixtureDir = `${FIXTURES_DIR}/${fixtureName}`
await cpy('**', process.cwd(), { cwd: fixtureDir, parents: true, overwrite: true, dot: true })
}
const netlifyConfig = { build: { command: 'npm run build' }, functions: {}, redirects: [] }
const defaultArgs = {
netlifyConfig,
utils,
constants,
}
let restoreCwd
let cleanup
// In each test, we change cwd to a temporary directory.
// This allows us not to have to mock filesystem operations.
beforeEach(async () => {
const tmpDir = await getTmpDir({ unsafeCleanup: true })
restoreCwd = changeCwd(tmpDir.path)
cleanup = tmpDir.cleanup
netlifyConfig.build.publish = path.posix.resolve('.next')
netlifyConfig.redirects = []
netlifyConfig.functions[HANDLER_FUNCTION_NAME] && (netlifyConfig.functions[HANDLER_FUNCTION_NAME].included_files = [])
netlifyConfig.functions[ODB_FUNCTION_NAME] && (netlifyConfig.functions[ODB_FUNCTION_NAME].included_files = [])
await useFixture('serverless_next_config')
})
afterEach(async () => {
jest.clearAllMocks()
jest.resetAllMocks()
delete process.env.NEXT_PRIVATE_TARGET
// Cleans up the temporary directory from `getTmpDir()` and do not make it
// the current directory anymore
restoreCwd()
await cleanup()
})
describe('preBuild()', () => {
test('fails if publishing the root of the project', () => {
defaultArgs.netlifyConfig.build.publish = path.resolve('.')
expect(plugin.onPreBuild(defaultArgs)).rejects.toThrowError(
/Your publish directory is pointing to the base directory of your site/,
)
})
test('fails if the build version is too old', () => {
expect(
plugin.onPreBuild({
...defaultArgs,
constants: { IS_LOCAL: true, NETLIFY_BUILD_VERSION: '18.15.0' },
}),
).rejects.toThrow('This version of the Essential Next.js plugin requires netlify-cli')
})
test('passes if the build version is new enough', async () => {
expect(
plugin.onPreBuild({
...defaultArgs,
constants: { IS_LOCAL: true, NETLIFY_BUILD_VERSION: '18.16.1' },
}),
).resolves.not.toThrow()
})
it('restores cache with right paths', async () => {
await useFixture('dist_dir_next_config')
const restore = jest.fn()
await plugin.onPreBuild({
...defaultArgs,
utils: { ...utils, cache: { restore } },
})
expect(restore).toHaveBeenCalledWith(path.posix.resolve('.next/cache'))
})
})
describe('onBuild()', () => {
test('runs onBuild', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
expect(onBuildHasRun(netlifyConfig)).toBe(true)
})
test("fails if BUILD_ID doesn't exist", async () => {
await moveNextDist()
await unlink(path.join(process.cwd(), '.next/BUILD_ID'))
const failBuild = jest.fn()
await plugin.onBuild({ ...defaultArgs, utils: { ...utils, build: { failBuild } } })
expect(failBuild).toHaveBeenCalled()
})
test('fails build if next export has run', async () => {
await moveNextDist()
await writeJSON(path.join(process.cwd(), '.next/export-detail.json'), {})
const failBuild = jest.fn()
await plugin.onBuild({ ...defaultArgs, utils: { ...utils, build: { failBuild } } })
expect(failBuild).toHaveBeenCalled()
})
test('copy handlers to the internal functions directory', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
expect(existsSync(`.netlify/internal-functions/___netlify-handler/___netlify-handler.js`)).toBeTruthy()
expect(existsSync(`.netlify/internal-functions/___netlify-handler/bridge.js`)).toBeTruthy()
expect(existsSync(`.netlify/internal-functions/___netlify-odb-handler/___netlify-odb-handler.js`)).toBeTruthy()
expect(existsSync(`.netlify/internal-functions/___netlify-odb-handler/bridge.js`)).toBeTruthy()
})
test('writes correct redirects to netlifyConfig', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
expect(netlifyConfig.redirects).toMatchSnapshot()
})
test('publish dir is/has next dist', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
expect(existsSync(path.resolve('.next/BUILD_ID'))).toBeTruthy()
})
test('sets correct config', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
const includes = [
'.next/server/**',
'.next/serverless/**',
'.next/*.json',
'.next/BUILD_ID',
'!../node_modules/next/dist/compiled/@ampproject/toolbox-optimizer/**/*',
`!node_modules/next/dist/server/lib/squoosh/**/*.wasm`,
`!node_modules/next/dist/next-server/server/lib/squoosh/**/*.wasm`,
'!node_modules/next/dist/compiled/webpack/bundle4.js',
'!node_modules/next/dist/compiled/webpack/bundle5.js',
'!node_modules/next/dist/compiled/terser/bundle.min.js',
'!node_modules/sharp/**/*',
]
// Relative paths in Windows are different
if (os.platform() !== 'win32') {
expect(netlifyConfig.functions[HANDLER_FUNCTION_NAME].included_files).toEqual(includes)
expect(netlifyConfig.functions[ODB_FUNCTION_NAME].included_files).toEqual(includes)
}
expect(netlifyConfig.functions[HANDLER_FUNCTION_NAME].node_bundler).toEqual('nft')
expect(netlifyConfig.functions[ODB_FUNCTION_NAME].node_bundler).toEqual('nft')
})
test('generates a file referencing all page sources', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
const handlerPagesFile = path.join(constants.INTERNAL_FUNCTIONS_SRC, HANDLER_FUNCTION_NAME, 'pages.js')
const odbHandlerPagesFile = path.join(constants.INTERNAL_FUNCTIONS_SRC, ODB_FUNCTION_NAME, 'pages.js')
expect(existsSync(handlerPagesFile)).toBeTruthy()
expect(existsSync(odbHandlerPagesFile)).toBeTruthy()
expect(readFileSync(handlerPagesFile, 'utf8')).toMatchSnapshot()
expect(readFileSync(odbHandlerPagesFile, 'utf8')).toMatchSnapshot()
})
})
describe('onPostBuild', () => {
test('saves cache with right paths', async () => {
await useFixture('dist_dir_next_config')
const save = jest.fn()
await plugin.onPostBuild({
...defaultArgs,
utils: { ...utils, cache: { save } },
})
expect(save).toHaveBeenCalledWith(path.posix.resolve('.next/cache'), {
digests: [path.posix.resolve('.next/build-manifest.json')],
})
})
})