wrangler 0.0.0-e978986 → 0.0.0-e98613f8

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