-
Notifications
You must be signed in to change notification settings - Fork 393
/
Copy pathdev-miscellaneous.test.ts
1471 lines (1307 loc) · 45 KB
/
dev-miscellaneous.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import events from 'node:events'
import { Buffer } from 'buffer'
import path from 'path'
import { platform } from 'process'
import { fileURLToPath } from 'url'
import { setProperty } from 'dot-prop'
import execa, { ExecaError } from 'execa'
import getAvailablePort from 'get-port'
import jwt from 'jsonwebtoken'
import fetch from 'node-fetch'
import { type TestContext, describe, test } from 'vitest'
import type { HandlerEvent, HandlerContext } from '@netlify/functions'
import type { Context as EdgeHandlerContext } from '@netlify/edge-functions'
import { cliPath } from '../../utils/cli-path.js'
import { getExecaOptions, withDevServer } from '../../utils/dev-server.js'
import { withMockApi } from '../../utils/mock-api.js'
import { pause } from '../../utils/pause.js'
import { withSiteBuilder, type SiteBuilder } from '../../utils/site-builder.js'
import { normalize } from '../../utils/snapshots.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const JWT_EXPIRY = 1_893_456_000
const getToken = async ({
jwtRolePath = 'app_metadata.authorization.roles',
jwtSecret = 'secret',
roles,
}: {
jwtRolePath?: string | undefined
jwtSecret?: string | undefined
roles?: string[] | undefined
}) => {
const payload = {
exp: JWT_EXPIRY,
sub: '12345678',
}
return Promise.resolve(jwt.sign(setProperty(payload, jwtRolePath, roles), jwtSecret))
}
const setupRoleBasedRedirectsSite = (builder: SiteBuilder) => {
builder
.withContentFiles([
{
path: 'index.html',
content: '<html>index</html>',
},
{
path: 'admin/foo.html',
content: '<html>foo</html>',
},
])
.withRedirectsFile({
redirects: [{ from: `/admin/*`, to: ``, status: '200!', condition: 'Role=admin' }],
})
return builder
}
const validateRoleBasedRedirectsSite = async ({
builder,
jwtRolePath,
jwtSecret,
t,
}: {
builder: SiteBuilder
jwtRolePath?: string | undefined
jwtSecret?: string | undefined
t: TestContext
}) => {
const [adminToken, editorToken] = await Promise.all([
getToken({ jwtSecret, jwtRolePath, roles: ['admin'] }),
getToken({ jwtSecret, jwtRolePath, roles: ['editor'] }),
])
await withDevServer({ cwd: builder.directory }, async (server) => {
const [unauthenticatedResponse, authenticatedResponse, wrongRoleResponse] = await Promise.all([
fetch(`${server.url}/admin`),
fetch(`${server.url}/admin/foo`, {
headers: {
cookie: `nf_jwt=${adminToken}`,
},
}),
fetch(`${server.url}/admin/foo`, {
headers: {
cookie: `nf_jwt=${editorToken}`,
},
}),
])
t.expect(unauthenticatedResponse.status).toBe(404)
t.expect(await unauthenticatedResponse.text()).toEqual('Not Found')
t.expect(authenticatedResponse.status).toBe(200)
t.expect(await authenticatedResponse.text()).toEqual('<html>foo</html>')
t.expect(wrongRoleResponse.status).toBe(404)
t.expect(await wrongRoleResponse.text()).toEqual('Not Found')
})
}
describe.concurrent('commands/dev-miscellaneous', () => {
test('should follow redirect for fully qualified rule', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: { publish: publicDir },
},
})
.withContentFiles([
{
path: path.join(publicDir, 'index.html'),
content: '<html>index</html>',
},
{
path: path.join(publicDir, 'local-hello.html'),
content: '<html>hello</html>',
},
])
.withRedirectsFile({
redirects: [{ from: `http://localhost/hello-world`, to: `/local-hello`, status: 200 }],
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const response = await fetch(`${server.url}/hello-world`)
t.expect(response.status).toBe(200)
t.expect(await response.text()).toEqual('<html>hello</html>')
})
})
})
test('should return 202 ok and empty response for background function', async (t) => {
await withSiteBuilder(t, async (builder) => {
builder.withNetlifyToml({ config: { functions: { directory: 'functions' } } }).withFunction({
path: 'hello-background.js',
handler: () => {
console.log("Look at me I'm a background task")
},
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const response = await fetch(`${server.url}/.netlify/functions/hello-background`)
t.expect(response.status).toBe(202)
t.expect(await response.text()).toEqual('')
})
})
})
test('should print logs emitted to `console` from user function handler', async (t) => {
await withSiteBuilder(t, async (builder) => {
await builder
.withNetlifyToml({ config: { functions: { directory: 'functions' } } })
.withFunction({
path: 'hello.js',
handler: () => {
console.log('Hello from the user function handler')
return Response.json({})
},
})
.build()
await withDevServer({ cwd: builder.directory }, async ({ outputBuffer, url }) => {
await fetch(`${url}/.netlify/functions/hello`)
const output = outputBuffer.toString()
t.expect(output).toMatch(/Hello from the user function handler/)
})
})
})
test('given a background function, context should have empty `clientContext` and null `identity`', async (t) => {
await withSiteBuilder(t, async (builder) => {
await builder
.withNetlifyToml({ config: { functions: { directory: 'functions' } } })
.withFunction({
path: 'hello-background.js',
handler: (_: HandlerEvent, context: HandlerContext) => {
console.log(`__CLIENT_CONTEXT__START__${JSON.stringify(context)}__CLIENT_CONTEXT__END__`)
},
})
.build()
await withDevServer({ cwd: builder.directory }, async ({ outputBuffer, url }) => {
await fetch(`${url}/.netlify/functions/hello-background`)
const output = outputBuffer.toString()
const context = JSON.parse(output.match(/__CLIENT_CONTEXT__START__(.*)__CLIENT_CONTEXT__END__/)?.[1] ?? '""')
t.expect(context).toHaveProperty('clientContext', {})
t.expect(context).toHaveProperty('identity', null)
})
})
})
test('function clientContext.custom.netlify should be set', async (t) => {
const { expect } = t
await withSiteBuilder(t, async (builder) => {
await builder
.withNetlifyToml({ config: { functions: { directory: 'functions' } } })
.withFunction({
path: 'hello.js',
handler: async (_: HandlerEvent, context: HandlerContext) =>
Promise.resolve({
statusCode: 200,
body: JSON.stringify(context),
}),
})
.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const res = await fetch(`${server.url}/.netlify/functions/hello`, {
headers: {
Authorization:
'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb3VyY2UiOiJuZXRsaWZ5IGRldiIsInRlc3REYXRhIjoiTkVUTElGWV9ERVZfTE9DQUxMWV9FTVVMQVRFRF9JREVOVElUWSJ9.2eSDqUOZAOBsx39FHFePjYj12k0LrxldvGnlvDu3GMI',
},
})
const body = await res.json()
expect(body).toHaveProperty(
'clientContext.identity.url',
'https://netlify-dev-locally-emulated-identity.netlify.app/.netlify/identity',
)
expect(body).toHaveProperty('clientContext.custom.netlify', expect.any(String))
const rawNetlifyContext = (body as { clientContext: { custom: { netlify: string } } }).clientContext.custom
.netlify
const netlifyContext = Buffer.from(rawNetlifyContext, 'base64').toString('utf-8')
expect(JSON.parse(netlifyContext)).toHaveProperty(
'identity.url',
'https://netlify-dev-locally-emulated-identity.netlify.app/.netlify/identity',
)
})
})
})
test('should enforce role based redirects with default secret and role path', async (t) => {
await withSiteBuilder(t, async (builder) => {
setupRoleBasedRedirectsSite(builder)
await builder.build()
await t.expect(validateRoleBasedRedirectsSite({ builder, t })).resolves.not.toThrowError()
})
})
test('should enforce role based redirects with custom secret and role path', async (t) => {
await withSiteBuilder(t, async (builder) => {
const jwtSecret = 'custom'
const jwtRolePath = 'roles'
setupRoleBasedRedirectsSite(builder).withNetlifyToml({
config: {
dev: {
jwtSecret,
jwtRolePath,
},
},
})
await builder.build()
await t.expect(validateRoleBasedRedirectsSite({ builder, t, jwtSecret, jwtRolePath })).resolves.not.toThrowError()
})
})
test('Serves an Edge Function that terminates a response', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
edge_functions: [
{
function: 'hello',
path: '/edge-function',
},
],
},
})
.withContentFiles([
{
path: path.join(publicDir, 'index.html'),
content: '<html>index</html>',
},
])
.withEdgeFunction({
handler: (req, context) =>
Response.json({
requestID: req.headers.get('x-nf-request-id'),
deploy: (context as EdgeHandlerContext & { deploy: { context: string; id: string; published: boolean } })
.deploy,
}),
name: 'hello',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const response = await fetch(`${server.url}/edge-function`)
const responseBody = await response.json()
t.expect(response.status).toBe(200)
t.expect(responseBody).toEqual({
requestID: response.headers.get('x-nf-request-id'),
deploy: {
context: 'dev',
id: '0',
published: false,
},
})
})
})
})
test('Serves an Edge Function with a rewrite', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
edge_functions: [
{
function: 'hello-legacy',
path: '/hello-legacy',
},
{
function: 'yell',
path: '/hello',
},
{
function: 'hello',
path: '/hello',
},
],
},
})
.withContentFiles([
{
path: path.join(publicDir, 'goodbye.html'),
content: '<html>goodbye</html>',
},
])
.withEdgeFunction({
handler: async (_: Request, context: EdgeHandlerContext) => {
const res = await context.next()
const text = await res.text()
return new Response(text.toUpperCase(), res)
},
name: 'yell',
})
.withEdgeFunction({
handler: (_, context) => context.rewrite('/goodbye'),
name: 'hello-legacy',
})
.withEdgeFunction({
handler: (req) => new URL('/goodbye', req.url),
name: 'hello',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const [response1, response2] = await Promise.all([
fetch(`${server.url}/hello-legacy`),
fetch(`${server.url}/hello`),
])
t.expect(response1.status).toBe(200)
t.expect(await response1.text()).toEqual('<html>goodbye</html>')
t.expect(response2.status).toBe(200)
t.expect(await response2.text()).toEqual('<HTML>GOODBYE</HTML>')
})
})
})
test('Serves an Edge Function with caching', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
edge_functions: [
{
function: 'hello',
path: '/edge-function',
cache: 'manual',
},
],
},
})
.withContentFiles([
{
path: path.join(publicDir, 'index.html'),
content: '<html>index</html>',
},
])
.withEdgeFunction({
handler: () => new Response('Hello world'),
name: 'hello',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const response = await fetch(`${server.url}/edge-function`)
t.expect(response.status).toBe(200)
t.expect(await response.text()).toEqual('Hello world')
})
})
})
test('Serves an Edge Function that includes context with site and deploy information', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
edge_functions: [
{
function: 'siteContext',
path: '/*',
},
],
},
})
.withEdgeFunction({
handler: async (_, context) => {
const { deploy, site } = context
return Promise.resolve(Response.json({ deploy, site }))
},
name: 'siteContext',
})
await builder.build()
const siteInfo = {
account_slug: 'test-account',
id: 'site_id',
name: 'site-name',
url: 'site-url',
}
const routes = [
{ path: 'sites/site_id', response: siteInfo },
{ path: 'sites/site_id/service-instances', response: [] },
{
path: 'accounts',
response: [{ slug: siteInfo.account_slug }],
},
]
await withMockApi(routes, async ({ apiUrl }) => {
await withDevServer(
{
cwd: builder.directory,
offline: false,
env: {
NETLIFY_API_URL: apiUrl,
NETLIFY_SITE_ID: 'site_id',
NETLIFY_AUTH_TOKEN: 'fake-token',
},
},
async (server) => {
const response = await fetch(server.url)
t.expect(response.status).toBe(200)
t.expect(JSON.parse(await response.text())).toStrictEqual({
deploy: { context: 'dev', id: '0', published: false },
site: { id: 'site_id', name: 'site-name', url: server.url },
})
},
)
})
})
})
test('Serves an Edge Function that transforms the response', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
edge_functions: [
{
function: 'yell',
path: '/*',
},
],
},
})
.withContentFiles([
{
path: path.join(publicDir, 'hello.html'),
content: '<html>hello</html>',
},
])
.withEdgeFunction({
handler: async (_, context) => {
const res = await context.next()
const text = await res.text()
return new Response(text.toUpperCase(), res)
},
name: 'yell',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const response = await fetch(`${server.url}/hello`)
t.expect(response.status).toBe(200)
t.expect(await response.text()).toEqual('<HTML>HELLO</HTML>')
})
})
})
test('Serves an Edge Function that streams the response', { retry: 3 }, async (t) => {
const { expect } = t
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
edge_functions: [
{
function: 'stream',
path: '/stream',
},
],
},
})
.withEdgeFunction({
handler: async () => {
const body = new ReadableStream({
async start(controller) {
setInterval(() => {
const msg = new TextEncoder().encode(`${Date.now().toString()}\r\n`)
controller.enqueue(msg)
}, 100)
setTimeout(() => {
controller.close()
}, 500)
},
})
return Promise.resolve(
new Response(body, {
headers: {
'content-type': 'text/event-stream',
},
status: 200,
}),
)
},
name: 'stream',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const res = await fetch(`${server.url}/stream`)
const stream = res.body
expect(stream).not.toBeNull()
let numberOfChunks = 0
stream!.on('data', () => {
numberOfChunks += 1
})
await events.once(stream!, 'end')
// streamed responses arrive in more than one batch
expect(numberOfChunks).not.toBe(1)
})
})
})
test('When an edge function fails, serves a fallback defined by its `on_error` mode', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
},
})
.withContentFiles([
{
path: path.join(publicDir, 'hello-1.html'),
content: '<html>hello from the origin</html>',
},
])
.withContentFiles([
{
path: path.join(publicDir, 'error-page.html'),
content: '<html>uh-oh!</html>',
},
])
.withEdgeFunction({
config: { onError: 'bypass', path: '/hello-1' },
handler: () => {
// @ts-expect-error: Intentionally referencing an undefined global
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
ermThisWillFail()
return new Response('I will never get here')
},
name: 'hello-1',
})
.withEdgeFunction({
config: { onError: '/error-page', path: '/hello-2' },
handler: () => {
// @ts-expect-error: Intentionally referencing an undefined global
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
ermThisWillFail()
return new Response('I will never get here')
},
name: 'hello-2',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const [response1, response2] = await Promise.all([
fetch(`${server.url}/hello-1`),
fetch(`${server.url}/hello-2`),
])
t.expect(response1.status).toBe(200)
t.expect(await response1.text()).toEqual('<html>hello from the origin</html>')
t.expect(response2.status).toBe(200)
t.expect(await response2.text()).toEqual('<html>uh-oh!</html>')
})
})
})
test('When an edge function throws uncaught exception, the dev server continues working', async (t) => {
await withSiteBuilder(t, async (builder) => {
builder
.withNetlifyToml({
config: {
build: {
edge_functions: 'netlify/edge-functions',
},
},
})
.withEdgeFunction({
config: { path: '/hello' },
handler: () => {
const url = new URL('/shouldve-provided-a-base')
return new Response(url.toString())
},
name: 'hello-1',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const response = await fetch(`${server.url}/hello`, {
headers: {
'Accept-Encoding': 'compress',
},
})
t.expect(response.status).toBe(500)
t.expect(await response.text()).toMatch(/TypeError: Invalid URL/)
})
})
})
test('redirect with country cookie', async (t) => {
await withSiteBuilder(t, async (builder) => {
builder
.withContentFiles([
{
path: 'index.html',
content: '<html>index</html>',
},
{
path: 'index-es.html',
content: '<html>index in spanish</html>',
},
])
.withRedirectsFile({
redirects: [{ from: `/`, to: `/index-es.html`, status: '200!', condition: 'Country=ES' }],
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async (server) => {
const response = await fetch(`${server.url}/`, {
headers: {
cookie: `nf_country=ES`,
},
})
t.expect(response.status).toBe(200)
t.expect(await response.text()).toEqual('<html>index in spanish</html>')
})
})
})
test('redirect with country flag', async (t) => {
await withSiteBuilder(t, async (builder) => {
builder
.withContentFiles([
{
path: 'index.html',
content: '<html>index</html>',
},
{
path: 'index-es.html',
content: '<html>index in spanish</html>',
},
])
.withRedirectsFile({
redirects: [{ from: `/`, to: `/index-es.html`, status: '200!', condition: 'Country=ES' }],
})
await builder.build()
// NOTE: default fallback for country is 'US' if no flag is provided
await withDevServer({ cwd: builder.directory }, async (server) => {
const response = await fetch(`${server.url}/`)
t.expect(response.status).toBe(200)
t.expect(await response.text()).toEqual('<html>index</html>')
})
await withDevServer({ cwd: builder.directory, args: ['--country=ES'] }, async (server) => {
const response = await fetch(`${server.url}/`)
t.expect(response.status).toBe(200)
t.expect(await response.text()).toEqual('<html>index in spanish</html>')
})
})
})
test(`doesn't hang when sending a application/json POST request to function server`, async (t) => {
await withSiteBuilder(t, async (builder) => {
const functionsPort = 6666
await builder
.withNetlifyToml({ config: { functions: { directory: 'functions' }, dev: { functionsPort } } })
.build()
await withDevServer({ cwd: builder.directory }, async ({ port, url }) => {
const response = await fetch(`${url.replace(port.toString(), functionsPort.toString())}/test`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: '{}',
})
t.expect(response.status).toBe(404)
t.expect(await response.text()).toEqual('Function not found...')
})
})
})
test(`catches invalid function names`, async (t) => {
await withSiteBuilder(t, async (builder) => {
const functionsPort = 6667
await builder
.withNetlifyToml({ config: { functions: { directory: 'functions' }, dev: { functionsPort } } })
.withFunction({
path: 'exclamat!on.js',
handler: async (event: HandlerEvent) =>
Promise.resolve({
statusCode: 200,
body: JSON.stringify(event),
}),
})
.build()
await withDevServer({ cwd: builder.directory }, async ({ port, url }) => {
const response = await fetch(
`${url.replace(port.toString(), functionsPort.toString())}/.netlify/functions/exclamat!on`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: '{}',
},
)
t.expect(response.status).toBe(400)
t.expect(await response.text()).toEqual(
'Function name should consist only of alphanumeric characters, hyphen & underscores.',
)
})
})
})
// on windows, fetch throws an error while files are refreshing instead of returning the old value
test.skipIf(platform === 'win32')('should detect content changes in edge functions', { retry: 3 }, async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
edge_functions: [
{
function: 'hello',
path: '/hello',
},
],
},
})
.withEdgeFunction({
handler: () => new Response('Hello world'),
name: 'hello',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async ({ port }) => {
const helloWorldMessage = await fetch(`http://localhost:${port}/hello`).then((res) => res.text())
await builder
.withEdgeFunction({
handler: () => new Response('Hello builder'),
name: 'hello',
})
.build()
const DETECT_FILE_CHANGE_DELAY = 500
await pause(DETECT_FILE_CHANGE_DELAY)
const helloBuilderMessage = await fetch(`http://localhost:${port}/hello`, {}).then((res) => res.text())
t.expect(helloWorldMessage).toEqual('Hello world')
t.expect(helloBuilderMessage).toEqual('Hello builder')
})
})
})
test('should detect deleted edge functions', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
edge_functions: [
{
function: 'auth',
path: '/auth',
},
],
},
})
.withEdgeFunction({
handler: () => new Response('Auth response'),
name: 'auth',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async ({ port }) => {
const authResponseMessage = await fetch(`http://localhost:${port}/auth`).then((response) => response.text())
await builder
.withoutFile({
path: 'netlify/edge-functions/auth.js',
})
.build()
const DETECT_FILE_CHANGE_DELAY = 500
await pause(DETECT_FILE_CHANGE_DELAY)
const authNotFoundMessage = await fetch(`http://localhost:${port}/auth`).then((response) => response.text())
t.expect(authResponseMessage).toEqual('Auth response')
t.expect(authNotFoundMessage).toEqual('404 Not Found')
})
})
})
test('should respect in-source configuration from edge functions', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
},
})
.withEdgeFunction({
config: { path: '/hello-1' },
handler: () => new Response('Hello world'),
name: 'hello',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async ({ port, waitForLogMatching }) => {
const res1 = await fetch(`http://localhost:${port}/hello-1`)
t.expect(res1.status).toBe(200)
t.expect(await res1.text()).toEqual('Hello world')
// wait for file watcher to be up and running, which might take a little
// if we do not wait, the next file change will not be picked up
await pause(500)
await builder
.withEdgeFunction({
config: { path: ['/hello-2', '/hello-3'] },
handler: () => new Response('Hello world'),
name: 'hello',
})
.build()
await waitForLogMatching('Reloaded edge function')
const [res2, res3, res4] = await Promise.all([
fetch(`http://localhost:${port}/hello-1`),
fetch(`http://localhost:${port}/hello-2`),
fetch(`http://localhost:${port}/hello-3`),
])
t.expect(res2.status).toBe(404)
t.expect(res3.status).toBe(200)
t.expect(await res3.text()).toEqual('Hello world')
t.expect(res4.status).toBe(200)
t.expect(await res4.text()).toEqual('Hello world')
})
})
})
test('should respect excluded paths', async (t) => {
await withSiteBuilder(t, async (builder) => {
const publicDir = 'public'
builder
.withNetlifyToml({
config: {
build: {
publish: publicDir,
edge_functions: 'netlify/edge-functions',
},
},
})
.withEdgeFunction({
config: { path: '/*', excludedPath: '/static/*' },
handler: () => new Response('Hello world'),
name: 'hello',
})
await builder.build()
await withDevServer({ cwd: builder.directory }, async ({ port }) => {
const [res1, res2] = await Promise.all([
fetch(`http://localhost:${port}/foo`),
fetch(`http://localhost:${port}/static/foo`),
])
t.expect(res1.status).toBe(200)