wrangler 0.0.0-e64812e → 0.0.0-e7a0cd5b

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 (291) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +150 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +1451 -21
  5. package/package.json +190 -152
  6. package/src/__tests__/access.test.ts +25 -0
  7. package/src/__tests__/api-dev.test.ts +209 -0
  8. package/src/__tests__/api-devregistry.test.js +57 -0
  9. package/src/__tests__/api.test.ts +80 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +30 -24
  12. package/src/__tests__/configuration.test.ts +4017 -3363
  13. package/src/__tests__/d1.test.ts +72 -0
  14. package/src/__tests__/delete.test.ts +230 -0
  15. package/src/__tests__/deployments.test.ts +95 -0
  16. package/src/__tests__/dev.test.tsx +1480 -951
  17. package/src/__tests__/dialogs.test.tsx +40 -0
  18. package/src/__tests__/generate.test.ts +235 -0
  19. package/src/__tests__/get-host-from-url.test.ts +16 -0
  20. package/src/__tests__/guess-worker-format.test.ts +68 -68
  21. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  22. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  23. package/src/__tests__/helpers/mock-bin.ts +20 -20
  24. package/src/__tests__/helpers/mock-cfetch.ts +216 -94
  25. package/src/__tests__/helpers/mock-console.ts +58 -39
  26. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  27. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  28. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  29. package/src/__tests__/helpers/mock-istty.ts +65 -18
  30. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  31. package/src/__tests__/helpers/mock-kv.ts +27 -27
  32. package/src/__tests__/helpers/mock-oauth-flow.ts +225 -228
  33. package/src/__tests__/helpers/mock-process.ts +39 -0
  34. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  35. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  36. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  37. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  38. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  39. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  40. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  41. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  42. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  43. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  44. package/src/__tests__/helpers/msw/index.ts +21 -0
  45. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  46. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  47. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  48. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  52. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  53. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  54. package/src/__tests__/https-options.test.ts +142 -109
  55. package/src/__tests__/index.test.ts +239 -233
  56. package/src/__tests__/init.test.ts +2869 -1603
  57. package/src/__tests__/jest.setup.ts +159 -34
  58. package/src/__tests__/kv.test.ts +1660 -1466
  59. package/src/__tests__/logger.test.ts +100 -74
  60. package/src/__tests__/metrics.test.ts +450 -0
  61. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  62. package/src/__tests__/middleware.test.ts +726 -0
  63. package/src/__tests__/package-manager.test.ts +303 -303
  64. package/src/__tests__/pages.test.ts +2204 -735
  65. package/src/__tests__/parse.test.ts +252 -252
  66. package/src/__tests__/paths.test.ts +39 -0
  67. package/src/__tests__/publish.test.ts +7543 -5351
  68. package/src/__tests__/pubsub.test.ts +370 -0
  69. package/src/__tests__/queues.test.ts +371 -0
  70. package/src/__tests__/r2.test.ts +371 -228
  71. package/src/__tests__/route.test.ts +18 -18
  72. package/src/__tests__/secret.test.ts +622 -459
  73. package/src/__tests__/tail.test.ts +677 -567
  74. package/src/__tests__/test-old-node-version.js +31 -0
  75. package/src/__tests__/type-generation.test.ts +217 -0
  76. package/src/__tests__/user.test.ts +140 -116
  77. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  78. package/src/__tests__/validate-dev-props.test.ts +56 -0
  79. package/src/__tests__/version.test.ts +35 -0
  80. package/src/__tests__/whoami.test.tsx +264 -91
  81. package/src/__tests__/worker-namespace.test.ts +326 -0
  82. package/src/abort.d.ts +1 -1
  83. package/src/api/dev.ts +208 -0
  84. package/src/api/index.ts +2 -0
  85. package/src/bundle-reporter.tsx +68 -0
  86. package/src/bundle.ts +746 -161
  87. package/src/cfetch/index.ts +120 -81
  88. package/src/cfetch/internal.ts +209 -91
  89. package/src/cli.ts +23 -8
  90. package/src/config/config.ts +236 -195
  91. package/src/config/diagnostics.ts +61 -61
  92. package/src/config/environment.ts +500 -357
  93. package/src/config/index.ts +310 -193
  94. package/src/config/validation-helpers.ts +379 -357
  95. package/src/config/validation.ts +1941 -1367
  96. package/src/config-cache.ts +81 -41
  97. package/src/create-worker-preview.ts +239 -142
  98. package/src/create-worker-upload-form.ts +305 -238
  99. package/src/d1/backups.tsx +218 -0
  100. package/src/d1/create.tsx +54 -0
  101. package/src/d1/delete.tsx +56 -0
  102. package/src/d1/execute.tsx +299 -0
  103. package/src/d1/formatTimeAgo.ts +14 -0
  104. package/src/d1/index.ts +76 -0
  105. package/src/d1/list.tsx +48 -0
  106. package/src/d1/options.ts +12 -0
  107. package/src/d1/types.tsx +14 -0
  108. package/src/d1/utils.ts +39 -0
  109. package/src/delete.ts +108 -0
  110. package/src/deployments.ts +74 -0
  111. package/src/deprecated/index.ts +438 -0
  112. package/src/dev/dev-vars.ts +20 -17
  113. package/src/dev/dev.tsx +520 -352
  114. package/src/dev/get-local-persistence-path.tsx +31 -0
  115. package/src/dev/local.tsx +697 -298
  116. package/src/dev/remote.tsx +591 -215
  117. package/src/dev/start-server.ts +513 -0
  118. package/src/dev/use-esbuild.ts +183 -97
  119. package/src/dev/validate-dev-props.ts +31 -0
  120. package/src/dev-registry.tsx +201 -0
  121. package/src/dev.tsx +869 -0
  122. package/src/dialogs.tsx +126 -98
  123. package/src/dispatch-namespace.ts +207 -0
  124. package/src/durable.ts +87 -87
  125. package/src/entry.ts +235 -228
  126. package/src/environment-variables.ts +38 -23
  127. package/src/errors.ts +6 -6
  128. package/src/git-client.ts +124 -0
  129. package/src/global-wrangler-config-path.ts +26 -0
  130. package/src/https-options.ts +84 -80
  131. package/src/index.tsx +627 -2807
  132. package/src/init.ts +970 -0
  133. package/src/inspect.ts +698 -593
  134. package/src/intl-polyfill.d.ts +123 -123
  135. package/src/is-ci.ts +14 -0
  136. package/src/is-interactive.ts +16 -0
  137. package/src/kv/helpers.ts +430 -0
  138. package/src/kv/index.ts +596 -0
  139. package/src/logger.ts +67 -41
  140. package/src/metrics/index.ts +5 -0
  141. package/src/metrics/metrics-config.ts +239 -0
  142. package/src/metrics/metrics-dispatcher.ts +96 -0
  143. package/src/metrics/metrics-usage-headers.ts +24 -0
  144. package/src/metrics/send-event.ts +94 -0
  145. package/src/miniflare-cli/assets.ts +215 -0
  146. package/src/miniflare-cli/index.ts +205 -33
  147. package/src/miniflare-cli/request-context.ts +18 -18
  148. package/src/module-collection.ts +221 -212
  149. package/src/open-in-browser.ts +4 -6
  150. package/src/package-manager.ts +173 -128
  151. package/src/pages/build.tsx +238 -0
  152. package/src/pages/constants.ts +18 -0
  153. package/src/pages/deployments.tsx +106 -0
  154. package/src/pages/dev.tsx +693 -0
  155. package/src/pages/errors.ts +66 -0
  156. package/src/pages/functions/buildPlugin.ts +110 -0
  157. package/src/pages/functions/buildWorker.ts +156 -0
  158. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  159. package/src/pages/functions/filepath-routing.ts +189 -0
  160. package/src/pages/functions/identifiers.ts +78 -0
  161. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  162. package/src/pages/functions/routes-consolidation.ts +73 -0
  163. package/src/pages/functions/routes-transformation.test.ts +282 -0
  164. package/src/pages/functions/routes-transformation.ts +115 -0
  165. package/src/pages/functions/routes-validation.test.ts +403 -0
  166. package/src/pages/functions/routes-validation.ts +202 -0
  167. package/src/pages/functions/routes.ts +151 -0
  168. package/src/pages/functions.tsx +82 -0
  169. package/src/pages/hash.tsx +13 -0
  170. package/src/pages/index.tsx +94 -0
  171. package/src/pages/projects.tsx +169 -0
  172. package/src/pages/publish.tsx +436 -0
  173. package/src/pages/types.ts +49 -0
  174. package/src/pages/upload.tsx +425 -0
  175. package/src/pages/utils.ts +12 -0
  176. package/src/parse.ts +209 -125
  177. package/src/paths.ts +53 -8
  178. package/src/proxy.ts +618 -394
  179. package/src/publish/index.ts +270 -0
  180. package/src/publish/publish.ts +1035 -0
  181. package/src/pubsub/index.ts +286 -0
  182. package/src/pubsub/pubsub-commands.tsx +624 -0
  183. package/src/queues/cli/commands/consumer/add.ts +71 -0
  184. package/src/queues/cli/commands/consumer/index.ts +22 -0
  185. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  186. package/src/queues/cli/commands/create.ts +25 -0
  187. package/src/queues/cli/commands/delete.ts +26 -0
  188. package/src/queues/cli/commands/index.ts +33 -0
  189. package/src/queues/cli/commands/list.ts +25 -0
  190. package/src/queues/client.ts +135 -0
  191. package/src/r2/helpers.ts +131 -0
  192. package/src/r2/index.ts +277 -0
  193. package/src/routes.ts +140 -0
  194. package/src/secret/index.ts +379 -0
  195. package/src/selfsigned.d.ts +23 -23
  196. package/src/sites.tsx +280 -203
  197. package/src/tail/createTail.ts +315 -0
  198. package/src/tail/filters.ts +108 -110
  199. package/src/tail/index.ts +211 -296
  200. package/src/tail/printing.ts +86 -46
  201. package/src/type-generation.ts +159 -0
  202. package/src/update-check.ts +11 -11
  203. package/src/user/access.ts +69 -0
  204. package/src/user/choose-account.tsx +69 -0
  205. package/src/user/env-vars.ts +46 -0
  206. package/src/user/generate-auth-url.ts +33 -0
  207. package/src/user/generate-random-state.ts +16 -0
  208. package/src/user/index.ts +3 -0
  209. package/src/user/user.tsx +1192 -0
  210. package/src/utils/collectKeyValues.ts +14 -0
  211. package/src/whoami.tsx +141 -42
  212. package/src/worker.ts +168 -106
  213. package/src/yargs-types.ts +20 -0
  214. package/src/zones.ts +191 -0
  215. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  216. package/templates/checked-fetch.js +17 -0
  217. package/templates/d1-beta-facade.js +174 -0
  218. package/templates/experimental-local-cache-stubs.js +27 -0
  219. package/templates/first-party-worker-module-facade.ts +18 -0
  220. package/templates/format-dev-errors.ts +32 -0
  221. package/templates/init-tests/test-jest-new-worker.js +25 -0
  222. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  223. package/templates/middleware/common.ts +62 -0
  224. package/templates/middleware/loader-modules.ts +84 -0
  225. package/templates/middleware/loader-sw.ts +213 -0
  226. package/templates/middleware/middleware-pretty-error.ts +40 -0
  227. package/templates/middleware/middleware-scheduled.ts +15 -0
  228. package/templates/new-worker-scheduled.js +3 -3
  229. package/templates/new-worker-scheduled.ts +15 -15
  230. package/templates/new-worker.js +3 -3
  231. package/templates/new-worker.ts +15 -15
  232. package/templates/no-op-worker.js +10 -0
  233. package/templates/pages-dev-pipeline.ts +28 -0
  234. package/templates/pages-dev-util.ts +52 -0
  235. package/templates/pages-shim.ts +9 -0
  236. package/templates/pages-template-plugin.ts +171 -0
  237. package/templates/pages-template-worker.ts +189 -0
  238. package/templates/serve-static-assets.ts +63 -0
  239. package/templates/service-bindings-module-facade.js +54 -0
  240. package/templates/service-bindings-sw-facade.js +42 -0
  241. package/templates/tsconfig.json +96 -95
  242. package/wrangler-dist/cli.d.ts +892 -0
  243. package/wrangler-dist/cli.js +145674 -108957
  244. package/pages/functions/buildPlugin.ts +0 -105
  245. package/pages/functions/buildWorker.ts +0 -151
  246. package/pages/functions/filepath-routing.ts +0 -189
  247. package/pages/functions/identifiers.ts +0 -78
  248. package/pages/functions/routes.ts +0 -156
  249. package/pages/functions/template-plugin.ts +0 -147
  250. package/pages/functions/template-worker.ts +0 -143
  251. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  252. package/src/kv.ts +0 -408
  253. package/src/miniflare-cli/enum-keys.ts +0 -17
  254. package/src/pages.tsx +0 -2038
  255. package/src/publish.ts +0 -583
  256. package/src/r2.ts +0 -50
  257. package/src/user.tsx +0 -1203
  258. package/templates/static-asset-facade.js +0 -47
  259. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  260. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  261. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  262. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  263. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  264. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  265. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  266. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  267. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  268. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  269. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  270. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  271. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  272. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  273. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  274. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  275. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  276. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  277. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  278. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  279. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  280. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  281. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  282. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  283. package/vendor/wrangler-mime/LICENSE +0 -21
  284. package/vendor/wrangler-mime/Mime.js +0 -97
  285. package/vendor/wrangler-mime/README.md +0 -187
  286. package/vendor/wrangler-mime/cli.js +0 -46
  287. package/vendor/wrangler-mime/index.js +0 -4
  288. package/vendor/wrangler-mime/lite.js +0 -4
  289. package/vendor/wrangler-mime/package.json +0 -52
  290. package/vendor/wrangler-mime/types/other.js +0 -1
  291. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -1,754 +1,2223 @@
1
1
  import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { chdir } from "node:process";
3
+ import { ROUTES_SPEC_VERSION } from "../pages/constants";
4
+ import { isRoutesJSONSpec } from "../pages/functions/routes-validation";
5
+ import { version } from "./../../package.json";
2
6
  import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
