-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathindex.js
434 lines (367 loc) · 14 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
const { writeJSON, unlink, existsSync, readFileSync, copy, ensureDir, readJson } = 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 { join } = require('pathe')
const { matchMiddleware, stripLocale } = require('../src/helpers/files')
const FIXTURES_DIR = `${__dirname}/fixtures`
const SAMPLE_PROJECT_DIR = `${__dirname}/../demo`
const constants = {
INTERNAL_FUNCTIONS_SRC: '.netlify/internal-functions',
PUBLISH_DIR: '.next',
FUNCTIONS_DIST: '.netlify/functions',
}
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')))
const rewriteAppDir = async function () {
const manifest = path.join('.next', 'required-server-files.json')
const manifestContent = await readJson(manifest)
manifestContent.appDir = process.cwd()
await writeJSON(manifest, manifestContent)
}
// Move .next from sample project to current directory
const moveNextDist = async function () {
await stubModules(['next', 'sharp'])
await copy(path.join(SAMPLE_PROJECT_DIR, '.next'), path.join(process.cwd(), '.next'))
await rewriteAppDir()
}
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.build.environment = {}
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()
// 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'))
})
it('forces the target to "server"', async () => {
const netlifyConfig = { ...defaultArgs.netlifyConfig }
await plugin.onPreBuild({ ...defaultArgs, netlifyConfig })
expect(netlifyConfig.build.environment.NEXT_PRIVATE_TARGET).toBe('server')
})
})
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('generates static files manifest', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
const manifestPath = path.resolve('.next/static-manifest.json')
expect(existsSync(manifestPath)).toBeTruthy()
const data = (await readJson(manifestPath)).sort()
expect(data).toMatchSnapshot()
})
test('moves static files to root', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
const data = JSON.parse(readFileSync(path.resolve('.next/static-manifest.json'), 'utf8'))
data.forEach((file) => {
expect(existsSync(path.resolve(path.join('.next', file)))).toBeTruthy()
expect(existsSync(path.resolve(path.join('.next', 'server', 'pages', file)))).toBeFalsy()
})
})
test('copies default locale files to top level', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
const data = JSON.parse(readFileSync(path.resolve('.next/static-manifest.json'), 'utf8'))
const locale = 'en/'
data.forEach((file) => {
if (!file.startsWith(locale)) {
return
}
const trimmed = file.substring(locale.length)
expect(existsSync(path.resolve(path.join('.next', trimmed)))).toBeTruthy()
})
})
test('skips static files that match middleware', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
expect(existsSync(path.resolve(path.join('.next', 'en', 'middle.html')))).toBeFalsy()
expect(existsSync(path.resolve(path.join('.next', 'server', 'pages', 'en', 'middle.html')))).toBeTruthy()
})
test('sets correct config', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
const includes = [
'.next/server/**',
'.next/serverless/**',
'.next/*.json',
'.next/BUILD_ID',
'.next/static/chunks/webpack-middleware*.js',
'!.next/server/**/*.js.nft.json',
'!../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()
})
test('generates entrypoints with correct references', async () => {
await moveNextDist()
await plugin.onBuild(defaultArgs)
const handlerFile = path.join(
constants.INTERNAL_FUNCTIONS_SRC,
HANDLER_FUNCTION_NAME,
`${HANDLER_FUNCTION_NAME}.js`,
)
const odbHandlerFile = path.join(constants.INTERNAL_FUNCTIONS_SRC, ODB_FUNCTION_NAME, `${ODB_FUNCTION_NAME}.js`)
expect(existsSync(handlerFile)).toBeTruthy()
expect(existsSync(odbHandlerFile)).toBeTruthy()
expect(readFileSync(handlerFile, 'utf8')).toMatch(`(config, "../../..", pageRoot, staticManifest)`)
expect(readFileSync(odbHandlerFile, 'utf8')).toMatch(`(config, "../../..", pageRoot, staticManifest)`)
expect(readFileSync(handlerFile, 'utf8')).toMatch(`require("../../../.next/required-server-files.json")`)
expect(readFileSync(odbHandlerFile, 'utf8')).toMatch(`require("../../../.next/required-server-files.json")`)
})
})
describe('onPostBuild', () => {
test('saves cache with right paths', async () => {
const save = jest.fn()
await plugin.onPostBuild({
...defaultArgs,
utils: { ...utils, cache: { save }, functions: { list: jest.fn().mockResolvedValue([]) } },
})
expect(save).toHaveBeenCalledWith(path.posix.resolve('.next/cache'), {
digests: [path.posix.resolve('.next/build-manifest.json')],
})
})
test('warns if old functions exist', async () => {
const list = jest.fn().mockResolvedValue([
{
name: 'next_test',
mainFile: join(constants.INTERNAL_FUNCTIONS_SRC, 'next_test', 'next_test.js'),
runtime: 'js',
extension: '.js',
},
{
name: 'next_demo',
mainFile: join(constants.INTERNAL_FUNCTIONS_SRC, 'next_demo', 'next_demo.js'),
runtime: 'js',
extension: '.js',
},
])
const oldLog = console.log
const logMock = jest.fn()
console.log = logMock
await plugin.onPostBuild({
...defaultArgs,
utils: { ...utils, cache: { save: jest.fn() }, functions: { list } },
})
expect(logMock).toHaveBeenCalledWith(
expect.stringContaining(
`We have found the following functions in your site that seem to be left over from the old Next.js plugin (v3). We have guessed this because the name starts with "next_".`,
),
)
console.log = oldLog
})
})
describe('utility functions', () => {
test('middleware tester matches correct paths', () => {
const middleware = ['middle', 'sub/directory']
const paths = [
'middle.html',
'middle',
'middle/',
'middle/ware',
'sub/directory',
'sub/directory.html',
'sub/directory/child',
'sub/directory/child.html',
]
for (const path of paths) {
expect(matchMiddleware(middleware, path)).toBeTruthy()
}
})
test('middleware tester does not match incorrect paths', () => {
const middleware = ['middle', 'sub/directory']
const paths = [
'middl',
'',
'somethingelse',
'another.html',
'another/middle.html',
'sub/anotherdirectory.html',
'sub/directoryelse',
'sub/directoryelse.html',
]
for (const path of paths) {
expect(matchMiddleware(middleware, path)).toBeFalsy()
}
})
test('middleware tester matches root middleware', () => {
const middleware = ['']
const paths = [
'middl',
'',
'somethingelse',
'another.html',
'another/middle.html',
'sub/anotherdirectory.html',
'sub/directoryelse',
'sub/directoryelse.html',
]
for (const path of paths) {
expect(matchMiddleware(middleware, path)).toBeTruthy()
}
})
test('stripLocale correctly strips matching locales', () => {
const locales = ['en', 'fr', 'en-GB']
const paths = [
['en/file.html', 'file.html'],
['fr/file.html', 'file.html'],
['en-GB/file.html', 'file.html'],
['file.html', 'file.html'],
]
for (const [path, expected] of paths) {
expect(stripLocale(path, locales)).toEqual(expected)
}
})
test('stripLocale does not touch non-matching matching locales', () => {
const locales = ['en', 'fr', 'en-GB']
const paths = ['de/file.html', 'enfile.html', 'en-US/file.html']
for (const path of paths) {
expect(stripLocale(path, locales)).toEqual(path)
}
})
})