forked from cloudflare/workers-sdk
-
Notifications
You must be signed in to change notification settings - Fork 2
/
dev.test.ts
1870 lines (1672 loc) · 59.9 KB
/
dev.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 * as fs from "node:fs";
import module from "node:module";
import getPort from "get-port";
import { http, HttpResponse } from "msw";
import patchConsole from "patch-console";
import dedent from "ts-dedent";
import { vi } from "vitest";
import { ConfigController } from "../api/startDevWorker/ConfigController";
import { unwrapHook } from "../api/startDevWorker/utils";
import registerDevHotKeys from "../dev/hotkeys";
import { getWorkerAccountAndContext } from "../dev/remote";
import { FatalError } from "../errors";
import { CI } from "../is-ci";
import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
import { mockConsoleMethods } from "./helpers/mock-console";
import { useMockIsTTY } from "./helpers/mock-istty";
import {
msw,
mswSuccessOauthHandlers,
mswSuccessUserHandlers,
mswZoneHandlers,
} from "./helpers/msw";
import { runInTempDir } from "./helpers/run-in-tmp";
import { runWrangler } from "./helpers/run-wrangler";
import { writeWranglerConfig } from "./helpers/write-wrangler-config";
import type {
Binding,
StartDevWorkerInput,
StartDevWorkerOptions,
Trigger,
} from "../api";
import type { Mock, MockInstance } from "vitest";
vi.mock("../api/startDevWorker/ConfigController", (importOriginal) =>
importOriginal()
);
vi.mock("../dev/hotkeys");
// Don't memoize in tests. If we did, it would memoize across test runs, which causes problems
vi.mock("../utils/memoizeGetPort", () => {
return {
memoizeGetPort: (port: number, host: string) => async () => {
return await getPort({ port: port, host: host });
},
};
});
async function expectedHostAndZone(
config: StartDevWorkerOptions & { input: StartDevWorkerInput },
host: string,
zone: string
): Promise<unknown> {
expect(config).toMatchObject({
dev: { origin: { hostname: host } },
});
const ctx = await getWorkerAccountAndContext({
accountId: "",
host: config.input.dev?.origin?.hostname,
routes: config.triggers
?.filter(
(trigger): trigger is Extract<Trigger, { type: "route" }> =>
trigger.type === "route"
)
.map((trigger) => {
const { type: _, ...route } = trigger;
if (
"custom_domain" in route ||
"zone_id" in route ||
"zone_name" in route
) {
return route;
} else {
return route.pattern;
}
}),
env: undefined,
legacyEnv: undefined,
sendMetrics: undefined,
configPath: config.config,
});
expect(ctx).toEqual(
expect.objectContaining({
workerContext: {
host,
zone,
routes: config.triggers
?.filter(
(trigger): trigger is Extract<Trigger, { type: "route" }> =>
trigger.type === "route"
)
.map((trigger) => {
const { type: _, ...route } = trigger;
if (
"custom_domain" in route ||
"zone_id" in route ||
"zone_name" in route
) {
return route;
} else {
return route.pattern;
}
}),
},
})
);
return config;
}
describe.sequential("wrangler dev", () => {
let spy: MockInstance;
let setSpy: MockInstance;
const { setIsTTY } = useMockIsTTY();
beforeEach(() => {
setIsTTY(true);
setSpy = vi.spyOn(ConfigController.prototype, "set");
spy = vi
.spyOn(ConfigController.prototype, "emitConfigUpdateEvent")
.mockImplementation(() => {
// In unit tests of `wrangler dev` we only care about the first config parse event, so exit early
throw new FatalError("Bailing early in tests");
});
msw.use(
...mswZoneHandlers,
...mswSuccessOauthHandlers,
...mswSuccessUserHandlers
);
});
runInTempDir();
mockAccountId();
mockApiToken();
const std = mockConsoleMethods();
afterEach(() => {
patchConsole(() => {});
msw.resetHandlers();
spy.mockClear();
setSpy.mockClear();
});
async function runWranglerUntilConfig(
cmd?: string,
env?: Record<string, string | undefined>
): Promise<StartDevWorkerOptions & { input: StartDevWorkerInput }> {
try {
await runWrangler(cmd, env);
} catch (e) {
console.error(e);
}
return { ...spy.mock.calls[0][0], input: setSpy.mock.calls[0][0] };
}
describe("config file support", () => {
it("should support wrangler.toml", async () => {
writeWranglerConfig({
name: "test-worker-toml",
main: "index.js",
compatibility_date: "2024-01-01",
});
fs.writeFileSync("index.js", `export default {};`);
const options = await runWranglerUntilConfig("dev");
expect(options.name).toMatchInlineSnapshot(`"test-worker-toml"`);
});
it("should support wrangler.json", async () => {
writeWranglerConfig(
{
name: "test-worker-json",
main: "index.js",
compatibility_date: "2024-01-01",
},
"wrangler.json"
);
fs.writeFileSync("index.js", `export default {};`);
const options = await runWranglerUntilConfig("dev");
expect(options.name).toMatchInlineSnapshot(`"test-worker-json"`);
});
it("should support wrangler.jsonc", async () => {
writeWranglerConfig(
{
name: "test-worker-jsonc",
main: "index.js",
compatibility_date: "2024-01-01",
},
"wrangler.jsonc"
);
fs.writeFileSync("index.js", `export default {};`);
const options = await runWranglerUntilConfig("dev");
expect(options.name).toMatchInlineSnapshot(`"test-worker-jsonc"`);
});
});
describe("authorization without env var", () => {
mockApiToken({ apiToken: null });
const isCISpy = vi.spyOn(CI, "isCI").mockReturnValue(true);
afterEach(() => {
isCISpy.mockClear();
});
it("should kick you to the login flow when running wrangler dev in remote mode without authorization", async () => {
fs.writeFileSync("index.js", `export default {};`);
await expect(
runWrangler("dev --remote index.js")
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: You must be logged in to use wrangler dev in remote mode. Try logging in, or run wrangler dev --local.]`
);
});
});
describe("authorization with env var", () => {
it("should use config.account_id over env var", async () => {
writeWranglerConfig({
name: "test-worker-toml",
main: "index.js",
compatibility_date: "2024-01-01",
account_id: "12345",
});
fs.writeFileSync("index.js", `export default {};`);
const options = await runWranglerUntilConfig("dev");
await expect(unwrapHook(options.dev.auth)).resolves.toMatchObject({
accountId: "12345",
});
});
it("should use env var when config.account_id is not set", async () => {
writeWranglerConfig({
name: "test-worker-toml",
main: "index.js",
compatibility_date: "2024-01-01",
});
fs.writeFileSync("index.js", `export default {};`);
const options = await runWranglerUntilConfig("dev");
await expect(unwrapHook(options.dev.auth)).resolves.toMatchObject({
accountId: "some-account-id",
});
});
});
describe("compatibility-date", () => {
it("should not warn if there is no wrangler.toml and no compatibility-date specified", async () => {
fs.writeFileSync("index.js", `export default {};`);
await runWranglerUntilConfig("dev index.js");
expect(std.warn).toMatchInlineSnapshot(`""`);
});
it("should warn if there is a wrangler.toml but no compatibility-date", async () => {
writeWranglerConfig({
main: "index.js",
compatibility_date: undefined,
});
fs.writeFileSync("index.js", `export default {};`);
await runWranglerUntilConfig("dev");
const miniflareEntry = require.resolve("miniflare");
const miniflareRequire = module.createRequire(miniflareEntry);
const miniflareWorkerd = miniflareRequire("workerd") as {
compatibilityDate: string;
};
const currentDate = miniflareWorkerd.compatibilityDate;
expect(std.warn.replaceAll(currentDate, "<current-date>"))
.toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mNo compatibility_date was specified. Using the installed Workers runtime's latest supported date: <current-date>.[0m
❯❯ Add one to your wrangler.toml file: compatibility_date = \\"<current-date>\\", or
❯❯ Pass it in your terminal: wrangler dev [<SCRIPT>] --compatibility-date=<current-date>
See [4mhttps://developers.cloudflare.com/workers/platform/compatibility-dates/[0m for more information.
"
`);
});
it("should not warn if there is a wrangler.toml but compatibility-date is specified at the command line", async () => {
writeWranglerConfig({
main: "index.js",
compatibility_date: undefined,
});
fs.writeFileSync("index.js", `export default {};`);
await runWranglerUntilConfig("dev --compatibility-date=2020-01-01");
expect(std.warn).toMatchInlineSnapshot(`""`);
});
});
describe("entry-points", () => {
it("should error if there is no entry-point specified", async () => {
writeWranglerConfig();
await expect(
runWrangler("dev")
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`main\` config field.]`
);
expect(std.out).toMatchInlineSnapshot(`""`);
expect(std.err).toMatchInlineSnapshot(`
"[31mX [41;31m[[41;97mERROR[41;31m][0m [1mMissing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`main\` config field.[0m
"
`);
});
it("should use `main` from the top-level environment", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev");
expect(config.entrypoint).toMatch(/index\.js$/);
});
it("should use `main` from a named environment", async () => {
writeWranglerConfig({
env: {
ENV1: {
main: "index.js",
},
},
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev --env=ENV1");
expect(config.entrypoint).toMatch(/index\.js$/);
});
it("should use `main` from a named environment, rather than the top-level", async () => {
writeWranglerConfig({
main: "other.js",
env: {
ENV1: {
main: "index.js",
},
},
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev --env=ENV1");
expect(config.entrypoint).toMatch(/index\.js$/);
});
});
describe("routes", () => {
it("should pass routes to emitConfigUpdate", async () => {
fs.writeFileSync("index.js", `export default {};`);
// config.routes
mockGetZones("5.some-host.com", [{ id: "some-zone-id-5" }]);
writeWranglerConfig({
main: "index.js",
routes: ["http://5.some-host.com/some/path/*"],
});
const config = await runWranglerUntilConfig("dev --remote");
const devConfig = await expectedHostAndZone(
config,
"5.some-host.com",
"some-zone-id-5"
);
expect(devConfig).toMatchObject({
triggers: [
{
pattern: "http://5.some-host.com/some/path/*",
},
],
});
});
it("should error if custom domains with paths are passed in but allow paths on normal routes", async () => {
fs.writeFileSync("index.js", `export default {};`);
writeWranglerConfig({
main: "index.js",
routes: [
"simple.co.uk/path",
"simple.co.uk/*",
"simple.co.uk",
{ pattern: "route.co.uk/path", zone_id: "asdfadsf" },
{ pattern: "route.co.uk/*", zone_id: "asdfadsf" },
{ pattern: "route.co.uk", zone_id: "asdfadsf" },
{ pattern: "custom.co.uk/path", custom_domain: true },
{ pattern: "custom.co.uk/*", custom_domain: true },
{ pattern: "custom.co.uk", custom_domain: true },
],
});
await expect(runWrangler(`dev`)).rejects
.toThrowErrorMatchingInlineSnapshot(`
[Error: Invalid Routes:
custom.co.uk/path:
Paths are not allowed in Custom Domains
custom.co.uk/*:
Wildcard operators (*) are not allowed in Custom Domains
Paths are not allowed in Custom Domains]
`);
});
it("should warn on mounted paths in dev", async () => {
writeWranglerConfig({
routes: [
"simple.co.uk/path/*",
"simple.co.uk/*",
"*/*",
"*/blog/*",
{ pattern: "example.com/blog/*", zone_id: "asdfadsf" },
{ pattern: "example.com/*", zone_id: "asdfadsf" },
{ pattern: "example.com/abc/def/*", zone_id: "asdfadsf" },
],
});
fs.mkdirSync("assets");
await runWranglerUntilConfig("dev --assets assets");
expect(std.warn).toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mWarning: The following routes will attempt to serve Assets on a configured path:[0m
• simple.co.uk/path/* (Will match assets: assets/path/*)
• */blog/* (Will match assets: assets/blog/*)
• example.com/blog/* (Will match assets: assets/blog/*)
• example.com/abc/def/* (Will match assets: assets/abc/def/*)
"
`);
});
});
describe("host", () => {
it("should resolve a host to its zone", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
const config = await runWranglerUntilConfig(
"dev --remote --host some-host.com"
);
await expectedHostAndZone(config, "some-host.com", "some-zone-id");
});
it("should read wrangler.toml's dev.host", async () => {
writeWranglerConfig({
main: "index.js",
dev: {
host: "some-host.com",
},
});
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
const config = await runWranglerUntilConfig("dev");
expect(config.dev.origin?.hostname).toEqual("some-host.com");
});
it("should read --route", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
const config = await runWranglerUntilConfig(
"dev --route http://some-host.com/some/path/*"
);
await expectedHostAndZone(config, "some-host.com", "some-zone-id");
});
it("should read wrangler.toml's routes", async () => {
writeWranglerConfig({
main: "index.js",
routes: [
"http://some-host.com/some/path/*",
"http://some-other-host.com/path/*",
],
});
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
const config = await runWranglerUntilConfig("dev");
await expectedHostAndZone(config, "some-host.com", "some-zone-id");
});
it("should read wrangler.toml's environment specific routes", async () => {
writeWranglerConfig({
main: "index.js",
routes: [
"http://a-host.com/some/path/*",
"http://another-host.com/path/*",
],
env: {
staging: {
routes: [
"http://some-host.com/some/path/*",
"http://some-other-host.com/path/*",
],
},
},
});
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
const config = await runWranglerUntilConfig("dev --env staging");
await expectedHostAndZone(config, "some-host.com", "some-zone-id");
});
it("should strip leading `*` from given host when deducing a zone id", async () => {
writeWranglerConfig({
main: "index.js",
route: "*some-host.com/some/path/*",
});
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
const config = await runWranglerUntilConfig("dev");
await expectedHostAndZone(config, "some-host.com", "some-zone-id");
});
it("should strip leading `*.` from given host when deducing a zone id", async () => {
writeWranglerConfig({
main: "index.js",
route: "*.some-host.com/some/path/*",
});
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
const config = await runWranglerUntilConfig("dev");
await expectedHostAndZone(config, "some-host.com", "some-zone-id");
});
it("should, when provided, use a configured zone_id", async () => {
writeWranglerConfig({
main: "index.js",
routes: [
{ pattern: "https://some-domain.com/*", zone_id: "some-zone-id" },
],
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev --remote");
await expectedHostAndZone(config, "some-domain.com", "some-zone-id");
});
it("should, when provided, use a zone_name to get a zone_id", async () => {
writeWranglerConfig({
main: "index.js",
routes: [
{
pattern: "https://some-zone.com/*",
zone_name: "some-zone.com",
},
],
});
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("some-zone.com", [{ id: "a-zone-id" }]);
const config = await runWranglerUntilConfig("dev --remote");
await expectedHostAndZone(config, "some-zone.com", "a-zone-id");
});
it("should find the host from the given pattern, not zone_name", async () => {
writeWranglerConfig({
main: "index.js",
routes: [
{
pattern: "https://subdomain.exists.com/*",
zone_name: "does-not-exist.com",
},
],
});
await fs.promises.writeFile("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev");
expect(config.dev.origin?.hostname).toBe("subdomain.exists.com");
});
it("should fail for non-existing zones, when falling back from */*", async () => {
writeWranglerConfig({
main: "index.js",
routes: [
{
pattern: "*/*",
zone_name: "does-not-exist.com",
},
],
});
await fs.promises.writeFile("index.js", `export default {};`);
await expect(runWrangler("dev --remote")).rejects
.toThrowErrorMatchingInlineSnapshot(`
[Error: Could not find zone for \`does-not-exist.com\`. Make sure the domain is set up to be proxied by Cloudflare.
For more details, refer to https://developers.cloudflare.com/workers/configuration/routing/routes/#set-up-a-route]
`);
});
it("should fallback to zone_name when given the pattern */*", async () => {
writeWranglerConfig({
main: "index.js",
routes: [
{
pattern: "*/*",
zone_name: "exists.com",
},
],
});
await fs.promises.writeFile("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev");
expect(config.triggers).toMatchObject([
{
zone_name: "exists.com",
},
]);
});
it("fails when given the pattern */* and no zone_name", async () => {
writeWranglerConfig({
main: "index.js",
routes: [
{
pattern: "*/*",
zone_id: "exists-com",
},
],
});
await fs.promises.writeFile("index.js", `export default {};`);
await expect(runWrangler("dev")).rejects.toMatchInlineSnapshot(`
[Error: Cannot infer host from first route: {"pattern":"*/*","zone_id":"exists-com"}.
You can explicitly set the \`dev.host\` configuration in your wrangler.toml file, for example:
\`\`\`
[dev]
host = "example.com"
\`\`\`
]
`);
});
it("given a long host, it should use the longest subdomain that resolves to a zone", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
msw.use(
http.get("*/zones", ({ request }) => {
const url = new URL(request.url);
let zone: [] | [{ id: "some-zone-id" }] = [];
if (url.searchParams.get("name") === "111.222.333.some-host.com") {
zone = [];
} else if (url.searchParams.get("name") === "222.333.some-host.com") {
zone = [];
} else if (url.searchParams.get("name") === "333.some-host.com") {
zone = [{ id: "some-zone-id" }];
}
return HttpResponse.json(
{
success: true,
errors: [],
messages: [],
result: zone,
},
{ status: 200 }
);
})
);
const config = await runWranglerUntilConfig(
"dev --remote --host 111.222.333.some-host.com"
);
await expectedHostAndZone(
config,
"111.222.333.some-host.com",
"some-zone-id"
);
});
describe("should, in order, use args.host/config.dev.host/args.routes/(config.route|config.routes)", () => {
it("config.routes", async () => {
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("5.some-host.com", [{ id: "some-zone-id-5" }]);
writeWranglerConfig({
main: "index.js",
routes: ["http://5.some-host.com/some/path/*"],
});
const config = await runWranglerUntilConfig("dev --remote");
await expectedHostAndZone(config, "5.some-host.com", "some-zone-id-5");
});
it("config.route", async () => {
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("4.some-host.com", [{ id: "some-zone-id-4" }]);
writeWranglerConfig({
main: "index.js",
route: "https://4.some-host.com/some/path/*",
});
const config2 = await runWranglerUntilConfig("dev --remote");
await expectedHostAndZone(config2, "4.some-host.com", "some-zone-id-4");
});
it("--routes", async () => {
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("3.some-host.com", [{ id: "some-zone-id-3" }]);
writeWranglerConfig({
main: "index.js",
route: "https://4.some-host.com/some/path/*",
});
const config3 = await runWranglerUntilConfig(
"dev --remote --routes http://3.some-host.com/some/path/*"
);
await expectedHostAndZone(config3, "3.some-host.com", "some-zone-id-3");
});
it("config.dev.host", async () => {
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("2.some-host.com", [{ id: "some-zone-id-2" }]);
writeWranglerConfig({
main: "index.js",
dev: {
host: `2.some-host.com`,
},
route: "4.some-host.com/some/path/*",
});
const config4 = await runWranglerUntilConfig(
"dev --remote --routes http://3.some-host.com/some/path/*"
);
expect(config4.dev.origin?.hostname).toBe("2.some-host.com");
});
it("host", async () => {
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("1.some-host.com", [{ id: "some-zone-id-1" }]);
writeWranglerConfig({
main: "index.js",
dev: {
host: `2.some-host.com`,
},
route: "4.some-host.com/some/path/*",
});
const config5 = await runWranglerUntilConfig(
"dev --remote --routes http://3.some-host.com/some/path/* --host 1.some-host.com"
);
await expectedHostAndZone(config5, "1.some-host.com", "some-zone-id-1");
});
});
it("should error if a host can't resolve to a zone", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
mockGetZones("some-host.com", []);
await expect(runWrangler("dev --remote --host some-host.com")).rejects
.toThrowErrorMatchingInlineSnapshot(`
[Error: Could not find zone for \`some-host.com\`. Make sure the domain is set up to be proxied by Cloudflare.
For more details, refer to https://developers.cloudflare.com/workers/configuration/routing/routes/#set-up-a-route]
`);
});
it("should not try to resolve a zone when starting in local mode", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev --host some-host.com");
// This is testing the _lack_ of the error in the test above: https://github.com/cloudflare/workers-sdk/tree/main/packages/wrangler/src/__tests__/dev.test.tsx#L725-L726
expect(config.dev.origin?.hostname).toBe("some-host.com");
});
});
describe("local upstream", () => {
it("should use dev.host from toml by default", async () => {
writeWranglerConfig({
main: "index.js",
dev: {
host: `2.some-host.com`,
},
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev");
expect(config.dev.origin?.hostname).toEqual("2.some-host.com");
});
it("should use route from toml by default", async () => {
writeWranglerConfig({
main: "index.js",
route: "https://4.some-host.com/some/path/*",
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev");
expect(config.dev.origin?.hostname).toEqual("4.some-host.com");
});
it("should respect the option when provided", async () => {
writeWranglerConfig({
main: "index.js",
route: `2.some-host.com`,
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig(
"dev --local-upstream some-host.com"
);
expect(config.dev.origin?.hostname).toEqual("some-host.com");
});
});
describe("custom builds", () => {
it("should run a custom build before starting `dev`", async () => {
writeWranglerConfig({
build: {
command: `node -e "4+4; require('fs').writeFileSync('index.js', 'export default { fetch(){ return new Response(123) } }')"`,
},
});
const config = await runWranglerUntilConfig("dev index.js");
expect(fs.readFileSync("index.js", "utf-8")).toMatchInlineSnapshot(
`"export default { fetch(){ return new Response(123) } }"`
);
// and the command would pass through
expect(config.build.custom).toEqual({
command:
"node -e \"4+4; require('fs').writeFileSync('index.js', 'export default { fetch(){ return new Response(123) } }')\"",
workingDirectory: undefined,
watch: "src",
});
expect(std.out).toMatchInlineSnapshot(
`
"Running custom build: node -e \\"4+4; require('fs').writeFileSync('index.js', 'export default { fetch(){ return new Response(123) } }')\\"
"
`
);
});
it.skipIf(process.platform === "win32")(
"should run a custom build of multiple steps combined by && before starting `dev`",
async () => {
writeWranglerConfig({
build: {
command: `echo "export default { fetch(){ return new Response(123) } }" > index.js`,
},
});
await runWranglerUntilConfig("dev index.js");
expect(fs.readFileSync("index.js", "utf-8")).toMatchInlineSnapshot(`
"export default { fetch(){ return new Response(123) } }
"
`);
expect(std.out).toMatchInlineSnapshot(
`
"Running custom build: echo \\"export default { fetch(){ return new Response(123) } }\\" > index.js
"
`
);
}
);
it("should throw an error if the entry doesn't exist after the build finishes", async () => {
writeWranglerConfig({
main: "index.js",
build: {
command: `node -e "4+4;"`,
},
});
await expect(runWrangler("dev")).rejects
.toThrowErrorMatchingInlineSnapshot(`
[Error: The expected output file at "index.js" was not found after running custom build: node -e "4+4;".
The \`main\` property in your wrangler.toml file should point to the file generated by the custom build.]
`);
expect(std.out).toMatchInlineSnapshot(`
"Running custom build: node -e \\"4+4;\\"
"
`);
expect(std.err).toMatchInlineSnapshot(`
"[31mX [41;31m[[41;97mERROR[41;31m][0m [1mThe expected output file at \\"index.js\\" was not found after running custom build: node -e \\"4+4;\\".[0m
The \`main\` property in your wrangler.toml file should point to the file generated by the custom
build.
"
`);
expect(std.warn).toMatchInlineSnapshot(`""`);
});
describe(".env", () => {
beforeEach(() => {
fs.writeFileSync(".env", "CUSTOM_BUILD_VAR=default");
fs.writeFileSync(".env.custom", "CUSTOM_BUILD_VAR=custom");
fs.writeFileSync("index.js", `export default {};`);
writeWranglerConfig({
main: "index.js",
env: { custom: {} },
build: {
// Ideally, we'd just log the var here and match it in `std.out`,
// but stdout from custom builds is piped directly to
// `process.stdout` which we don't capture.
command: `node -e "require('fs').writeFileSync('var.txt', process.env.CUSTOM_BUILD_VAR)"`,
},
});
// We won't overwrite existing process.env keys with .env values (to
// allow .env overrides to be specified on the shell), so make sure this
// key definitely doesn't exist.
vi.stubEnv("CUSTOM_BUILD_VAR", "");
delete process.env.CUSTOM_BUILD_VAR;
});
it("should load environment variables from `.env`", async () => {
await runWranglerUntilConfig("dev");
const output = fs.readFileSync("var.txt", "utf8");
expect(output).toMatch("default");
});
it("should prefer to load environment variables from `.env.<environment>` if `--env <environment>` is set", async () => {
await runWranglerUntilConfig("dev --env custom");
const output = fs.readFileSync("var.txt", "utf8");
expect(output).toMatch("custom");
});
it("should show reasonable debug output if `.env` does not exist", async () => {
fs.rmSync(".env");
writeWranglerConfig({
main: "index.js",
});
await runWranglerUntilConfig("dev --log-level debug");
expect(std.debug).toContain(".env file not found at");
});
});
});
describe("upstream-protocol", () => {
it("should default upstream-protocol to `https` if remote mode", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev --remote");
expect(config.dev.origin?.secure).toEqual(true);
});
it("should warn if `--upstream-protocol=http` is used in remote mode", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig(
"dev --upstream-protocol=http --remote"
);
expect(config.dev.origin?.secure).toEqual(false);
expect(std.warn).toMatchInlineSnapshot(`
"[33m▲ [43;33m[[43;30mWARNING[43;33m][0m [1mSetting upstream-protocol to http is not currently supported for remote mode.[0m
If this is required in your project, please add your use case to the following issue:
[4mhttps://github.com/cloudflare/workers-sdk/issues/583[0m.
"
`);
});
it("should default upstream-protocol to local-protocol if local mode", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev --local-protocol=https");
expect(config.dev.origin?.secure).toEqual(true);
});
it("should default upstream-protocol to http if no local-protocol in local mode", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev");
expect(config.dev.origin?.secure).toEqual(false);
});
});
describe("local-protocol", () => {
it("should default local-protocol to `http`", async () => {
writeWranglerConfig({
main: "index.js",
});
fs.writeFileSync("index.js", `export default {};`);
const config = await runWranglerUntilConfig("dev");
expect(config.dev.server?.secure).toEqual(false);
});
it("should use `local_protocol` from `wrangler.toml`, if available", async () => {
writeWranglerConfig({