3
7
  import {
4
- createFetchResult,
5
- setMockRawResponse,
6
- setMockResponse,
7
- unsetAllMocks,
8
+ createFetchResult,
9
+ setMockRawResponse,
10
+ setMockResponse,
11
+ unsetAllMocks,
8
12
  } from "./helpers/mock-cfetch";
9
13
  import { mockConsoleMethods } from "./helpers/mock-console";
10
14
  import { runInTempDir } from "./helpers/run-in-tmp";
11
15
  import { runWrangler } from "./helpers/run-wrangler";
12
- import type { Deployment, Project, UploadPayloadFile } from "../pages";
16
+ import type { Deployment, Project, UploadPayloadFile } from "../pages/types";
13
17
  import type { FormData, RequestInit } from "undici";
14
18
 
15
19
  // Asserting within mock responses get swallowed, so run them out-of-band
16
20
  const outOfBandTests: (() => void)[] = [];
17
21
  function assertLater(fn: () => void) {
18
- outOfBandTests.push(fn);
22
+ outOfBandTests.push(fn);
19
23
  }
20
24
 
21
25
  function mockGetToken(jwt: string) {
22
- return setMockResponse(
23
- "/accounts/:accountId/pages/projects/foo/upload-token",
24
- async ([_url, accountId]) => {
25
- assertLater(() => {
26
- expect(accountId).toEqual("some-account-id");
27
- });
28
-
29
- return { jwt };
30
- }
31
- );
26
+ return setMockResponse(
27
+ "/accounts/:accountId/pages/projects/foo/upload-token",
28
+ async ([_url, accountId]) => {
29
+ assertLater(() => {
30
+ expect(accountId).toEqual("some-account-id");
31
+ });
32
+
33
+ return { jwt };
34
+ }
35
+ );
32
36
  }
33
37
 
