wrangler 0.0.0-e3cab74 → 0.0.0-e452a35

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 (102) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +49 -5
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +42 -28
  6. package/pages/functions/buildPlugin.ts +105 -0
  7. package/pages/functions/buildWorker.ts +93 -4
  8. package/pages/functions/filepath-routing.test.ts +136 -25
  9. package/pages/functions/filepath-routing.ts +14 -3
  10. package/pages/functions/routes.ts +6 -1
  11. package/pages/functions/template-plugin.ts +147 -0
  12. package/pages/functions/template-worker.ts +21 -8
  13. package/src/__tests__/config-cache.test.ts +36 -0
  14. package/src/__tests__/configuration.test.ts +1514 -367
  15. package/src/__tests__/dev.test.tsx +870 -84
  16. package/src/__tests__/guess-worker-format.test.ts +37 -18
  17. package/src/__tests__/helpers/mock-account-id.ts +22 -4
  18. package/src/__tests__/helpers/mock-cfetch.ts +8 -4
  19. package/src/__tests__/helpers/mock-console.ts +35 -10
  20. package/src/__tests__/helpers/mock-dialogs.ts +26 -1
  21. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  22. package/src/__tests__/helpers/mock-istty.ts +27 -0
  23. package/src/__tests__/helpers/mock-kv.ts +9 -16
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +10 -0
  27. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  28. package/src/__tests__/https-options.test.ts +130 -0
  29. package/src/__tests__/index.test.ts +137 -747
  30. package/src/__tests__/init.test.ts +1557 -0
  31. package/src/__tests__/jest.setup.ts +28 -8
  32. package/src/__tests__/kv.test.ts +598 -258
  33. package/src/__tests__/logger.test.ts +115 -0
  34. package/src/__tests__/pages.test.ts +657 -0
  35. package/src/__tests__/parse.test.ts +8 -0
  36. package/src/__tests__/publish.test.ts +4003 -941
  37. package/src/__tests__/r2.test.ts +69 -34
  38. package/src/__tests__/route.test.ts +45 -0
  39. package/src/__tests__/secret.test.ts +228 -73
  40. package/src/__tests__/tail.test.ts +146 -20
  41. package/src/__tests__/user.test.ts +131 -0
  42. package/src/__tests__/whoami.test.tsx +26 -7
  43. package/src/abort.d.ts +3 -0
  44. package/src/bundle.ts +74 -7
  45. package/src/cfetch/index.ts +21 -4
  46. package/src/cfetch/internal.ts +20 -14
  47. package/src/cli.ts +5 -11
  48. package/src/config/README.md +7 -7
  49. package/src/config/config.ts +69 -100
  50. package/src/config/environment.ts +119 -4
  51. package/src/config/index.ts +177 -4
  52. package/src/config/validation-helpers.ts +228 -23
  53. package/src/config/validation.ts +687 -174
  54. package/src/config-cache.ts +45 -0
  55. package/src/{api/preview.ts → create-worker-preview.ts} +74 -36
  56. package/src/{api/form_data.ts → create-worker-upload-form.ts} +55 -18
  57. package/src/dev/dev-vars.ts +36 -0
  58. package/src/dev/dev.tsx +422 -0
  59. package/src/dev/local.tsx +318 -0
  60. package/src/dev/remote.tsx +227 -0
  61. package/src/dev/use-esbuild.ts +118 -0
  62. package/src/dialogs.tsx +16 -6
  63. package/src/durable.ts +102 -0
  64. package/src/entry.ts +279 -14
  65. package/src/environment-variables.ts +3 -1
  66. package/src/errors.ts +11 -0
  67. package/src/https-options.ts +123 -0
  68. package/src/index.tsx +1268 -806
  69. package/src/inspect.ts +64 -11
  70. package/src/intl-polyfill.d.ts +139 -0
  71. package/src/{kv.tsx → kv.ts} +195 -62
  72. package/src/logger.ts +66 -0
  73. package/src/miniflare-cli/README.md +30 -0
  74. package/src/miniflare-cli/enum-keys.ts +17 -0
  75. package/src/miniflare-cli/index.ts +41 -0
  76. package/src/miniflare-cli/request-context.ts +40 -0
  77. package/src/module-collection.ts +94 -6
  78. package/src/open-in-browser.ts +9 -3
  79. package/src/package-manager.ts +9 -8
  80. package/src/pages.tsx +1057 -75
  81. package/src/parse.ts +24 -5
  82. package/src/proxy.ts +143 -54
  83. package/src/publish.ts +444 -229
  84. package/src/selfsigned.d.ts +29 -0
  85. package/src/sites.tsx +98 -44
  86. package/src/tail/index.ts +2 -2
  87. package/src/tail/printing.ts +13 -8
  88. package/src/update-check.ts +19 -0
  89. package/src/user.tsx +263 -109
  90. package/src/whoami.tsx +2 -1
  91. package/src/{api/worker.ts → worker.ts} +24 -30
  92. package/templates/gitignore +171 -0
  93. package/templates/new-worker.ts +16 -1
  94. package/templates/static-asset-facade.js +1 -1
  95. package/wrangler-dist/cli.js +55345 -69246
  96. package/src/__tests__/helpers/mock-user.ts +0 -27
  97. package/src/__tests__/logout.test.ts +0 -50
  98. package/src/__tests__/sentry.test.ts +0 -146
  99. package/src/dev.tsx +0 -961
  100. package/src/guess-worker-format.ts +0 -68
  101. package/src/reporting.ts +0 -115
  102. package/wrangler-dist/cli.js.map +0 -7
package/src/pages.tsx CHANGED
@@ -2,36 +2,118 @@
2
2
 
3
3
  import { execSync, spawn } from "node:child_process";
4
4
  import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { readdir, readFile, stat } from "node:fs/promises";
5
6
  import { tmpdir } from "node:os";
6
- import { join } from "node:path";
7
+ import { dirname, join, sep, extname, basename } from "node:path";
8
+ import { cwd } from "node:process";
7
9
  import { URL } from "node:url";
10
+ import { hash } from "blake3-wasm";
8
11
  import { watch } from "chokidar";
12
+ import { render, Text } from "ink";
13
+ import SelectInput from "ink-select-input";
14
+ import Spinner from "ink-spinner";
15
+ import Table from "ink-table";
9
16
  import { getType } from "mime";
17
+ import PQueue from "p-queue";
18
+ import prettyBytes from "pretty-bytes";
19
+ import React from "react";
20
+ import { format as timeagoFormat } from "timeago.js";
21
+ import { File, FormData } from "undici";
22
+ import { buildPlugin } from "../pages/functions/buildPlugin";
10
23
  import { buildWorker } from "../pages/functions/buildWorker";
11
24
  import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
12
25
  import { writeRoutesModule } from "../pages/functions/routes";
26
+ import { fetchResult } from "./cfetch";
27
+ import { getConfigCache, saveToConfigCache } from "./config-cache";
28
+ import { prompt } from "./dialogs";
29
+ import { FatalError } from "./errors";
30
+ import { logger } from "./logger";
31
+ import { getRequestContextCheckOptions } from "./miniflare-cli/request-context";
13
32
  import openInBrowser from "./open-in-browser";
