-
Notifications
You must be signed in to change notification settings - Fork 8
/
config.test.ts
330 lines (272 loc) · 8.78 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
import { promises as fs } from 'fs'
import { join, resolve } from 'path'
import { pathToFileURL } from 'url'
import { deleteAsync } from 'del'
import tmp from 'tmp-promise'
import { test, expect, vi } from 'vitest'
import { fixturesDir, useFixture } from '../test/util.js'
import { DenoBridge } from './bridge.js'
import { bundle } from './bundler.js'
import { getFunctionConfig } from './config.js'
import type { Declaration } from './declaration.js'
import { ImportMap } from './import_map.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.`
test('`getFunctionConfig` extracts configuration properties from function file', async () => {
const { path: tmpDir } = await tmp.dir()
const deno = new DenoBridge({
cacheDirectory: tmpDir,
})
const functions = [
// No config
{
expectedConfig: {},
name: 'func1',
source: `export default async () => new Response("Hello from function one")`,
},
// Empty config
{
expectedConfig: {},
name: 'func2',
source: `
export default async () => new Response("Hello from function two")
export const config = () => ({})
`,
},
// Config with the wrong type
{
expectedConfig: {},
name: 'func3',
source: `
export default async () => new Response("Hello from function two")
export const config = {}
`,
userLog: /^'config' export in edge function at '(.*)' must be a function$/,
},
// Config with a syntax error
{
expectedConfig: {},
name: 'func4',
source: `
export default async () => new Response("Hello from function two")
export const config
`,
userLog: /^Could not load edge function at '(.*)'$/,
},
// Config that throws
{
expectedConfig: {},
name: 'func5',
source: `
export default async () => new Response("Hello from function two")
export const config = () => {
throw new Error('uh-oh')
}
`,
userLog: /^Error while running 'config' function in edge function at '(.*)'$/,
},
// Config with `path`
{
expectedConfig: { path: '/home' },
name: 'func6',
source: `
export default async () => new Response("Hello from function three")
export const config = () => ({ path: "/home" })
`,
},
// Config that prints to stdout
{
expectedConfig: { path: '/home' },
name: 'func7',
source: `
export default async () => new Response("Hello from function three")
export const config = () => {
console.log("Hello from config!")
return { path: "/home" }
}
`,
userLog: /^Hello from config!$/,
},
]
for (const func of functions) {
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 config = await getFunctionConfig(
{
name: func.name,
path,
},
new ImportMap([importMapFile]),
deno,
logger,
)
expect(config).toEqual(func.expectedConfig)
if (func.userLog) {
expect(logger.user).toHaveBeenNthCalledWith(1, expect.stringMatching(func.userLog))
} else {
expect(logger.user).not.toHaveBeenCalled()
}
}
await deleteAsync(tmpDir, { force: true })
})
test('Ignores function paths from the in-source `config` function if the feature flag is off', 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[] = []
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(6)
expect(generatedFiles.length).toBe(2)
const manifestFile = await fs.readFile(resolve(distPath, 'manifest.json'), 'utf8')
const manifest = JSON.parse(manifestFile)
const { bundles, routes } = manifest
expect(bundles.length).toBe(1)
expect(bundles[0].format).toBe('eszip2')
expect(generatedFiles.includes(bundles[0].asset)).toBe(true)
expect(routes.length).toBe(0)
await cleanup()
})
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',
},
]
const result = await bundle([internalDirectory, userDirectory], distPath, declarations, {
basePath,
configPath: join(internalDirectory, 'config.json'),
featureFlags: {
edge_functions_config_export: true,
},
})
const generatedFiles = await fs.readdir(distPath)
expect(result.functions.length).toBe(6)
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 } = manifest
expect(bundles.length).toBe(1)
expect(bundles[0].format).toBe('eszip2')
expect(generatedFiles.includes(bundles[0].asset)).toBe(true)
expect(routes.length).toBe(5)
expect(routes[0]).toEqual({ function: 'framework-func2', pattern: '^/framework-func2/?$' })
expect(routes[1]).toEqual({ function: 'user-func2', pattern: '^/user-func2/?$' })
expect(routes[2]).toEqual({ function: 'framework-func1', pattern: '^/framework-func1/?$' })
expect(routes[3]).toEqual({ function: 'user-func1', pattern: '^/user-func1/?$' })
expect(routes[4]).toEqual({ function: 'user-func3', pattern: '^/user-func3/?$' })
expect(postCacheRoutes.length).toBe(1)
expect(postCacheRoutes[0]).toEqual({ function: 'user-func4', pattern: '^/user-func4/?$' })
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)
expect(async () => {
await getFunctionConfig(
{
name: func.name,
path,
},
new ImportMap([importMapFile]),
deno,
logger,
)
}).not.toThrow()
await deleteAsync(tmpDir, { force: true })
})
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(
{
name: func.name,
path,
},
new ImportMap([importMapFile]),
deno,
logger,
)
await expect(config).rejects.toThrowError(invalidDefaultExportErr(path))
await deleteAsync(tmpDir, { force: true })
})
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(
{
name: func.name,
path,
},
new ImportMap([importMapFile]),
deno,
logger,
)
await expect(config).rejects.toThrowError(invalidDefaultExportErr(path))
await deleteAsync(tmpDir, { force: true })
})