wrangler 0.0.0-e2f9bb2 → 0.0.0-e305903a

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