34
38
  describe("pages", () => {
35
- runInTempDir();
36
- const std = mockConsoleMethods();
37
- function endEventLoop() {
38
- return new Promise((resolve) => setImmediate(resolve));
39
- }
40
- beforeEach(() => {
41
- outOfBandTests.length = 0;
42
- });
43
- afterEach(() => {
44
- outOfBandTests.forEach((fn) => fn());
45
- });
46
-
47
- it("should should display a list of available subcommands, for pages with no subcommand", async () => {
48
- await runWrangler("pages");
49
- await endEventLoop();
50
-
51
- expect(std.out).toMatchInlineSnapshot(`
52
- "wrangler pages
53
-
54
- ⚡️ Configure Cloudflare Pages
55
-
56
- Commands:
57
- wrangler pages dev [directory] [-- command..] 🧑‍💻 Develop your full-stack Pages application locally
58
- wrangler pages project ⚡️ Interact with your Pages projects
59
- wrangler pages deployment 🚀 Interact with the deployments of a project
60
- wrangler pages publish [directory] 🆙 Publish a directory of static assets as a Pages deployment
61
-
62
- Flags:
63
- -c, --config Path to .toml configuration file [string]
64
- -h, --help Show help [boolean]
65
- -v, --version Show version number [boolean]
66
-
67
- 🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose"
68
- `);
69
- });
70
-
71
- describe("beta message for subcommands", () => {
72
- it("should display for pages:dev", async () => {
73
- await expect(
74
- runWrangler("pages dev")
75
- ).rejects.toThrowErrorMatchingInlineSnapshot(
76
- `"Must specify a directory of static assets to serve or a command to run."`
77
- );
78
-
79
- expect(std.out).toMatchInlineSnapshot(`
80
- "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose
81
-
82
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
83
- `);
84
- });
85
-
86
- it("should display for pages:functions:build", async () => {
87
- await expect(runWrangler("pages functions build")).rejects.toThrowError();
88
-
89
- expect(std.out).toMatchInlineSnapshot(`
90
- "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose
91
-
92
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
93
- `);
94
- });
95
- });
96
-
97
- describe("project list", () => {
98
- mockAccountId();
99
- mockApiToken();
100
-
101
- afterEach(() => {
102
- unsetAllMocks();
103
- });
104
-
105
- function mockListRequest(projects: unknown[]) {
106
- const requests = { count: 0 };
107
- setMockResponse(
108
- "/accounts/:accountId/pages/projects",
109
- ([_url, accountId], init, query) => {
110
- requests.count++;
111
- const pageSize = Number(query.get("per_page"));
112
- const page = Number(query.get("page"));
113
- const expectedPageSize = 10;
114
- const expectedPage = requests.count;
115
- assertLater(() => {
116
- expect(accountId).toEqual("some-account-id");
117
- expect(pageSize).toEqual(expectedPageSize);
118
- expect(page).toEqual(expectedPage);
119
- expect(init).toEqual({});
120
- });
121
- return projects.slice((page - 1) * pageSize, page * pageSize);
122
- }
123
- );
124
- return requests;
125
- }
126
-
127
- it("should make request to list projects", async () => {
128
- const projects: Project[] = [
129
- {
130
- name: "dogs",
131
- subdomain: "docs.pages.dev",
132
- domains: ["dogs.pages.dev"],
133
- source: {
134
- type: "github",
135
- },
136
- latest_deployment: {
137
- modified_on: "2021-11-17T14:52:26.133835Z",
138
- },
139
- created_on: "2021-11-17T14:52:26.133835Z",
140
- production_branch: "main",
141
- },
142
- {
143
- name: "cats",
144
- subdomain: "cats.pages.dev",
145
- domains: ["cats.pages.dev", "kitten.com"],
146
- latest_deployment: {
147
- modified_on: "2021-11-17T14:52:26.133835Z",
148
- },
149
- created_on: "2021-11-17T14:52:26.133835Z",
150
- production_branch: "main",
151
- },
152
- ];
153
-
154
- const requests = mockListRequest(projects);
155
- await runWrangler("pages project list");
156
-
157
- expect(requests.count).toBe(1);
158
- });
159
-
160
- it("should make multiple requests for paginated results", async () => {
161
- const projects: Project[] = [];
162
- for (let i = 0; i < 15; i++) {
163
- projects.push({
164
- name: "dogs" + i,
165
- subdomain: i + "dogs.pages.dev",
166
- domains: [i + "dogs.pages.dev"],
167
- source: {
168
- type: "github",
169
- },
170
- latest_deployment: {
171
- modified_on: "2021-11-17T14:52:26.133835Z",
172
- },
173
- created_on: "2021-11-17T14:52:26.133835Z",
174
- production_branch: "main",
175
- });
176
- }
177
- const requests = mockListRequest(projects);
178
- await runWrangler("pages project list");
179
- expect(requests.count).toEqual(2);
180
- });
181
- });
182
-
183
- describe("project create", () => {
184
- mockAccountId();
185
- mockApiToken();
186
-
187
- afterEach(() => {
188
- unsetAllMocks();
189
- });
190
-
191
- it("should create a project with a production branch", async () => {
192
- setMockResponse(
193
- "/accounts/:accountId/pages/projects",
194
- ([_url, accountId], init) => {
195
- const body = JSON.parse(init.body as string);
196
- assertLater(() => {
197
- expect(accountId).toEqual("some-account-id");
198
- expect(init.method).toEqual("POST");
199
- expect(body).toEqual({
200
- name: "a-new-project",
201
- production_branch: "main",
202
- });
203
- });
204
- return {
205
- name: "a-new-project",
206
- subdomain: "a-new-project.pages.dev",
207
- production_branch: "main",
208
- };
209
- }
210
- );
211
- await runWrangler(
212
- "pages project create a-new-project --production-branch=main"
213
- );
214
- expect(std.out).toMatchInlineSnapshot(`
215
- "✨ Successfully created the 'a-new-project' project. It will be available at https://a-new-project.pages.dev/ once you create your first deployment.
216
- To deploy a folder of assets, run 'wrangler pages publish [directory]'."
217
- `);
218
- });
219
- });
220
-
221
- describe("deployment list", () => {
222
- mockAccountId();
223
- mockApiToken();
224
-
225
- afterEach(() => {
226
- unsetAllMocks();
227
- });
228
- function mockListRequest(deployments: unknown[]) {
229
- const requests = { count: 0 };
230
- setMockResponse(
231
- "/accounts/:accountId/pages/projects/:project/deployments",
232
- ([_url, accountId, project]) => {
233
- requests.count++;
234
- assertLater(() => {
235
- expect(project).toEqual("images");
236
- expect(accountId).toEqual("some-account-id");
237
- });
238
- return deployments;
239
- }
240
- );
241
- return requests;
242
- }
243
-
244
- it("should make request to list deployments", async () => {
245
- const deployments: Deployment[] = [
246
- {
247
- id: "87bbc8fe-16be-45cd-81e0-63d722e82cdf",
248
- url: "https://87bbc8fe.images.pages.dev",
249
- environment: "preview",
250
- latest_stage: {
251
- ended_on: "2021-11-17T14:52:26.133835Z",
252
- status: "success",
253
- },
254
- deployment_trigger: {
255
- metadata: {
256
- branch: "main",
257
- commit_hash: "c7649364c4cb32ad4f65b530b9424e8be5bec9d6",
258
- },
259
- },
260
- project_name: "images",
261
- },
262
- ];
263
-
264
- const requests = mockListRequest(deployments);
265
- await runWrangler("pages deployment list --project-name=images");
266
-
267
- expect(requests.count).toBe(1);
268
- });
269
- });
270
-
271
- describe("deployment create", () => {
272
- let actualProcessEnvCI: string | undefined;
273
-
274
- mockAccountId();
275
- mockApiToken();
276
- runInTempDir();
277
-
278
- beforeEach(() => {
279
- actualProcessEnvCI = process.env.CI;
280
- process.env.CI = "true";
281
- });
282
-
283
- afterEach(() => {
284
- unsetAllMocks();
285
- process.env.CI = actualProcessEnvCI;
286
- });
287
-
288
- it("should be aliased with 'wrangler pages publish'", async () => {
289
- await runWrangler("pages publish --help");
290
- await endEventLoop();
291
-
292
- expect(std.out).toMatchInlineSnapshot(`
293
- "wrangler pages publish [directory]
294
-
295
- 🆙 Publish a directory of static assets as a Pages deployment
296
-
297
- Positionals:
298
- directory The directory of static files to upload [string]
299
-
300
- Flags:
301
- -c, --config Path to .toml configuration file [string]
302
- -h, --help Show help [boolean]
303
- -v, --version Show version number [boolean]
304
-
305
- Options:
306
- --project-name The name of the project you want to deploy to [string]
307
- --branch The name of the branch you want to deploy to [string]
308
- --commit-hash The SHA to attach to this deployment [string]
309
- --commit-message The commit message to attach to this deployment [string]
310
- --commit-dirty Whether or not the workspace should be considered dirty for this deployment [boolean]
311
-
312
- 🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose"
313
- `);
314
- });
315
-
316
- it("should upload a directory of files", async () => {
317
- writeFileSync("logo.png", "foobar");
318
-
319
- setMockResponse(
320
- "/accounts/:accountId/pages/projects/foo/upload-token",
321
- async ([_url, accountId]) => {
322
- assertLater(() => {
323
- expect(accountId).toEqual("some-account-id");
324
- });
325
-
326
- return {
327
- jwt: "<<funfetti-auth-jwt>>",
328
- };
329
- }
330
- );
331
-
332
- setMockResponse(
333
- "/pages/assets/check-missing",
334
- "POST",
335
- async (_, init) => {
336
- const body = JSON.parse(init.body as string) as { hashes: string[] };
337
- assertLater(() => {
338
- expect(init.headers).toMatchObject({
339
- Authorization: "Bearer <<funfetti-auth-jwt>>",
340
- });
341
- expect(body).toMatchObject({
342
- hashes: ["2082190357cfd3617ccfe04f340c6247"],
343
- });
344
- });
345
- return body.hashes;
346
- }
347
- );
348
-
349
- setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
350
- assertLater(() => {
351
- expect(init.headers).toMatchObject({
352
- Authorization: "Bearer <<funfetti-auth-jwt>>",
353
- });
354
- const body = JSON.parse(init.body as string) as UploadPayloadFile[];
355
- expect(body).toMatchObject([
356
- {
357
- key: "2082190357cfd3617ccfe04f340c6247",
358
- value: Buffer.from("foobar").toString("base64"),
359
- metadata: {
360
- contentType: "image/png",
361
- },
362
- base64: true,
363
- },
364
- ]);
365
- });
366
- });
367
-
368
- setMockResponse(
369
- "/accounts/:accountId/pages/projects/foo/deployments",
370
- async ([_url, accountId], init) => {
371
- assertLater(() => {
372
- expect(accountId).toEqual("some-account-id");
373
- expect(init.method).toEqual("POST");
374
- const body = init.body as FormData;
375
- const manifest = JSON.parse(body.get("manifest") as string);
376
- expect(manifest).toMatchInlineSnapshot(`
377
- Object {
378
- "/logo.png": "2082190357cfd3617ccfe04f340c6247",
379
- }
380
- `);
381
- });
382
-
383
- return {
384
- url: "https://abcxyz.foo.pages.dev/",
385
- };
386
- }
387
- );
388
-
389
- await runWrangler("pages publish . --project-name=foo");
390
-
391
- // TODO: Unmounting somehow loses this output
392
-
393
- // expect(std.out).toMatchInlineSnapshot(`
394
- // "✨ Success! Uploaded 1 files (TIMINGS)
395
-
396
- // ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
397
- // `);
398
- });
399
-
400
- it("should retry uploads", async () => {
401
- writeFileSync("logo.txt", "foobar");
402
-
403
- mockGetToken("<<funfetti-auth-jwt>>");
404
-
405
- setMockResponse(
406
- "/pages/assets/check-missing",
407
- "POST",
408
- async (_, init) => {
409
- const body = JSON.parse(init.body as string) as { hashes: string[] };
410
- assertLater(() => {
411
- expect(init.headers).toMatchObject({
412
- Authorization: "Bearer <<funfetti-auth-jwt>>",
413
- });
414
- expect(body).toMatchObject({
415
- hashes: ["1a98fb08af91aca4a7df1764a2c4ddb0"],
416
- });
417
- });
418
- return body.hashes;
419
- }
420
- );
421
-
422
- // Accumulate multiple requests then assert afterwards
423
- const requests: RequestInit[] = [];
424
- setMockRawResponse("/pages/assets/upload", "POST", async (_, init) => {
425
- requests.push(init);
426
-
427
- if (requests.length < 2) {
428
- return createFetchResult(null, false, [
429
- {
430
- code: 800000,
431
- message: "Something exploded, please retry",
432
- },
433
- ]);
434
- } else {
435
- return createFetchResult(null, true);
436
- }
437
- });
438
-
439
- setMockResponse(
440
- "/accounts/:accountId/pages/projects/foo/deployments",
441
- async ([_url, accountId], init) => {
442
- assertLater(() => {
443
- expect(accountId).toEqual("some-account-id");
444
- expect(init.method).toEqual("POST");
445
- const body = init.body as FormData;
446
- const manifest = JSON.parse(body.get("manifest") as string);
447
- expect(manifest).toMatchInlineSnapshot(`
448
- Object {
449
- "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
450
- }
451
- `);
452
- });
453
-
454
- return {
455
- url: "https://abcxyz.foo.pages.dev/",
456
- };
457
- }
458
- );
459
-
460
- await runWrangler("pages publish . --project-name=foo");
461
-
462
- // Assert two identical requests
463
- expect(requests.length).toBe(2);
464
- for (const init of requests) {
465
- assertLater(() => {
466
- expect(init.headers).toMatchObject({
467
- Authorization: "Bearer <<funfetti-auth-jwt>>",
468
- });
469
-
470
- const body = JSON.parse(init.body as string) as UploadPayloadFile[];
471
- expect(body).toMatchObject([
472
- {
473
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
474
- value: Buffer.from("foobar").toString("base64"),
475
- metadata: {
476
- contentType: "text/plain",
477
- },
478
- base64: true,
479
- },
480
- ]);
481
- });
482
- }
483
-
484
- expect(std.out).toMatchInlineSnapshot(`
485
- "✨ Success! Uploaded 1 files (TIMINGS)
486
-
487
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
488
- `);
489
- });
490
-
491
- it("should refetch a JWT if it expires while uploading", async () => {
492
- writeFileSync("logo.txt", "foobar");
493
-
494
- const cancelMockGetToken = mockGetToken("<<funfetti-auth-jwt>>");
495
-
496
- setMockResponse(
497
- "/pages/assets/check-missing",
498
- "POST",
499
- async (_, init) => {
500
- const body = JSON.parse(init.body as string) as { hashes: string[] };
501
- assertLater(() => {
502
- expect(init.headers).toMatchObject({
503
- Authorization: "Bearer <<funfetti-auth-jwt>>",
504
- });
505
- expect(body).toMatchObject({
506
- hashes: ["1a98fb08af91aca4a7df1764a2c4ddb0"],
507
- });
508
- });
509
- return body.hashes;
510
- }
511
- );
512
-
513
- // Accumulate multiple requests then assert afterwards
514
- const requests: RequestInit[] = [];
515
- setMockRawResponse("/pages/assets/upload", "POST", async (_, init) => {
516
- requests.push(init);
517
-
518
- // Fail just the first request
519
- if (requests.length < 2) {
520
- cancelMockGetToken();
521
- mockGetToken("<<funfetti-auth-jwt2>>");
522
- return createFetchResult(null, false, [
523
- {
524
- code: 8000013,
525
- message: "Authorization failed",
526
- },
527
- ]);
528
- } else {
529
- return createFetchResult(null, true);
530
- }
531
- });
532
-
533
- setMockResponse(
534
- "/accounts/:accountId/pages/projects/foo/deployments",
535
- async ([_url, accountId], init) => {
536
- assertLater(() => {
537
- expect(accountId).toEqual("some-account-id");
538
- expect(init.method).toEqual("POST");
539
- const body = init.body as FormData;
540
- const manifest = JSON.parse(body.get("manifest") as string);
541
- expect(manifest).toMatchInlineSnapshot(`
542
- Object {
543
- "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
544
- }
545
- `);
546
- });
547
-
548
- return {
549
- url: "https://abcxyz.foo.pages.dev/",
550
- };
551
- }
552
- );
553
-
554
- await runWrangler("pages publish . --project-name=foo");
555
-
556
- // Assert two requests
557
- expect(requests.length).toBe(2);
558
-
559
- expect(requests[0].headers).toMatchObject({
560
- Authorization: "Bearer <<funfetti-auth-jwt>>",
561
- });
562
-
563
- expect(requests[1].headers).toMatchObject({
564
- Authorization: "Bearer <<funfetti-auth-jwt2>>",
565
- });
566
-
567
- for (const init of requests) {
568
- const body = JSON.parse(init.body as string) as UploadPayloadFile[];
569
- expect(body).toMatchObject([
570
- {
571
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
572
- value: Buffer.from("foobar").toString("base64"),
573
- metadata: {
574
- contentType: "text/plain",
575
- },
576
- base64: true,
577
- },
578
- ]);
579
- }
580
-
581
- expect(std.out).toMatchInlineSnapshot(`
582
- "✨ Success! Uploaded 1 files (TIMINGS)
583
-
584
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
585
- `);
586
- });
587
-
588
- it("should try to use multiple buckets (up to the max concurrency)", async () => {
589
- writeFileSync("logo.txt", "foobar");
590
- writeFileSync("logo.png", "foobar");
591
- writeFileSync("logo.html", "foobar");
592
- writeFileSync("logo.js", "foobar");
593
-
594
- mockGetToken("<<funfetti-auth-jwt>>");
595
-
596
- setMockResponse(
597
- "/pages/assets/check-missing",
598
- "POST",
599
- async (_, init) => {
600
- const body = JSON.parse(init.body as string) as { hashes: string[] };
601
- assertLater(() => {
602
- expect(init.headers).toMatchObject({
603
- Authorization: "Bearer <<funfetti-auth-jwt>>",
604
- });
605
- expect(body).toMatchObject({
606
- hashes: expect.arrayContaining([
607
- "d96fef225537c9f5e44a3cb27fd0b492",
608
- "2082190357cfd3617ccfe04f340c6247",
609
- "6be321bef99e758250dac034474ddbb8",
610
- "1a98fb08af91aca4a7df1764a2c4ddb0",
611
- ]),
612
- });
613
- });
614
- return body.hashes;
615
- }
616
- );
617
-
618
- // Accumulate multiple requests then assert afterwards
619
- const requests: RequestInit[] = [];
620
- setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
621
- requests.push(init);
622
- });
623
-
624
- setMockResponse(
625
- "/accounts/:accountId/pages/projects/foo/deployments",
626
- async ([_url, accountId], init) => {
627
- assertLater(() => {
628
- expect(accountId).toEqual("some-account-id");
629
- expect(init.method).toEqual("POST");
630
- const body = init.body as FormData;
631
- const manifest = JSON.parse(body.get("manifest") as string);
632
- expect(manifest).toMatchInlineSnapshot(`
633
- Object {
634
- "/logo.html": "d96fef225537c9f5e44a3cb27fd0b492",
635
- "/logo.js": "6be321bef99e758250dac034474ddbb8",
636
- "/logo.png": "2082190357cfd3617ccfe04f340c6247",
637
- "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
638
- }
639
- `);
640
- });
641
-
642
- return {
643
- url: "https://abcxyz.foo.pages.dev/",
644
- };
645
- }
646
- );
647
-
648
- await runWrangler("pages publish . --project-name=foo");
649
-
650
- // We have 3 buckets, so expect 3 uploads
651
- expect(requests.length).toBe(3);
652
- const bodies: UploadPayloadFile[][] = [];
653
- for (const init of requests) {
654
- expect(init.headers).toMatchObject({
655
- Authorization: "Bearer <<funfetti-auth-jwt>>",
656
- });
657
- bodies.push(JSON.parse(init.body as string) as UploadPayloadFile[]);
658
- }
659
- // First bucket should end up with 2 files
660
- expect(bodies.map((b) => b.length)).toEqual([2, 1, 1]);
661
- // But we don't know the order, so flatten and test without ordering
662
- expect(bodies.flatMap((b) => b)).toEqual(
663
- expect.arrayContaining([
664
- {
665
- base64: true,
666
- key: "d96fef225537c9f5e44a3cb27fd0b492",
667
- metadata: { contentType: "text/html" },
668
- value: "Zm9vYmFy",
669
- },
670
- {
671
- base64: true,
672
- key: "1a98fb08af91aca4a7df1764a2c4ddb0",
673
- metadata: { contentType: "text/plain" },
674
- value: "Zm9vYmFy",
675
- },
676
- {
677
- base64: true,
678
- key: "6be321bef99e758250dac034474ddbb8",
679
- metadata: { contentType: "application/javascript" },
680
- value: "Zm9vYmFy",
681
- },
682
- {
683
- base64: true,
684
- key: "2082190357cfd3617ccfe04f340c6247",
685
- metadata: { contentType: "image/png" },
686
- value: "Zm9vYmFy",
687
- },
688
- ])
689
- );
690
-
691
- expect(std.out).toMatchInlineSnapshot(`
692
- "✨ Success! Uploaded 4 files (TIMINGS)
693
-
694
- ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
695
- `);
696
- });
697
-
698
- it("should not error when directory names contain periods and houses a extensionless file", async () => {
699
- mkdirSync(".well-known");
700
- // Note: same content as previous test, but since it's a different extension,
701
- // it hashes to a different value
702
- writeFileSync(".well-known/foobar", "foobar");
703
-
704
- mockGetToken("<<funfetti-auth-jwt>>");
705
-
706
- setMockResponse(
707
- "/pages/assets/check-missing",
708
- "POST",
709
- async (_, init) => {
710
- const body = JSON.parse(init.body as string) as { hashes: string[] };
711
- assertLater(() => {
712
- expect(init.headers).toMatchObject({
713
- Authorization: "Bearer <<funfetti-auth-jwt>>",
714
- });
715
- expect(body).toMatchObject({
716
- hashes: ["7b764dacfd211bebd8077828a7ddefd7"],
717
- });
718
- });
719
- return body.hashes;
720
- }
721
- );
722
-
723
- setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
724
- assertLater(() => {
725
- expect(init.headers).toMatchObject({
726
- Authorization: "Bearer <<funfetti-auth-jwt>>",
727
- });
728
- const body = JSON.parse(init.body as string) as UploadPayloadFile[];
729
- expect(body).toMatchObject([
730
- {
731
- key: "7b764dacfd211bebd8077828a7ddefd7",
732
- value: Buffer.from("foobar").toString("base64"),
733
- metadata: {
734
- contentType: "application/octet-stream",
735
- },
736
- base64: true,
737
- },
738
- ]);
739
- });
740
- });
741
-
742
- setMockResponse(
743
- "/accounts/:accountId/pages/projects/foo/deployments",
744
- async () => ({
745
- url: "https://abcxyz.foo.pages.dev/",
746
- })
747
- );
748
-
749
- await runWrangler("pages publish . --project-name=foo");
750
-
751
- expect(std.err).toMatchInlineSnapshot(`""`);
752
- });
753
- });
39
+ runInTempDir();
40
+ const std = mockConsoleMethods();
41
+ function endEventLoop() {
42
+ return new Promise((resolve) => setImmediate(resolve));
43
+ }
44
+ beforeEach(() => {
45
+ outOfBandTests.length = 0;
46
+ });
47
+ afterEach(() => {
48
+ outOfBandTests.forEach((fn) => fn());
49
+ });
50
+
51
+ beforeEach(() => {
52
+ // @ts-expect-error we're using a very simple setTimeout mock here
53
+ jest.spyOn(global, "setTimeout").mockImplementation((fn, _period) => {
54
+ setImmediate(fn);
55
+ });
56
+ });
57
+
58
+ it("should should display a list of available subcommands, for pages with no subcommand", async () => {
59
+ await runWrangler("pages");
60
+ await endEventLoop();
61
+
62
+ expect(std.out).toMatchInlineSnapshot(`
63
+ "wrangler pages
64
+
65
+ ⚡️ Configure Cloudflare Pages
66
+
67
+ Commands:
68
+ wrangler pages dev [directory] [-- command..] 🧑‍💻 Develop your full-stack Pages application locally
69
+ wrangler pages project ⚡️ Interact with your Pages projects
70
+ wrangler pages deployment 🚀 Interact with the deployments of a project
71
+ wrangler pages publish [directory] 🆙 Publish a directory of static assets as a Pages deployment
72
+
73
+ Flags:
74
+ -c, --config Path to .toml configuration file [string]
75
+ -e, --env Environment to use for operations and .env files [string]
76
+ -h, --help Show help [boolean]
77
+ -v, --version Show version number [boolean]
78
+
79
+ 🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose"
80
+ `);
81
+ });
82
+
83
+ describe("beta message for subcommands", () => {
84
+ it("should display for pages:dev", async () => {
85
+ await expect(
86
+ runWrangler("pages dev")
87
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
88
+ `"Must specify a directory of static assets to serve or a command to run or a proxy port."`
89
+ );
90
+
91
+ expect(std.out).toMatchInlineSnapshot(`
92
+ "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose
93
+
94
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
95
+ `);
96
+ });
97
+
98
+ it("should display for pages:functions:build", async () => {
99
+ await expect(runWrangler("pages functions build")).rejects.toThrowError();
100
+
101
+ expect(std.out).toMatchInlineSnapshot(`
102
+ "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose
103
+
104
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
105
+ `);
106
+ });
107
+
108
+ it("should display for pages:functions:optimize-routes", async () => {
109
+ await expect(
110
+ runWrangler(
111
+ 'pages functions optimize-routes --routes-path="/build/_routes.json" --output-routes-path="/build/_optimized-routes.json"'
112
+ )
113
+ ).rejects.toThrowError();
114
+
115
+ expect(std.out).toMatchInlineSnapshot(`
116
+ "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose
117
+
118
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
119
+ `);
120
+ });
121
+ });
122
+
123
+ describe("project list", () => {
124
+ mockAccountId();
125
+ mockApiToken();
126
+
127
+ afterEach(() => {
128
+ unsetAllMocks();
129
+ });
130
+
131
+ function mockListRequest(projects: unknown[]) {
132
+ const requests = { count: 0 };
133
+ setMockResponse(
134
+ "/accounts/:accountId/pages/projects",
135
+ ([_url, accountId], init, query) => {
136
+ requests.count++;
137
+ const pageSize = Number(query.get("per_page"));
138
+ const page = Number(query.get("page"));
139
+ const expectedPageSize = 10;
140
+ const expectedPage = requests.count;
141
+ assertLater(() => {
142
+ expect(accountId).toEqual("some-account-id");
143
+ expect(pageSize).toEqual(expectedPageSize);
144
+ expect(page).toEqual(expectedPage);
145
+ expect(init).toEqual({});
146
+ });
147
+ return projects.slice((page - 1) * pageSize, page * pageSize);
148
+ }
149
+ );
150
+ return requests;
151
+ }
152
+
153
+ it("should make request to list projects", async () => {
154
+ const projects: Project[] = [
155
+ {
156
+ name: "dogs",
157
+ subdomain: "docs.pages.dev",
158
+ domains: ["dogs.pages.dev"],
159
+ source: {
160
+ type: "github",
161
+ },
162
+ latest_deployment: {
163
+ modified_on: "2021-11-17T14:52:26.133835Z",
164
+ },
165
+ created_on: "2021-11-17T14:52:26.133835Z",
166
+ production_branch: "main",
167
+ },
168
+ {
169
+ name: "cats",
170
+ subdomain: "cats.pages.dev",
171
+ domains: ["cats.pages.dev", "kitten.com"],
172
+ latest_deployment: {
173
+ modified_on: "2021-11-17T14:52:26.133835Z",
174
+ },
175
+ created_on: "2021-11-17T14:52:26.133835Z",
176
+ production_branch: "main",
177
+ },
178
+ ];
179
+
180
+ const requests = mockListRequest(projects);
181
+ await runWrangler("pages project list");
182
+
183
+ expect(requests.count).toBe(1);
184
+ });
185
+
186
+ it("should make multiple requests for paginated results", async () => {
187
+ const projects: Project[] = [];
188
+ for (let i = 0; i < 15; i++) {
189
+ projects.push({
190
+ name: "dogs" + i,
191
+ subdomain: i + "dogs.pages.dev",
192
+ domains: [i + "dogs.pages.dev"],
193
+ source: {
194
+ type: "github",
195
+ },
196
+ latest_deployment: {
197
+ modified_on: "2021-11-17T14:52:26.133835Z",
198
+ },
199
+ created_on: "2021-11-17T14:52:26.133835Z",
200
+ production_branch: "main",
201
+ });
202
+ }
203
+ const requests = mockListRequest(projects);
204
+ await runWrangler("pages project list");
205
+ expect(requests.count).toEqual(2);
206
+ });
207
+ });
208
+
209
+ describe("project create", () => {
210
+ mockAccountId();
211
+ mockApiToken();
212
+
213
+ afterEach(() => {
214
+ unsetAllMocks();
215
+ });
216
+
217
+ it("should create a project with a production branch", async () => {
218
+ setMockResponse(
219
+ "/accounts/:accountId/pages/projects",
220
+ ([_url, accountId], init) => {
221
+ const body = JSON.parse(init.body as string);
222
+ assertLater(() => {
223
+ expect(accountId).toEqual("some-account-id");
224
+ expect(init.method).toEqual("POST");
225
+ expect(body).toEqual({
226
+ name: "a-new-project",
227
+ production_branch: "main",
228
+ });
229
+ });
230
+ return {
231
+ name: "a-new-project",
232
+ subdomain: "a-new-project.pages.dev",
233
+ production_branch: "main",
234
+ };
235
+ }
236
+ );
237
+ await runWrangler(
238
+ "pages project create a-new-project --production-branch=main"
239
+ );
240
+ expect(std.out).toMatchInlineSnapshot(`
241
+ "✨ Successfully created the 'a-new-project' project. It will be available at https://a-new-project.pages.dev/ once you create your first deployment.
242
+ To deploy a folder of assets, run 'wrangler pages publish [directory]'."
243
+ `);
244
+ });
245
+ });
246
+
247
+ describe("deployment list", () => {
248
+ mockAccountId();
249
+ mockApiToken();
250
+
251
+ afterEach(() => {
252
+ unsetAllMocks();
253
+ });
254
+ function mockListRequest(deployments: unknown[]) {
255
+ const requests = { count: 0 };
256
+ setMockResponse(
257
+ "/accounts/:accountId/pages/projects/:project/deployments",
258
+ ([_url, accountId, project]) => {
259
+ requests.count++;
260
+ assertLater(() => {
261
+ expect(project).toEqual("images");
262
+ expect(accountId).toEqual("some-account-id");
263
+ });
264
+ return deployments;
265
+ }
266
+ );
267
+ return requests;
268
+ }
269
+
270
+ it("should make request to list deployments", async () => {
271
+ const deployments: Deployment[] = [
272
+ {
273
+ id: "87bbc8fe-16be-45cd-81e0-63d722e82cdf",
274
+ url: "https://87bbc8fe.images.pages.dev",
275
+ environment: "preview",
276
+ latest_stage: {
277
+ ended_on: "2021-11-17T14:52:26.133835Z",
278
+ status: "success",
279
+ },
280
+ deployment_trigger: {
281
+ metadata: {
282
+ branch: "main",
283
+ commit_hash: "c7649364c4cb32ad4f65b530b9424e8be5bec9d6",
284
+ },
285
+ },
286
+ project_name: "images",
287
+ },
288
+ ];
289
+
290
+ const requests = mockListRequest(deployments);
291
+ await runWrangler("pages deployment list --project-name=images");
292
+
293
+ expect(requests.count).toBe(1);
294
+ });
295
+ });
296
+
297
+ describe("deployment create", () => {
298
+ let actualProcessEnvCI: string | undefined;
299
+
300
+ mockAccountId();
301
+ mockApiToken();
302
+ runInTempDir();
303
+
304
+ beforeEach(() => {
305
+ actualProcessEnvCI = process.env.CI;
306
+ process.env.CI = "true";
307
+ });
308
+
309
+ afterEach(() => {
310
+ unsetAllMocks();
311
+ process.env.CI = actualProcessEnvCI;
312
+ });
313
+
314
+ it("should be aliased with 'wrangler pages publish'", async () => {
315
+ await runWrangler("pages publish --help");
316
+ await endEventLoop();
317
+
318
+ expect(std.out).toMatchInlineSnapshot(`
319
+ "wrangler pages publish [directory]
320
+
321
+ 🆙 Publish a directory of static assets as a Pages deployment
322
+
323
+ Positionals:
324
+ directory The directory of static files to upload [string]
325
+
326
+ Flags:
327
+ -e, --env Environment to use for operations and .env files [string]
328
+ -h, --help Show help [boolean]
329
+ -v, --version Show version number [boolean]
330
+
331
+ Options:
332
+ --project-name The name of the project you want to deploy to [string]
333
+ --branch The name of the branch you want to deploy to [string]
334
+ --commit-hash The SHA to attach to this deployment [string]
335
+ --commit-message The commit message to attach to this deployment [string]
336
+ --commit-dirty Whether or not the workspace should be considered dirty for this deployment [boolean]
337
+
338
+ 🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose"
339
+ `);
340
+ });
341
+
342
+ it("should upload a directory of files", async () => {
343
+ writeFileSync("logo.png", "foobar");
344
+
345
+ mockGetToken("<<funfetti-auth-jwt>>");
346
+
347
+ setMockResponse(
348
+ "/pages/assets/check-missing",
349
+ "POST",
350
+ async (_, init) => {
351
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
352
+ assertLater(() => {
353
+ expect(init.headers).toMatchObject({
354
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
355
+ });
356
+ expect(body).toMatchObject({
357
+ hashes: ["2082190357cfd3617ccfe04f340c6247"],
358
+ });
359
+ });
360
+ return body.hashes;
361
+ }
362
+ );
363
+
364
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
365
+ assertLater(() => {
366
+ expect(init.headers).toMatchObject({
367
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
368
+ });
369
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
370
+ expect(body).toMatchObject([
371
+ {
372
+ key: "2082190357cfd3617ccfe04f340c6247",
373
+ value: Buffer.from("foobar").toString("base64"),
374
+ metadata: {
375
+ contentType: "image/png",
376
+ },
377
+ base64: true,
378
+ },
379
+ ]);
380
+ });
381
+ });
382
+
383
+ setMockResponse(
384
+ "/accounts/:accountId/pages/projects/foo/deployments",
385
+ async ([_url, accountId], init) => {
386
+ assertLater(() => {
387
+ expect(accountId).toEqual("some-account-id");
388
+ expect(init.method).toEqual("POST");
389
+ const body = init.body as FormData;
390
+ const manifest = JSON.parse(body.get("manifest") as string);
391
+ expect(manifest).toMatchInlineSnapshot(`
392
+ Object {
393
+ "/logo.png": "2082190357cfd3617ccfe04f340c6247",
394
+ }
395
+ `);
396
+ });
397
+
398
+ return {
399
+ url: "https://abcxyz.foo.pages.dev/",
400
+ };
401
+ }
402
+ );
403
+
404
+ await runWrangler("pages publish . --project-name=foo");
405
+
406
+ expect(std.out).toMatchInlineSnapshot(`
407
+ "✨ Success! Uploaded 1 files (TIMINGS)
408
+
409
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
410
+ `);
411
+ });
412
+
413
+ it("should retry uploads", async () => {
414
+ writeFileSync("logo.txt", "foobar");
415
+
416
+ mockGetToken("<<funfetti-auth-jwt>>");
417
+
418
+ setMockResponse(
419
+ "/pages/assets/check-missing",
420
+ "POST",
421
+ async (_, init) => {
422
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
423
+ assertLater(() => {
424
+ expect(init.headers).toMatchObject({
425
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
426
+ });
427
+ expect(body).toMatchObject({
428
+ hashes: ["1a98fb08af91aca4a7df1764a2c4ddb0"],
429
+ });
430
+ });
431
+ return body.hashes;
432
+ }
433
+ );
434
+
435
+ // Accumulate multiple requests then assert afterwards
436
+ const requests: RequestInit[] = [];
437
+ setMockRawResponse("/pages/assets/upload", "POST", async (_, init) => {
438
+ requests.push(init);
439
+
440
+ if (requests.length < 2) {
441
+ return createFetchResult(null, false, [
442
+ {
443
+ code: 800000,
444
+ message: "Something exploded, please retry",
445
+ },
446
+ ]);
447
+ } else {
448
+ return createFetchResult(null, true);
449
+ }
450
+ });
451
+
452
+ setMockResponse(
453
+ "/accounts/:accountId/pages/projects/foo/deployments",
454
+ async ([_url, accountId], init) => {
455
+ assertLater(() => {
456
+ expect(accountId).toEqual("some-account-id");
457
+ expect(init.method).toEqual("POST");
458
+ const body = init.body as FormData;
459
+ const manifest = JSON.parse(body.get("manifest") as string);
460
+ expect(manifest).toMatchInlineSnapshot(`
461
+ Object {
462
+ "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
463
+ }
464
+ `);
465
+ });
466
+
467
+ return {
468
+ url: "https://abcxyz.foo.pages.dev/",
469
+ };
470
+ }
471
+ );
472
+
473
+ await runWrangler("pages publish . --project-name=foo");
474
+
475
+ // Assert two identical requests
476
+ expect(requests.length).toBe(2);
477
+ for (const init of requests) {
478
+ assertLater(() => {
479
+ expect(init.headers).toMatchObject({
480
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
481
+ });
482
+
483
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
484
+ expect(body).toMatchObject([
485
+ {
486
+ key: "1a98fb08af91aca4a7df1764a2c4ddb0",
487
+ value: Buffer.from("foobar").toString("base64"),
488
+ metadata: {
489
+ contentType: "text/plain",
490
+ },
491
+ base64: true,
492
+ },
493
+ ]);
494
+ });
495
+ }
496
+
497
+ expect(std.out).toMatchInlineSnapshot(`
498
+ "✨ Success! Uploaded 1 files (TIMINGS)
499
+
500
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
501
+ `);
502
+ });
503
+
504
+ it("should refetch a JWT if it expires while uploading", async () => {
505
+ writeFileSync("logo.txt", "foobar");
506
+
507
+ const cancelMockGetToken = mockGetToken("<<funfetti-auth-jwt>>");
508
+
509
+ setMockResponse(
510
+ "/pages/assets/check-missing",
511
+ "POST",
512
+ async (_, init) => {
513
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
514
+ assertLater(() => {
515
+ expect(init.headers).toMatchObject({
516
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
517
+ });
518
+ expect(body).toMatchObject({
519
+ hashes: ["1a98fb08af91aca4a7df1764a2c4ddb0"],
520
+ });
521
+ });
522
+ return body.hashes;
523
+ }
524
+ );
525
+
526
+ // Accumulate multiple requests then assert afterwards
527
+ const requests: RequestInit[] = [];
528
+ setMockRawResponse("/pages/assets/upload", "POST", async (_, init) => {
529
+ requests.push(init);
530
+
531
+ // Fail just the first request
532
+ if (requests.length < 2) {
533
+ cancelMockGetToken();
534
+ mockGetToken("<<funfetti-auth-jwt2>>");
535
+ return createFetchResult(null, false, [
536
+ {
537
+ code: 8000013,
538
+ message: "Authorization failed",
539
+ },
540
+ ]);
541
+ } else {
542
+ return createFetchResult(null, true);
543
+ }
544
+ });
545
+
546
+ setMockResponse(
547
+ "/accounts/:accountId/pages/projects/foo/deployments",
548
+ async ([_url, accountId], init) => {
549
+ assertLater(() => {
550
+ expect(accountId).toEqual("some-account-id");
551
+ expect(init.method).toEqual("POST");
552
+ const body = init.body as FormData;
553
+ const manifest = JSON.parse(body.get("manifest") as string);
554
+ expect(manifest).toMatchInlineSnapshot(`
555
+ Object {
556
+ "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
557
+ }
558
+ `);
559
+ });
560
+
561
+ return {
562
+ url: "https://abcxyz.foo.pages.dev/",
563
+ };
564
+ }
565
+ );
566
+
567
+ await runWrangler("pages publish . --project-name=foo");
568
+
569
+ // Assert two requests
570
+ expect(requests.length).toBe(2);
571
+
572
+ expect(requests[0].headers).toMatchObject({
573
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
574
+ });
575
+
576
+ expect(requests[1].headers).toMatchObject({
577
+ Authorization: "Bearer <<funfetti-auth-jwt2>>",
578
+ });
579
+
580
+ for (const init of requests) {
581
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
582
+ expect(body).toMatchObject([
583
+ {
584
+ key: "1a98fb08af91aca4a7df1764a2c4ddb0",
585
+ value: Buffer.from("foobar").toString("base64"),
586
+ metadata: {
587
+ contentType: "text/plain",
588
+ },
589
+ base64: true,
590
+ },
591
+ ]);
592
+ }
593
+
594
+ expect(std.out).toMatchInlineSnapshot(`
595
+ "✨ Success! Uploaded 1 files (TIMINGS)
596
+
597
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
598
+ `);
599
+ });
600
+
601
+ it("should try to use multiple buckets (up to the max concurrency)", async () => {
602
+ writeFileSync("logo.txt", "foobar");
603
+ writeFileSync("logo.png", "foobar");
604
+ writeFileSync("logo.html", "foobar");
605
+ writeFileSync("logo.js", "foobar");
606
+
607
+ mockGetToken("<<funfetti-auth-jwt>>");
608
+
609
+ setMockResponse(
610
+ "/pages/assets/check-missing",
611
+ "POST",
612
+ async (_, init) => {
613
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
614
+ assertLater(() => {
615
+ expect(init.headers).toMatchObject({
616
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
617
+ });
618
+ expect(body).toMatchObject({
619
+ hashes: expect.arrayContaining([
620
+ "d96fef225537c9f5e44a3cb27fd0b492",
621
+ "2082190357cfd3617ccfe04f340c6247",
622
+ "6be321bef99e758250dac034474ddbb8",
623
+ "1a98fb08af91aca4a7df1764a2c4ddb0",
624
+ ]),
625
+ });
626
+ });
627
+ return body.hashes;
628
+ }
629
+ );
630
+
631
+ // Accumulate multiple requests then assert afterwards
632
+ const requests: RequestInit[] = [];
633
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
634
+ requests.push(init);
635
+ });
636
+
637
+ setMockResponse(
638
+ "/accounts/:accountId/pages/projects/foo/deployments",
639
+ async ([_url, accountId], init) => {
640
+ assertLater(() => {
641
+ expect(accountId).toEqual("some-account-id");
642
+ expect(init.method).toEqual("POST");
643
+ const body = init.body as FormData;
644
+ const manifest = JSON.parse(body.get("manifest") as string);
645
+ expect(manifest).toMatchInlineSnapshot(`
646
+ Object {
647
+ "/logo.html": "d96fef225537c9f5e44a3cb27fd0b492",
648
+ "/logo.js": "6be321bef99e758250dac034474ddbb8",
649
+ "/logo.png": "2082190357cfd3617ccfe04f340c6247",
650
+ "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
651
+ }
652
+ `);
653
+ });
654
+
655
+ return {
656
+ url: "https://abcxyz.foo.pages.dev/",
657
+ };
658
+ }
659
+ );
660
+
661
+ await runWrangler("pages publish . --project-name=foo");
662
+
663
+ // We have 3 buckets, so expect 3 uploads
664
+ expect(requests.length).toBe(3);
665
+ const bodies: UploadPayloadFile[][] = [];
666
+ for (const init of requests) {
667
+ expect(init.headers).toMatchObject({
668
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
669
+ });
670
+ bodies.push(JSON.parse(init.body as string) as UploadPayloadFile[]);
671
+ }
672
+ // One bucket should end up with 2 files
673
+ expect(bodies.map((b) => b.length).sort()).toEqual([1, 1, 2]);
674
+ // But we don't know the order, so flatten and test without ordering
675
+ expect(bodies.flatMap((b) => b)).toEqual(
676
+ expect.arrayContaining([
677
+ {
678
+ base64: true,
679
+ key: "d96fef225537c9f5e44a3cb27fd0b492",
680
+ metadata: { contentType: "text/html" },
681
+ value: "Zm9vYmFy",
682
+ },
683
+ {
684
+ base64: true,
685
+ key: "1a98fb08af91aca4a7df1764a2c4ddb0",
686
+ metadata: { contentType: "text/plain" },
687
+ value: "Zm9vYmFy",
688
+ },
689
+ {
690
+ base64: true,
691
+ key: "6be321bef99e758250dac034474ddbb8",
692
+ metadata: { contentType: "application/javascript" },
693
+ value: "Zm9vYmFy",
694
+ },
695
+ {
696
+ base64: true,
697
+ key: "2082190357cfd3617ccfe04f340c6247",
698
+ metadata: { contentType: "image/png" },
699
+ value: "Zm9vYmFy",
700
+ },
701
+ ])
702
+ );
703
+
704
+ expect(std.out).toMatchInlineSnapshot(`
705
+ "✨ Success! Uploaded 4 files (TIMINGS)
706
+
707
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
708
+ `);
709
+ });
710
+
711
+ it("should resolve child directories correctly", async () => {
712
+ mkdirSync("public");
713
+ mkdirSync("public/imgs");
714
+ writeFileSync("public/logo.txt", "foobar");
715
+ writeFileSync("public/imgs/logo.png", "foobar");
716
+ writeFileSync("public/logo.html", "foobar");
717
+ writeFileSync("public/logo.js", "foobar");
718
+
719
+ mockGetToken("<<funfetti-auth-jwt>>");
720
+
721
+ setMockResponse(
722
+ "/pages/assets/check-missing",
723
+ "POST",
724
+ async (_, init) => {
725
+ const body = JSON.parse(init.body as string) as {
726
+ hashes: string[];
727
+ };
728
+ assertLater(() => {
729
+ expect(init.headers).toMatchObject({
730
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
731
+ });
732
+ expect(body).toMatchObject({
733
+ hashes: expect.arrayContaining([
734
+ "d96fef225537c9f5e44a3cb27fd0b492",
735
+ "2082190357cfd3617ccfe04f340c6247",
736
+ "6be321bef99e758250dac034474ddbb8",
737
+ "1a98fb08af91aca4a7df1764a2c4ddb0",
738
+ ]),
739
+ });
740
+ });
741
+ return body.hashes;
742
+ }
743
+ );
744
+
745
+ // Accumulate multiple requests then assert afterwards
746
+ const requests: RequestInit[] = [];
747
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
748
+ requests.push(init);
749
+ });
750
+
751
+ setMockResponse(
752
+ "/accounts/:accountId/pages/projects/foo/deployments",
753
+ async ([_url, accountId], init) => {
754
+ assertLater(() => {
755
+ expect(accountId).toEqual("some-account-id");
756
+ expect(init.method).toEqual("POST");
757
+ const body = init.body as FormData;
758
+ const manifest = JSON.parse(body.get("manifest") as string);
759
+ expect(manifest).toMatchInlineSnapshot(`
760
+ Object {
761
+ "/imgs/logo.png": "2082190357cfd3617ccfe04f340c6247",
762
+ "/logo.html": "d96fef225537c9f5e44a3cb27fd0b492",
763
+ "/logo.js": "6be321bef99e758250dac034474ddbb8",
764
+ "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
765
+ }
766
+ `);
767
+ });
768
+
769
+ return {
770
+ url: "https://abcxyz.foo.pages.dev/",
771
+ };
772
+ }
773
+ );
774
+
775
+ await runWrangler(`pages publish public --project-name=foo`);
776
+
777
+ // We have 3 buckets, so expect 3 uploads
778
+ expect(requests.length).toBe(3);
779
+ const bodies: UploadPayloadFile[][] = [];
780
+ for (const init of requests) {
781
+ expect(init.headers).toMatchObject({
782
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
783
+ });
784
+ bodies.push(JSON.parse(init.body as string) as UploadPayloadFile[]);
785
+ }
786
+ // One bucket should end up with 2 files
787
+ expect(bodies.map((b) => b.length).sort()).toEqual([1, 1, 2]);
788
+ // But we don't know the order, so flatten and test without ordering
789
+ expect(bodies.flatMap((b) => b)).toEqual(
790
+ expect.arrayContaining([
791
+ {
792
+ base64: true,
793
+ key: "d96fef225537c9f5e44a3cb27fd0b492",
794
+ metadata: { contentType: "text/html" },
795
+ value: "Zm9vYmFy",
796
+ },
797
+ {
798
+ base64: true,
799
+ key: "1a98fb08af91aca4a7df1764a2c4ddb0",
800
+ metadata: { contentType: "text/plain" },
801
+ value: "Zm9vYmFy",
802
+ },
803
+ {
804
+ base64: true,
805
+ key: "6be321bef99e758250dac034474ddbb8",
806
+ metadata: { contentType: "application/javascript" },
807
+ value: "Zm9vYmFy",
808
+ },
809
+ {
810
+ base64: true,
811
+ key: "2082190357cfd3617ccfe04f340c6247",
812
+ metadata: { contentType: "image/png" },
813
+ value: "Zm9vYmFy",
814
+ },
815
+ ])
816
+ );
817
+
818
+ expect(std.out).toMatchInlineSnapshot(`
819
+ "✨ Success! Uploaded 4 files (TIMINGS)
820
+
821
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
822
+ `);
823
+ });
824
+
825
+ it("should resolve the current directory correctly", async () => {
826
+ mkdirSync("public");
827
+ mkdirSync("public/imgs");
828
+ writeFileSync("public/logo.txt", "foobar");
829
+ writeFileSync("public/imgs/logo.png", "foobar");
830
+ writeFileSync("public/logo.html", "foobar");
831
+ writeFileSync("public/logo.js", "foobar");
832
+
833
+ mockGetToken("<<funfetti-auth-jwt>>");
834
+
835
+ setMockResponse(
836
+ "/pages/assets/check-missing",
837
+ "POST",
838
+ async (_, init) => {
839
+ const body = JSON.parse(init.body as string) as {
840
+ hashes: string[];
841
+ };
842
+ assertLater(() => {
843
+ expect(init.headers).toMatchObject({
844
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
845
+ });
846
+ expect(body).toMatchObject({
847
+ hashes: expect.arrayContaining([
848
+ "d96fef225537c9f5e44a3cb27fd0b492",
849
+ "2082190357cfd3617ccfe04f340c6247",
850
+ "6be321bef99e758250dac034474ddbb8",
851
+ "1a98fb08af91aca4a7df1764a2c4ddb0",
852
+ ]),
853
+ });
854
+ });
855
+ return body.hashes;
856
+ }
857
+ );
858
+
859
+ // Accumulate multiple requests then assert afterwards
860
+ const requests: RequestInit[] = [];
861
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
862
+ requests.push(init);
863
+ });
864
+
865
+ setMockResponse(
866
+ "/accounts/:accountId/pages/projects/foo/deployments",
867
+ async ([_url, accountId], init) => {
868
+ assertLater(() => {
869
+ expect(accountId).toEqual("some-account-id");
870
+ expect(init.method).toEqual("POST");
871
+ const body = init.body as FormData;
872
+ const manifest = JSON.parse(body.get("manifest") as string);
873
+ expect(manifest).toMatchInlineSnapshot(`
874
+ Object {
875
+ "/imgs/logo.png": "2082190357cfd3617ccfe04f340c6247",
876
+ "/logo.html": "d96fef225537c9f5e44a3cb27fd0b492",
877
+ "/logo.js": "6be321bef99e758250dac034474ddbb8",
878
+ "/logo.txt": "1a98fb08af91aca4a7df1764a2c4ddb0",
879
+ }
880
+ `);
881
+ });
882
+
883
+ return {
884
+ url: "https://abcxyz.foo.pages.dev/",
885
+ };
886
+ }
887
+ );
888
+
889
+ chdir("public");
890
+ await runWrangler(`pages publish . --project-name=foo`);
891
+
892
+ // We have 3 buckets, so expect 3 uploads
893
+ expect(requests.length).toBe(3);
894
+ const bodies: UploadPayloadFile[][] = [];
895
+ for (const init of requests) {
896
+ expect(init.headers).toMatchObject({
897
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
898
+ });
899
+ bodies.push(JSON.parse(init.body as string) as UploadPayloadFile[]);
900
+ }
901
+ // One bucket should end up with 2 files
902
+ expect(bodies.map((b) => b.length).sort()).toEqual([1, 1, 2]);
903
+ // But we don't know the order, so flatten and test without ordering
904
+ expect(bodies.flatMap((b) => b)).toEqual(
905
+ expect.arrayContaining([
906
+ {
907
+ base64: true,
908
+ key: "d96fef225537c9f5e44a3cb27fd0b492",
909
+ metadata: { contentType: "text/html" },
910
+ value: "Zm9vYmFy",
911
+ },
912
+ {
913
+ base64: true,
914
+ key: "1a98fb08af91aca4a7df1764a2c4ddb0",
915
+ metadata: { contentType: "text/plain" },
916
+ value: "Zm9vYmFy",
917
+ },
918
+ {
919
+ base64: true,
920
+ key: "6be321bef99e758250dac034474ddbb8",
921
+ metadata: { contentType: "application/javascript" },
922
+ value: "Zm9vYmFy",
923
+ },
924
+ {
925
+ base64: true,
926
+ key: "2082190357cfd3617ccfe04f340c6247",
927
+ metadata: { contentType: "image/png" },
928
+ value: "Zm9vYmFy",
929
+ },
930
+ ])
931
+ );
932
+
933
+ expect(std.out).toMatchInlineSnapshot(`
934
+ "✨ Success! Uploaded 4 files (TIMINGS)
935
+
936
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
937
+ `);
938
+ });
939
+
940
+ it("should not error when directory names contain periods and houses a extensionless file", async () => {
941
+ mkdirSync(".well-known");
942
+ // Note: same content as previous test, but since it's a different extension,
943
+ // it hashes to a different value
944
+ writeFileSync(".well-known/foobar", "foobar");
945
+
946
+ mockGetToken("<<funfetti-auth-jwt>>");
947
+
948
+ setMockResponse(
949
+ "/pages/assets/check-missing",
950
+ "POST",
951
+ async (_, init) => {
952
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
953
+ assertLater(() => {
954
+ expect(init.headers).toMatchObject({
955
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
956
+ });
957
+ expect(body).toMatchObject({
958
+ hashes: ["7b764dacfd211bebd8077828a7ddefd7"],
959
+ });
960
+ });
961
+ return body.hashes;
962
+ }
963
+ );
964
+
965
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
966
+ assertLater(() => {
967
+ expect(init.headers).toMatchObject({
968
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
969
+ });
970
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
971
+ expect(body).toMatchObject([
972
+ {
973
+ key: "7b764dacfd211bebd8077828a7ddefd7",
974
+ value: Buffer.from("foobar").toString("base64"),
975
+ metadata: {
976
+ contentType: "application/octet-stream",
977
+ },
978
+ base64: true,
979
+ },
980
+ ]);
981
+ });
982
+ });
983
+
984
+ setMockResponse(
985
+ "/accounts/:accountId/pages/projects/foo/deployments",
986
+ async () => ({
987
+ url: "https://abcxyz.foo.pages.dev/",
988
+ })
989
+ );
990
+
991
+ await runWrangler("pages publish . --project-name=foo");
992
+
993
+ expect(std.err).toMatchInlineSnapshot(`""`);
994
+ });
995
+
996
+ it("should throw an error if user attempts to use config with pages", async () => {
997
+ await expect(
998
+ runWrangler("pages dev --config foo.toml")
999
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
1000
+ `"Pages does not support wrangler.toml"`
1001
+ );
1002
+ await expect(
1003
+ runWrangler("pages publish --config foo.toml")
1004
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
1005
+ `"Pages does not support wrangler.toml"`
1006
+ );
1007
+ });
1008
+
1009
+ it("should upload a Functions project", async () => {
1010
+ // set up the directory of static files to upload.
1011
+ mkdirSync("public");
1012
+ writeFileSync("public/README.md", "This is a readme");
1013
+
1014
+ // set up /functions
1015
+ mkdirSync("functions");
1016
+ writeFileSync(
1017
+ "functions/hello.js",
1018
+ `
1019
+ export async function onRequest() {
1020
+ return new Response("Hello, world!");
1021
+ }
1022
+ `
1023
+ );
1024
+
1025
+ mockGetToken("<<funfetti-auth-jwt>>");
1026
+
1027
+ setMockResponse(
1028
+ "/pages/assets/check-missing",
1029
+ "POST",
1030
+ async (_, init) => {
1031
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
1032
+ assertLater(() => {
1033
+ expect(init.headers).toMatchObject({
1034
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1035
+ });
1036
+ expect(body).toMatchObject({
1037
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1038
+ });
1039
+ });
1040
+ return body.hashes;
1041
+ }
1042
+ );
1043
+
1044
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
1045
+ assertLater(() => {
1046
+ expect(init.headers).toMatchObject({
1047
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1048
+ });
1049
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1050
+ expect(body).toMatchObject([
1051
+ {
1052
+ key: "13a03eaf24ae98378acd36ea00f77f2f",
1053
+ value: Buffer.from("This is a readme").toString("base64"),
1054
+ metadata: {
1055
+ contentType: "text/markdown",
1056
+ },
1057
+ base64: true,
1058
+ },
1059
+ ]);
1060
+ });
1061
+ });
1062
+
1063
+ setMockResponse(
1064
+ `/pages/assets/upsert-hashes`,
1065
+ "POST",
1066
+ async (_, init) => {
1067
+ assertLater(() => {
1068
+ expect(init.headers).toMatchObject({
1069
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1070
+ });
1071
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1072
+ expect(body).toMatchObject({
1073
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1074
+ });
1075
+ });
1076
+
1077
+ return Promise.resolve(true);
1078
+ }
1079
+ );
1080
+
1081
+ setMockResponse(
1082
+ "/accounts/:accountId/pages/projects/foo/deployments",
1083
+ async ([_url, accountId], init) => {
1084
+ assertLater(async () => {
1085
+ expect(accountId).toEqual("some-account-id");
1086
+ expect(init.method).toEqual("POST");
1087
+ const body = init.body as FormData;
1088
+ const manifest = JSON.parse(body.get("manifest") as string);
1089
+
1090
+ // for Functions projects, we auto-generate a `_worker.js` and `_routes.json`
1091
+ // file, based on the contents of `/functions`
1092
+ const generatedWorkerJS = body.get("_worker.js") as Blob;
1093
+ const generatedRoutesJSON = await (
1094
+ body.get("_routes.json") as Blob
1095
+ ).text();
1096
+
1097
+ // make sure this is all we uploaded
1098
+ expect([...body.keys()]).toEqual([
1099
+ "manifest",
1100
+ "_worker.js",
1101
+ "_routes.json",
1102
+ ]);
1103
+
1104
+ expect(manifest).toMatchInlineSnapshot(`
1105
+ Object {
1106
+ "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
1107
+ }
1108
+ `);
1109
+
1110
+ // the contents of the generated `_worker.js` file is pretty massive, so I don't
1111
+ // think snapshot testing makes much sense here. Plus, calling
1112
+ // `.toMatchInlineSnapshot()` without any arguments, in order to generate that
1113
+ // snapshot value, doesn't generate anything in this case (probably because the
1114
+ // file contents is too big). So for now, let's test that _worker.js was indeed
1115
+ // generated and that the file size is greater than zero
1116
+ expect(generatedWorkerJS).not.toBeNull();
1117
+ expect(generatedWorkerJS.size).toBeGreaterThan(0);
1118
+
1119
+ const maybeRoutesJSONSpec = JSON.parse(generatedRoutesJSON);
1120
+ expect(isRoutesJSONSpec(maybeRoutesJSONSpec)).toBe(true);
1121
+ expect(maybeRoutesJSONSpec).toMatchObject({
1122
+ version: ROUTES_SPEC_VERSION,
1123
+ description: `Generated by wrangler@${version}`,
1124
+ include: ["/hello"],
1125
+ exclude: [],
1126
+ });
1127
+ });
1128
+
1129
+ return {
1130
+ url: "https://abcxyz.foo.pages.dev/",
1131
+ };
1132
+ }
1133
+ );
1134
+
1135
+ await runWrangler("pages publish public --project-name=foo");
1136
+
1137
+ expect(std.out).toMatchInlineSnapshot(`
1138
+ "Compiled Worker successfully.
1139
+ ✨ Success! Uploaded 1 files (TIMINGS)
1140
+
1141
+ ✨ Uploading Functions
1142
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1143
+ `);
1144
+
1145
+ expect(std.err).toMatchInlineSnapshot('""');
1146
+ });
1147
+
1148
+ it("should upload an Advanced Mode project", async () => {
1149
+ // set up the directory of static files to upload.
1150
+ mkdirSync("public");
1151
+ writeFileSync("public/README.md", "This is a readme");
1152
+
1153
+ // set up _worker.js
1154
+ writeFileSync(
1155
+ "public/_worker.js",
1156
+ `
1157
+ export default {
1158
+ async fetch(request, env) {
1159
+ const url = new URL(request.url);
1160
+ return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
1161
+ };
1162
+ `
1163
+ );
1164
+
1165
+ mockGetToken("<<funfetti-auth-jwt>>");
1166
+
1167
+ setMockResponse(
1168
+ "/pages/assets/check-missing",
1169
+ "POST",
1170
+ async (_, init) => {
1171
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
1172
+ assertLater(() => {
1173
+ expect(init.headers).toMatchObject({
1174
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1175
+ });
1176
+ expect(body).toMatchObject({
1177
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1178
+ });
1179
+ });
1180
+ return body.hashes;
1181
+ }
1182
+ );
1183
+
1184
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
1185
+ assertLater(() => {
1186
+ expect(init.headers).toMatchObject({
1187
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1188
+ });
1189
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1190
+ expect(body).toMatchObject([
1191
+ {
1192
+ key: "13a03eaf24ae98378acd36ea00f77f2f",
1193
+ value: Buffer.from("This is a readme").toString("base64"),
1194
+ metadata: {
1195
+ contentType: "text/markdown",
1196
+ },
1197
+ base64: true,
1198
+ },
1199
+ ]);
1200
+ });
1201
+ });
1202
+
1203
+ setMockResponse(
1204
+ "/accounts/:accountId/pages/projects/foo/deployments",
1205
+ async ([_url, accountId], init) => {
1206
+ assertLater(async () => {
1207
+ expect(accountId).toEqual("some-account-id");
1208
+ expect(init.method).toEqual("POST");
1209
+ const body = init.body as FormData;
1210
+ const manifest = JSON.parse(body.get("manifest") as string);
1211
+ const customWorkerJS = await (
1212
+ body.get("_worker.js") as Blob
1213
+ ).text();
1214
+
1215
+ // make sure this is all we uploaded
1216
+ expect([...body.keys()]).toEqual(["manifest", "_worker.js"]);
1217
+
1218
+ expect(manifest).toMatchInlineSnapshot(`
1219
+ Object {
1220
+ "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
1221
+ }
1222
+ `);
1223
+
1224
+ expect(customWorkerJS).toMatchInlineSnapshot(`
1225
+ "
1226
+ export default {
1227
+ async fetch(request, env) {
1228
+ const url = new URL(request.url);
1229
+ return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
1230
+ };
1231
+ "
1232
+ `);
1233
+ });
1234
+
1235
+ return {
1236
+ url: "https://abcxyz.foo.pages.dev/",
1237
+ };
1238
+ }
1239
+ );
1240
+
1241
+ await runWrangler("pages publish public --project-name=foo");
1242
+
1243
+ expect(std.out).toMatchInlineSnapshot(`
1244
+ "✨ Success! Uploaded 1 files (TIMINGS)
1245
+
1246
+ ✨ Uploading _worker.js
1247
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1248
+ `);
1249
+
1250
+ expect(std.err).toMatchInlineSnapshot('""');
1251
+ });
1252
+
1253
+ it("should upload _routes.json for Functions projects, if provided", async () => {
1254
+ // set up the directory of static files to upload.
1255
+ mkdirSync("public");
1256
+ writeFileSync("public/README.md", "This is a readme");
1257
+
1258
+ // set up /functions
1259
+ mkdirSync("functions");
1260
+ writeFileSync(
1261
+ "functions/hello.js",
1262
+ `
1263
+ export async function onRequest() {
1264
+ return new Response("Hello, world!");
1265
+ }
1266
+ `
1267
+ );
1268
+
1269
+ writeFileSync(
1270
+ "functions/goodbye.ts",
1271
+ `
1272
+ export async function onRequest() {
1273
+ return new Response("Bye bye!");
1274
+ }
1275
+ `
1276
+ );
1277
+
1278
+ // set up _routes.json
1279
+ writeFileSync(
1280
+ "public/_routes.json",
1281
+ `
1282
+ {
1283
+ "version": ${ROUTES_SPEC_VERSION},
1284
+ "description": "Custom _routes.json file",
1285
+ "include": ["/hello"],
1286
+ "exclude": []
1287
+ }
1288
+ `
1289
+ );
1290
+
1291
+ mockGetToken("<<funfetti-auth-jwt>>");
1292
+
1293
+ setMockResponse(
1294
+ "/pages/assets/check-missing",
1295
+ "POST",
1296
+ async (_, init) => {
1297
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
1298
+ assertLater(() => {
1299
+ expect(init.headers).toMatchObject({
1300
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1301
+ });
1302
+ expect(body).toMatchObject({
1303
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1304
+ });
1305
+ });
1306
+ return body.hashes;
1307
+ }
1308
+ );
1309
+
1310
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
1311
+ assertLater(() => {
1312
+ expect(init.headers).toMatchObject({
1313
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1314
+ });
1315
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1316
+ expect(body).toMatchObject([
1317
+ {
1318
+ key: "13a03eaf24ae98378acd36ea00f77f2f",
1319
+ value: Buffer.from("This is a readme").toString("base64"),
1320
+ metadata: {
1321
+ contentType: "text/markdown",
1322
+ },
1323
+ base64: true,
1324
+ },
1325
+ ]);
1326
+ });
1327
+ });
1328
+
1329
+ setMockResponse(
1330
+ `/pages/assets/upsert-hashes`,
1331
+ "POST",
1332
+ async (_, init) => {
1333
+ assertLater(() => {
1334
+ expect(init.headers).toMatchObject({
1335
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1336
+ });
1337
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1338
+ expect(body).toMatchObject({
1339
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1340
+ });
1341
+ });
1342
+
1343
+ return Promise.resolve(true);
1344
+ }
1345
+ );
1346
+
1347
+ setMockResponse(
1348
+ "/accounts/:accountId/pages/projects/foo/deployments",
1349
+ async ([_url, accountId], init) => {
1350
+ assertLater(async () => {
1351
+ expect(accountId).toEqual("some-account-id");
1352
+ expect(init.method).toEqual("POST");
1353
+ const body = init.body as FormData;
1354
+ const manifest = JSON.parse(body.get("manifest") as string);
1355
+ const generatedWorkerJS = body.get("_worker.js") as Blob;
1356
+ const customRoutesJSON = await (
1357
+ body.get("_routes.json") as Blob
1358
+ ).text();
1359
+
1360
+ // make sure this is all we uploaded
1361
+ expect([...body.keys()]).toEqual([
1362
+ "manifest",
1363
+ "_worker.js",
1364
+ "_routes.json",
1365
+ ]);
1366
+
1367
+ expect(manifest).toMatchInlineSnapshot(`
1368
+ Object {
1369
+ "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
1370
+ }
1371
+ `);
1372
+
1373
+ // file content of generated `_worker.js` is too massive to snapshot test
1374
+ expect(generatedWorkerJS).not.toBeNull();
1375
+ expect(generatedWorkerJS.size).toBeGreaterThan(0);
1376
+
1377
+ const customRoutes = JSON.parse(customRoutesJSON);
1378
+ expect(customRoutes).toMatchObject({
1379
+ version: ROUTES_SPEC_VERSION,
1380
+ description: "Custom _routes.json file",
1381
+ include: ["/hello"],
1382
+ exclude: [],
1383
+ });
1384
+ });
1385
+
1386
+ return {
1387
+ url: "https://abcxyz.foo.pages.dev/",
1388
+ };
1389
+ }
1390
+ );
1391
+
1392
+ await runWrangler("pages publish public --project-name=foo");
1393
+
1394
+ expect(std.out).toMatchInlineSnapshot(`
1395
+ "Compiled Worker successfully.
1396
+ ✨ Success! Uploaded 1 files (TIMINGS)
1397
+
1398
+ ✨ Uploading Functions
1399
+ ✨ Uploading _routes.json
1400
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1401
+ `);
1402
+
1403
+ expect(std.warn).toMatchInlineSnapshot(`
1404
+ "▲ [WARNING] _routes.json is an experimental feature and is subject to change. Please use with care.
1405
+
1406
+ "
1407
+ `);
1408
+
1409
+ expect(std.err).toMatchInlineSnapshot('""');
1410
+ });
1411
+
1412
+ it("should not deploy Functions projects that provide an invalid custom _routes.json file", async () => {
1413
+ // set up the directory of static files to upload.
1414
+ mkdirSync("public");
1415
+ writeFileSync("public/README.md", "This is a readme");
1416
+
1417
+ // set up _routes.json
1418
+ writeFileSync(
1419
+ "public/_routes.json",
1420
+ `
1421
+ {
1422
+ "description": "Custom _routes.json file",
1423
+ "include": [],
1424
+ "exclude": []
1425
+ }
1426
+ `
1427
+ );
1428
+
1429
+ // set up /functions
1430
+ mkdirSync("functions");
1431
+ writeFileSync(
1432
+ "functions/hello.js",
1433
+ `
1434
+ export async function onRequest() {
1435
+ return new Response("Hello, world!");
1436
+ }
1437
+ `
1438
+ );
1439
+
1440
+ mockGetToken("<<funfetti-auth-jwt>>");
1441
+
1442
+ setMockResponse(
1443
+ "/pages/assets/check-missing",
1444
+ "POST",
1445
+ async (_, init) => {
1446
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
1447
+ assertLater(() => {
1448
+ expect(init.headers).toMatchObject({
1449
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1450
+ });
1451
+ expect(body).toMatchObject({
1452
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1453
+ });
1454
+ });
1455
+ return body.hashes;
1456
+ }
1457
+ );
1458
+
1459
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
1460
+ assertLater(() => {
1461
+ expect(init.headers).toMatchObject({
1462
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1463
+ });
1464
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1465
+ expect(body).toMatchObject([
1466
+ {
1467
+ key: "13a03eaf24ae98378acd36ea00f77f2f",
1468
+ value: Buffer.from("This is a readme").toString("base64"),
1469
+ metadata: {
1470
+ contentType: "text/markdown",
1471
+ },
1472
+ base64: true,
1473
+ },
1474
+ ]);
1475
+ });
1476
+ });
1477
+
1478
+ await expect(runWrangler("pages publish public --project-name=foo"))
1479
+ .rejects
1480
+ .toThrow(`Invalid _routes.json file found at: public/_routes.json
1481
+ Please make sure the JSON object has the following format:
1482
+ {
1483
+ version: ${ROUTES_SPEC_VERSION};
1484
+ include: string[];
1485
+ exclude: string[];
1486
+ }
1487
+ and that at least one include rule is provided.
1488
+ `);
1489
+ });
1490
+
1491
+ it("should upload _routes.json for Advanced Mode projects, if provided", async () => {
1492
+ // set up the directory of static files to upload.
1493
+ mkdirSync("public");
1494
+ writeFileSync("public/README.md", "This is a readme");
1495
+
1496
+ // set up _routes.json
1497
+ writeFileSync(
1498
+ "public/_routes.json",
1499
+ `
1500
+ {
1501
+ "version": ${ROUTES_SPEC_VERSION},
1502
+ "description": "Custom _routes.json file",
1503
+ "include": ["/api/*"],
1504
+ "exclude": []
1505
+ }
1506
+ `
1507
+ );
1508
+
1509
+ // set up _worker.js
1510
+ writeFileSync(
1511
+ "public/_worker.js",
1512
+ `
1513
+ export default {
1514
+ async fetch(request, env) {
1515
+ const url = new URL(request.url);
1516
+ return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
1517
+ };
1518
+ `
1519
+ );
1520
+
1521
+ mockGetToken("<<funfetti-auth-jwt>>");
1522
+
1523
+ setMockResponse(
1524
+ "/pages/assets/check-missing",
1525
+ "POST",
1526
+ async (_, init) => {
1527
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
1528
+ assertLater(() => {
1529
+ expect(init.headers).toMatchObject({
1530
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1531
+ });
1532
+ expect(body).toMatchObject({
1533
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1534
+ });
1535
+ });
1536
+ return body.hashes;
1537
+ }
1538
+ );
1539
+
1540
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
1541
+ assertLater(() => {
1542
+ expect(init.headers).toMatchObject({
1543
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1544
+ });
1545
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1546
+ expect(body).toMatchObject([
1547
+ {
1548
+ key: "13a03eaf24ae98378acd36ea00f77f2f",
1549
+ value: Buffer.from("This is a readme").toString("base64"),
1550
+ metadata: {
1551
+ contentType: "text/markdown",
1552
+ },
1553
+ base64: true,
1554
+ },
1555
+ ]);
1556
+ });
1557
+ });
1558
+
1559
+ setMockResponse(
1560
+ `/pages/assets/upsert-hashes`,
1561
+ "POST",
1562
+ async (_, init) => {
1563
+ assertLater(() => {
1564
+ expect(init.headers).toMatchObject({
1565
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1566
+ });
1567
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1568
+ expect(body).toMatchObject({
1569
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1570
+ });
1571
+ });
1572
+
1573
+ return Promise.resolve(true);
1574
+ }
1575
+ );
1576
+
1577
+ setMockResponse(
1578
+ "/accounts/:accountId/pages/projects/foo/deployments",
1579
+ async ([_url, accountId], init) => {
1580
+ assertLater(async () => {
1581
+ expect(accountId).toEqual("some-account-id");
1582
+ expect(init.method).toEqual("POST");
1583
+ const body = init.body as FormData;
1584
+ const manifest = JSON.parse(body.get("manifest") as string);
1585
+ const customWorkerJS = await (
1586
+ body.get("_worker.js") as Blob
1587
+ ).text();
1588
+ const customRoutesJSON = await (
1589
+ body.get("_routes.json") as Blob
1590
+ ).text();
1591
+
1592
+ // make sure this is all we uploaded
1593
+ expect([...body.keys()]).toEqual([
1594
+ "manifest",
1595
+ "_worker.js",
1596
+ "_routes.json",
1597
+ ]);
1598
+
1599
+ expect(manifest).toMatchInlineSnapshot(`
1600
+ Object {
1601
+ "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
1602
+ }
1603
+ `);
1604
+
1605
+ expect(customWorkerJS).toMatchInlineSnapshot(`
1606
+ "
1607
+ export default {
1608
+ async fetch(request, env) {
1609
+ const url = new URL(request.url);
1610
+ return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
1611
+ };
1612
+ "
1613
+ `);
1614
+
1615
+ const customRoutes = JSON.parse(customRoutesJSON);
1616
+ expect(customRoutes).toMatchObject({
1617
+ version: ROUTES_SPEC_VERSION,
1618
+ description: "Custom _routes.json file",
1619
+ include: ["/api/*"],
1620
+ exclude: [],
1621
+ });
1622
+ });
1623
+
1624
+ return {
1625
+ url: "https://abcxyz.foo.pages.dev/",
1626
+ };
1627
+ }
1628
+ );
1629
+
1630
+ await runWrangler("pages publish public --project-name=foo");
1631
+
1632
+ expect(std.out).toMatchInlineSnapshot(`
1633
+ "✨ Success! Uploaded 1 files (TIMINGS)
1634
+
1635
+ ✨ Uploading _worker.js
1636
+ ✨ Uploading _routes.json
1637
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1638
+ `);
1639
+
1640
+ expect(std.warn).toMatchInlineSnapshot(`
1641
+ "▲ [WARNING] _routes.json is an experimental feature and is subject to change. Please use with care.
1642
+
1643
+ "
1644
+ `);
1645
+ expect(std.err).toMatchInlineSnapshot(`""`);
1646
+ });
1647
+
1648
+ it("should not deploy Advanced Mode projects that provide an invalid _routes.json file", async () => {
1649
+ // set up the directory of static files to upload.
1650
+ mkdirSync("public");
1651
+ writeFileSync("public/README.md", "This is a readme");
1652
+
1653
+ // set up _routes.json
1654
+ writeFileSync(
1655
+ "public/_routes.json",
1656
+ `
1657
+ {
1658
+ "description": "Custom _routes.json file",
1659
+ "include": [],
1660
+ "exclude": []
1661
+ }
1662
+ `
1663
+ );
1664
+
1665
+ // set up _worker.js
1666
+ writeFileSync(
1667
+ "public/_worker.js",
1668
+ `
1669
+ export default {
1670
+ async fetch(request, env) {
1671
+ const url = new URL(request.url);
1672
+ return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
1673
+ };
1674
+ `
1675
+ );
1676
+
1677
+ mockGetToken("<<funfetti-auth-jwt>>");
1678
+
1679
+ setMockResponse(
1680
+ "/pages/assets/check-missing",
1681
+ "POST",
1682
+ async (_, init) => {
1683
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
1684
+ assertLater(() => {
1685
+ expect(init.headers).toMatchObject({
1686
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1687
+ });
1688
+ expect(body).toMatchObject({
1689
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1690
+ });
1691
+ });
1692
+ return body.hashes;
1693
+ }
1694
+ );
1695
+
1696
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
1697
+ assertLater(() => {
1698
+ expect(init.headers).toMatchObject({
1699
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1700
+ });
1701
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1702
+ expect(body).toMatchObject([
1703
+ {
1704
+ key: "13a03eaf24ae98378acd36ea00f77f2f",
1705
+ value: Buffer.from("This is a readme").toString("base64"),
1706
+ metadata: {
1707
+ contentType: "text/markdown",
1708
+ },
1709
+ base64: true,
1710
+ },
1711
+ ]);
1712
+ });
1713
+ });
1714
+
1715
+ await expect(runWrangler("pages publish public --project-name=foo"))
1716
+ .rejects
1717
+ .toThrow(`Invalid _routes.json file found at: public/_routes.json
1718
+ Please make sure the JSON object has the following format:
1719
+ {
1720
+ version: ${ROUTES_SPEC_VERSION};
1721
+ include: string[];
1722
+ exclude: string[];
1723
+ }
1724
+ and that at least one include rule is provided.
1725
+ `);
1726
+ });
1727
+
1728
+ it("should ignore the entire /functions directory if _worker.js is provided", async () => {
1729
+ // set up the directory of static files to upload.
1730
+ mkdirSync("public");
1731
+ writeFileSync("public/README.md", "This is a readme");
1732
+
1733
+ // set up /functions
1734
+ mkdirSync("functions");
1735
+ writeFileSync(
1736
+ "functions/hello.js",
1737
+ `
1738
+ export async function onRequest() {
1739
+ return new Response("Hello, world!");
1740
+ }
1741
+ `
1742
+ );
1743
+
1744
+ // set up _worker.js
1745
+ writeFileSync(
1746
+ "public/_worker.js",
1747
+ `
1748
+ export default {
1749
+ async fetch(request, env) {
1750
+ const url = new URL(request.url);
1751
+ return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
1752
+ };
1753
+ `
1754
+ );
1755
+
1756
+ mockGetToken("<<funfetti-auth-jwt>>");
1757
+
1758
+ setMockResponse(
1759
+ "/pages/assets/check-missing",
1760
+ "POST",
1761
+ async (_, init) => {
1762
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
1763
+ assertLater(() => {
1764
+ expect(init.headers).toMatchObject({
1765
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1766
+ });
1767
+ expect(body).toMatchObject({
1768
+ hashes: ["13a03eaf24ae98378acd36ea00f77f2f"],
1769
+ });
1770
+ });
1771
+ return body.hashes;
1772
+ }
1773
+ );
1774
+
1775
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
1776
+ assertLater(() => {
1777
+ expect(init.headers).toMatchObject({
1778
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1779
+ });
1780
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1781
+ expect(body).toMatchObject([
1782
+ {
1783
+ key: "13a03eaf24ae98378acd36ea00f77f2f",
1784
+ value: Buffer.from("This is a readme").toString("base64"),
1785
+ metadata: {
1786
+ contentType: "text/markdown",
1787
+ },
1788
+ base64: true,
1789
+ },
1790
+ ]);
1791
+ });
1792
+ });
1793
+
1794
+ setMockResponse(
1795
+ "/accounts/:accountId/pages/projects/foo/deployments",
1796
+ async ([_url, accountId], init) => {
1797
+ assertLater(async () => {
1798
+ expect(accountId).toEqual("some-account-id");
1799
+ expect(init.method).toEqual("POST");
1800
+ const body = init.body as FormData;
1801
+ const manifest = JSON.parse(body.get("manifest") as string);
1802
+ const customWorkerJS = await (
1803
+ body.get("_worker.js") as Blob
1804
+ ).text();
1805
+
1806
+ // make sure this is all we uploaded
1807
+ expect([...body.keys()]).toEqual(["manifest", "_worker.js"]);
1808
+
1809
+ expect(manifest).toMatchInlineSnapshot(`
1810
+ Object {
1811
+ "/README.md": "13a03eaf24ae98378acd36ea00f77f2f",
1812
+ }
1813
+ `);
1814
+
1815
+ expect(customWorkerJS).toMatchInlineSnapshot(`
1816
+ "
1817
+ export default {
1818
+ async fetch(request, env) {
1819
+ const url = new URL(request.url);
1820
+ return url.pathname.startsWith('/api/') ? new Response('Ok') : env.ASSETS.fetch(request);
1821
+ };
1822
+ "
1823
+ `);
1824
+ });
1825
+
1826
+ return {
1827
+ url: "https://abcxyz.foo.pages.dev/",
1828
+ };
1829
+ }
1830
+ );
1831
+
1832
+ await runWrangler("pages publish public --project-name=foo");
1833
+
1834
+ expect(std.out).toMatchInlineSnapshot(`
1835
+ "✨ Success! Uploaded 1 files (TIMINGS)
1836
+
1837
+ ✨ Uploading _worker.js
1838
+ ✨ Deployment complete! Take a peek over at https://abcxyz.foo.pages.dev/"
1839
+ `);
1840
+
1841
+ expect(std.err).toMatchInlineSnapshot('""');
1842
+ });
1843
+ });
1844
+
1845
+ describe("project upload", () => {
1846
+ const ENV_COPY = process.env;
1847
+
1848
+ mockAccountId();
1849
+ mockApiToken();
1850
+ runInTempDir();
1851
+
1852
+ beforeEach(() => {
1853
+ process.env.CI = "true";
1854
+ process.env.CF_PAGES_UPLOAD_JWT = "<<funfetti-auth-jwt>>";
1855
+ });
1856
+
1857
+ afterEach(() => {
1858
+ unsetAllMocks();
1859
+ process.env = ENV_COPY;
1860
+ });
1861
+
1862
+ it("should upload a directory of files with a provided JWT", async () => {
1863
+ writeFileSync("logo.png", "foobar");
1864
+
1865
+ setMockResponse(
1866
+ "/pages/assets/check-missing",
1867
+ "POST",
1868
+ async (_, init) => {
1869
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
1870
+ assertLater(() => {
1871
+ expect(init.headers).toMatchObject({
1872
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1873
+ });
1874
+ expect(body).toMatchObject({
1875
+ hashes: ["2082190357cfd3617ccfe04f340c6247"],
1876
+ });
1877
+ });
1878
+ return body.hashes;
1879
+ }
1880
+ );
1881
+
1882
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
1883
+ assertLater(() => {
1884
+ expect(init.headers).toMatchObject({
1885
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1886
+ });
1887
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
1888
+ expect(body).toMatchObject([
1889
+ {
1890
+ key: "2082190357cfd3617ccfe04f340c6247",
1891
+ value: Buffer.from("foobar").toString("base64"),
1892
+ metadata: {
1893
+ contentType: "image/png",
1894
+ },
1895
+ base64: true,
1896
+ },
1897
+ ]);
1898
+ });
1899
+ });
1900
+
1901
+ await runWrangler("pages project upload .");
1902
+
1903
+ expect(std.out).toMatchInlineSnapshot(`
1904
+ "✨ Success! Uploaded 1 files (TIMINGS)
1905
+
1906
+ ✨ Upload complete!"
1907
+ `);
1908
+ });
1909
+
1910
+ it("should avoid uploading some files", async () => {
1911
+ mkdirSync("some_dir/node_modules", { recursive: true });
1912
+ mkdirSync("some_dir/functions", { recursive: true });
1913
+
1914
+ writeFileSync("logo.png", "foobar");
1915
+ writeFileSync("some_dir/functions/foo.js", "func");
1916
+ writeFileSync("some_dir/_headers", "headersfile");
1917
+
1918
+ writeFileSync("_headers", "headersfile");
1919
+ writeFileSync("_redirects", "redirectsfile");
1920
+ writeFileSync("_worker.js", "workerfile");
1921
+ writeFileSync("_routes.json", "routesfile");
1922
+ mkdirSync(".git");
1923
+ writeFileSync(".git/foo", "gitfile");
1924
+ writeFileSync("some_dir/node_modules/some_package", "nodefile");
1925
+ mkdirSync("functions");
1926
+ writeFileSync("functions/foo.js", "func");
1927
+
1928
+ setMockResponse(
1929
+ "/pages/assets/check-missing",
1930
+ "POST",
1931
+ async (_, init) => {
1932
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
1933
+ assertLater(() => {
1934
+ expect(init.headers).toMatchObject({
1935
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1936
+ });
1937
+ expect(body).toMatchObject({
1938
+ hashes: [
1939
+ "2082190357cfd3617ccfe04f340c6247",
1940
+ "95dedb64e6d4940fc2e0f11f711cc2f4",
1941
+ "09a79777abda8ccc8bdd51dd3ff8e9e9",
1942
+ ],
1943
+ });
1944
+ });
1945
+ return body.hashes;
1946
+ }
1947
+ );
1948
+
1949
+ // Accumulate multiple requests then assert afterwards
1950
+ const requests: RequestInit[] = [];
1951
+ setMockRawResponse("/pages/assets/upload", "POST", async (_, init) => {
1952
+ requests.push(init);
1953
+
1954
+ return createFetchResult(null, true);
1955
+ });
1956
+
1957
+ assertLater(() => {
1958
+ expect(requests.length).toBe(3);
1959
+
1960
+ expect(requests[0].headers).toMatchObject({
1961
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1962
+ });
1963
+
1964
+ let body = JSON.parse(
1965
+ requests[0].body as string
1966
+ ) as UploadPayloadFile[];
1967
+ expect(body).toMatchObject([
1968
+ {
1969
+ key: "95dedb64e6d4940fc2e0f11f711cc2f4",
1970
+ value: Buffer.from("headersfile").toString("base64"),
1971
+ metadata: {
1972
+ contentType: "application/octet-stream",
1973
+ },
1974
+ base64: true,
1975
+ },
1976
+ ]);
1977
+
1978
+ expect(requests[1].headers).toMatchObject({
1979
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1980
+ });
1981
+
1982
+ body = JSON.parse(requests[1].body as string) as UploadPayloadFile[];
1983
+ expect(body).toMatchObject([
1984
+ {
1985
+ key: "2082190357cfd3617ccfe04f340c6247",
1986
+ value: Buffer.from("foobar").toString("base64"),
1987
+ metadata: {
1988
+ contentType: "image/png",
1989
+ },
1990
+ base64: true,
1991
+ },
1992
+ ]);
1993
+
1994
+ expect(requests[2].headers).toMatchObject({
1995
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
1996
+ });
1997
+
1998
+ body = JSON.parse(requests[2].body as string) as UploadPayloadFile[];
1999
+ expect(body).toMatchObject([
2000
+ {
2001
+ key: "09a79777abda8ccc8bdd51dd3ff8e9e9",
2002
+ value: Buffer.from("func").toString("base64"),
2003
+ metadata: {
2004
+ contentType: "application/javascript",
2005
+ },
2006
+ base64: true,
2007
+ },
2008
+ ]);
2009
+ });
2010
+
2011
+ await runWrangler("pages project upload .");
2012
+
2013
+ expect(std.out).toMatchInlineSnapshot(`
2014
+ "✨ Success! Uploaded 3 files (TIMINGS)
2015
+
2016
+ ✨ Upload complete!"
2017
+ `);
2018
+ });
2019
+
2020
+ it("should retry uploads", async () => {
2021
+ writeFileSync("logo.txt", "foobar");
2022
+
2023
+ setMockResponse(
2024
+ "/pages/assets/check-missing",
2025
+ "POST",
2026
+ async (_, init) => {
2027
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
2028
+ assertLater(() => {
2029
+ expect(init.headers).toMatchObject({
2030
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
2031
+ });
2032
+ expect(body).toMatchObject({
2033
+ hashes: ["1a98fb08af91aca4a7df1764a2c4ddb0"],
2034
+ });
2035
+ });
2036
+ return body.hashes;
2037
+ }
2038
+ );
2039
+
2040
+ // Accumulate multiple requests then assert afterwards
2041
+ const requests: RequestInit[] = [];
2042
+ setMockRawResponse("/pages/assets/upload", "POST", async (_, init) => {
2043
+ requests.push(init);
2044
+
2045
+ if (requests.length < 2) {
2046
+ return createFetchResult(null, false, [
2047
+ {
2048
+ code: 800000,
2049
+ message: "Something exploded, please retry",
2050
+ },
2051
+ ]);
2052
+ } else {
2053
+ return createFetchResult(null, true);
2054
+ }
2055
+ });
2056
+
2057
+ await runWrangler("pages project upload .");
2058
+
2059
+ // Assert two identical requests
2060
+ expect(requests.length).toBe(2);
2061
+ for (const init of requests) {
2062
+ assertLater(() => {
2063
+ expect(init.headers).toMatchObject({
2064
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
2065
+ });
2066
+
2067
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
2068
+ expect(body).toMatchObject([
2069
+ {
2070
+ key: "1a98fb08af91aca4a7df1764a2c4ddb0",
2071
+ value: Buffer.from("foobar").toString("base64"),
2072
+ metadata: {
2073
+ contentType: "text/plain",
2074
+ },
2075
+ base64: true,
2076
+ },
2077
+ ]);
2078
+ });
2079
+ }
2080
+
2081
+ expect(std.out).toMatchInlineSnapshot(`
2082
+ "✨ Success! Uploaded 1 files (TIMINGS)
2083
+
2084
+ ✨ Upload complete!"
2085
+ `);
2086
+ });
2087
+
2088
+ it("should try to use multiple buckets (up to the max concurrency)", async () => {
2089
+ writeFileSync("logo.txt", "foobar");
2090
+ writeFileSync("logo.png", "foobar");
2091
+ writeFileSync("logo.html", "foobar");
2092
+ writeFileSync("logo.js", "foobar");
2093
+
2094
+ mockGetToken("<<funfetti-auth-jwt>>");
2095
+
2096
+ setMockResponse(
2097
+ "/pages/assets/check-missing",
2098
+ "POST",
2099
+ async (_, init) => {
2100
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
2101
+ assertLater(() => {
2102
+ expect(init.headers).toMatchObject({
2103
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
2104
+ });
2105
+ expect(body).toMatchObject({
2106
+ hashes: expect.arrayContaining([
2107
+ "d96fef225537c9f5e44a3cb27fd0b492",
2108
+ "2082190357cfd3617ccfe04f340c6247",
2109
+ "6be321bef99e758250dac034474ddbb8",
2110
+ "1a98fb08af91aca4a7df1764a2c4ddb0",
2111
+ ]),
2112
+ });
2113
+ });
2114
+ return body.hashes;
2115
+ }
2116
+ );
2117
+
2118
+ // Accumulate multiple requests then assert afterwards
2119
+ const requests: RequestInit[] = [];
2120
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
2121
+ requests.push(init);
2122
+ });
2123
+
2124
+ await runWrangler("pages project upload .");
2125
+
2126
+ // We have 3 buckets, so expect 3 uploads
2127
+ expect(requests.length).toBe(3);
2128
+ const bodies: UploadPayloadFile[][] = [];
2129
+ for (const init of requests) {
2130
+ expect(init.headers).toMatchObject({
2131
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
2132
+ });
2133
+ bodies.push(JSON.parse(init.body as string) as UploadPayloadFile[]);
2134
+ }
2135
+ // One bucket should end up with 2 files
2136
+ expect(bodies.map((b) => b.length).sort()).toEqual([1, 1, 2]);
2137
+ // But we don't know the order, so flatten and test without ordering
2138
+ expect(bodies.flatMap((b) => b)).toEqual(
2139
+ expect.arrayContaining([
2140
+ {
2141
+ base64: true,
2142
+ key: "d96fef225537c9f5e44a3cb27fd0b492",
2143
+ metadata: { contentType: "text/html" },
2144
+ value: "Zm9vYmFy",
2145
+ },
2146
+ {
2147
+ base64: true,
2148
+ key: "1a98fb08af91aca4a7df1764a2c4ddb0",
2149
+ metadata: { contentType: "text/plain" },
2150
+ value: "Zm9vYmFy",
2151
+ },
2152
+ {
2153
+ base64: true,
2154
+ key: "6be321bef99e758250dac034474ddbb8",
2155
+ metadata: { contentType: "application/javascript" },
2156
+ value: "Zm9vYmFy",
2157
+ },
2158
+ {
2159
+ base64: true,
2160
+ key: "2082190357cfd3617ccfe04f340c6247",
2161
+ metadata: { contentType: "image/png" },
2162
+ value: "Zm9vYmFy",
2163
+ },
2164
+ ])
2165
+ );
2166
+
2167
+ expect(std.out).toMatchInlineSnapshot(`
2168
+ "✨ Success! Uploaded 4 files (TIMINGS)
2169
+
2170
+ ✨ Upload complete!"
2171
+ `);
2172
+ });
2173
+
2174
+ it("should not error when directory names contain periods and houses a extensionless file", async () => {
2175
+ mkdirSync(".well-known");
2176
+ // Note: same content as previous test, but since it's a different extension,
2177
+ // it hashes to a different value
2178
+ writeFileSync(".well-known/foobar", "foobar");
2179
+
2180
+ mockGetToken("<<funfetti-auth-jwt>>");
2181
+
2182
+ setMockResponse(
2183
+ "/pages/assets/check-missing",
2184
+ "POST",
2185
+ async (_, init) => {
2186
+ const body = JSON.parse(init.body as string) as { hashes: string[] };
2187
+ assertLater(() => {
2188
+ expect(init.headers).toMatchObject({
2189
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
2190
+ });
2191
+ expect(body).toMatchObject({
2192
+ hashes: ["7b764dacfd211bebd8077828a7ddefd7"],
2193
+ });
2194
+ });
2195
+ return body.hashes;
2196
+ }
2197
+ );
2198
+
2199
+ setMockResponse("/pages/assets/upload", "POST", async (_, init) => {
2200
+ assertLater(() => {
2201
+ expect(init.headers).toMatchObject({
2202
+ Authorization: "Bearer <<funfetti-auth-jwt>>",
2203
+ });
2204
+ const body = JSON.parse(init.body as string) as UploadPayloadFile[];
2205
+ expect(body).toMatchObject([
2206
+ {
2207
+ key: "7b764dacfd211bebd8077828a7ddefd7",
2208
+ value: Buffer.from("foobar").toString("base64"),
2209
+ metadata: {
2210
+ contentType: "application/octet-stream",
2211
+ },
2212
+ base64: true,
2213
+ },
2214
+ ]);
2215
+ });
2216
+ });
2217
+
2218
+ await runWrangler("pages project upload .");
2219
+
2220
+ expect(std.err).toMatchInlineSnapshot(`""`);
2221
+ });
2222
+ });
754
2223
  });