wrangler 2.9.0 → 2.10.0

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