wrangler 0.0.0-e1b8ac4 → 0.0.0-e1c2f5b9

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