14
33
  import { toUrlPath } from "./paths";
34
+ import { requireAuth } from "./user";
15
35
  import type { Config } from "../pages/functions/routes";
16
- import type { Headers, Request, fetch } from "@miniflare/core";
36
+ import type {
37
+ Headers as MiniflareHeaders,
38
+ Request as MiniflareRequest,
39
+ fetch as miniflareFetch,
40
+ } from "@miniflare/core";
17
41
  import type { BuildResult } from "esbuild";
18
42
  import type { MiniflareOptions } from "miniflare";
19
- import type { BuilderCallback } from "yargs";
43
+ import type { BuilderCallback, CommandModule } from "yargs";
44
+
45
+ export type Project = {
46
+ name: string;
47
+ subdomain: string;
48
+ domains: Array<string>;
49
+ source?: {
50
+ type: string;
51
+ };
52
+ latest_deployment?: {
53
+ modified_on: string;
54
+ };
55
+ created_on: string;
56
+ production_branch: string;
57
+ };
58
+
59
+ export type Deployment = {
60
+ id: string;
61
+ environment: string;
62
+ deployment_trigger: {
63
+ metadata: {
64
+ commit_hash: string;
65
+ branch: string;
66
+ };
67
+ };
68
+ url: string;
69
+ latest_stage: {
70
+ status: string;
71
+ ended_on: string;
72
+ };
73
+ project_name: string;
74
+ };
75
+
76
+ export type UploadPayloadFile = {
77
+ key: string;
78
+ value: string;
79
+ metadata: { contentType: string };
80
+ base64: boolean;
81
+ };
82
+
83
+ interface PagesConfigCache {
84
+ account_id?: string;
85
+ project_name?: string;
86
+ }
87
+
88
+ const PAGES_CONFIG_CACHE_FILENAME = "pages.json";
89
+ const MAX_BUCKET_SIZE = 50 * 1024 * 1024;
90
+ const MAX_BUCKET_FILE_COUNT = 5000;
91
+ const BULK_UPLOAD_CONCURRENCY = 3;
92
+ const MAX_UPLOAD_ATTEMPTS = 5;
20
93
 
21
94
  // Defer importing miniflare until we really need it. This takes ~0.5s
22
95
  // and also modifies some `stream/web` and `undici` prototypes, so we
23
96
  // don't want to do this if pages commands aren't being called.
24
97
 
