wrangler 2.9.0 → 2.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2905 +0,0 @@
1
- /* eslint-disable no-shadow */
2
- import { Blob } from "node:buffer";
3
- import { mkdirSync, writeFileSync } from "node:fs";
4
- import { chdir } from "node:process";
5
- import { MockedRequest, rest } from "msw";
6
- import { FormData } from "undici";
7
- import { ROUTES_SPEC_VERSION } from "../pages/constants";
8
- import { isRoutesJSONSpec } from "../pages/functions/routes-validation";
9
- import { version } from "./../../package.json";
10
- import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
11
- import { mockConsoleMethods } from "./helpers/mock-console";
12
- import { msw } from "./helpers/msw";
13
- import { FileReaderSync } from "./helpers/msw/read-file-sync";
14
- import { runInTempDir } from "./helpers/run-in-tmp";
15
- import { runWrangler } from "./helpers/run-wrangler";
16
- import type { Deployment, Project, UploadPayloadFile } from "../pages/types";
17
- import type { RestRequest } from "msw";
18
-
19
- function mockGetToken(jwt: string) {
20
- msw.use(
21
- rest.get(
22
- "*/accounts/:accountId/pages/projects/foo/upload-token",
23
- (req, res, ctx) => {
24
- expect(req.params.accountId).toEqual("some-account-id");
25
-
26
- return res(
27
- ctx.status(200),
28
- ctx.json({ success: true, errors: [], messages: [], result: { jwt } })
29
- );
30
- }
31
- )
32
- );
33
- }
34
-
35
- describe("pages", () => {
36
- runInTempDir();
37
- const std = mockConsoleMethods();
38
- function endEventLoop() {
39
- return new Promise((resolve) => setImmediate(resolve));
40
- }
41
-
42
- beforeEach(() => {
43
- // @ts-expect-error we're using a very simple setTimeout mock here
44
- jest.spyOn(global, "setTimeout").mockImplementation((fn, _period) => {
45
- setImmediate(fn);
46
- });
47
- });
48
- afterEach(async () => {
49
- // Force a tick to ensure that all promises resolve
50
- await endEventLoop();
51
- // Reset MSW after tick to ensure that all requests have been handled
52
- msw.resetHandlers();
53
- msw.restoreHandlers();
54
- });
55
-
56
- it("should should display a list of available subcommands, for pages with no subcommand", async () => {
57
- await runWrangler("pages");
58
- await endEventLoop();
59
-
60
- expect(std.out).toMatchInlineSnapshot(`
61
- "wrangler pages
62
-
63
- ⚡️ Configure Cloudflare Pages
64
-
65
- Commands:
66
- wrangler pages dev [directory] [-- command..] 🧑‍💻 Develop your full-stack Pages application locally
67
- wrangler pages project ⚡️ Interact with your Pages projects
68
- wrangler pages deployment 🚀 Interact with the deployments of a project
69
- wrangler pages publish [directory] 🆙 Publish a directory of static assets as a Pages deployment
70
-
71
- Flags:
72
- -j, --experimental-json-config Experimental: Support wrangler.json [boolean]
73
- -c, --config Path to .toml configuration file [string]
74
- -e, --env Environment to use for operations and .env files [string]
75
- -h, --help Show help [boolean]
76
- -v, --version Show version number [boolean]
77
-
78
- 🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose"
79
- `);
80
- });
81
-
82
- describe("beta message for subcommands", () => {
83
- it("should display for pages:dev", async () => {
84
- await expect(
85
- runWrangler("pages dev")
86
- ).rejects.toThrowErrorMatchingInlineSnapshot(
87
- `"Must specify a directory of static assets to serve or a command to run or a proxy port."`
88
- );
89
-
90
- expect(std.out).toMatchInlineSnapshot(`
91
- "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose
92
-
93
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
94
- `);
95
- });
96
-
97
- it("should display for pages:functions:build", async () => {
98
- await expect(runWrangler("pages functions build")).rejects.toThrowError();
99
-
100
- expect(std.out).toMatchInlineSnapshot(`
101
- "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose
102
-
103
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
104
- `);
105
- });
106
-
107
- it("should display for pages:functions:optimize-routes", async () => {
108
- await expect(
109
- runWrangler(
110
- 'pages functions optimize-routes --routes-path="/build/_routes.json" --output-routes-path="/build/_optimized-routes.json"'
111
- )
112
- ).rejects.toThrowError();
113
-
114
- expect(std.out).toMatchInlineSnapshot(`
115
- "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose
116
-
117
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
118
- `);
119
- });
120
- });
121
-
122
- describe("project list", () => {
123
- mockAccountId();
124
- mockApiToken();
125
-
126
- function mockListRequest(projects: unknown[]) {
127
- const requests = { count: 0 };
128
- msw.use(
129
- rest.get(
130
- "*/accounts/:accountId/pages/projects",
131
- async (req, res, ctx) => {
132
- requests.count++;
133
- const pageSize = Number(req.url.searchParams.get("per_page"));
134
- const page = Number(req.url.searchParams.get("page"));
135
- const expectedPageSize = 10;
136
- const expectedPage = requests.count;
137
- expect(req.params.accountId).toEqual("some-account-id");
138
- expect(pageSize).toEqual(expectedPageSize);
139
- expect(page).toEqual(expectedPage);
140
- expect(await req.text()).toEqual("");
141
-
142
- return res(
143
- ctx.status(200),
144
- ctx.json({
145
- success: true,
146
- errors: [],
147
- messages: [],
148
- result: projects.slice((page - 1) * pageSize, page * pageSize),
149
- })
150
- );
151
- }
152
- )
153
- );
154
- return requests;
155
- }
156
-
157
- it("should make request to list projects", async () => {
158
- const projects: Project[] = [
159
- {
160
- name: "dogs",
161
- subdomain: "docs.pages.dev",
162
- domains: ["dogs.pages.dev"],
163
- source: {
164
- type: "github",
165
- },
166
- latest_deployment: {
167
- modified_on: "2021-11-17T14:52:26.133835Z",
168
- },
169
- created_on: "2021-11-17T14:52:26.133835Z",
170
- production_branch: "main",
171
- },
172
- {
173
- name: "cats",
174
- subdomain: "cats.pages.dev",
175
- domains: ["cats.pages.dev", "kitten.com"],
176
- latest_deployment: {
177
- modified_on: "2021-11-17T14:52:26.133835Z",
178
- },
179
- created_on: "2021-11-17T14:52:26.133835Z",
180
- production_branch: "main",
181
- },
182
- ];
183
-
184
- const requests = mockListRequest(projects);
185
- await runWrangler("pages project list");
186
-
187
- expect(requests.count).toBe(1);
188
- });
189
-
190
- it("should make multiple requests for paginated results", async () => {
191
- const projects: Project[] = [];
192
- for (let i = 0; i < 15; i++) {
193
- projects.push({
194
- name: "dogs" + i,
195
- subdomain: i + "dogs.pages.dev",
196
- domains: [i + "dogs.pages.dev"],
197
- source: {
198
- type: "github",
199
- },
200
- latest_deployment: {
201
- modified_on: "2021-11-17T14:52:26.133835Z",
202
- },
203
- created_on: "2021-11-17T14:52:26.133835Z",
204
- production_branch: "main",
205
- });
206
- }
207
- const requests = mockListRequest(projects);
208
- await runWrangler("pages project list");
209
- expect(requests.count).toEqual(2);
210
- });
211
- });
212
-
213
- describe("project create", () => {
214
- mockAccountId();
215
- mockApiToken();
216
-
217
- it("should create a project with a production branch", async () => {
218
- msw.use(
219
- rest.post(
220
- "*/accounts/:accountId/pages/projects",
221
- async (req, res, ctx) => {
222
- const body = await req.json();
223
-
224
- expect(req.params.accountId).toEqual("some-account-id");
225
- expect(body).toEqual({
226
- name: "a-new-project",
227
- production_branch: "main",
228
- });
229
-
230
- return res.once(
231
- ctx.status(200),
232
- ctx.json({
233
- success: true,
234
- errors: [],
235
- messages: [],
236
- result: {
237
- name: "a-new-project",
238
- subdomain: "a-new-project.pages.dev",
239
- production_branch: "main",
240
- },
241
- })
242
- );
243
- }
244
- )
245
- );
246
- await runWrangler(
247
- "pages project create a-new-project --production-branch=main"
248
- );
249
- expect(std.out).toMatchInlineSnapshot(`
250
- "✨ Successfully created the 'a-new-project' project. It will be available at https://a-new-project.pages.dev/ once you create your first deployment.
251
- To deploy a folder of assets, run 'wrangler pages publish [directory]'."
252
- `);
253
- });
254
- });
255
-
256
- describe("deployment list", () => {
257
- mockAccountId();
258
- mockApiToken();
259
-
260
- function mockListRequest(deployments: unknown[]) {
261
- const requests = { count: 0 };
262
- msw.use(
263
- rest.get(
264
- "*/accounts/:accountId/pages/projects/:project/deployments",
265
- (req, res, ctx) => {
266
- requests.count++;
267
-
268
- expect(req.params.project).toEqual("images");
269
- expect(req.params.accountId).toEqual("some-account-id");
270
-
271
- return res.once(
272
- ctx.status(200),
273
- ctx.json({
274
- success: true,
275
- errors: [],
276
- messages: [],
277
- result: deployments,
278
- })
279
- );
280
- }
281
- )
282
- );
283
- return requests;
284
- }
285
-
286
- it("should make request to list deployments", async () => {
287
- const deployments: Deployment[] = [
288
- {
289
- id: "87bbc8fe-16be-45cd-81e0-63d722e82cdf",
290
- url: "https://87bbc8fe.images.pages.dev",
291
- environment: "preview",
292
- created_on: "2021-11-17T14:52:26.133835Z",
293
- latest_stage: {
294
- ended_on: "2021-11-17T14:52:26.133835Z",
295
- status: "success",
296
- },
297
- deployment_trigger: {
298
- metadata: {
299
- branch: "main",
300
- commit_hash: "c7649364c4cb32ad4f65b530b9424e8be5bec9d6",
301
- },
302
- },
303
- project_name: "images",
304
- },
305
- ];
306
-
307
- const requests = mockListRequest(deployments);
308
- await runWrangler("pages deployment list --project-name=images");
309
-
310
- expect(requests.count).toBe(1);
311
- });
312
- });
313
-
314
- describe("deployment create", () => {
315
- let actualProcessEnvCI: string | undefined;
316
-
317
- mockAccountId();
318
- mockApiToken();
319
- runInTempDir();
320
-
321
- //TODO Abstract MSW handlers that repeat to this level - JACOB
322
- beforeEach(() => {
323
- actualProcessEnvCI = process.env.CI;
324
- process.env.CI = "true";
325
- });
326
-
327
- afterEach(() => {
328
- process.env.CI = actualProcessEnvCI;
329
- });
330
-
331
- it("should be aliased with 'wrangler pages publish'", async () => {
332
- await runWrangler("pages publish --help");
333
- await endEventLoop();
334
-
335
- expect(std.out).toMatchInlineSnapshot(`
336
- "wrangler pages publish [directory]
337
-
338
- 🆙 Publish a directory of static assets as a Pages deployment
339
-
340
- Positionals:
341
- directory The directory of static files to upload [string]
342
-
343
- Flags:
344
- -j, --experimental-json-config Experimental: Support wrangler.json [boolean]
345
- -e, --env Environment to use for operations and .env files [string]
346
- -h, --help Show help [boolean]
347
- -v, --version Show version number [boolean]
348
-
349
- Options:
350
- --project-name The name of the project you want to deploy to [string]
351
- --branch The name of the branch you want to deploy to [string]
352
- --commit-hash The SHA to attach to this deployment [string]
353
- --commit-message The commit message to attach to this deployment [string]
354
- --commit-dirty Whether or not the workspace should be considered dirty for this deployment [boolean]
355
- --skip-caching Skip asset caching which speeds up builds [boolean]
356
- --no-bundle Whether to run bundling on \`_worker.js\` before deploying [boolean] [default: true]
357
-
358
- 🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose"
359
- `);
360
- });
361
-
362
- it("should upload a directory of files", async () => {
363
- writeFileSync("logo.png", "foobar");
364
- mockGetToken("<<funfetti-auth-jwt>>");
365
-
366
- msw.use(
367
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
368
- const body = await req.json();
369
-
370
- expect(req.headers.get("Authorization")).toBe(
371
- "Bearer <<funfetti-auth-jwt>>"
372
- );
373
- expect(body).toMatchObject({
374
- hashes: ["2082190357cfd3617ccfe04f340c6247"],
375
- });
376
-
377
- return res.once(
378
- ctx.status(200),
379
- ctx.json({
380
- success: true,
381
- errors: [],
382
- messages: [],
383
- result: body.hashes,
384
- })
385
- );
386
- }),
387
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
388
- expect(req.headers.get("Authorization")).toMatchInlineSnapshot(
389
- `"Bearer <<funfetti-auth-jwt>>"`
390
- );
391
- expect(await req.json()).toMatchObject([
392
- {
393
- key: "2082190357cfd3617ccfe04f340c6247",
394
- value: Buffer.from("foobar").toString("base64"),
395
- metadata: {
396
- contentType: "image/png",
397
- },
398
- base64: true,
399
- },
400
- ]);
401
- return res.once(
402
- ctx.status(200),
403
- ctx.json({ success: true, errors: [], messages: [], result: null })
404
- );
405
- }),
406
- rest.post(
407
- "*/accounts/:accountId/pages/projects/foo/deployments",
408
- async (req, res, ctx) => {
409
- expect(req.params.accountId).toEqual("some-account-id");
410
- expect(await (req as RestRequestWithFormData).formData())
411
- .toMatchInlineSnapshot(`
412
- FormData {
413
- Symbol(state): Array [
414
- Object {
415
- "name": "manifest",
416
- "value": "{\\"/logo.png\\":\\"2082190357cfd3617ccfe04f340c6247\\"}",
417
- },
418
- ],
419
- }
420
- `);
421
- return res.once(
422
- ctx.status(200),
423
- ctx.json({
424
- success: true,
425
- errors: [],
426
- messages: [],
427
- result: {
428
- url: "https://abcxyz.foo.pages.dev/",
429
- },
430
- })
431
- );
432
- }
433
- ),
434
- rest.get(
435
- "*/accounts/:accountId/pages/projects/foo",
436
- async (req, res, ctx) => {
437
- expect(req.params.accountId).toEqual("some-account-id");
438
-
439
- return res.once(
440
- ctx.status(200),
441
- ctx.json({
442
- success: true,
443
- errors: [],
444
- messages: [],
445
- result: { deployment_configs: { production: {}, preview: {} } },
446
- })
447
- );
448
- }
449
- )
450
- );
451
-
452
- await runWrangler("pages publish . --project-name=foo");
453
-
454
- expect(std.out).toMatchInlineSnapshot(`
455
- "✨ Success! Uploaded 1 files (TIMINGS)
456
-
457
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
458
- `);
459
- });
460
-
461
- it("should retry uploads", async () => {
462
- writeFileSync("logo.txt", "foobar");
463
-
464
- mockGetToken("<<funfetti-auth-jwt>>");
465
-
466
- // Accumulate multiple requests then assert afterwards
467
- const requests: RestRequest[] = [];
468
- msw.use(
469
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
470
- const body = await req.json();
471
-
472
- expect(req.headers.get("Authorization")).toBe(
473
- "Bearer <<funfetti-auth-jwt>>"
474
- );
475
- expect(body).toMatchObject({
476
- hashes: ["1a98fb08af91aca4a7df1764a2c4ddb0"],
477
- });
478
-
479
- return res.once(
480
- ctx.status(200),
481
- ctx.json({
482
- success: true,
483
- errors: [],
484
- messages: [],
485
- result: body.hashes,
486
- })
487
- );
488
- }),
489
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
490
- requests.push(req);
491
- expect(req.headers.get("Authorization")).toBe(
492
- "Bearer <<funfetti-auth-jwt>>"
493
- );
494
- expect(await req.json()).toMatchObject([
495
- {
496
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
497
- value: Buffer.from("foobar").toString("base64"),
498
- metadata: {
499
- contentType: "text/plain",
500
- },
501
- base64: true,
502
- },
503
- ]);
504
-
505
- if (requests.length < 2) {
506
- return res(
507
- ctx.status(200),
508
- ctx.json({
509
- success: false,
510
- errors: [
511
- {
512
- code: 800000,
513
- message: "Something exploded, please retry",
514
- },
515
- ],
516
- messages: [],
517
- result: null,
518
- })
519
- );
520
- } else {
521
- return res(
522
- ctx.status(200),
523
- ctx.json({
524
- success: true,
525
- errors: [],
526
- messages: [],
527
- result: null,
528
- })
529
- );
530
- }
531
- }),
532
- rest.post(
533
- "*/accounts/:accountId/pages/projects/foo/deployments",
534
- async (req, res, ctx) => {
535
- expect(req.params.accountId).toEqual("some-account-id");
536
- expect(await (req as RestRequestWithFormData).formData())
537
- .toMatchInlineSnapshot(`
538
- FormData {
539
- Symbol(state): Array [
540
- Object {
541
- "name": "manifest",
542
- "value": "{\\"/logo.txt\\":\\"1a98fb08af91aca4a7df1764a2c4ddb0\\"}",
543
- },
544
- ],
545
- }
546
- `);
547
-
548
- return res.once(
549
- ctx.status(200),
550
- ctx.json({
551
- success: true,
552
- errors: [],
553
- messages: [],
554
- result: { url: "https://abcxyz.foo.pages.dev/" },
555
- })
556
- );
557
- }
558
- ),
559
- rest.get(
560
- "*/accounts/:accountId/pages/projects/foo",
561
- async (req, res, ctx) => {
562
- expect(req.params.accountId).toEqual("some-account-id");
563
-
564
- return res.once(
565
- ctx.status(200),
566
- ctx.json({
567
- success: true,
568
- errors: [],
569
- messages: [],
570
- result: { deployment_configs: { production: {}, preview: {} } },
571
- })
572
- );
573
- }
574
- )
575
- );
576
-
577
- await runWrangler("pages publish . --project-name=foo");
578
-
579
- expect(std.out).toMatchInlineSnapshot(`
580
- "✨ Success! Uploaded 1 files (TIMINGS)
581
-
582
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
583
- `);
584
- });
585
-
586
- it("should refetch a JWT if it expires while uploading", async () => {
587
- writeFileSync("logo.txt", "foobar");
588
- mockGetToken("<<funfetti-auth-jwt>>");
589
-
590
- const requests: RestRequest[] = [];
591
- msw.use(
592
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
593
- const body = (await req.json()) as { hashes: string[] };
594
-
595
- expect(req.headers.get("Authorization")).toBe(
596
- "Bearer <<funfetti-auth-jwt>>"
597
- );
598
- expect(body).toMatchObject({
599
- hashes: ["1a98fb08af91aca4a7df1764a2c4ddb0"],
600
- });
601
-
602
- return res.once(
603
- ctx.status(200),
604
- ctx.json({
605
- success: true,
606
- errors: [],
607
- messages: [],
608
- result: body.hashes,
609
- })
610
- );
611
- }),
612
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
613
- requests.push(req);
614
- expect(await req.json()).toMatchObject([
615
- {
616
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
617
- value: Buffer.from("foobar").toString("base64"),
618
- metadata: {
619
- contentType: "text/plain",
620
- },
621
- base64: true,
622
- },
623
- ]);
624
- // Fail just the first request
625
- if (requests.length < 2) {
626
- mockGetToken("<<funfetti-auth-jwt2>>");
627
- return res(
628
- ctx.status(200),
629
- ctx.json({
630
- success: false,
631
- errors: [
632
- {
633
- code: 8000013,
634
- message: "Authorization failed",
635
- },
636
- ],
637
- messages: [],
638
- result: null,
639
- })
640
- );
641
- } else {
642
- return res(
643
- ctx.status(200),
644
- ctx.json({
645
- success: true,
646
- errors: [],
647
- messages: [],
648
- result: null,
649
- })
650
- );
651
- }
652
- }),
653
- rest.post(
654
- "*/accounts/:accountId/pages/projects/foo/deployments",
655
- async (req, res, ctx) => {
656
- expect(req.params.accountId).toEqual("some-account-id");
657
- expect(await (req as RestRequestWithFormData).formData())
658
- .toMatchInlineSnapshot(`
659
- FormData {
660
- Symbol(state): Array [
661
- Object {
662
- "name": "manifest",
663
- "value": "{\\"/logo.txt\\":\\"1a98fb08af91aca4a7df1764a2c4ddb0\\"}",
664
- },
665
- ],
666
- }
667
- `);
668
-
669
- return res.once(
670
- ctx.status(200),
671
- ctx.json({
672
- success: true,
673
- errors: [],
674
- messages: [],
675
- result: { url: "https://abcxyz.foo.pages.dev/" },
676
- })
677
- );
678
- }
679
- ),
680
- rest.get(
681
- "*/accounts/:accountId/pages/projects/foo",
682
- async (req, res, ctx) => {
683
- expect(req.params.accountId).toEqual("some-account-id");
684
-
685
- return res.once(
686
- ctx.status(200),
687
- ctx.json({
688
- success: true,
689
- errors: [],
690
- messages: [],
691
- result: { deployment_configs: { production: {}, preview: {} } },
692
- })
693
- );
694
- }
695
- )
696
- );
697
-
698
- await runWrangler("pages publish . --project-name=foo");
699
-
700
- expect(requests[0].headers.get("Authorization")).toBe(
701
- "Bearer <<funfetti-auth-jwt>>"
702
- );
703
-
704
- expect(requests[1].headers.get("Authorization")).toBe(
705
- "Bearer <<funfetti-auth-jwt2>>"
706
- );
707
-
708
- expect(std.out).toMatchInlineSnapshot(`
709
- "✨ Success! Uploaded 1 files (TIMINGS)
710
-
711
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
712
- `);
713
- });
714
-
715
- it("should try to use multiple buckets (up to the max concurrency)", async () => {
716
- writeFileSync("logo.txt", "foobar");
717
- writeFileSync("logo.png", "foobar");
718
- writeFileSync("logo.html", "foobar");
719
- writeFileSync("logo.js", "foobar");
720
-
721
- mockGetToken("<<funfetti-auth-jwt>>");
722
-
723
- // Accumulate multiple requests then assert afterwards
724
- const requests: RestRequest[] = [];
725
- const bodies: UploadPayloadFile[][] = [];
726
- msw.use(
727
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
728
- const body = (await req.json()) as {
729
- hashes: string[];
730
- };
731
-
732
- expect(req.headers.get("Authorization")).toBe(
733
- "Bearer <<funfetti-auth-jwt>>"
734
- );
735
- expect(body).toMatchObject({
736
- hashes: expect.arrayContaining([
737
- "d96fef225537c9f5e44a3cb27fd0b492",
738
- "2082190357cfd3617ccfe04f340c6247",
739
- "6be321bef99e758250dac034474ddbb8",
740
- "1a98fb08af91aca4a7df1764a2c4ddb0",
741
- ]),
742
- });
743
-
744
- return res.once(
745
- ctx.status(200),
746
- ctx.json({
747
- success: true,
748
- errors: [],
749
- messages: [],
750
- result: body.hashes,
751
- })
752
- );
753
- }),
754
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
755
- requests.push(req);
756
-
757
- expect(req.headers.get("Authorization")).toBe(
758
- "Bearer <<funfetti-auth-jwt>>"
759
- );
760
- bodies.push((await req.json()) as UploadPayloadFile[]);
761
-
762
- return res(
763
- ctx.status(200),
764
- ctx.json({
765
- success: true,
766
- errors: [],
767
- messages: [],
768
- result: null,
769
- })
770
- );
771
- }),
772
- rest.post(
773
- "*/accounts/:accountId/pages/projects/foo/deployments",
774
- async (req, res, ctx) => {
775
- expect(req.params.accountId).toEqual("some-account-id");
776
-
777
- const body = await (req as RestRequestWithFormData).formData();
778
- const manifest = JSON.parse(body.get("manifest") as string);
779
-
780
- expect(manifest).toMatchInlineSnapshot(`
781
- Object {
782
- "/logo.html": "d96fef225537c9f5e44a3cb27fd0b492",
783
- "/logo.js": "6be321bef99e758250dac034474ddbb8",
784
- "/logo.png": "2082190357cfd3617ccfe04f340c6247",
785
- "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
786
- }
787
- `);
788
-
789
- return res.once(
790
- ctx.status(200),
791
- ctx.json({
792
- success: true,
793
- errors: [],
794
- messages: [],
795
- result: {
796
- url: "https://abcxyz.foo.pages.dev/",
797
- },
798
- })
799
- );
800
- }
801
- ),
802
- rest.get(
803
- "*/accounts/:accountId/pages/projects/foo",
804
- async (req, res, ctx) => {
805
- expect(req.params.accountId).toEqual("some-account-id");
806
-
807
- return res.once(
808
- ctx.status(200),
809
- ctx.json({
810
- success: true,
811
- errors: [],
812
- messages: [],
813
- result: {
814
- deployment_configs: { production: {}, preview: {} },
815
- },
816
- })
817
- );
818
- }
819
- )
820
- );
821
-
822
- await runWrangler("pages publish . --project-name=foo");
823
-
824
- // We have 3 buckets, so expect 3 uploads
825
- expect(requests.length).toBe(3);
826
-
827
- // One bucket should end up with 2 files
828
- expect(bodies.map((b) => b.length).sort()).toEqual([1, 1, 2]);
829
- // But we don't know the order, so flatten and test without ordering
830
- expect(bodies.flatMap((b) => b)).toEqual(
831
- expect.arrayContaining([
832
- {
833
- base64: true,
834
- key: "d96fef225537c9f5e44a3cb27fd0b492",
835
- metadata: { contentType: "text/html" },
836
- value: "Zm9vYmFy",
837
- },
838
- {
839
- base64: true,
840
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
841
- metadata: { contentType: "text/plain" },
842
- value: "Zm9vYmFy",
843
- },
844
- {
845
- base64: true,
846
- key: "6be321bef99e758250dac034474ddbb8",
847
- metadata: { contentType: "application/javascript" },
848
- value: "Zm9vYmFy",
849
- },
850
- {
851
- base64: true,
852
- key: "2082190357cfd3617ccfe04f340c6247",
853
- metadata: { contentType: "image/png" },
854
- value: "Zm9vYmFy",
855
- },
856
- ])
857
- );
858
-
859
- expect(std.out).toMatchInlineSnapshot(`
860
- "✨ Success! Uploaded 4 files (TIMINGS)
861
-
862
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
863
- `);
864
- });
865
-
866
- it("should resolve child directories correctly", async () => {
867
- mkdirSync("public");
868
- mkdirSync("public/imgs");
869
- writeFileSync("public/logo.txt", "foobar");
870
- writeFileSync("public/imgs/logo.png", "foobar");
871
- writeFileSync("public/logo.html", "foobar");
872
- writeFileSync("public/logo.js", "foobar");
873
-
874
- mockGetToken("<<funfetti-auth-jwt>>");
875
-
876
- // Accumulate multiple requests then assert afterwards
877
- const requests: RestRequest[] = [];
878
- const bodies: UploadPayloadFile[][] = [];
879
- msw.use(
880
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
881
- const body = (await req.json()) as {
882
- hashes: string[];
883
- };
884
-
885
- expect(req.headers.get("Authorization")).toBe(
886
- "Bearer <<funfetti-auth-jwt>>"
887
- );
888
- expect(body).toMatchObject({
889
- hashes: expect.arrayContaining([
890
- "d96fef225537c9f5e44a3cb27fd0b492",
891
- "2082190357cfd3617ccfe04f340c6247",
892
- "6be321bef99e758250dac034474ddbb8",
893
- "1a98fb08af91aca4a7df1764a2c4ddb0",
894
- ]),
895
- });
896
-
897
- return res.once(
898
- ctx.status(200),
899
- ctx.json({
900
- success: true,
901
- errors: [],
902
- messages: [],
903
- result: body.hashes,
904
- })
905
- );
906
- }),
907
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
908
- requests.push(req);
909
-
910
- expect(req.headers.get("Authorization")).toBe(
911
- "Bearer <<funfetti-auth-jwt>>"
912
- );
913
- bodies.push((await req.json()) as UploadPayloadFile[]);
914
-
915
- return res(
916
- ctx.status(200),
917
- ctx.json({
918
- success: true,
919
- errors: [],
920
- messages: [],
921
- result: null,
922
- })
923
- );
924
- }),
925
- rest.post(
926
- "*/accounts/:accountId/pages/projects/foo/deployments",
927
- async (req, res, ctx) => {
928
- expect(req.params.accountId).toEqual("some-account-id");
929
- const body = await (req as RestRequestWithFormData).formData();
930
- const manifest = JSON.parse(body.get("manifest") as string);
931
- expect(manifest).toMatchInlineSnapshot(`
932
- Object {
933
- "/imgs/logo.png": "2082190357cfd3617ccfe04f340c6247",
934
- "/logo.html": "d96fef225537c9f5e44a3cb27fd0b492",
935
- "/logo.js": "6be321bef99e758250dac034474ddbb8",
936
- "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
937
- }
938
- `);
939
-
940
- return res.once(
941
- ctx.status(200),
942
- ctx.json({
943
- success: true,
944
- errors: [],
945
- messages: [],
946
- result: { url: "https://abcxyz.foo.pages.dev/" },
947
- })
948
- );
949
- }
950
- ),
951
- rest.get(
952
- "*/accounts/:accountId/pages/projects/foo",
953
- async (req, res, ctx) => {
954
- expect(req.params.accountId).toEqual("some-account-id");
955
-
956
- return res.once(
957
- ctx.status(200),
958
- ctx.json({
959
- success: true,
960
- errors: [],
961
- messages: [],
962
- result: {
963
- deployment_configs: { production: {}, preview: {} },
964
- },
965
- })
966
- );
967
- }
968
- )
969
- );
970
-
971
- await runWrangler(`pages publish public --project-name=foo`);
972
-
973
- // We have 3 buckets, so expect 3 uploads
974
- expect(requests.length).toBe(3);
975
- // One bucket should end up with 2 files
976
- expect(bodies.map((b) => b.length).sort()).toEqual([1, 1, 2]);
977
- // But we don't know the order, so flatten and test without ordering
978
- expect(bodies.flatMap((b) => b)).toEqual(
979
- expect.arrayContaining([
980
- {
981
- base64: true,
982
- key: "d96fef225537c9f5e44a3cb27fd0b492",
983
- metadata: { contentType: "text/html" },
984
- value: "Zm9vYmFy",
985
- },
986
- {
987
- base64: true,
988
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
989
- metadata: { contentType: "text/plain" },
990
- value: "Zm9vYmFy",
991
- },
992
- {
993
- base64: true,
994
- key: "6be321bef99e758250dac034474ddbb8",
995
- metadata: { contentType: "application/javascript" },
996
- value: "Zm9vYmFy",
997
- },
998
- {
999
- base64: true,
1000
- key: "2082190357cfd3617ccfe04f340c6247",
1001
- metadata: { contentType: "image/png" },
1002
- value: "Zm9vYmFy",
1003
- },
1004
- ])
1005
- );
1006
-
1007
- expect(std.out).toMatchInlineSnapshot(`
1008
- "✨ Success! Uploaded 4 files (TIMINGS)
1009
-
1010
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1011
- `);
1012
- });
1013
-
1014
- it("should resolve the current directory correctly", async () => {
1015
- mkdirSync("public");
1016
- mkdirSync("public/imgs");
1017
- writeFileSync("public/logo.txt", "foobar");
1018
- writeFileSync("public/imgs/logo.png", "foobar");
1019
- writeFileSync("public/logo.html", "foobar");
1020
- writeFileSync("public/logo.js", "foobar");
1021
-
1022
- mockGetToken("<<funfetti-auth-jwt>>");
1023
-
1024
- // Accumulate multiple requests then assert afterwards
1025
- const requests: RestRequest[] = [];
1026
- const bodies: UploadPayloadFile[][] = [];
1027
- msw.use(
1028
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
1029
- const body = (await req.json()) as {
1030
- hashes: string[];
1031
- };
1032
-
1033
- expect(req.headers.get("Authorization")).toBe(
1034
- "Bearer <<funfetti-auth-jwt>>"
1035
- );
1036
- expect(body).toMatchObject({
1037
- hashes: expect.arrayContaining([
1038
- "d96fef225537c9f5e44a3cb27fd0b492",
1039
- "2082190357cfd3617ccfe04f340c6247",
1040
- "6be321bef99e758250dac034474ddbb8",
1041
- "1a98fb08af91aca4a7df1764a2c4ddb0",
1042
- ]),
1043
- });
1044
-
1045
- return res.once(
1046
- ctx.status(200),
1047
- ctx.json({
1048
- success: true,
1049
- errors: [],
1050
- messages: [],
1051
- result: body.hashes,
1052
- })
1053
- );
1054
- }),
1055
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
1056
- requests.push(req);
1057
-
1058
- expect(req.headers.get("Authorization")).toBe(
1059
- "Bearer <<funfetti-auth-jwt>>"
1060
- );
1061
- bodies.push((await req.json()) as UploadPayloadFile[]);
1062
-
1063
- return res(
1064
- ctx.status(200),
1065
- ctx.json({
1066
- success: true,
1067
- errors: [],
1068
- messages: [],
1069
- result: null,
1070
- })
1071
- );
1072
- }),
1073
- rest.post(
1074
- "*/accounts/:accountId/pages/projects/foo/deployments",
1075
- async (req, res, ctx) => {
1076
- expect(req.params.accountId).toEqual("some-account-id");
1077
-
1078
- const body = await (req as RestRequestWithFormData).formData();
1079
- const manifest = JSON.parse(body.get("manifest") as string);
1080
- expect(manifest).toMatchInlineSnapshot(`
1081
- Object {
1082
- "/imgs/logo.png": "2082190357cfd3617ccfe04f340c6247",
1083
- "/logo.html": "d96fef225537c9f5e44a3cb27fd0b492",
1084
- "/logo.js": "6be321bef99e758250dac034474ddbb8",
1085
- "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
1086
- }
1087
- `);
1088
-
1089
- return res.once(
1090
- ctx.status(200),
1091
- ctx.json({
1092
- success: true,
1093
- errors: [],
1094
- messages: [],
1095
- result: { url: "https://abcxyz.foo.pages.dev/" },
1096
- })
1097
- );
1098
- }
1099
- ),
1100
- rest.get(
1101
- "*/accounts/:accountId/pages/projects/foo",
1102
- async (req, res, ctx) => {
1103
- expect(req.params.accountId).toEqual("some-account-id");
1104
-
1105
- return res.once(
1106
- ctx.status(200),
1107
- ctx.json({
1108
- success: true,
1109
- errors: [],
1110
- messages: [],
1111
- result: {
1112
- deployment_configs: { production: {}, preview: {} },
1113
- },
1114
- })
1115
- );
1116
- }
1117
- )
1118
- );
1119
-
1120
- chdir("public");
1121
- await runWrangler(`pages publish . --project-name=foo`);
1122
- // We have 3 buckets, so expect 3 uploads
1123
- expect(requests.length).toBe(3);
1124
- // One bucket should end up with 2 files
1125
- expect(bodies.map((b) => b.length).sort()).toEqual([1, 1, 2]);
1126
- // But we don't know the order, so flatten and test without ordering
1127
- expect(bodies.flatMap((b) => b)).toEqual(
1128
- expect.arrayContaining([
1129
- {
1130
- base64: true,
1131
- key: "d96fef225537c9f5e44a3cb27fd0b492",
1132
- metadata: { contentType: "text/html" },
1133
- value: "Zm9vYmFy",
1134
- },
1135
- {
1136
- base64: true,
1137
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
1138
- metadata: { contentType: "text/plain" },
1139
- value: "Zm9vYmFy",
1140
- },
1141
- {
1142
- base64: true,
1143
- key: "6be321bef99e758250dac034474ddbb8",
1144
- metadata: { contentType: "application/javascript" },
1145
- value: "Zm9vYmFy",
1146
- },
1147
- {
1148
- base64: true,
1149
- key: "2082190357cfd3617ccfe04f340c6247",
1150
- metadata: { contentType: "image/png" },
1151
- value: "Zm9vYmFy",
1152
- },
1153
- ])
1154
- );
1155
-
1156
- expect(std.out).toMatchInlineSnapshot(`
1157
- "✨ Success! Uploaded 4 files (TIMINGS)
1158
-
1159
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1160
- `);
1161
- });
1162
-
1163
- it("should not error when directory names contain periods and houses a extensionless file", async () => {
1164
- mkdirSync(".well-known");
1165
- // Note: same content as previous test, but since it's a different extension,
1166
- // it hashes to a different value
1167
- writeFileSync(".well-known/foobar", "foobar");
1168
-
1169
- mockGetToken("<<funfetti-auth-jwt>>");
1170
-
1171
- msw.use(
1172
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
1173
- const body = (await req.json()) as {
1174
- hashes: string[];
1175
- };
1176
-
1177
- expect(req.headers.get("Authorization")).toBe(
1178
- "Bearer <<funfetti-auth-jwt>>"
1179
- );
1180
- expect(body).toMatchObject({
1181
- hashes: ["7b764dacfd211bebd8077828a7ddefd7"],
1182
- });
1183
-
1184
- return res.once(
1185
- ctx.status(200),
1186
- ctx.json({
1187
- success: true,
1188
- errors: [],
1189
- messages: [],
1190
- result: body.hashes,
1191
- })
1192
- );
1193
- }),
1194
-
1195
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
1196
- expect(req.headers.get("Authorization")).toBe(
1197
- "Bearer <<funfetti-auth-jwt>>"
1198
- );
1199
- const body = (await req.json()) as UploadPayloadFile[];
1200
- expect(body).toMatchObject([
1201
- {
1202
- key: "7b764dacfd211bebd8077828a7ddefd7",
1203
- value: Buffer.from("foobar").toString("base64"),
1204
- metadata: {
1205
- contentType: "application/octet-stream",
1206
- },
1207
- base64: true,
1208
- },
1209
- ]);
1210
- return res.once(
1211
- ctx.status(200),
1212
- ctx.json({
1213
- success: true,
1214
- errors: [],
1215
- messages: [],
1216
- result: null,
1217
- })
1218
- );
1219
- }),
1220
- rest.post(
1221
- "*/accounts/:accountId/pages/projects/foo/deployments",
1222
- async (req, res, ctx) => {
1223
- expect(req.params.accountId).toEqual("some-account-id");
1224
-
1225
- return res.once(
1226
- ctx.status(200),
1227
- ctx.json({
1228
- success: true,
1229
- errors: [],
1230
- messages: [],
1231
- result: { url: "https://abcxyz.foo.pages.dev/" },
1232
- })
1233
- );
1234
- }
1235
- ),
1236
- rest.get(
1237
- "*/accounts/:accountId/pages/projects/foo",
1238
- async (req, res, ctx) => {
1239
- expect(req.params.accountId).toEqual("some-account-id");
1240
-
1241
- return res.once(
1242
- ctx.status(200),
1243
- ctx.json({
1244
- success: true,
1245
- errors: [],
1246
- messages: [],
1247
- result: {
1248
- deployment_configs: { production: {}, preview: {} },
1249
- },
1250
- })
1251
- );
1252
- }
1253
- )
1254
- );
1255
-
1256
- await runWrangler("pages publish . --project-name=foo");
1257
-
1258
- expect(std.err).toMatchInlineSnapshot(`""`);
1259
- });
1260
-
1261
- it("should throw an error if user attempts to use config with pages", async () => {
1262
- await expect(
1263
- runWrangler("pages dev --config foo.toml")
1264
- ).rejects.toThrowErrorMatchingInlineSnapshot(
1265
- `"Pages does not support wrangler.toml"`
1266
- );
1267
- await expect(
1268
- runWrangler("pages publish --config foo.toml")
1269
- ).rejects.toThrowErrorMatchingInlineSnapshot(
1270
- `"Pages does not support wrangler.toml"`
1271
- );
1272
- });
1273
-
1274
- it("should upload a Functions project", async () => {
1275
- // set up the directory of static files to upload.
1276
- mkdirSync("public");
1277
- writeFileSync("public/README.md", "This is a readme");
1278
-
1279
- // set up /functions
1280
- mkdirSync("functions");
1281
- writeFileSync(
1282
- "functions/hello.js",
1283
- `
1284
- export async function onRequest() {
1285
- return new Response("Hello, world!");
1286
- }
1287
- `
1288
- );
1289
-
1290
- mockGetToken("<<funfetti-auth-jwt>>");
1291
-
1292
- msw.use(
1293
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
1294
- const body = (await req.json()) as {
1295
- hashes: string[];
1296
- };
1297
-
1298
- expect(req.headers.get("Authorization")).toBe(
1299
- "Bearer <<funfetti-auth-jwt>>"
1300
- );
1301
- expect(body).toMatchObject({
1302
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1303
- });
1304
-
1305
- return res.once(
1306
- ctx.status(200),
1307
- ctx.json({
1308
- success: true,
1309
- errors: [],
1310
- messages: [],
1311
- result: body.hashes,
1312
- })
1313
- );
1314
- }),
1315
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
1316
- expect(req.headers.get("Authorization")).toBe(
1317
- "Bearer <<funfetti-auth-jwt>>"
1318
- );
1319
-
1320
- expect(await req.json()).toMatchObject([
1321
- {
1322
- key: "13a03eaf24ae98378acd36ea00f77f2f",
1323
- value: Buffer.from("This is a readme").toString("base64"),
1324
- metadata: {
1325
- contentType: "text/markdown",
1326
- },
1327
- base64: true,
1328
- },
1329
- ]);
1330
- return res.once(
1331
- ctx.status(200),
1332
- ctx.json({
1333
- success: true,
1334
- errors: [],
1335
- messages: [],
1336
- result: true,
1337
- })
1338
- );
1339
- }),
1340
- rest.post(`*/pages/assets/upsert-hashes`, async (req, res, ctx) => {
1341
- expect(req.headers.get("Authorization")).toBe(
1342
- "Bearer <<funfetti-auth-jwt>>"
1343
- );
1344
-
1345
- expect(await req.json()).toMatchObject({
1346
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1347
- });
1348
-
1349
- return res.once(
1350
- ctx.status(200),
1351
- ctx.json({
1352
- success: true,
1353
- errors: [],
1354
- messages: [],
1355
- result: true,
1356
- })
1357
- );
1358
- }),
1359
-
1360
- rest.post(
1361
- "*/accounts/:accountId/pages/projects/foo/deployments",
1362
- async (req, res, ctx) => {
1363
- expect(req.params.accountId).toEqual("some-account-id");
1364
- const body = await (req as RestRequestWithFormData).formData();
1365
- const manifest = JSON.parse(body.get("manifest") as string);
1366
-
1367
- // for Functions projects, we auto-generate a `_worker.js`,
1368
- // `functions-filepath-routing-config.json`, and `_routes.json`
1369
- // file, based on the contents of `/functions`
1370
- const generatedWorkerJS = body.get("_worker.js") as string;
1371
- const generatedRoutesJSON = body.get("_routes.json") as string;
1372
- const generatedFilepathRoutingConfig = body.get(
1373
- "functions-filepath-routing-config.json"
1374
- ) as string;
1375
-
1376
- // make sure this is all we uploaded
1377
- expect([...body.keys()]).toEqual([
1378
- "manifest",
1379
- "functions-filepath-routing-config.json",
1380
- "_worker.js",
1381
- "_routes.json",
1382
- ]);
1383
-
1384
- expect(manifest).toMatchInlineSnapshot(`
1385
- Object {
1386
- "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
1387
- }
1388
- `);
1389
-
1390
- // the contents of the generated `_worker.js` file is pretty massive, so I don't
1391
- // think snapshot testing makes much sense here. Plus, calling
1392
- // `.toMatchInlineSnapshot()` without any arguments, in order to generate that
1393
- // snapshot value, doesn't generate anything in this case (probably because the
1394
- // file contents is too big). So for now, let's test that _worker.js was indeed
1395
- // generated and that the file size is greater than zero
1396
- expect(generatedWorkerJS).not.toBeNull();
1397
- expect(generatedWorkerJS.length).toBeGreaterThan(0);
1398
-
1399
- const maybeRoutesJSONSpec = JSON.parse(generatedRoutesJSON);
1400
- expect(isRoutesJSONSpec(maybeRoutesJSONSpec)).toBe(true);
1401
- expect(maybeRoutesJSONSpec).toMatchObject({
1402
- version: ROUTES_SPEC_VERSION,
1403
- description: `Generated by wrangler@${version}`,
1404
- include: ["/hello"],
1405
- exclude: [],
1406
- });
1407
-
1408
- // Make sure the routing config is valid json
1409
- const parsedFilepathRoutingConfig = JSON.parse(
1410
- generatedFilepathRoutingConfig
1411
- );
1412
- // The actual shape doesn't matter that much since this
1413
- // is only used for display in Dash, but it's still useful for
1414
- // tracking unexpected changes to this config.
1415
- expect(parsedFilepathRoutingConfig).toStrictEqual({
1416
- routes: [
1417
- {
1418
- routePath: "/hello",
1419
- mountPath: "/",
1420
- method: "",
1421
- module: ["hello.js:onRequest"],
1422
- },
1423
- ],
1424
- baseURL: "/",
1425
- });
1426
-
1427
- return res.once(
1428
- ctx.status(200),
1429
- ctx.json({
1430
- success: true,
1431
- errors: [],
1432
- messages: [],
1433
- result: {
1434
- url: "https://abcxyz.foo.pages.dev/",
1435
- },
1436
- })
1437
- );
1438
- }
1439
- ),
1440
- rest.get(
1441
- "*/accounts/:accountId/pages/projects/foo",
1442
- async (req, res, ctx) => {
1443
- expect(req.params.accountId).toEqual("some-account-id");
1444
-
1445
- return res.once(
1446
- ctx.status(200),
1447
- ctx.json({
1448
- success: true,
1449
- errors: [],
1450
- messages: [],
1451
- result: {
1452
- deployment_configs: { production: {}, preview: {} },
1453
- },
1454
- })
1455
- );
1456
- }
1457
- )
1458
- );
1459
-
1460
- await runWrangler("pages publish public --project-name=foo");
1461
-
1462
- expect(std.out).toMatchInlineSnapshot(`
1463
- "✨ Compiled Worker successfully
1464
- ✨ Success! Uploaded 1 files (TIMINGS)
1465
-
1466
- ✨ Uploading Functions
1467
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1468
- `);
1469
-
1470
- expect(std.err).toMatchInlineSnapshot('""');
1471
- });
1472
-
1473
- const workerHasD1Shim = (contents: string) => contents.includes("D1_ERROR");
1474
-
1475
- it("should upload an Advanced Mode project", async () => {
1476
- // set up the directory of static files to upload.
1477
- mkdirSync("public");
1478
- writeFileSync("public/README.md", "This is a readme");
1479
-
1480
- // set up _worker.js
1481
- writeFileSync(
1482
- "public/_worker.js",
1483
- `
1484
- export default {
1485
- async fetch(request, env) {
1486
- const url = new URL(request.url);
1487
- console.log("SOMETHING FROM WITHIN THE WORKER");
1488
- return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
1489
- }
1490
- };
1491
- `
1492
- );
1493
-
1494
- mockGetToken("<<funfetti-auth-jwt>>");
1495
-
1496
- msw.use(
1497
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
1498
- const body = (await req.json()) as {
1499
- hashes: string[];
1500
- };
1501
-
1502
- expect(req.headers.get("Authorization")).toBe(
1503
- "Bearer <<funfetti-auth-jwt>>"
1504
- );
1505
- expect(body).toMatchObject({
1506
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1507
- });
1508
-
1509
- return res.once(
1510
- ctx.status(200),
1511
- ctx.json({
1512
- success: true,
1513
- errors: [],
1514
- messages: [],
1515
- result: body.hashes,
1516
- })
1517
- );
1518
- }),
1519
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
1520
- expect(req.headers.get("Authorization")).toBe(
1521
- "Bearer <<funfetti-auth-jwt>>"
1522
- );
1523
-
1524
- expect(await req.json()).toMatchObject([
1525
- {
1526
- key: "13a03eaf24ae98378acd36ea00f77f2f",
1527
- value: Buffer.from("This is a readme").toString("base64"),
1528
- metadata: {
1529
- contentType: "text/markdown",
1530
- },
1531
- base64: true,
1532
- },
1533
- ]);
1534
- return res.once(
1535
- ctx.status(200),
1536
- ctx.json({
1537
- success: true,
1538
- errors: [],
1539
- messages: [],
1540
- result: true,
1541
- })
1542
- );
1543
- }),
1544
- rest.post(
1545
- "*/accounts/:accountId/pages/projects/foo/deployments",
1546
- async (req, res, ctx) => {
1547
- expect(req.params.accountId).toEqual("some-account-id");
1548
- const body = await (req as RestRequestWithFormData).formData();
1549
- const manifest = JSON.parse(body.get("manifest") as string);
1550
- const customWorkerJS = body.get("_worker.js");
1551
-
1552
- // make sure this is all we uploaded
1553
- expect([...body.keys()].sort()).toEqual(
1554
- ["manifest", "_worker.js"].sort()
1555
- );
1556
-
1557
- expect(manifest).toMatchInlineSnapshot(`
1558
- Object {
1559
- "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
1560
- }
1561
- `);
1562
-
1563
- expect(workerHasD1Shim(customWorkerJS as string)).toBeTruthy();
1564
- expect(customWorkerJS).toContain(
1565
- `console.log("SOMETHING FROM WITHIN THE WORKER");`
1566
- );
1567
-
1568
- return res.once(
1569
- ctx.status(200),
1570
- ctx.json({
1571
- success: true,
1572
- errors: [],
1573
- messages: [],
1574
- result: {
1575
- url: "https://abcxyz.foo.pages.dev/",
1576
- },
1577
- })
1578
- );
1579
- }
1580
- ),
1581
- rest.get(
1582
- "*/accounts/:accountId/pages/projects/foo",
1583
- async (req, res, ctx) => {
1584
- expect(req.params.accountId).toEqual("some-account-id");
1585
-
1586
- return res.once(
1587
- ctx.status(200),
1588
- ctx.json({
1589
- success: true,
1590
- errors: [],
1591
- messages: [],
1592
- result: {
1593
- deployment_configs: {
1594
- production: {
1595
- d1_databases: { MY_D1_DB: { id: "fake-db" } },
1596
- },
1597
- preview: {
1598
- d1_databases: { MY_D1_DB: { id: "fake-db" } },
1599
- },
1600
- },
1601
- } as Partial<Project>,
1602
- })
1603
- );
1604
- }
1605
- )
1606
- );
1607
-
1608
- await runWrangler("pages publish public --project-name=foo --bundle");
1609
-
1610
- expect(std.out).toMatchInlineSnapshot(`
1611
- "✨ Success! Uploaded 1 files (TIMINGS)
1612
-
1613
- ✨ Compiled Worker successfully
1614
- ✨ Uploading _worker.js
1615
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1616
- `);
1617
-
1618
- expect(std.err).toMatchInlineSnapshot('""');
1619
- });
1620
-
1621
- it("should upload _routes.json for Functions projects, if provided", async () => {
1622
- // set up the directory of static files to upload.
1623
- mkdirSync("public");
1624
- writeFileSync("public/README.md", "This is a readme");
1625
-
1626
- // set up /functions
1627
- mkdirSync("functions");
1628
- writeFileSync(
1629
- "functions/hello.js",
1630
- `
1631
- export async function onRequest() {
1632
- return new Response("Hello, world!");
1633
- }
1634
- `
1635
- );
1636
-
1637
- writeFileSync(
1638
- "functions/goodbye.ts",
1639
- `
1640
- export async function onRequest() {
1641
- return new Response("Bye bye!");
1642
- }
1643
- `
1644
- );
1645
-
1646
- // set up _routes.json
1647
- writeFileSync(
1648
- "public/_routes.json",
1649
- `
1650
- {
1651
- "version": ${ROUTES_SPEC_VERSION},
1652
- "description": "Custom _routes.json file",
1653
- "include": ["/hello"],
1654
- "exclude": []
1655
- }
1656
- `
1657
- );
1658
-
1659
- mockGetToken("<<funfetti-auth-jwt>>");
1660
- msw.use(
1661
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
1662
- const body = (await req.json()) as {
1663
- hashes: string[];
1664
- };
1665
-
1666
- expect(req.headers.get("Authorization")).toBe(
1667
- "Bearer <<funfetti-auth-jwt>>"
1668
- );
1669
- expect(body).toMatchObject({
1670
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1671
- });
1672
-
1673
- return res.once(
1674
- ctx.status(200),
1675
- ctx.json({
1676
- success: true,
1677
- errors: [],
1678
- messages: [],
1679
- result: body.hashes,
1680
- })
1681
- );
1682
- }),
1683
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
1684
- expect(req.headers.get("Authorization")).toBe(
1685
- "Bearer <<funfetti-auth-jwt>>"
1686
- );
1687
-
1688
- expect(await req.json()).toMatchObject([
1689
- {
1690
- key: "13a03eaf24ae98378acd36ea00f77f2f",
1691
- value: Buffer.from("This is a readme").toString("base64"),
1692
- metadata: {
1693
- contentType: "text/markdown",
1694
- },
1695
- base64: true,
1696
- },
1697
- ]);
1698
-
1699
- return res.once(
1700
- ctx.status(200),
1701
- ctx.json({
1702
- success: true,
1703
- errors: [],
1704
- messages: [],
1705
- result: null,
1706
- })
1707
- );
1708
- }),
1709
- rest.post(`*/pages/assets/upsert-hashes`, async (req, res, ctx) => {
1710
- expect(req.headers.get("Authorization")).toBe(
1711
- "Bearer <<funfetti-auth-jwt>>"
1712
- );
1713
-
1714
- expect(await req.json()).toMatchObject({
1715
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1716
- });
1717
-
1718
- return res.once(
1719
- ctx.status(200),
1720
- ctx.json({
1721
- success: true,
1722
- errors: [],
1723
- messages: [],
1724
- result: true,
1725
- })
1726
- );
1727
- }),
1728
- rest.post(
1729
- "*/accounts/:accountId/pages/projects/foo/deployments",
1730
- async (req, res, ctx) => {
1731
- expect(req.params.accountId).toEqual("some-account-id");
1732
- const body = await (req as RestRequestWithFormData).formData();
1733
- const manifest = JSON.parse(body.get("manifest") as string);
1734
- const generatedWorkerJS = body.get("_worker.js") as string;
1735
- const customRoutesJSON = body.get("_routes.json") as string;
1736
- const generatedFilepathRoutingConfig = body.get(
1737
- "functions-filepath-routing-config.json"
1738
- ) as string;
1739
-
1740
- // make sure this is all we uploaded
1741
- expect([...body.keys()].sort()).toEqual(
1742
- [
1743
- "manifest",
1744
- "functions-filepath-routing-config.json",
1745
- "_worker.js",
1746
- "_routes.json",
1747
- ].sort()
1748
- );
1749
-
1750
- expect(manifest).toMatchInlineSnapshot(`
1751
- Object {
1752
- "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
1753
- }
1754
- `);
1755
-
1756
- // file content of generated `_worker.js` is too massive to snapshot test
1757
- expect(generatedWorkerJS).not.toBeNull();
1758
- expect(generatedWorkerJS.length).toBeGreaterThan(0);
1759
-
1760
- const customRoutes = JSON.parse(customRoutesJSON);
1761
- expect(customRoutes).toMatchObject({
1762
- version: ROUTES_SPEC_VERSION,
1763
- description: "Custom _routes.json file",
1764
- include: ["/hello"],
1765
- exclude: [],
1766
- });
1767
-
1768
- // Make sure the routing config is valid json
1769
- const parsedFilepathRoutingConfig = JSON.parse(
1770
- generatedFilepathRoutingConfig
1771
- );
1772
- // The actual shape doesn't matter that much since this
1773
- // is only used for display in Dash, but it's still useful for
1774
- // tracking unexpected changes to this config.
1775
- expect(parsedFilepathRoutingConfig).toStrictEqual({
1776
- routes: [
1777
- {
1778
- routePath: "/goodbye",
1779
- mountPath: "/",
1780
- method: "",
1781
- module: ["goodbye.ts:onRequest"],
1782
- },
1783
- {
1784
- routePath: "/hello",
1785
- mountPath: "/",
1786
- method: "",
1787
- module: ["hello.js:onRequest"],
1788
- },
1789
- ],
1790
- baseURL: "/",
1791
- });
1792
-
1793
- return res.once(
1794
- ctx.status(200),
1795
- ctx.json({
1796
- success: true,
1797
- errors: [],
1798
- messages: [],
1799
- result: {
1800
- url: "https://abcxyz.foo.pages.dev/",
1801
- },
1802
- })
1803
- );
1804
- }
1805
- ),
1806
- rest.get(
1807
- "*/accounts/:accountId/pages/projects/foo",
1808
- async (req, res, ctx) => {
1809
- expect(req.params.accountId).toEqual("some-account-id");
1810
-
1811
- return res.once(
1812
- ctx.status(200),
1813
- ctx.json({
1814
- success: true,
1815
- errors: [],
1816
- messages: [],
1817
- result: {
1818
- deployment_configs: { production: {}, preview: {} },
1819
- },
1820
- })
1821
- );
1822
- }
1823
- )
1824
- );
1825
-
1826
- await runWrangler("pages publish public --project-name=foo");
1827
-
1828
- expect(std.out).toMatchInlineSnapshot(`
1829
- "✨ Compiled Worker successfully
1830
- ✨ Success! Uploaded 1 files (TIMINGS)
1831
-
1832
- ✨ Uploading Functions
1833
- ✨ Uploading _routes.json
1834
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1835
- `);
1836
-
1837
- expect(std.warn).toMatchInlineSnapshot(`""`);
1838
- expect(std.err).toMatchInlineSnapshot('""');
1839
- });
1840
-
1841
- it("should not deploy Functions projects that provide an invalid custom _routes.json file", async () => {
1842
- // set up the directory of static files to upload.
1843
- mkdirSync("public");
1844
- writeFileSync("public/README.md", "This is a readme");
1845
-
1846
- // set up _routes.json
1847
- writeFileSync(
1848
- "public/_routes.json",
1849
- `
1850
- {
1851
- "description": "Custom _routes.json file",
1852
- "include": [],
1853
- "exclude": []
1854
- }
1855
- `
1856
- );
1857
-
1858
- // set up /functions
1859
- mkdirSync("functions");
1860
- writeFileSync(
1861
- "functions/hello.js",
1862
- `
1863
- export async function onRequest() {
1864
- return new Response("Hello, world!");
1865
- }
1866
- `
1867
- );
1868
-
1869
- mockGetToken("<<funfetti-auth-jwt>>");
1870
- msw.use(
1871
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
1872
- const body = (await req.json()) as {
1873
- hashes: string[];
1874
- };
1875
-
1876
- expect(req.headers.get("Authorization")).toBe(
1877
- "Bearer <<funfetti-auth-jwt>>"
1878
- );
1879
- expect(body).toMatchObject({
1880
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1881
- });
1882
-
1883
- return res.once(
1884
- ctx.status(200),
1885
- ctx.json({
1886
- success: true,
1887
- errors: [],
1888
- messages: [],
1889
- result: body.hashes,
1890
- })
1891
- );
1892
- }),
1893
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
1894
- expect(req.headers.get("Authorization")).toBe(
1895
- "Bearer <<funfetti-auth-jwt>>"
1896
- );
1897
-
1898
- expect(await req.json()).toMatchObject([
1899
- {
1900
- key: "13a03eaf24ae98378acd36ea00f77f2f",
1901
- value: Buffer.from("This is a readme").toString("base64"),
1902
- metadata: {
1903
- contentType: "text/markdown",
1904
- },
1905
- base64: true,
1906
- },
1907
- ]);
1908
-
1909
- return res.once(
1910
- ctx.status(200),
1911
- ctx.json({
1912
- success: true,
1913
- errors: [],
1914
- messages: [],
1915
- result: null,
1916
- })
1917
- );
1918
- }),
1919
- rest.get(
1920
- "*/accounts/:accountId/pages/projects/foo",
1921
- async (req, res, ctx) => {
1922
- expect(req.params.accountId).toEqual("some-account-id");
1923
-
1924
- return res.once(
1925
- ctx.status(200),
1926
- ctx.json({
1927
- success: true,
1928
- errors: [],
1929
- messages: [],
1930
- result: {
1931
- deployment_configs: { production: {}, preview: {} },
1932
- },
1933
- })
1934
- );
1935
- }
1936
- )
1937
- );
1938
-
1939
- await expect(runWrangler("pages publish public --project-name=foo"))
1940
- .rejects
1941
- .toThrow(`Invalid _routes.json file found at: public/_routes.json
1942
- Please make sure the JSON object has the following format:
1943
- {
1944
- version: ${ROUTES_SPEC_VERSION};
1945
- include: string[];
1946
- exclude: string[];
1947
- }
1948
- and that at least one include rule is provided.
1949
- `);
1950
- });
1951
-
1952
- it("should upload _routes.json for Advanced Mode projects, if provided", async () => {
1953
- // set up the directory of static files to upload.
1954
- mkdirSync("public");
1955
- writeFileSync("public/README.md", "This is a readme");
1956
-
1957
- // set up _routes.json
1958
- writeFileSync(
1959
- "public/_routes.json",
1960
- `
1961
- {
1962
- "version": ${ROUTES_SPEC_VERSION},
1963
- "description": "Custom _routes.json file",
1964
- "include": ["/api/*"],
1965
- "exclude": []
1966
- }
1967
- `
1968
- );
1969
-
1970
- // set up _worker.js
1971
- writeFileSync(
1972
- "public/_worker.js",
1973
- `
1974
- export default {
1975
- async fetch(request, env) {
1976
- const url = new URL(request.url);
1977
- return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
1978
- }
1979
- };
1980
- `
1981
- );
1982
-
1983
- mockGetToken("<<funfetti-auth-jwt>>");
1984
-
1985
- msw.use(
1986
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
1987
- const body = (await req.json()) as {
1988
- hashes: string[];
1989
- };
1990
-
1991
- expect(req.headers.get("Authorization")).toBe(
1992
- "Bearer <<funfetti-auth-jwt>>"
1993
- );
1994
- expect(body).toMatchObject({
1995
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1996
- });
1997
-
1998
- return res.once(
1999
- ctx.status(200),
2000
- ctx.json({
2001
- success: true,
2002
- errors: [],
2003
- messages: [],
2004
- result: body.hashes,
2005
- })
2006
- );
2007
- }),
2008
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
2009
- expect(req.headers.get("Authorization")).toBe(
2010
- "Bearer <<funfetti-auth-jwt>>"
2011
- );
2012
-
2013
- expect(await req.json()).toMatchObject([
2014
- {
2015
- key: "13a03eaf24ae98378acd36ea00f77f2f",
2016
- value: Buffer.from("This is a readme").toString("base64"),
2017
- metadata: {
2018
- contentType: "text/markdown",
2019
- },
2020
- base64: true,
2021
- },
2022
- ]);
2023
-
2024
- return res.once(
2025
- ctx.status(200),
2026
- ctx.json({
2027
- success: true,
2028
- errors: [],
2029
- messages: [],
2030
- result: null,
2031
- })
2032
- );
2033
- }),
2034
- rest.post(`*/pages/assets/upsert-hashes`, async (req, res, ctx) => {
2035
- expect(req.headers.get("Authorization")).toBe(
2036
- "Bearer <<funfetti-auth-jwt>>"
2037
- );
2038
-
2039
- expect(await req.json()).toMatchObject({
2040
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
2041
- });
2042
-
2043
- return res.once(
2044
- ctx.status(200),
2045
- ctx.json({
2046
- success: true,
2047
- errors: [],
2048
- messages: [],
2049
- result: true,
2050
- })
2051
- );
2052
- }),
2053
- rest.post(
2054
- "*/accounts/:accountId/pages/projects/foo/deployments",
2055
- async (req, res, ctx) => {
2056
- const body = await (req as RestRequestWithFormData).formData();
2057
-
2058
- const manifest = JSON.parse(body.get("manifest") as string);
2059
- const customWorkerJS = body.get("_worker.js") as string;
2060
- const customRoutesJSON = body.get("_routes.json") as string;
2061
-
2062
- // make sure this is all we uploaded
2063
- expect([...body.keys()]).toEqual([
2064
- "manifest",
2065
- "_worker.js",
2066
- "_routes.json",
2067
- ]);
2068
- expect(req.params.accountId).toEqual("some-account-id");
2069
- expect(manifest).toMatchInlineSnapshot(`
2070
- Object {
2071
- "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
2072
- }
2073
- `);
2074
-
2075
- expect(customWorkerJS).toMatchInlineSnapshot(`
2076
- "
2077
- export default {
2078
- async fetch(request, env) {
2079
- const url = new URL(request.url);
2080
- return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
2081
- }
2082
- };
2083
- "
2084
- `);
2085
-
2086
- expect(JSON.parse(customRoutesJSON)).toMatchObject({
2087
- version: ROUTES_SPEC_VERSION,
2088
- description: "Custom _routes.json file",
2089
- include: ["/api/*"],
2090
- exclude: [],
2091
- });
2092
-
2093
- return res.once(
2094
- ctx.status(200),
2095
- ctx.json({
2096
- success: true,
2097
- errors: [],
2098
- messages: [],
2099
- result: {
2100
- url: "https://abcxyz.foo.pages.dev/",
2101
- },
2102
- })
2103
- );
2104
- }
2105
- ),
2106
- rest.get(
2107
- "*/accounts/:accountId/pages/projects/foo",
2108
- async (req, res, ctx) => {
2109
- expect(req.params.accountId).toEqual("some-account-id");
2110
-
2111
- return res.once(
2112
- ctx.status(200),
2113
- ctx.json({
2114
- success: true,
2115
- errors: [],
2116
- messages: [],
2117
- result: {
2118
- deployment_configs: { production: {}, preview: {} },
2119
- },
2120
- })
2121
- );
2122
- }
2123
- )
2124
- );
2125
-
2126
- await runWrangler("pages publish public --project-name=foo");
2127
-
2128
- expect(std.out).toMatchInlineSnapshot(`
2129
- "✨ Success! Uploaded 1 files (TIMINGS)
2130
-
2131
- ✨ Compiled Worker successfully
2132
- ✨ Uploading _worker.js
2133
- ✨ Uploading _routes.json
2134
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
2135
- `);
2136
-
2137
- expect(std.warn).toMatchInlineSnapshot(`""`);
2138
- expect(std.err).toMatchInlineSnapshot(`""`);
2139
- });
2140
-
2141
- it("should not deploy Advanced Mode projects that provide an invalid _routes.json file", async () => {
2142
- // set up the directory of static files to upload.
2143
- mkdirSync("public");
2144
- writeFileSync("public/README.md", "This is a readme");
2145
-
2146
- // set up _routes.json
2147
- writeFileSync(
2148
- "public/_routes.json",
2149
- `
2150
- {
2151
- "description": "Custom _routes.json file",
2152
- "include": [],
2153
- "exclude": []
2154
- }
2155
- `
2156
- );
2157
-
2158
- // set up _worker.js
2159
- writeFileSync(
2160
- "public/_worker.js",
2161
- `
2162
- export default {
2163
- async fetch(request, env) {
2164
- const url = new URL(request.url);
2165
- return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
2166
- }
2167
- };
2168
- `
2169
- );
2170
-
2171
- mockGetToken("<<funfetti-auth-jwt>>");
2172
-
2173
- msw.use(
2174
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
2175
- const body = (await req.json()) as {
2176
- hashes: string[];
2177
- };
2178
-
2179
- expect(req.headers.get("Authorization")).toBe(
2180
- "Bearer <<funfetti-auth-jwt>>"
2181
- );
2182
- expect(body).toMatchObject({
2183
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
2184
- });
2185
-
2186
- return res.once(
2187
- ctx.status(200),
2188
- ctx.json({
2189
- success: true,
2190
- errors: [],
2191
- messages: [],
2192
- result: body.hashes,
2193
- })
2194
- );
2195
- }),
2196
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
2197
- expect(req.headers.get("Authorization")).toBe(
2198
- "Bearer <<funfetti-auth-jwt>>"
2199
- );
2200
-
2201
- expect(await req.json()).toMatchObject([
2202
- {
2203
- key: "13a03eaf24ae98378acd36ea00f77f2f",
2204
- value: Buffer.from("This is a readme").toString("base64"),
2205
- metadata: {
2206
- contentType: "text/markdown",
2207
- },
2208
- base64: true,
2209
- },
2210
- ]);
2211
-
2212
- return res.once(
2213
- ctx.status(200),
2214
- ctx.json({
2215
- success: true,
2216
- errors: [],
2217
- messages: [],
2218
- result: null,
2219
- })
2220
- );
2221
- }),
2222
-
2223
- rest.get(
2224
- "*/accounts/:accountId/pages/projects/foo",
2225
- async (req, res, ctx) => {
2226
- expect(req.params.accountId).toEqual("some-account-id");
2227
- return res.once(
2228
- ctx.status(200),
2229
- ctx.json({
2230
- success: true,
2231
- errors: [],
2232
- messages: [],
2233
- result: {
2234
- deployment_configs: { production: {}, preview: {} },
2235
- },
2236
- })
2237
- );
2238
- }
2239
- )
2240
- );
2241
-
2242
- await expect(runWrangler("pages publish public --project-name=foo"))
2243
- .rejects
2244
- .toThrow(`Invalid _routes.json file found at: public/_routes.json
2245
- Please make sure the JSON object has the following format:
2246
- {
2247
- version: ${ROUTES_SPEC_VERSION};
2248
- include: string[];
2249
- exclude: string[];
2250
- }
2251
- and that at least one include rule is provided.
2252
- `);
2253
- });
2254
-
2255
- it("should ignore the entire /functions directory if _worker.js is provided", async () => {
2256
- // set up the directory of static files to upload.
2257
- mkdirSync("public");
2258
- writeFileSync("public/README.md", "This is a readme");
2259
-
2260
- // set up /functions
2261
- mkdirSync("functions");
2262
- writeFileSync(
2263
- "functions/hello.js",
2264
- `
2265
- export async function onRequest() {
2266
- return new Response("Hello, world!");
2267
- }
2268
- `
2269
- );
2270
-
2271
- // set up _worker.js
2272
- writeFileSync(
2273
- "public/_worker.js",
2274
- `
2275
- export default {
2276
- async fetch(request, env) {
2277
- const url = new URL(request.url);
2278
- return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
2279
- }
2280
- };
2281
- `
2282
- );
2283
-
2284
- mockGetToken("<<funfetti-auth-jwt>>");
2285
-
2286
- msw.use(
2287
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
2288
- const body = (await req.json()) as {
2289
- hashes: string[];
2290
- };
2291
-
2292
- expect(req.headers.get("Authorization")).toBe(
2293
- "Bearer <<funfetti-auth-jwt>>"
2294
- );
2295
- expect(body).toMatchObject({
2296
- hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
2297
- });
2298
-
2299
- return res.once(
2300
- ctx.status(200),
2301
- ctx.json({
2302
- success: true,
2303
- errors: [],
2304
- messages: [],
2305
- result: body.hashes,
2306
- })
2307
- );
2308
- }),
2309
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
2310
- expect(req.headers.get("Authorization")).toBe(
2311
- "Bearer <<funfetti-auth-jwt>>"
2312
- );
2313
-
2314
- expect(await req.json()).toMatchObject([
2315
- {
2316
- key: "13a03eaf24ae98378acd36ea00f77f2f",
2317
- value: Buffer.from("This is a readme").toString("base64"),
2318
- metadata: {
2319
- contentType: "text/markdown",
2320
- },
2321
- base64: true,
2322
- },
2323
- ]);
2324
-
2325
- return res.once(
2326
- ctx.status(200),
2327
- ctx.json({
2328
- success: true,
2329
- errors: [],
2330
- messages: [],
2331
- result: null,
2332
- })
2333
- );
2334
- }),
2335
-
2336
- rest.post(
2337
- "*/accounts/:accountId/pages/projects/foo/deployments",
2338
- async (req, res, ctx) => {
2339
- const body = await (req as RestRequestWithFormData).formData();
2340
- const manifest = JSON.parse(body.get("manifest") as string);
2341
- const customWorkerJS = body.get("_worker.js");
2342
-
2343
- expect(req.params.accountId).toEqual("some-account-id");
2344
- // make sure this is all we uploaded
2345
- expect([...body.keys()].sort()).toEqual(
2346
- ["manifest", "_worker.js"].sort()
2347
- );
2348
- expect(manifest).toMatchInlineSnapshot(`
2349
- Object {
2350
- "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
2351
- }
2352
- `);
2353
- expect(customWorkerJS).toMatchInlineSnapshot(`
2354
- "
2355
- export default {
2356
- async fetch(request, env) {
2357
- const url = new URL(request.url);
2358
- return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
2359
- }
2360
- };
2361
- "
2362
- `);
2363
-
2364
- return res.once(
2365
- ctx.status(200),
2366
- ctx.json({
2367
- success: true,
2368
- errors: [],
2369
- messages: [],
2370
- result: {
2371
- url: "https://abcxyz.foo.pages.dev/",
2372
- },
2373
- })
2374
- );
2375
- }
2376
- ),
2377
- rest.get(
2378
- "*/accounts/:accountId/pages/projects/foo",
2379
- async (req, res, ctx) => {
2380
- expect(req.params.accountId).toEqual("some-account-id");
2381
-
2382
- return res.once(
2383
- ctx.status(200),
2384
- ctx.json({
2385
- success: true,
2386
- errors: [],
2387
- messages: [],
2388
- result: {
2389
- deployment_configs: { production: {}, preview: {} },
2390
- },
2391
- })
2392
- );
2393
- }
2394
- )
2395
- );
2396
-
2397
- await runWrangler("pages publish public --project-name=foo");
2398
-
2399
- expect(std.out).toMatchInlineSnapshot(`
2400
- "✨ Success! Uploaded 1 files (TIMINGS)
2401
-
2402
- ✨ Compiled Worker successfully
2403
- ✨ Uploading _worker.js
2404
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
2405
- `);
2406
-
2407
- expect(std.err).toMatchInlineSnapshot('""');
2408
- });
2409
- });
2410
-
2411
- describe("project upload", () => {
2412
- const ENV_COPY = process.env;
2413
-
2414
- mockAccountId();
2415
- mockApiToken();
2416
- runInTempDir();
2417
-
2418
- beforeEach(() => {
2419
- process.env.CI = "true";
2420
- process.env.CF_PAGES_UPLOAD_JWT = "<<funfetti-auth-jwt>>";
2421
- });
2422
-
2423
- afterEach(() => {
2424
- process.env = ENV_COPY;
2425
- });
2426
-
2427
- it("should upload a directory of files with a provided JWT", async () => {
2428
- writeFileSync("logo.png", "foobar");
2429
-
2430
- msw.use(
2431
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
2432
- const body = (await req.json()) as {
2433
- hashes: string[];
2434
- };
2435
-
2436
- expect(req.headers.get("Authorization")).toBe(
2437
- "Bearer <<funfetti-auth-jwt>>"
2438
- );
2439
- expect(body).toMatchObject({
2440
- hashes: ["2082190357cfd3617ccfe04f340c6247"],
2441
- });
2442
-
2443
- return res.once(
2444
- ctx.status(200),
2445
- ctx.json({
2446
- success: true,
2447
- errors: [],
2448
- messages: [],
2449
- result: body.hashes,
2450
- })
2451
- );
2452
- }),
2453
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
2454
- expect(req.headers.get("Authorization")).toBe(
2455
- "Bearer <<funfetti-auth-jwt>>"
2456
- );
2457
-
2458
- expect(await req.json()).toMatchObject([
2459
- {
2460
- base64: true,
2461
- key: "2082190357cfd3617ccfe04f340c6247",
2462
- metadata: {
2463
- contentType: "image/png",
2464
- },
2465
- value: "Zm9vYmFy",
2466
- },
2467
- ]);
2468
-
2469
- return res(
2470
- ctx.status(200),
2471
- ctx.json({
2472
- success: true,
2473
- errors: [],
2474
- messages: [],
2475
- result: null,
2476
- })
2477
- );
2478
- })
2479
- );
2480
-
2481
- await runWrangler("pages project upload .");
2482
-
2483
- expect(std.out).toMatchInlineSnapshot(`
2484
- "✨ Success! Uploaded 1 files (TIMINGS)
2485
-
2486
- ✨ Upload complete!"
2487
- `);
2488
- });
2489
-
2490
- it("should avoid uploading some files", async () => {
2491
- mkdirSync("some_dir/node_modules", { recursive: true });
2492
- mkdirSync("some_dir/functions", { recursive: true });
2493
-
2494
- writeFileSync("logo.png", "foobar");
2495
- writeFileSync("some_dir/functions/foo.js", "func");
2496
- writeFileSync("some_dir/_headers", "headersfile");
2497
-
2498
- writeFileSync("_headers", "headersfile");
2499
- writeFileSync("_redirects", "redirectsfile");
2500
- writeFileSync("_worker.js", "workerfile");
2501
- writeFileSync("_routes.json", "routesfile");
2502
- mkdirSync(".git");
2503
- writeFileSync(".git/foo", "gitfile");
2504
- writeFileSync("some_dir/node_modules/some_package", "nodefile");
2505
- mkdirSync("functions");
2506
- writeFileSync("functions/foo.js", "func");
2507
-
2508
- // Accumulate multiple requests then assert afterwards
2509
- const requests: RestRequest[] = [];
2510
- msw.use(
2511
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
2512
- const body = (await req.json()) as {
2513
- hashes: string[];
2514
- };
2515
-
2516
- expect(req.headers.get("Authorization")).toBe(
2517
- "Bearer <<funfetti-auth-jwt>>"
2518
- );
2519
- expect(body).toMatchObject({
2520
- hashes: [
2521
- "2082190357cfd3617ccfe04f340c6247",
2522
- "95dedb64e6d4940fc2e0f11f711cc2f4",
2523
- "09a79777abda8ccc8bdd51dd3ff8e9e9",
2524
- ],
2525
- });
2526
-
2527
- return res.once(
2528
- ctx.status(200),
2529
- ctx.json({
2530
- success: true,
2531
- errors: [],
2532
- messages: [],
2533
- result: body.hashes,
2534
- })
2535
- );
2536
- }),
2537
- rest.post("*/pages/assets/upload", (req, res, ctx) => {
2538
- requests.push(req);
2539
-
2540
- return res(
2541
- ctx.status(200),
2542
- ctx.json({
2543
- success: true,
2544
- errors: [],
2545
- messages: [],
2546
- result: null,
2547
- })
2548
- );
2549
- })
2550
- );
2551
-
2552
- await runWrangler("pages project upload .");
2553
- expect(requests.length).toBe(3);
2554
-
2555
- const resolvedRequests = (
2556
- await Promise.all(
2557
- requests.map(async (req) => await req.json<UploadPayloadFile[]>())
2558
- )
2559
- ).flat();
2560
-
2561
- const requestMap = resolvedRequests.reduce<{
2562
- [key: string]: UploadPayloadFile;
2563
- }>(
2564
- (requestMap, req) => Object.assign(requestMap, { [req.key]: req }),
2565
- {}
2566
- );
2567
-
2568
- for (const req of requests) {
2569
- expect(req.headers.get("Authorization")).toBe(
2570
- "Bearer <<funfetti-auth-jwt>>"
2571
- );
2572
- }
2573
-
2574
- expect(Object.keys(requestMap).length).toBe(3);
2575
-
2576
- expect(requestMap["95dedb64e6d4940fc2e0f11f711cc2f4"]).toMatchObject({
2577
- base64: true,
2578
- key: "95dedb64e6d4940fc2e0f11f711cc2f4",
2579
- metadata: {
2580
- contentType: "application/octet-stream",
2581
- },
2582
- value: "aGVhZGVyc2ZpbGU=",
2583
- });
2584
-
2585
- expect(requestMap["2082190357cfd3617ccfe04f340c6247"]).toMatchObject({
2586
- base64: true,
2587
- key: "2082190357cfd3617ccfe04f340c6247",
2588
- metadata: {
2589
- contentType: "image/png",
2590
- },
2591
- value: "Zm9vYmFy",
2592
- });
2593
-
2594
- expect(requestMap["09a79777abda8ccc8bdd51dd3ff8e9e9"]).toMatchObject({
2595
- base64: true,
2596
- key: "09a79777abda8ccc8bdd51dd3ff8e9e9",
2597
- metadata: {
2598
- contentType: "application/javascript",
2599
- },
2600
- value: "ZnVuYw==",
2601
- });
2602
-
2603
- expect(std.out).toMatchInlineSnapshot(`
2604
- "✨ Success! Uploaded 3 files (TIMINGS)
2605
-
2606
- ✨ Upload complete!"
2607
- `);
2608
- });
2609
-
2610
- it("should retry uploads", async () => {
2611
- writeFileSync("logo.txt", "foobar");
2612
-
2613
- // Accumulate multiple requests then assert afterwards
2614
- const requests: RestRequest[] = [];
2615
- msw.use(
2616
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
2617
- const body = (await req.json()) as { hashes: string[] };
2618
-
2619
- expect(req.headers.get("Authorization")).toBe(
2620
- "Bearer <<funfetti-auth-jwt>>"
2621
- );
2622
- expect(body).toMatchObject({
2623
- hashes: ["1a98fb08af91aca4a7df1764a2c4ddb0"],
2624
- });
2625
-
2626
- return res.once(
2627
- ctx.status(200),
2628
- ctx.json({
2629
- success: true,
2630
- errors: [],
2631
- messages: [],
2632
- result: body.hashes,
2633
- })
2634
- );
2635
- }),
2636
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
2637
- requests.push(req);
2638
-
2639
- if (requests.length < 2) {
2640
- return res(
2641
- ctx.status(200),
2642
- ctx.json({
2643
- success: false,
2644
- errors: [
2645
- {
2646
- code: 800000,
2647
- message: "Something exploded, please retry",
2648
- },
2649
- ],
2650
- messages: [],
2651
- result: null,
2652
- })
2653
- );
2654
- } else {
2655
- return res(
2656
- ctx.status(200),
2657
- ctx.json({
2658
- success: true,
2659
- errors: [],
2660
- messages: [],
2661
- result: null,
2662
- })
2663
- );
2664
- }
2665
- })
2666
- );
2667
-
2668
- await runWrangler("pages project upload .");
2669
-
2670
- // Assert two identical requests
2671
- expect(requests.length).toBe(2);
2672
- for (const init of requests) {
2673
- expect(init.headers.get("Authorization")).toBe(
2674
- "Bearer <<funfetti-auth-jwt>>"
2675
- );
2676
-
2677
- const body = (await init.json()) as UploadPayloadFile[];
2678
- expect(body).toMatchObject([
2679
- {
2680
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
2681
- value: Buffer.from("foobar").toString("base64"),
2682
- metadata: {
2683
- contentType: "text/plain",
2684
- },
2685
- base64: true,
2686
- },
2687
- ]);
2688
- }
2689
-
2690
- expect(std.out).toMatchInlineSnapshot(`
2691
- "✨ Success! Uploaded 1 files (TIMINGS)
2692
-
2693
- ✨ Upload complete!"
2694
- `);
2695
- });
2696
-
2697
- it("should try to use multiple buckets (up to the max concurrency)", async () => {
2698
- writeFileSync("logo.txt", "foobar");
2699
- writeFileSync("logo.png", "foobar");
2700
- writeFileSync("logo.html", "foobar");
2701
- writeFileSync("logo.js", "foobar");
2702
-
2703
- mockGetToken("<<funfetti-auth-jwt>>");
2704
-
2705
- // Accumulate multiple requests then assert afterwards
2706
- const requests: RestRequest[] = [];
2707
- msw.use(
2708
- rest.post("*/pages/assets/check-missing", async (req, res, ctx) => {
2709
- const body = (await req.json()) as { hashes: string[] };
2710
-
2711
- expect(req.headers.get("Authorization")).toBe(
2712
- "Bearer <<funfetti-auth-jwt>>"
2713
- );
2714
- expect(body).toMatchObject({
2715
- hashes: expect.arrayContaining([
2716
- "d96fef225537c9f5e44a3cb27fd0b492",
2717
- "2082190357cfd3617ccfe04f340c6247",
2718
- "6be321bef99e758250dac034474ddbb8",
2719
- "1a98fb08af91aca4a7df1764a2c4ddb0",
2720
- ]),
2721
- });
2722
-
2723
- return res.once(
2724
- ctx.status(200),
2725
- ctx.json({
2726
- success: true,
2727
- errors: [],
2728
- messages: [],
2729
- result: body.hashes,
2730
- })
2731
- );
2732
- }),
2733
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
2734
- requests.push(req);
2735
-
2736
- expect(req.headers.get("Authorization")).toBe(
2737
- "Bearer <<funfetti-auth-jwt>>"
2738
- );
2739
-
2740
- return res(
2741
- ctx.status(200),
2742
- ctx.json({
2743
- success: true,
2744
- errors: [],
2745
- messages: [],
2746
- result: null,
2747
- })
2748
- );
2749
- })
2750
- );
2751
-
2752
- await runWrangler("pages project upload .");
2753
-
2754
- // We have 3 buckets, so expect 3 uploads
2755
- expect(requests.length).toBe(3);
2756
- const bodies: UploadPayloadFile[][] = [];
2757
- for (const init of requests) {
2758
- bodies.push((await init.json()) as UploadPayloadFile[]);
2759
- }
2760
- // One bucket should end up with 2 files
2761
- expect(bodies.map((b) => b.length).sort()).toEqual([1, 1, 2]);
2762
- // But we don't know the order, so flatten and test without ordering
2763
- expect(bodies.flatMap((b) => b)).toEqual(
2764
- expect.arrayContaining([
2765
- {
2766
- base64: true,
2767
- key: "d96fef225537c9f5e44a3cb27fd0b492",
2768
- metadata: { contentType: "text/html" },
2769
- value: "Zm9vYmFy",
2770
- },
2771
- {
2772
- base64: true,
2773
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
2774
- metadata: { contentType: "text/plain" },
2775
- value: "Zm9vYmFy",
2776
- },
2777
- {
2778
- base64: true,
2779
- key: "6be321bef99e758250dac034474ddbb8",
2780
- metadata: { contentType: "application/javascript" },
2781
- value: "Zm9vYmFy",
2782
- },
2783
- {
2784
- base64: true,
2785
- key: "2082190357cfd3617ccfe04f340c6247",
2786
- metadata: { contentType: "image/png" },
2787
- value: "Zm9vYmFy",
2788
- },
2789
- ])
2790
- );
2791
-
2792
- expect(std.out).toMatchInlineSnapshot(`
2793
- "✨ Success! Uploaded 4 files (TIMINGS)
2794
-
2795
- ✨ Upload complete!"
2796
- `);
2797
- });
2798
-
2799
- it("should not error when directory names contain periods and houses a extensionless file", async () => {
2800
- mkdirSync(".well-known");
2801
- // Note: same content as previous test, but since it's a different extension,
2802
- // it hashes to a different value
2803
- writeFileSync(".well-known/foobar", "foobar");
2804
-
2805
- mockGetToken("<<funfetti-auth-jwt>>");
2806
-
2807
- msw.use(
2808
- rest.post(
2809
- "*/pages/assets/check-missing",
2810
-
2811
- async (req, res, ctx) => {
2812
- const body = (await req.json()) as { hashes: string[] };
2813
-
2814
- expect(req.headers.get("Authorization")).toBe(
2815
- "Bearer <<funfetti-auth-jwt>>"
2816
- );
2817
- expect(body).toMatchObject({
2818
- hashes: ["7b764dacfd211bebd8077828a7ddefd7"],
2819
- });
2820
-
2821
- return res.once(
2822
- ctx.status(200),
2823
- ctx.json({
2824
- success: true,
2825
- errors: [],
2826
- messages: [],
2827
- result: body.hashes,
2828
- })
2829
- );
2830
- }
2831
- ),
2832
- rest.post("*/pages/assets/upload", async (req, res, ctx) => {
2833
- expect(req.headers.get("Authorization")).toBe(
2834
- "Bearer <<funfetti-auth-jwt>>"
2835
- );
2836
- const body = (await req.json()) as UploadPayloadFile[];
2837
- expect(body).toMatchObject([
2838
- {
2839
- key: "7b764dacfd211bebd8077828a7ddefd7",
2840
- value: Buffer.from("foobar").toString("base64"),
2841
- metadata: {
2842
- contentType: "application/octet-stream",
2843
- },
2844
- base64: true,
2845
- },
2846
- ]);
2847
-
2848
- return res.once(
2849
- ctx.status(200),
2850
- ctx.json({
2851
- success: true,
2852
- errors: [],
2853
- messages: [],
2854
- result: null,
2855
- })
2856
- );
2857
- })
2858
- );
2859
-
2860
- await runWrangler("pages project upload .");
2861
-
2862
- expect(std.err).toMatchInlineSnapshot(`""`);
2863
- });
2864
- });
2865
- });
2866
-
2867
- function mockFormDataToString(this: FormData) {
2868
- const entries = [];
2869
- for (const [key, value] of this.entries()) {
2870
- if (value instanceof Blob) {
2871
- const reader = new FileReaderSync();
2872
- reader.readAsText(value);
2873
- const result = reader.result;
2874
- entries.push([key, result]);
2875
- } else {
2876
- entries.push([key, value]);
2877
- }
2878
- }
2879
- return JSON.stringify({
2880
- __formdata: entries,
2881
- });
2882
- }
2883
-
2884
- async function mockFormDataFromString(this: MockedRequest): Promise<FormData> {
2885
- const { __formdata } = await this.json();
2886
- expect(__formdata).toBeInstanceOf(Array);
2887
-
2888
- const form = new FormData();
2889
- for (const [key, value] of __formdata) {
2890
- form.set(key, value);
2891
- }
2892
- return form;
2893
- }
2894
-
2895
- // The following two functions workaround the fact that MSW does not yet support FormData in requests.
2896
- // We use the fact that MSW relies upon `node-fetch` internally, which will call `toString()` on the FormData object,
2897
- // rather than passing it through or serializing it as a proper FormData object.
2898
- // The hack is to serialize FormData to a JSON string by overriding `FormData.toString()`.
2899
- // And then to deserialize back to a FormData object by monkey-patching a `formData()` helper onto `MockedRequest`.
2900
- FormData.prototype.toString = mockFormDataToString;
2901
- export interface RestRequestWithFormData extends MockedRequest, RestRequest {
2902
- formData(): Promise<FormData>;
2903
- }
2904
- (MockedRequest.prototype as RestRequestWithFormData).formData =
2905
- mockFormDataFromString;