wrangler 0.0.0-e928f94 → 0.0.0-e93063e9

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