wrangler 0.0.0-e2f9bb2 → 0.0.0-e30d1013

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