-
Notifications
You must be signed in to change notification settings - Fork 8
/
config.test.ts
419 lines (372 loc) · 10.9 KB
/
config.test.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
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
import { promises as fs } from 'fs'
import { rm } from 'fs/promises'
import { join, resolve } from 'path'
import { pathToFileURL } from 'url'
import tmp from 'tmp-promise'
import { test, expect, vi, describe } from 'vitest'
import { fixturesDir, useFixture } from '../test/util.js'
import { DenoBridge } from './bridge.js'
import { bundle } from './bundler.js'
import { FunctionConfig, getFunctionConfig } from './config.js'
import type { Declaration } from './declaration.js'
import { ImportMap } from './import_map.js'
import { RateLimitAction, RateLimitAggregator } from './rate_limit.js'
const importMapFile = {
baseURL: new URL('file:///some/path/import-map.json'),
imports: {
'alias:helper': pathToFileURL(join(fixturesDir, 'helper.ts')).toString(),
},
}
const invalidDefaultExportErr = (path: string) =>
`Default export in '${path}' must be a function. More on the Edge Functions API at https://ntl.fyi/edge-api.`
interface TestFunctions {
error?: RegExp
expectedConfig?: FunctionConfig
name: string
source: string
testName: string
userLog?: string
}
const functions: TestFunctions[] = [
{
testName: 'no config',
expectedConfig: {},
name: 'func1',
source: `export default async () => new Response("Hello from function one")`,
},
{
testName: 'empty config',
expectedConfig: {},
name: 'func2',
source: `
export default async () => new Response("Hello from function two")
export const config = {}
`,
},
{
testName: 'config with wrong type',
name: 'func3',
source: `
export default async () => new Response("Hello from function two")
export const config = () => ({})
`,
error:
/^The 'config' export in edge function at '(.*)' must be an object\. More on the Edge Functions API at https:\/\/ntl\.fyi\/edge-api\.$/,
},
{
testName: 'config with syntax error',
name: 'func4',
source: `
export default async () => new Response("Hello from function two")
export const config
`,
error:
/^Could not load edge function at '(.*)'\. More on the Edge Functions API at https:\/\/ntl\.fyi\/edge-api\.$/,
},
{
testName: 'config with correct onError',
expectedConfig: { onError: 'bypass' },
name: 'func5',
source: `
export default async () => new Response("Hello from function two")
export const config = { onError: "bypass" }
`,
},
{
testName: 'config with wrong onError',
name: 'func6',
source: `
export default async () => new Response("Hello from function two")
export const config = { onError: "foo" }
`,
error: /The 'onError' configuration property in edge function at .*/,
},
{
testName: 'config with `path`',
expectedConfig: { path: '/home' },
name: 'func7',
source: `
export default async () => new Response("Hello from function three")
export const config = { path: "/home" }
`,
},
{
testName: 'config with path, generator, name and onError`',
expectedConfig: {
path: '/home',
generator: '@netlify/fake-plugin@1.0.0',
name: 'a displayName',
onError: 'bypass',
},
name: 'func8',
source: `
export default async () => new Response("Hello from function three")
export const config = {
path: "/home",
generator: '@netlify/fake-plugin@1.0.0',
name: 'a displayName',
onError: 'bypass',
}
`,
},
{
testName: 'config with ratelimit',
expectedConfig: {
path: '/ratelimit',
name: 'a limit rate',
rateLimit: {
windowSize: 10,
windowLimit: 100,
aggregateBy: [RateLimitAggregator.IP, RateLimitAggregator.Domain],
},
},
name: 'func9',
source: `
export default async () => new Response("Rate my limits")
export const config = {
path: "/ratelimit",
rateLimit: {
windowSize: 10,
windowLimit: 100,
aggregateBy: ["ip", "domain"],
},
name: 'a limit rate',
}
`,
},
{
testName: 'config with rewrite',
expectedConfig: {
path: '/rewrite',
name: 'a limit rewrite',
rateLimit: {
action: RateLimitAction.Rewrite,
to: '/rewritten',
windowSize: 20,
windowLimit: 200,
aggregateBy: [RateLimitAggregator.IP, RateLimitAggregator.Domain],
},
},
name: 'func9',
source: `
export default async () => new Response("Rate my limits")
export const config = {
path: "/rewrite",
rateLimit: {
action: "rewrite",
to: "/rewritten",
windowSize: 20,
windowLimit: 200,
aggregateBy: ["ip", "domain"],
},
name: 'a limit rewrite',
}
`,
},
]
describe('`getFunctionConfig` extracts configuration properties from function file', () => {
test.each(functions)('$testName', async (func) => {
const { path: tmpDir } = await tmp.dir()
const deno = new DenoBridge({
cacheDirectory: tmpDir,
})
const logger = {
user: vi.fn().mockResolvedValue(null),
system: vi.fn().mockResolvedValue(null),
}
const path = join(tmpDir, `${func.name}.js`)
await fs.writeFile(path, func.source)
const funcCall = () =>
getFunctionConfig({
func: {
name: func.name,
path,
},
importMap: new ImportMap([importMapFile]),
deno,
log: logger,
})
if (func.error) {
await expect(funcCall()).rejects.toThrowError(func.error)
} else if (func.userLog) {
await expect(funcCall()).resolves.not.toThrowError()
expect(logger.user).toHaveBeenCalledWith(expect.stringMatching(func.userLog))
} else {
const config = await funcCall()
expect(config).toEqual(func.expectedConfig)
expect(logger.user).not.toHaveBeenCalled()
}
await rm(tmpDir, { force: true, recursive: true, maxRetries: 10 })
})
})
test('Loads function paths from the in-source `config` function', async () => {
const { basePath, cleanup, distPath } = await useFixture('with_config')
const userDirectory = resolve(basePath, 'netlify', 'edge-functions')
const internalDirectory = resolve(basePath, '.netlify', 'edge-functions')
const declarations: Declaration[] = [
{
function: 'framework-func2',
path: '/framework-func2',
},
{
function: 'user-func2',
path: '/user-func2',
method: ['PATCH'],
},
]
const result = await bundle([internalDirectory, userDirectory], distPath, declarations, {
basePath,
configPath: join(internalDirectory, 'config.json'),
})
const generatedFiles = await fs.readdir(distPath)
expect(result.functions.length).toBe(7)
expect(generatedFiles.length).toBe(2)
const manifestFile = await fs.readFile(resolve(distPath, 'manifest.json'), 'utf8')
const manifest = JSON.parse(manifestFile)
const { bundles, routes, post_cache_routes: postCacheRoutes, function_config: functionConfig } = manifest
expect(bundles.length).toBe(1)
expect(bundles[0].format).toBe('eszip2')
expect(generatedFiles.includes(bundles[0].asset)).toBe(true)
expect(routes.length).toBe(6)
expect(routes[0]).toEqual({
function: 'framework-func2',
pattern: '^/framework-func2/?$',
excluded_patterns: [],
path: '/framework-func2',
})
expect(routes[1]).toEqual({
function: 'user-func2',
pattern: '^/user-func2/?$',
excluded_patterns: [],
path: '/user-func2',
methods: ['PATCH'],
})
expect(routes[2]).toEqual({
function: 'framework-func1',
pattern: '^/framework-func1/?$',
excluded_patterns: [],
path: '/framework-func1',
})
expect(routes[3]).toEqual({
function: 'user-func1',
pattern: '^/user-func1/?$',
excluded_patterns: [],
path: '/user-func1',
})
expect(routes[4]).toEqual({
function: 'user-func3',
pattern: '^/user-func3/?$',
excluded_patterns: [],
path: '/user-func3',
})
expect(routes[5]).toEqual({
function: 'user-func5',
pattern: '^/user-func5(?:/(.*))/?$',
excluded_patterns: [],
path: '/user-func5/*',
methods: ['GET'],
})
expect(postCacheRoutes.length).toBe(1)
expect(postCacheRoutes[0]).toEqual({
function: 'user-func4',
pattern: '^/user-func4/?$',
excluded_patterns: [],
path: '/user-func4',
methods: ['POST', 'PUT'],
})
expect(Object.keys(functionConfig)).toHaveLength(1)
expect(functionConfig['user-func5']).toEqual({
excluded_patterns: ['^/user-func5/excluded/?$'],
})
await cleanup()
})
test('Passes validation if default export exists and is a function', async () => {
const { path: tmpDir } = await tmp.dir()
const deno = new DenoBridge({
cacheDirectory: tmpDir,
})
const func = {
name: 'func1',
source: `
const func = () => new Response("Hello world!")
export default func
`,
}
const logger = {
user: vi.fn().mockResolvedValue(null),
system: vi.fn().mockResolvedValue(null),
}
const path = join(tmpDir, `${func.name}.ts`)
await fs.writeFile(path, func.source)
await expect(
getFunctionConfig({
func: {
name: func.name,
path,
},
importMap: new ImportMap([importMapFile]),
deno,
log: logger,
}),
).resolves.not.toThrow()
await rm(tmpDir, { force: true, recursive: true, maxRetries: 10 })
})
test('Fails validation if default export is not function', async () => {
const { path: tmpDir } = await tmp.dir()
const deno = new DenoBridge({
cacheDirectory: tmpDir,
})
const func = {
name: 'func2',
source: `
const func = new Response("Hello world!")
export default func
`,
}
const logger = {
user: vi.fn().mockResolvedValue(null),
system: vi.fn().mockResolvedValue(null),
}
const path = join(tmpDir, `${func.name}.ts`)
await fs.writeFile(path, func.source)
const config = getFunctionConfig({
func: {
name: func.name,
path,
},
importMap: new ImportMap([importMapFile]),
deno,
log: logger,
})
await expect(config).rejects.toThrowError(invalidDefaultExportErr(path))
await rm(tmpDir, { force: true, recursive: true, maxRetries: 10 })
})
test('Fails validation if default export is not present', async () => {
const { path: tmpDir } = await tmp.dir()
const deno = new DenoBridge({
cacheDirectory: tmpDir,
})
const func = {
name: 'func3',
source: `
export const func = () => new Response("Hello world!")
`,
}
const logger = {
user: vi.fn().mockResolvedValue(null),
system: vi.fn().mockResolvedValue(null),
}
const path = join(tmpDir, `${func.name}.ts`)
await fs.writeFile(path, func.source)
const config = getFunctionConfig({
func: {
name: func.name,
path,
},
importMap: new ImportMap([importMapFile]),
deno,
log: logger,
})
await expect(config).rejects.toThrowError(invalidDefaultExportErr(path))
await rm(tmpDir, { force: true, recursive: true, maxRetries: 10 })
})