25
- const EXIT_CALLBACKS: (() => void)[] = [];
26
- const EXIT = (message?: string, code?: number) => {
27
- if (message) console.log(message);
28
- if (code) process.exitCode = code;
29
- EXIT_CALLBACKS.forEach((callback) => callback());
30
- process.exit(code);
98
+ export const pagesBetaWarning =
99
+ "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose";
100
+
101
+ const isInPagesCI = !!process.env.CF_PAGES;
102
+
103
+ const CLEANUP_CALLBACKS: (() => void)[] = [];
104
+ const CLEANUP = () => {
105
+ CLEANUP_CALLBACKS.forEach((callback) => callback());
106
+ RUNNING_BUILDERS.forEach((builder) => builder.stop?.());
31
107
  };
32
108
 
33
- process.on("SIGINT", () => EXIT());
34
- process.on("SIGTERM", () => EXIT());
109
+ process.on("SIGINT", () => {
110
+ CLEANUP();
111
+ process.exit();
112
+ });
113
+ process.on("SIGTERM", () => {
114
+ CLEANUP();
115
+ process.exit();
116
+ });
35
117
 
36
118
  function isWindows() {
37
119
  return process.platform === "win32";
@@ -91,7 +173,7 @@ function getPort(pid: number) {
91
173
  const match = matches[0];
92
174
  if (match) return parseInt(match[1]);
93
175
  } catch (thrown) {
94
- console.error(
176
+ logger.error(
95
177
  `Error scanning for ports of process with PID ${pid}: ${thrown}`
96
178
  );
97
179
  }
@@ -104,13 +186,15 @@ async function spawnProxyProcess({
104
186
  port?: number;
105
187
  command: (string | number)[];
106
188
  }): Promise<void | number> {
107
- if (command.length === 0)
108
- return EXIT(
189
+ if (command.length === 0) {
190
+ CLEANUP();
191
+ throw new FatalError(
109
192
  "Must specify a directory of static assets to serve or a command to run.",
110
193
  1
111
194
  );
195
+ }
112
196
 
113
- console.log(`Running ${command.join(" ")}...`);
197
+ logger.log(`Running ${command.join(" ")}...`);
114
198
  const proxy = spawn(
115
199
  command[0].toString(),
116
200
  command.slice(1).map((value) => value.toString()),
@@ -122,30 +206,30 @@ async function spawnProxyProcess({
122
206
  },
123
207
  }
124
208
  );
125
- EXIT_CALLBACKS.push(() => {
209
+ CLEANUP_CALLBACKS.push(() => {
126
210
  proxy.kill();
127
211
  });
128
212
 
129
213
  proxy.stdout.on("data", (data) => {
130
- console.log(`[proxy]: ${data}`);
214
+ logger.log(`[proxy]: ${data}`);
131
215
  });
132
216
 
133
217
  proxy.stderr.on("data", (data) => {
134
- console.error(`[proxy]: ${data}`);
218
+ logger.error(`[proxy]: ${data}`);
135
219
  });
136
220
 
137
221
  proxy.on("close", (code) => {
138
- console.error(`Proxy exited with status ${code}.`);
222
+ logger.error(`Proxy exited with status ${code}.`);
139
223
  });
140
224
 
141
225
  // Wait for proxy process to start...
142
226
  while (!proxy.pid) {}
143
227
 
144
228
  if (port === undefined) {
145
- console.log(
229
+ logger.log(
146
230
  `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
147
231
  );
148
- console.log("To skip, specify the proxy port with --proxy.");
232
+ logger.log("To skip, specify the proxy port with --proxy.");
149
233
  await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
150
234
 
151
235
  port = getPids(proxy.pid)
@@ -153,12 +237,13 @@ async function spawnProxyProcess({
153
237
  .filter((port) => port !== undefined)[0];
154
238
 
155
239
  if (port === undefined) {
156
- return EXIT(
240
+ CLEANUP();
241
+ throw new FatalError(
157
242
  "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
158
243
  1
159
244
  );
160
245
  } else {
161
- console.log(`Automatically determined the proxy port to be ${port}.`);
246
+ logger.log(`Automatically determined the proxy port to be ${port}.`);
162
247
  }
163
248
  }
164
249
 
@@ -215,7 +300,7 @@ function generateRulesMatcher<T>(
215
300
  T
216
301
  ][];
217
302
 
218
- return ({ request }: { request: Request }) => {
303
+ return ({ request }: { request: MiniflareRequest }) => {
219
304
  const { pathname, host } = new URL(request.url);
220
305
 
221
306
  return compiledRules
@@ -288,7 +373,7 @@ function generateHeadersMatcher(headersFile: string) {
288
373
  )
289
374
  );
290
375
 
291
- return (request: Request) => {
376
+ return (request: MiniflareRequest) => {
292
377
  const matches = rulesMatcher({
293
378
  request,
294
379
  });
@@ -337,7 +422,7 @@ function generateRedirectsMatcher(redirectsFile: string) {
337
422
  })
338
423
  );
339
424
 
340
- return (request: Request) => {
425
+ return (request: MiniflareRequest) => {
341
426
  const match = rulesMatcher({
342
427
  request,
343
428
  })[0];
@@ -392,7 +477,9 @@ function hasFileExtension(pathname: string) {
392
477
  return /\/.+\.[a-z0-9]+$/i.test(pathname);
393
478
  }
394
479
 
395
- async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
480
+ async function generateAssetsFetch(
481
+ directory: string
482
+ ): Promise<typeof miniflareFetch> {
396
483
  // Defer importing miniflare until we really need it
397
484
  const { Headers, Request, Response } = await import("@miniflare/core");
398
485
 
@@ -425,12 +512,12 @@ async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
425
512
  }).on("change", (path) => {
426
513
  switch (path) {
427
514
  case headersFile: {
428
- console.log("_headers modified. Re-evaluating...");
515
+ logger.log("_headers modified. Re-evaluating...");
429
516
  headersMatcher = generateHeadersMatcher(headersFile);
430
517
  break;
431
518
  }
432
519
  case redirectsFile: {
433
- console.log("_redirects modified. Re-evaluating...");
520
+ logger.log("_redirects modified. Re-evaluating...");
434
521
  redirectsMatcher = generateRedirectsMatcher(redirectsFile);
435
522
  break;
436
523
  }
@@ -441,12 +528,12 @@ async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
441
528
  return readFileSync(file);
442
529
  };
443
530
 
444
- const generateResponse = (request: Request) => {
531
+ const generateResponse = (request: MiniflareRequest) => {
445
532
  const url = new URL(request.url);
446
533
 
447
534
  const deconstructedResponse: {
448
535
  status: number;
449
- headers: Headers;
536
+ headers: MiniflareHeaders;
450
537
  body?: Buffer;
451
538
  } = {
452
539
  status: 200,
@@ -598,8 +685,12 @@ async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
598
685
  };
599
686
 
600
687
  const attachHeaders = (
601
- request: Request,
602
- deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
688
+ request: MiniflareRequest,
689
+ deconstructedResponse: {
690
+ status: number;
691
+ headers: MiniflareHeaders;
692
+ body?: Buffer;
693
+ }
603
694
  ) => {
604
695
  const headers = deconstructedResponse.headers;
605
696
  const newHeaders = new Headers({});
@@ -643,7 +734,7 @@ async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
643
734
  const RUNNING_BUILDERS: BuildResult[] = [];
644
735
 
645
736
  async function buildFunctions({
646
- scriptPath,
737
+ outfile,
647
738
  outputConfigPath,
648
739
  functionsDirectory,
649
740
  minify = false,
@@ -651,8 +742,11 @@ async function buildFunctions({
651
742
  fallbackService = "ASSETS",
652
743
  watch = false,
653
744
  onEnd,
745
+ plugin = false,
746
+ buildOutputDirectory,
747
+ nodeCompat,
654
748
  }: {
655
- scriptPath: string;
749
+ outfile: string;
656
750
  outputConfigPath?: string;
657
751
  functionsDirectory: string;
658
752
  minify?: boolean;
@@ -660,12 +754,15 @@ async function buildFunctions({
660
754
  fallbackService?: string;
661
755
  watch?: boolean;
662
756
  onEnd?: () => void;
757
+ plugin?: boolean;
758
+ buildOutputDirectory?: string;
759
+ nodeCompat?: boolean;
663
760
  }) {
664
761
  RUNNING_BUILDERS.forEach(
665
762
  (runningBuilder) => runningBuilder.stop && runningBuilder.stop()
666
763
  );
667
764
 
668
- const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
765
+ const routesModule = join(tmpdir(), `./functionsRoutes-${Math.random()}.mjs`);
669
766
  const baseURL = toUrlPath("/");
670
767
 
671
768
  const config: Config = await generateConfigFromFileTree({
@@ -686,23 +783,578 @@ async function buildFunctions({
686
783
  outfile: routesModule,
687
784
  });
688
785
 
689
- RUNNING_BUILDERS.push(
690
- await buildWorker({
691
- routesModule,
692
- outfile: scriptPath,
693
- minify,
694
- sourcemap,
695
- fallbackService,
696
- watch,
697
- onEnd,
698
- })
699
- );
786
+ if (plugin) {
787
+ RUNNING_BUILDERS.push(
788
+ await buildPlugin({
789
+ routesModule,
790
+ outfile,
791
+ minify,
792
+ sourcemap,
793
+ watch,
794
+ nodeCompat,
795
+ onEnd,
796
+ })
797
+ );
798
+ } else {
799
+ RUNNING_BUILDERS.push(
800
+ await buildWorker({
801
+ routesModule,
802
+ outfile,
803
+ minify,
804
+ sourcemap,
805
+ fallbackService,
806
+ watch,
807
+ onEnd,
808
+ buildOutputDirectory,
809
+ nodeCompat,
810
+ })
811
+ );
812
+ }
700
813
  }
701
814
 
815
+ interface CreateDeploymentArgs {
816
+ directory: string;
817
+ projectName?: string;
818
+ branch?: string;
819
+ commitHash?: string;
820
+ commitMessage?: string;
821
+ commitDirty?: boolean;
822
+ }
823
+
824
+ const createDeployment: CommandModule<
825
+ CreateDeploymentArgs,
826
+ CreateDeploymentArgs
827
+ > = {
828
+ describe: "🆙 Publish a directory of static assets as a Pages deployment",
829
+ builder: (yargs) => {
830
+ return yargs
831
+ .positional("directory", {
832
+ type: "string",
833
+ demandOption: true,
834
+ description: "The directory of static files to upload",
835
+ })
836
+ .options({
837
+ "project-name": {
838
+ type: "string",
839
+ description: "The name of the project you want to deploy to",
840
+ },
841
+ branch: {
842
+ type: "string",
843
+ description: "The name of the branch you want to deploy to",
844
+ },
845
+ "commit-hash": {
846
+ type: "string",
847
+ description: "The SHA to attach to this deployment",
848
+ },
849
+ "commit-message": {
850
+ type: "string",
851
+ description: "The commit message to attach to this deployment",
852
+ },
853
+ "commit-dirty": {
854
+ type: "boolean",
855
+ description:
856
+ "Whether or not the workspace should be considered dirty for this deployment",
857
+ },
858
+ })
859
+ .epilogue(pagesBetaWarning);
860
+ },
861
+ handler: async ({
862
+ directory,
863
+ projectName,
864
+ branch,
865
+ commitHash,
866
+ commitMessage,
867
+ commitDirty,
868
+ }) => {
869
+ if (!directory) {
870
+ throw new FatalError("Must specify a directory.", 1);
871
+ }
872
+
873
+ const config = getConfigCache<PagesConfigCache>(
874
+ PAGES_CONFIG_CACHE_FILENAME
875
+ );
876
+ const accountId = await requireAuth(config);
877
+
878
+ projectName ??= config.project_name;
879
+
880
+ const isInteractive = process.stdin.isTTY;
881
+ if (!projectName && isInteractive) {
882
+ const projects = (await listProjects({ accountId })).filter(
883
+ (project) => !project.source
884
+ );
885
+
886
+ let existingOrNew: "existing" | "new" = "new";
887
+
888
+ if (projects.length > 0) {
889
+ existingOrNew = await new Promise<"new" | "existing">((resolve) => {
890
+ const { unmount } = render(
891
+ <>
892
+ <Text>
893
+ No project selected. Would you like to create one or use an
894
+ existing project?
895
+ </Text>
896
+ <SelectInput
897
+ items={[
898
+ {
899
+ key: "new",
900
+ label: "Create a new project",
901
+ value: "new",
902
+ },
903
+ {
904
+ key: "existing",
905
+ label: "Use an existing project",
906
+ value: "existing",
907
+ },
908
+ ]}
909
+ onSelect={async (selected) => {
910
+ resolve(selected.value as "new" | "existing");
911
+ unmount();
912
+ }}
913
+ />
914
+ </>
915
+ );
916
+ });
917
+ }
918
+
919
+ switch (existingOrNew) {
920
+ case "existing": {
921
+ projectName = await new Promise((resolve) => {
922
+ const { unmount } = render(
923
+ <>
924
+ <Text>Select a project:</Text>
925
+ <SelectInput
926
+ items={projects.map((project) => ({
927
+ key: project.name,
928
+ label: project.name,
929
+ value: project,
930
+ }))}
931
+ onSelect={async (selected) => {
932
+ resolve(selected.value.name);
933
+ unmount();
934
+ }}
935
+ />
936
+ </>
937
+ );
938
+ });
939
+ break;
940
+ }
941
+ case "new": {
942
+ projectName = await prompt("Enter the name of your new project:");
943
+
944
+ if (!projectName) {
945
+ throw new FatalError("Must specify a project name.", 1);
946
+ }
947
+
948
+ let isGitDir = true;
949
+ try {
950
+ execSync(`git rev-parse --is-inside-work-tree`, {
951
+ stdio: "ignore",
952
+ });
953
+ } catch (err) {
954
+ isGitDir = false;
955
+ }
956
+
957
+ const productionBranch = await prompt(
958
+ "Enter the production branch name:",
959
+ "text",
960
+ isGitDir
961
+ ? execSync(`git rev-parse --abbrev-ref HEAD`).toString().trim()
962
+ : "production"
963
+ );
964
+
965
+ if (!productionBranch) {
966
+ throw new FatalError("Must specify a production branch.", 1);
967
+ }
968
+
969
+ await fetchResult<Project>(`/accounts/${accountId}/pages/projects`, {
970
+ method: "POST",
971
+ body: JSON.stringify({
972
+ name: projectName,
973
+ production_branch: productionBranch,
974
+ }),
975
+ });
976
+
977
+ saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
978
+ account_id: accountId,
979
+ project_name: projectName,
980
+ });
981
+
982
+ logger.log(`✨ Successfully created the '${projectName}' project.`);
983
+ break;
984
+ }
985
+ }
986
+ }
987
+
988
+ if (!projectName) {
989
+ throw new FatalError("Must specify a project name.", 1);
990
+ }
991
+
992
+ // We infer git info by default is not passed in
993
+
994
+ let isGitDir = true;
995
+ try {
996
+ execSync(`git rev-parse --is-inside-work-tree`, {
997
+ stdio: "ignore",
998
+ });
999
+ } catch (err) {
1000
+ isGitDir = false;
1001
+ }
1002
+
1003
+ let isGitDirty = false;
1004
+
1005
+ if (isGitDir) {
1006
+ try {
1007
+ isGitDirty = Boolean(
1008
+ execSync(`git status --porcelain`).toString().length
1009
+ );
1010
+
1011
+ if (!branch) {
1012
+ branch = execSync(`git rev-parse --abbrev-ref HEAD`)
1013
+ .toString()
1014
+ .trim();
1015
+ }
1016
+
1017
+ if (!commitHash) {
1018
+ commitHash = execSync(`git rev-parse HEAD`).toString().trim();
1019
+ }
1020
+
1021
+ if (!commitMessage) {
1022
+ commitMessage = execSync(`git show -s --format=%B ${commitHash}`)
1023
+ .toString()
1024
+ .trim();
1025
+ }
1026
+ } catch (err) {}
1027
+
1028
+ if (isGitDirty && !commitDirty) {
1029
+ logger.warn(
1030
+ `Warning: Your working directory is a git repo and has uncommitted changes\nTo silence this warning, pass in --commit-dirty=true`
1031
+ );
1032
+ }
1033
+
1034
+ if (commitDirty === undefined) {
1035
+ commitDirty = isGitDirty;
1036
+ }
1037
+ }
1038
+
1039
+ let builtFunctions: string | undefined = undefined;
1040
+ const functionsDirectory = join(cwd(), "functions");
1041
+ if (existsSync(functionsDirectory)) {
1042
+ const outfile = join(tmpdir(), `./functionsWorker-${Math.random()}.js`);
1043
+
1044
+ await new Promise((resolve) =>
1045
+ buildFunctions({
1046
+ outfile,
1047
+ functionsDirectory,
1048
+ onEnd: () => resolve(null),
1049
+ buildOutputDirectory: dirname(outfile),
1050
+ })
1051
+ );
1052
+
1053
+ builtFunctions = readFileSync(outfile, "utf-8");
1054
+ }
1055
+
1056
+ type FileContainer = {
1057
+ content: string;
1058
+ contentType: string;
1059
+ sizeInBytes: number;
1060
+ hash: string;
1061
+ };
1062
+
1063
+ const IGNORE_LIST = [
1064
+ "_worker.js",
1065
+ "_redirects",
1066
+ "_headers",
1067
+ ".DS_Store",
1068
+ "node_modules",
1069
+ ".git",
1070
+ ];
1071
+
1072
+ const walk = async (
1073
+ dir: string,
1074
+ fileMap: Map<string, FileContainer> = new Map(),
1075
+ depth = 0
1076
+ ) => {
1077
+ const files = await readdir(dir);
1078
+
1079
+ await Promise.all(
1080
+ files.map(async (file) => {
1081
+ const filepath = join(dir, file);
1082
+ const filestat = await stat(filepath);
1083
+
1084
+ if (IGNORE_LIST.includes(file)) {
1085
+ return;
1086
+ }
1087
+
1088
+ if (filestat.isSymbolicLink()) {
1089
+ return;
1090
+ }
1091
+
1092
+ if (filestat.isDirectory()) {
1093
+ fileMap = await walk(filepath, fileMap, depth + 1);
1094
+ } else {
1095
+ let name;
1096
+ if (depth) {
1097
+ name = filepath.split(sep).slice(1).join("/");
1098
+ } else {
1099
+ name = file;
1100
+ }
1101
+
1102
+ // TODO: Move this to later so we don't hold as much in memory
1103
+ const fileContent = await readFile(filepath);
1104
+
1105
+ const base64Content = fileContent.toString("base64");
1106
+ const extension = extname(basename(name)).substring(1);
1107
+
1108
+ if (filestat.size > 25 * 1024 * 1024) {
1109
+ throw new Error(
1110
+ `Error: Pages only supports files up to ${prettyBytes(
1111
+ 25 * 1024 * 1024
1112
+ )} in size\n${name} is ${prettyBytes(filestat.size)} in size`
1113
+ );
1114
+ }
1115
+
1116
+ fileMap.set(name, {
1117
+ content: base64Content,
1118
+ contentType: getType(name) || "application/octet-stream",
1119
+ sizeInBytes: filestat.size,
1120
+ hash: hash(base64Content + extension)
1121
+ .toString("hex")
1122
+ .slice(0, 32),
1123
+ });
1124
+ }
1125
+ })
1126
+ );
1127
+
1128
+ return fileMap;
1129
+ };
1130
+
1131
+ const fileMap = await walk(directory);
1132
+
1133
+ if (fileMap.size > 20000) {
1134
+ throw new FatalError(
1135
+ `Error: Pages only supports up to 20,000 files in a deployment. Ensure you have specified your build output directory correctly.`,
1136
+ 1
1137
+ );
1138
+ }
1139
+
1140
+ const files = [...fileMap.values()];
1141
+
1142
+ const { jwt } = await fetchResult<{ jwt: string }>(
1143
+ `/accounts/${accountId}/pages/projects/${projectName}/upload-token`
1144
+ );
1145
+
1146
+ const start = Date.now();
1147
+
1148
+ const missingHashes = await fetchResult<string[]>(
1149
+ `/pages/assets/check-missing`,
1150
+ {
1151
+ method: "POST",
1152
+ headers: {
1153
+ "Content-Type": "application/json",
1154
+ Authorization: `Bearer ${jwt}`,
1155
+ },
1156
+ body: JSON.stringify({
1157
+ hashes: files.map(({ hash }) => hash),
1158
+ }),
1159
+ }
1160
+ );
1161
+
1162
+ const sortedFiles = files
1163
+ .filter((file) => missingHashes.includes(file.hash))
1164
+ .sort((a, b) => b.sizeInBytes - a.sizeInBytes);
1165
+
1166
+ // Start with a few buckets so small projects still get
1167
+ // the benefit of multiple upload streams
1168
+ const buckets: {
1169
+ files: FileContainer[];
1170
+ remainingSize: number;
1171
+ }[] = new Array(BULK_UPLOAD_CONCURRENCY).fill(null).map(() => ({
1172
+ files: [],
1173
+ remainingSize: MAX_BUCKET_SIZE,
1174
+ }));
1175
+
1176
+ let bucketOffset = 0;
1177
+ for (const file of sortedFiles) {
1178
+ let inserted = false;
1179
+
1180
+ for (let i = 0; i < buckets.length; i++) {
1181
+ // Start at a different bucket for each new file
1182
+ const bucket = buckets[(i + bucketOffset) % buckets.length];
1183
+ if (
1184
+ bucket.remainingSize >= file.sizeInBytes &&
1185
+ bucket.files.length < MAX_BUCKET_FILE_COUNT
1186
+ ) {
1187
+ bucket.files.push(file);
1188
+ bucket.remainingSize -= file.sizeInBytes;
1189
+ inserted = true;
1190
+ break;
1191
+ }
1192
+ }
1193
+
1194
+ if (!inserted) {
1195
+ buckets.push({
1196
+ files: [file],
1197
+ remainingSize: MAX_BUCKET_SIZE - file.sizeInBytes,
1198
+ });
1199
+ }
1200
+ bucketOffset++;
1201
+ }
1202
+
1203
+ let counter = fileMap.size - sortedFiles.length;
1204
+ const { rerender, unmount } = render(
1205
+ <Progress done={counter} total={fileMap.size} />
1206
+ );
1207
+
1208
+ const queue = new PQueue({ concurrency: BULK_UPLOAD_CONCURRENCY });
1209
+
1210
+ for (const bucket of buckets) {
1211
+ // Don't upload empty buckets (can happen for tiny projects)
1212
+ if (bucket.files.length === 0) continue;
1213
+
1214
+ const payload: UploadPayloadFile[] = bucket.files.map((file) => ({
1215
+ key: file.hash,
1216
+ value: file.content,
1217
+ metadata: {
1218
+ contentType: file.contentType,
1219
+ },
1220
+ base64: true,
1221
+ }));
1222
+
1223
+ let attempts = 0;
1224
+ const doUpload = async (): Promise<void> => {
1225
+ try {
1226
+ return await fetchResult(`/pages/assets/upload`, {
1227
+ method: "POST",
1228
+ headers: {
1229
+ "Content-Type": "application/json",
1230
+ Authorization: `Bearer ${jwt}`,
1231
+ },
1232
+ body: JSON.stringify(payload),
1233
+ });
1234
+ } catch (e) {
1235
+ if (attempts < MAX_UPLOAD_ATTEMPTS) {
1236
+ // Linear backoff, 0 second first time, then 1 second etc.
1237
+ await new Promise((resolve) =>
1238
+ setTimeout(resolve, attempts++ * 1000)
1239
+ );
1240
+ return doUpload();
1241
+ } else {
1242
+ throw e;
1243
+ }
1244
+ }
1245
+ };
1246
+
1247
+ queue.add(() =>
1248
+ doUpload().then(
1249
+ () => {
1250
+ counter += bucket.files.length;
1251
+ rerender(<Progress done={counter} total={fileMap.size} />);
1252
+ },
1253
+ (error) => {
1254
+ return Promise.reject(
1255
+ new FatalError(
1256
+ "Failed to upload files. Please try again.",
1257
+ error.code || 1
1258
+ )
1259
+ );
1260
+ }
1261
+ )
1262
+ );
1263
+ }
1264
+
1265
+ await queue.onIdle();
1266
+
1267
+ unmount();
1268
+
1269
+ const uploadMs = Date.now() - start;
1270
+
1271
+ logger.log(
1272
+ `✨ Success! Uploaded ${fileMap.size} files ${formatTime(uploadMs)}\n`
1273
+ );
1274
+
1275
+ const formData = new FormData();
1276
+
1277
+ formData.append(
1278
+ "manifest",
1279
+ JSON.stringify(
1280
+ Object.fromEntries(
1281
+ [...fileMap.entries()].map(([fileName, file]) => [
1282
+ `/${fileName}`,
1283
+ file.hash,
1284
+ ])
1285
+ )
1286
+ )
1287
+ );
1288
+
1289
+ if (branch) {
1290
+ formData.append("branch", branch);
1291
+ }
1292
+
1293
+ if (commitMessage) {
1294
+ formData.append("commit_message", commitMessage);
1295
+ }
1296
+
1297
+ if (commitHash) {
1298
+ formData.append("commit_hash", commitHash);
1299
+ }
1300
+
1301
+ if (commitDirty !== undefined) {
1302
+ formData.append("commit_dirty", commitDirty);
1303
+ }
1304
+
1305
+ let _headers: string | undefined,
1306
+ _redirects: string | undefined,
1307
+ _workerJS: string | undefined;
1308
+
1309
+ try {
1310
+ _headers = readFileSync(join(directory, "_headers"), "utf-8");
1311
+ } catch {}
1312
+
1313
+ try {
1314
+ _redirects = readFileSync(join(directory, "_redirects"), "utf-8");
1315
+ } catch {}
1316
+
1317
+ try {
1318
+ _workerJS = readFileSync(join(directory, "_worker.js"), "utf-8");
1319
+ } catch {}
1320
+
1321
+ if (_headers) {
1322
+ formData.append("_headers", new File([_headers], "_headers"));
1323
+ }
1324
+
1325
+ if (_redirects) {
1326
+ formData.append("_redirects", new File([_redirects], "_redirects"));
1327
+ }
1328
+
1329
+ if (builtFunctions) {
1330
+ formData.append("_worker.js", new File([builtFunctions], "_worker.js"));
1331
+ } else if (_workerJS) {
1332
+ formData.append("_worker.js", new File([_workerJS], "_worker.js"));
1333
+ }
1334
+
1335
+ const deploymentResponse = await fetchResult<Deployment>(
1336
+ `/accounts/${accountId}/pages/projects/${projectName}/deployments`,
1337
+ {
1338
+ method: "POST",
1339
+ body: formData,
1340
+ }
1341
+ );
1342
+
1343
+ saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1344
+ account_id: accountId,
1345
+ project_name: projectName,
1346
+ });
1347
+
1348
+ logger.log(
1349
+ `✨ Deployment complete! Take a peek over at ${deploymentResponse.url}`
1350
+ );
1351
+ },
1352
+ };
1353
+
702
1354
  export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
703
1355
  return yargs
704
1356
  .command(
705
- "dev [directory] [-- command]",
1357
+ "dev [directory] [-- command..]",
706
1358
  "🧑‍💻 Develop your full-stack Pages application locally",
707
1359
  (yargs) => {
708
1360
  return yargs
@@ -758,8 +1410,15 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
758
1410
  default: false,
759
1411
  description: "Auto reload HTML pages when change is detected",
760
1412
  },
1413
+ "node-compat": {
1414
+ describe: "Enable node.js compatibility",
1415
+ default: false,
1416
+ type: "boolean",
1417
+ hidden: true,
1418
+ },
761
1419
  // TODO: Miniflare user options
762
- });
1420
+ })
1421
+ .epilogue(pagesBetaWarning);
763
1422
  },
764
1423
  async ({
765
1424
  local,
@@ -771,10 +1430,14 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
771
1430
  kv: kvs = [],
772
1431
  do: durableObjects = [],
773
1432
  "live-reload": liveReload,
1433
+ "node-compat": nodeCompat,
774
1434
  _: [_pages, _dev, ...remaining],
775
1435
  }) => {
1436
+ // Beta message for `wrangler pages <commands>` usage
1437
+ logger.log(pagesBetaWarning);
1438
+
776
1439
  if (!local) {
777
- console.error("Only local mode is supported at the moment.");
1440
+ logger.error("Only local mode is supported at the moment.");
778
1441
  return;
779
1442
  }
780
1443
 
@@ -801,33 +1464,48 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
801
1464
  );
802
1465
 
803
1466
  if (usingFunctions) {
804
- const scriptPath = join(tmpdir(), "./functionsWorker.js");
1467
+ const outfile = join(
1468
+ tmpdir(),
1469
+ `./functionsWorker-${Math.random()}.js`
1470
+ );
805
1471
 
806
- console.log(`Compiling worker to "${scriptPath}"...`);
1472
+ if (nodeCompat) {
1473
+ console.warn(
1474
+ "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
1475
+ );
1476
+ }
807
1477
 
808
- await buildFunctions({
809
- scriptPath,
810
- functionsDirectory,
811
- sourcemap: true,
812
- watch: true,
813
- onEnd: () => scriptReadyResolve(),
814
- });
1478
+ logger.log(`Compiling worker to "${outfile}"...`);
1479
+
1480
+ try {
1481
+ await buildFunctions({
1482
+ outfile,
1483
+ functionsDirectory,
1484
+ sourcemap: true,
1485
+ watch: true,
1486
+ onEnd: () => scriptReadyResolve(),
1487
+ buildOutputDirectory: directory,
1488
+ nodeCompat,
1489
+ });
1490
+ } catch {}
815
1491
 
816
1492
  watch([functionsDirectory], {
817
1493
  persistent: true,
818
1494
  ignoreInitial: true,
819
1495
  }).on("all", async () => {
820
1496
  await buildFunctions({
821
- scriptPath,
1497
+ outfile,
822
1498
  functionsDirectory,
823
1499
  sourcemap: true,
824
1500
  watch: true,
825
1501
  onEnd: () => scriptReadyResolve(),
1502
+ buildOutputDirectory: directory,
1503
+ nodeCompat,
826
1504
  });
827
1505
  });
828
1506
 
829
1507
  miniflareArgs = {
830
- scriptPath,
1508
+ scriptPath: outfile,
831
1509
  };
832
1510
  } else {
833
1511
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -843,8 +1521,11 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
843
1521
  scriptPath,
844
1522
  };
845
1523
  } else {
846
- console.log("No functions. Shimming...");
1524
+ logger.log("No functions. Shimming...");
847
1525
  miniflareArgs = {
1526
+ // cfFetch sets the `cf` object that a function could expect
1527
+ // If there are no functions, there's no reason to set this up (and not make that network call)
1528
+ cfFetch: false,
848
1529
  // TODO: The fact that these request/response hacks are necessary is ridiculous.
849
1530
  // We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well)
850
1531
  script: `
@@ -875,6 +1556,9 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
875
1556
  ? await generateAssetsFetch(directory)
876
1557
  : invalidAssetsFetch;
877
1558
 
1559
+ const requestContextCheckOptions =
1560
+ await getRequestContextCheckOptions();
1561
+
878
1562
  const miniflare = new Miniflare({
879
1563
  port,
880
1564
  watch: true,
@@ -895,20 +1579,22 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
895
1579
  // User bindings
896
1580
  bindings: {
897
1581
  ...Object.fromEntries(
898
- bindings.map((binding) => binding.toString().split("="))
1582
+ bindings
1583
+ .map((binding) => binding.toString().split("="))
1584
+ .map(([key, ...values]) => [key, values.join("=")])
899
1585
  ),
900
1586
  },
901
1587
 
902
1588
  // env.ASSETS.fetch
903
1589
  serviceBindings: {
904
- async ASSETS(request: Request) {
1590
+ async ASSETS(request: MiniflareRequest) {
905
1591
  if (proxyPort) {
906
1592
  try {
907
1593
  const url = new URL(request.url);
908
1594
  url.host = `localhost:${proxyPort}`;
909
1595
  return await fetch(url, request);
910
1596
  } catch (thrown) {
911
- console.error(`Could not proxy request: ${thrown}`);
1597
+ logger.error(`Could not proxy request: ${thrown}`);
912
1598
 
913
1599
  // TODO: Pretty error page
914
1600
  return new Response(
@@ -920,7 +1606,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
920
1606
  try {
921
1607
  return await assetsFetch(request);
922
1608
  } catch (thrown) {
923
- console.error(`Could not serve static asset: ${thrown}`);
1609
+ logger.error(`Could not serve static asset: ${thrown}`);
924
1610
 
925
1611
  // TODO: Pretty error page
926
1612
  return new Response(
@@ -937,13 +1623,14 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
937
1623
  cachePersist: true,
938
1624
  liveReload,
939
1625
 
1626
+ ...requestContextCheckOptions,
940
1627
  ...miniflareArgs,
941
1628
  });
942
1629
 
943
1630
  try {
944
1631
  // `startServer` might throw if user code contains errors
945
1632
  const server = await miniflare.startServer();
946
- console.log(`Serving at http://localhost:${port}/`);
1633
+ logger.log(`Serving at http://localhost:${port}/`);
947
1634
 
948
1635
  if (process.env.BROWSER !== "none") {
949
1636
  await openInBrowser(`http://localhost:${port}/`);
@@ -958,13 +1645,14 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
958
1645
  });
959
1646
  }
960
1647
 
961
- EXIT_CALLBACKS.push(() => {
1648
+ CLEANUP_CALLBACKS.push(() => {
962
1649
  server.close();
963
1650
  miniflare.dispose().catch((err) => miniflare.log.error(err));
964
1651
  });
965
1652
  } catch (e) {
966
1653
  miniflare.log.error(e as Error);
967
- EXIT("Could not start Miniflare.", 1);
1654
+ CLEANUP();
1655
+ throw new FatalError("Could not start Miniflare.", 1);
968
1656
  }
969
1657
  }
970
1658
  )
@@ -982,7 +1670,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
982
1670
  description: "The directory of Pages Functions",
983
1671
  })
984
1672
  .options({
985
- "script-path": {
1673
+ outfile: {
986
1674
  type: "string",
987
1675
  default: "_worker.js",
988
1676
  description: "The location of the output Worker script",
@@ -1014,32 +1702,326 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1014
1702
  description:
1015
1703
  "Watch for changes to the functions and automatically rebuild the Worker script",
1016
1704
  },
1017
- }),
1705
+ plugin: {
1706
+ type: "boolean",
1707
+ default: false,
1708
+ description: "Build a plugin rather than a Worker script",
1709
+ },
1710
+ "build-output-directory": {
1711
+ type: "string",
1712
+ description: "The directory to output static assets to",
1713
+ },
1714
+ "node-compat": {
1715
+ describe: "Enable node.js compatibility",
1716
+ default: false,
1717
+ type: "boolean",
1718
+ hidden: true,
1719
+ },
1720
+ })
1721
+ .epilogue(pagesBetaWarning),
1018
1722
  async ({
1019
1723
  directory,
1020
- "script-path": scriptPath,
1724
+ outfile,
1021
1725
  "output-config-path": outputConfigPath,
1022
1726
  minify,
1023
1727
  sourcemap,
1024
1728
  fallbackService,
1025
1729
  watch,
1730
+ plugin,
1731
+ "build-output-directory": buildOutputDirectory,
1732
+ "node-compat": nodeCompat,
1026
1733
  }) => {
1734
+ if (!isInPagesCI) {
1735
+ // Beta message for `wrangler pages <commands>` usage
1736
+ logger.log(pagesBetaWarning);
1737
+ }
1738
+
1739
+ if (nodeCompat) {
1740
+ console.warn(
1741
+ "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
1742
+ );
1743
+ }
1744
+
1745
+ buildOutputDirectory ??= dirname(outfile);
1746
+
1027
1747
  await buildFunctions({
1028
- scriptPath,
1748
+ outfile,
1029
1749
  outputConfigPath,
1030
1750
  functionsDirectory: directory,
1031
1751
  minify,
1032
1752
  sourcemap,
1033
1753
  fallbackService,
1034
1754
  watch,
1755
+ plugin,
1756
+ buildOutputDirectory,
1757
+ nodeCompat,
1035
1758
  });
1036
1759
  }
1037
1760
  )
1038
- );
1761
+ )
1762
+ .command("project", "⚡️ Interact with your Pages projects", (yargs) =>
1763
+ yargs
1764
+ .command(
1765
+ "list",
1766
+ "List your Cloudflare Pages projects",
1767
+ (yargs) => yargs.epilogue(pagesBetaWarning),
1768
+ async () => {
1769
+ const config = getConfigCache<PagesConfigCache>(
1770
+ PAGES_CONFIG_CACHE_FILENAME
1771
+ );
1772
+
1773
+ const accountId = await requireAuth(config);
1774
+
1775
+ const projects: Array<Project> = await listProjects({ accountId });
1776
+
1777
+ const data = projects.map((project) => {
1778
+ return {
1779
+ "Project Name": project.name,
1780
+ "Project Domains": `${project.domains.join(", ")}`,
1781
+ "Git Provider": project.source ? "Yes" : "No",
1782
+ "Last Modified": project.latest_deployment
1783
+ ? timeagoFormat(project.latest_deployment.modified_on)
1784
+ : timeagoFormat(project.created_on),
1785
+ };
1786
+ });
1787
+
1788
+ saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1789
+ account_id: accountId,
1790
+ });
1791
+
1792
+ render(<Table data={data}></Table>);
1793
+ }
1794
+ )
1795
+ .command(
1796
+ "create [project-name]",
1797
+ "Create a new Cloudflare Pages project",
1798
+ (yargs) =>
1799
+ yargs
1800
+ .positional("project-name", {
1801
+ type: "string",
1802
+ demandOption: true,
1803
+ description: "The name of your Pages project",
1804
+ })
1805
+ .options({
1806
+ "production-branch": {
1807
+ type: "string",
1808
+ description:
1809
+ "The name of the production branch of your project",
1810
+ },
1811
+ })
1812
+ .epilogue(pagesBetaWarning),
1813
+ async ({ productionBranch, projectName }) => {
1814
+ const config = getConfigCache<PagesConfigCache>(
1815
+ PAGES_CONFIG_CACHE_FILENAME
1816
+ );
1817
+ const accountId = await requireAuth(config);
1818
+
1819
+ const isInteractive = process.stdin.isTTY;
1820
+ if (!projectName && isInteractive) {
1821
+ projectName = await prompt("Enter the name of your new project:");
1822
+ }
1823
+
1824
+ if (!projectName) {
1825
+ throw new FatalError("Must specify a project name.", 1);
1826
+ }
1827
+
1828
+ if (!productionBranch && isInteractive) {
1829
+ let isGitDir = true;
1830
+ try {
1831
+ execSync(`git rev-parse --is-inside-work-tree`, {
1832
+ stdio: "ignore",
1833
+ });
1834
+ } catch (err) {
1835
+ isGitDir = false;
1836
+ }
1837
+
1838
+ productionBranch = await prompt(
1839
+ "Enter the production branch name:",
1840
+ "text",
1841
+ isGitDir
1842
+ ? execSync(`git rev-parse --abbrev-ref HEAD`)
1843
+ .toString()
1844
+ .trim()
1845
+ : "production"
1846
+ );
1847
+ }
1848
+
1849
+ if (!productionBranch) {
1850
+ throw new FatalError("Must specify a production branch.", 1);
1851
+ }
1852
+
1853
+ const { subdomain } = await fetchResult<Project>(
1854
+ `/accounts/${accountId}/pages/projects`,
1855
+ {
1856
+ method: "POST",
1857
+ body: JSON.stringify({
1858
+ name: projectName,
1859
+ production_branch: productionBranch,
1860
+ }),
1861
+ }
1862
+ );
1863
+
1864
+ saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1865
+ account_id: accountId,
1866
+ project_name: projectName,
1867
+ });
1868
+
1869
+ logger.log(
1870
+ `✨ Successfully created the '${projectName}' project. It will be available at https://${subdomain}/ once you create your first deployment.`
1871
+ );
1872
+ logger.log(
1873
+ `To deploy a folder of assets, run 'wrangler pages publish [directory]'.`
1874
+ );
1875
+ }
1876
+ )
1877
+ .epilogue(pagesBetaWarning)
1878
+ )
1879
+ .command(
1880
+ "deployment",
1881
+ "🚀 Interact with the deployments of a project",
1882
+ (yargs) =>
1883
+ yargs
1884
+ .command(
1885
+ "list",
1886
+ "List deployments in your Cloudflare Pages project",
1887
+ (yargs) =>
1888
+ yargs
1889
+ .options({
1890
+ "project-name": {
1891
+ type: "string",
1892
+ description:
1893
+ "The name of the project you would like to list deployments for",
1894
+ },
1895
+ })
1896
+ .epilogue(pagesBetaWarning),
1897
+ async ({ projectName }) => {
1898
+ const config = getConfigCache<PagesConfigCache>(
1899
+ PAGES_CONFIG_CACHE_FILENAME
1900
+ );
1901
+ const accountId = await requireAuth(config);
1902
+
1903
+ projectName ??= config.project_name;
1904
+
1905
+ const isInteractive = process.stdin.isTTY;
1906
+ if (!projectName && isInteractive) {
1907
+ const projects = await listProjects({ accountId });
1908
+ projectName = await new Promise((resolve) => {
1909
+ const { unmount } = render(
1910
+ <>
1911
+ <Text>Select a project:</Text>
1912
+ <SelectInput
1913
+ items={projects.map((project) => ({
1914
+ key: project.name,
1915
+ label: project.name,
1916
+ value: project,
1917
+ }))}
1918
+ onSelect={async (selected) => {
1919
+ resolve(selected.value.name);
1920
+ unmount();
1921
+ }}
1922
+ />
1923
+ </>
1924
+ );
1925
+ });
1926
+ }
1927
+
1928
+ if (!projectName) {
1929
+ throw new FatalError("Must specify a project name.", 1);
1930
+ }
1931
+
1932
+ const deployments: Array<Deployment> = await fetchResult(
1933
+ `/accounts/${accountId}/pages/projects/${projectName}/deployments`
1934
+ );
1935
+
1936
+ const titleCase = (word: string) =>
1937
+ word.charAt(0).toUpperCase() + word.slice(1);
1938
+
1939
+ const shortSha = (sha: string) => sha.slice(0, 7);
1940
+
1941
+ const getStatus = (deployment: Deployment) => {
1942
+ // Return a pretty time since timestamp if successful otherwise the status
1943
+ if (deployment.latest_stage.status === `success`) {
1944
+ return timeagoFormat(deployment.latest_stage.ended_on);
1945
+ }
1946
+ return titleCase(deployment.latest_stage.status);
1947
+ };
1948
+
1949
+ const data = deployments.map((deployment) => {
1950
+ return {
1951
+ Environment: titleCase(deployment.environment),
1952
+ Branch: deployment.deployment_trigger.metadata.branch,
1953
+ Source: shortSha(
1954
+ deployment.deployment_trigger.metadata.commit_hash
1955
+ ),
1956
+ Deployment: deployment.url,
1957
+ Status: getStatus(deployment),
1958
+ // TODO: Use a url shortener
1959
+ Build: `https://dash.cloudflare.com/${accountId}/pages/view/${deployment.project_name}/${deployment.id}`,
1960
+ };
1961
+ });
1962
+
1963
+ saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1964
+ account_id: accountId,
1965
+ });
1966
+
1967
+ render(<Table data={data}></Table>);
1968
+ }
1969
+ )
1970
+ .command({
1971
+ command: "create [directory]",
1972
+ ...createDeployment,
1973
+ } as CommandModule)
1974
+ .epilogue(pagesBetaWarning)
1975
+ )
1976
+ .command({
1977
+ command: "publish [directory]",
1978
+ ...createDeployment,
1979
+ } as CommandModule);
1039
1980
  };
1040
1981
 
1041
- const invalidAssetsFetch: typeof fetch = () => {
1982
+ const invalidAssetsFetch: typeof miniflareFetch = () => {
1042
1983
  throw new Error(
1043
1984
  "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
1044
1985
  );
1045
1986
  };
1987
+
1988
+ const listProjects = async ({
1989
+ accountId,
1990
+ }: {
1991
+ accountId: string;
1992
+ }): Promise<Array<Project>> => {
1993
+ const pageSize = 10;
1994
+ let page = 1;
1995
+ const results = [];
1996
+ while (results.length % pageSize === 0) {
1997
+ const json: Array<Project> = await fetchResult(
1998
+ `/accounts/${accountId}/pages/projects`,
1999
+ {},
2000
+ new URLSearchParams({
2001
+ per_page: pageSize.toString(),
2002
+ page: page.toString(),
2003
+ })
2004
+ );
2005
+ page++;
2006
+ results.push(...json);
2007
+ if (json.length < pageSize) {
2008
+ break;
2009
+ }
2010
+ }
2011
+ return results;
2012
+ };
2013
+
2014
+ function formatTime(duration: number) {
2015
+ return `(${(duration / 1000).toFixed(2)} sec)`;
2016
+ }
2017
+
2018
+ function Progress({ done, total }: { done: number; total: number }) {
2019
+ return (
2020
+ <>
2021
+ <Text>
2022
+ <Spinner type="earth" />
2023
+ {` Uploading... (${done}/${total})\n`}
2024
+ </Text>
2025
+ </>
2026
+ );
2027
+ }