wrangler 0.0.0-ece06ea → 0.0.0-ed4f2ef

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 (109) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +12 -3
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +49 -22
  6. package/pages/functions/buildWorker.ts +62 -0
  7. package/pages/functions/filepath-routing.test.ts +223 -0
  8. package/pages/functions/filepath-routing.ts +181 -0
  9. package/pages/functions/identifiers.ts +78 -0
  10. package/pages/functions/routes.ts +151 -0
  11. package/pages/functions/template-worker.ts +130 -0
  12. package/src/__tests__/configuration.test.ts +2874 -0
  13. package/src/__tests__/dev.test.tsx +588 -0
  14. package/src/__tests__/guess-worker-format.test.ts +83 -0
  15. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  16. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  17. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  18. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  19. package/src/__tests__/helpers/mock-bin.ts +36 -0
  20. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  21. package/src/__tests__/helpers/mock-console.ts +70 -0
  22. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  23. package/src/__tests__/helpers/mock-kv.ts +33 -0
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +178 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +127 -0
  31. package/src/__tests__/index.test.ts +953 -119
  32. package/src/__tests__/jest.setup.ts +74 -0
  33. package/src/__tests__/kv.test.ts +1380 -0
  34. package/src/__tests__/package-manager.test.ts +206 -0
  35. package/src/__tests__/pages.test.ts +180 -0
  36. package/src/__tests__/parse.test.ts +322 -0
  37. package/src/__tests__/publish.test.ts +3946 -0
  38. package/src/__tests__/r2.test.ts +198 -0
  39. package/src/__tests__/route.test.ts +45 -0
  40. package/src/__tests__/secret.test.ts +425 -0
  41. package/src/__tests__/sentry.test.ts +146 -0
  42. package/src/__tests__/tail.test.ts +638 -0
  43. package/src/__tests__/user.test.ts +83 -0
  44. package/src/__tests__/whoami.test.tsx +95 -0
  45. package/src/bundle.ts +155 -0
  46. package/src/cfetch/index.ts +104 -0
  47. package/src/cfetch/internal.ts +139 -0
  48. package/src/cli.ts +18 -7
  49. package/src/config/README.md +107 -0
  50. package/src/config/config.ts +229 -0
  51. package/src/config/diagnostics.ts +80 -0
  52. package/src/config/environment.ts +371 -0
  53. package/src/config/index.ts +62 -0
  54. package/src/config/validation-helpers.ts +557 -0
  55. package/src/config/validation.ts +1240 -0
  56. package/src/create-worker-preview.ts +173 -0
  57. package/src/create-worker-upload-form.ts +240 -0
  58. package/src/dev/dev.tsx +413 -0
  59. package/src/dev/local.tsx +287 -0
  60. package/src/dev/remote.tsx +209 -0
  61. package/src/dev/use-esbuild.ts +109 -0
  62. package/src/dialogs.tsx +6 -14
  63. package/src/entry.ts +256 -0
  64. package/src/environment-variables.ts +33 -0
  65. package/src/errors.ts +11 -0
  66. package/src/https-options.ts +122 -0
  67. package/src/index.tsx +1503 -959
  68. package/src/inspect.ts +624 -0
  69. package/src/intl-polyfill.d.ts +139 -0
  70. package/src/kv.ts +319 -0
  71. package/src/miniflare-cli/README.md +30 -0
  72. package/src/miniflare-cli/enum-keys.ts +17 -0
  73. package/src/miniflare-cli/index.ts +38 -0
  74. package/src/module-collection.ts +257 -0
  75. package/src/open-in-browser.ts +25 -0
  76. package/src/package-manager.ts +126 -0
  77. package/src/pages.tsx +1074 -212
  78. package/src/parse.ts +183 -0
  79. package/src/paths.ts +26 -0
  80. package/src/proxy.ts +455 -0
  81. package/src/publish.ts +326 -295
  82. package/src/r2.ts +50 -0
  83. package/src/reporting.ts +131 -0
  84. package/src/selfsigned.d.ts +29 -0
  85. package/src/sites.tsx +224 -59
  86. package/src/tail/filters.ts +279 -0
  87. package/src/tail/index.ts +299 -0
  88. package/src/tail/printing.ts +62 -0
  89. package/src/user.tsx +340 -203
  90. package/src/whoami.tsx +69 -0
  91. package/src/worker.ts +172 -0
  92. package/templates/new-worker.js +15 -0
  93. package/templates/new-worker.ts +15 -0
  94. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  95. package/templates/tsconfig.json +105 -0
  96. package/wrangler-dist/cli.js +136988 -131174
  97. package/wrangler-dist/cli.js.map +3 -3
  98. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  99. package/src/__tests__/mock-cfetch.js +0 -46
  100. package/src/api/form_data.ts +0 -158
  101. package/src/api/inspect.ts +0 -441
  102. package/src/api/preview.ts +0 -123
  103. package/src/api/worker.ts +0 -161
  104. package/src/cfetch.ts +0 -72
  105. package/src/config.ts +0 -124
  106. package/src/dev.tsx +0 -736
  107. package/src/kv.tsx +0 -211
  108. package/src/tail.tsx +0 -71
  109. package/src/util/fetch.ts +0 -74
package/src/pages.tsx CHANGED
@@ -1,24 +1,94 @@
1
- import type { BuilderCallback } from "yargs";
2
- import { join } from "path";
3
- import { tmpdir } from "os";
4
- import { existsSync } from "fs";
5
- import type { ChildProcess } from "child_process";
6
- import { execSync, spawn } from "child_process";
7
- import express from "express";
1
+ /* eslint-disable no-shadow */
2
+
3
+ import { execSync, spawn } from "node:child_process";
4
+ import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { URL } from "node:url";
8
+ import { watch } from "chokidar";
9
+ import { render } from "ink";
10
+ import Table from "ink-table";
11
+ import { getType } from "mime";
12
+ import React from "react";
13
+ import { format } from "timeago.js";
14
+ import { buildWorker } from "../pages/functions/buildWorker";
15
+ import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
16
+ import { writeRoutesModule } from "../pages/functions/routes";
17
+ import { fetchResult } from "./cfetch";
18
+ import { readConfig } from "./config";
19
+ import { FatalError } from "./errors";
20
+ import openInBrowser from "./open-in-browser";
21
+ import { toUrlPath } from "./paths";
22
+ import { requireAuth } from "./user";
23
+ import type { Config } from "../pages/functions/routes";
24
+ import type { Headers, Request, fetch } from "@miniflare/core";
25
+ import type { BuildResult } from "esbuild";
8
26
  import type { MiniflareOptions } from "miniflare";
9
- import type { RequestInfo, RequestInit } from "@miniflare/core";
10
- import httpProxyMiddleware from "http-proxy-middleware";
27
+ import type { BuilderCallback } from "yargs";
28
+
29
+ type ConfigPath = string | undefined;
30
+
31
+ export type Project = {
32
+ name: string;
33
+ domains: Array<string>;
34
+ source?: {
35
+ type: string;
36
+ };
37
+ latest_deployment: {
38
+ modified_on: string;
39
+ };
40
+ };
41
+
42
+ export type Deployment = {
43
+ id: string;
44
+ environment: string;
45
+ deployment_trigger: {
46
+ metadata: {
47
+ commit_hash: string;
48
+ branch: string;
49
+ };
50
+ };
51
+ url: string;
52
+ latest_stage: {
53
+ status: string;
54
+ ended_on: string;
55
+ };
56
+ project_name: string;
57
+ };
58
+
59
+ // Defer importing miniflare until we really need it. This takes ~0.5s
60
+ // and also modifies some `stream/web` and `undici` prototypes, so we
61
+ // don't want to do this if pages commands aren't being called.
62
+
63
+ export const pagesBetaWarning =
64
+ "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose";
65
+
66
+ const CLEANUP_CALLBACKS: (() => void)[] = [];
67
+ const CLEANUP = () => {
68
+ CLEANUP_CALLBACKS.forEach((callback) => callback());
69
+ RUNNING_BUILDERS.forEach((builder) => builder.stop?.());
70
+ };
11
71
 
12
- type Exit = (message?: string) => undefined;
72
+ process.on("SIGINT", () => {
73
+ CLEANUP();
74
+ process.exit();
75
+ });
76
+ process.on("SIGTERM", () => {
77
+ CLEANUP();
78
+ process.exit();
79
+ });
13
80
 
14
- const isWindows = () => process.platform === "win32";
81
+ function isWindows() {
82
+ return process.platform === "win32";
83
+ }
15
84
 
16
85
  const SECONDS_TO_WAIT_FOR_PROXY = 5;
17
86
 
18
- const sleep = async (ms: number) =>
87
+ async function sleep(ms: number) {
19
88
  await new Promise((resolve) => setTimeout(resolve, ms));
89
+ }
20
90
 
21
- const getPids = (pid: number) => {
91
+ function getPids(pid: number) {
22
92
  const pids: number[] = [pid];
23
93
  let command: string, regExp: RegExp;
24
94
 
@@ -43,9 +113,9 @@ const getPids = (pid: number) => {
43
113
  } catch {}
44
114
 
45
115
  return pids;
46
- };
116
+ }
47
117
 
48
- const getPort = (pid: number) => {
118
+ function getPort(pid: number) {
49
119
  let command: string, regExp: RegExp;
50
120
 
51
121
  if (isWindows()) {
@@ -70,45 +140,39 @@ const getPort = (pid: number) => {
70
140
  `Error scanning for ports of process with PID ${pid}: ${thrown}`
71
141
  );
72
142
  }
73
- };
143
+ }
74
144
 
75
- const spawnProxyProcess = async ({
76
- directory,
145
+ async function spawnProxyProcess({
77
146
  port,
78
- remaining,
147
+ command,
79
148
  }: {
80
- directory?: string;
81
149
  port?: number;
82
- remaining: (string | number)[];
83
- }) => {
84
- let proxy: ChildProcess;
85
-
86
- const exit: Exit = (message) => {
87
- if (message) console.error(message);
88
- if (proxy) proxy.kill();
89
- return undefined;
90
- };
91
-
92
- if (directory !== undefined) {
93
- console.log(`Serving ${directory}...`);
94
- const args = ["serve", directory];
95
- if (port) args.push("-p", port.toString());
96
- proxy = spawn("npx", args, { shell: isWindows() });
97
- } else {
98
- const command = remaining;
99
- if (command.length === 0)
100
- return exit(
101
- "Must specify a directory of static assets to serve or a command to run."
102
- );
103
-
104
- console.log(`Running ${command.join(" ")}...`);
105
- proxy = spawn(
106
- command[0].toString(),
107
- command.slice(1).map((value) => value.toString()),
108
- { shell: isWindows() }
150
+ command: (string | number)[];
151
+ }): Promise<void | number> {
152
+ if (command.length === 0) {
153
+ CLEANUP();
154
+ throw new FatalError(
155
+ "Must specify a directory of static assets to serve or a command to run.",
156
+ 1
109
157
  );
110
158
  }
111
159
 
160
+ console.log(`Running ${command.join(" ")}...`);
161
+ const proxy = spawn(
162
+ command[0].toString(),
163
+ command.slice(1).map((value) => value.toString()),
164
+ {
165
+ shell: isWindows(),
166
+ env: {
167
+ BROWSER: "none",
168
+ ...process.env,
169
+ },
170
+ }
171
+ );
172
+ CLEANUP_CALLBACKS.push(() => {
173
+ proxy.kill();
174
+ });
175
+
112
176
  proxy.stdout.on("data", (data) => {
113
177
  console.log(`[proxy]: ${data}`);
114
178
  });
@@ -136,209 +200,1007 @@ const spawnProxyProcess = async ({
136
200
  .filter((port) => port !== undefined)[0];
137
201
 
138
202
  if (port === undefined) {
139
- return exit(
140
- "Could not automatically determin proxy port. Please specify the proxy port with --proxy."
203
+ CLEANUP();
204
+ throw new FatalError(
205
+ "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
206
+ 1
141
207
  );
142
208
  } else {
143
209
  console.log(`Automatically determined the proxy port to be ${port}.`);
144
210
  }
145
211
  }
146
212
 
147
- return { proxy, port, exit };
148
- };
213
+ return port;
214
+ }
149
215
 
150
- export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
151
- return yargs.command(
152
- "dev [directory] [-- command]",
153
- "🧑‍💻 Develop your full-stack Pages application locally",
154
- (yargs) => {
155
- return yargs
156
- .positional("directory", {
157
- type: "string",
158
- demandOption: undefined,
159
- description: "The directory of static assets to serve",
160
- })
161
- .positional("command", {
162
- type: "string",
163
- demandOption: undefined,
164
- description: "The proxy command to run",
165
- })
166
- .options({
167
- local: {
168
- type: "boolean",
169
- default: true,
170
- description: "Run on my machine",
171
- },
172
- port: {
173
- type: "number",
174
- default: 8788,
175
- description: "The port to listen on (serve from)",
176
- },
177
- proxy: {
178
- type: "number",
179
- description:
180
- "The port to proxy (where the static assets are served)",
181
- },
182
- "script-path": {
183
- type: "string",
184
- default: "_worker.js",
185
- description:
186
- "The location of the single Worker script if not using functions",
187
- },
188
- binding: {
189
- type: "array",
190
- description: "Bind variable/secret (KEY=VALUE)",
191
- alias: "b",
192
- },
193
- kv: {
194
- type: "array",
195
- description: "KV namespace to bind",
196
- alias: "k",
197
- },
198
- do: {
199
- type: "array",
200
- description: "Durable Object to bind (NAME=CLASS)",
201
- alias: "o",
202
- },
203
- // TODO: Miniflare user options
204
- });
205
- },
206
- async ({
207
- local,
208
- directory,
209
- port,
210
- proxy: requestedProxyPort,
211
- "script-path": singleWorkerScriptPath,
212
- binding: bindings = [],
213
- kv: kvs = [],
214
- do: durableObjects = [],
215
- "--": remaining = [],
216
- }) => {
217
- if (!local) {
218
- console.error("Only local mode is supported at the moment.");
219
- return;
216
+ function escapeRegex(str: string) {
217
+ return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
218
+ }
219
+
220
+ type Replacements = Record<string, string>;
221
+
222
+ function replacer(str: string, replacements: Replacements) {
223
+ for (const [replacement, value] of Object.entries(replacements)) {
224
+ str = str.replace(`:${replacement}`, value);
225
+ }
226
+ return str;
227
+ }
228
+
229
+ function generateRulesMatcher<T>(
230
+ rules?: Record<string, T>,
231
+ replacer: (match: T, replacements: Replacements) => T = (match) => match
232
+ ) {
233
+ // TODO: How can you test cross-host rules?
234
+ if (!rules) return () => [];
235
+
236
+ const compiledRules = Object.entries(rules)
237
+ .map(([rule, match]) => {
238
+ const crossHost = rule.startsWith("https://");
239
+
240
+ rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
241
+
242
+ const host_matches = rule.matchAll(
243
+ /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
244
+ );
245
+ for (const match of host_matches) {
246
+ rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`);
220
247
  }
221
248
 
222
- const functionsDirectory = "./functions";
223
- const usingFunctions = existsSync(functionsDirectory);
249
+ const path_matches = rule.matchAll(/:(\w+)/g);
250
+ for (const match of path_matches) {
251
+ rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);
252
+ }
224
253
 
225
- const proxy = await spawnProxyProcess({
226
- directory,
227
- port: requestedProxyPort,
228
- remaining: remaining as (string | number)[],
254
+ rule = "^" + rule + "$";
255
+
256
+ try {
257
+ const regExp = new RegExp(rule);
258
+ return [{ crossHost, regExp }, match];
259
+ } catch {}
260
+ })
261
+ .filter((value) => value !== undefined) as [
262
+ { crossHost: boolean; regExp: RegExp },
263
+ T
264
+ ][];
265
+
266
+ return ({ request }: { request: Request }) => {
267
+ const { pathname, host } = new URL(request.url);
268
+
269
+ return compiledRules
270
+ .map(([{ crossHost, regExp }, match]) => {
271
+ const test = crossHost ? `https://${host}${pathname}` : pathname;
272
+ const result = regExp.exec(test);
273
+ if (result) {
274
+ return replacer(match, result.groups || {});
275
+ }
276
+ })
277
+ .filter((value) => value !== undefined) as T[];
278
+ };
279
+ }
280
+
281
+ function generateHeadersMatcher(headersFile: string) {
282
+ if (existsSync(headersFile)) {
283
+ const contents = readFileSync(headersFile).toString();
284
+
285
+ // TODO: Log errors
286
+ const lines = contents
287
+ .split("\n")
288
+ .map((line) => line.trim())
289
+ .filter((line) => !line.startsWith("#") && line !== "");
290
+
291
+ const rules: Record<string, Record<string, string>> = {};
292
+ let rule: { path: string; headers: Record<string, string> } | undefined =
293
+ undefined;
294
+
295
+ for (const line of lines) {
296
+ if (/^([^\s]+:\/\/|^\/)/.test(line)) {
297
+ if (rule && Object.keys(rule.headers).length > 0) {
298
+ rules[rule.path] = rule.headers;
299
+ }
300
+
301
+ const path = validateURL(line);
302
+ if (path) {
303
+ rule = {
304
+ path,
305
+ headers: {},
306
+ };
307
+ continue;
308
+ }
309
+ }
310
+
311
+ if (!line.includes(":")) continue;
312
+
313
+ const [rawName, ...rawValue] = line.split(":");
314
+ const name = rawName.trim().toLowerCase();
315
+ const value = rawValue.join(":").trim();
316
+
317
+ if (name === "") continue;
318
+ if (!rule) continue;
319
+
320
+ const existingValues = rule.headers[name];
321
+ rule.headers[name] = existingValues
322
+ ? `${existingValues}, ${value}`
323
+ : value;
324
+ }
325
+
326
+ if (rule && Object.keys(rule.headers).length > 0) {
327
+ rules[rule.path] = rule.headers;
328
+ }
329
+
330
+ const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
331
+ Object.fromEntries(
332
+ Object.entries(match).map(([name, value]) => [
333
+ name,
334
+ replacer(value, replacements),
335
+ ])
336
+ )
337
+ );
338
+
339
+ return (request: Request) => {
340
+ const matches = rulesMatcher({
341
+ request,
229
342
  });
230
- if (proxy === undefined) return undefined;
343
+ if (matches) return matches;
344
+ };
345
+ } else {
346
+ return () => undefined;
347
+ }
348
+ }
349
+
350
+ function generateRedirectsMatcher(redirectsFile: string) {
351
+ if (existsSync(redirectsFile)) {
352
+ const contents = readFileSync(redirectsFile).toString();
353
+
354
+ // TODO: Log errors
355
+ const lines = contents
356
+ .split("\n")
357
+ .map((line) => line.trim())
358
+ .filter((line) => !line.startsWith("#") && line !== "");
359
+
360
+ const rules = Object.fromEntries(
361
+ lines
362
+ .map((line) => line.split(" "))
363
+ .filter((tokens) => tokens.length === 2 || tokens.length === 3)
364
+ .map((tokens) => {
365
+ const from = validateURL(tokens[0], true, false, false);
366
+ const to = validateURL(tokens[1], false, true, true);
367
+ let status: number | undefined = parseInt(tokens[2]) || 302;
368
+ status = [301, 302, 303, 307, 308].includes(status)
369
+ ? status
370
+ : undefined;
371
+
372
+ return from && to && status ? [from, { to, status }] : undefined;
373
+ })
374
+ .filter((rule) => rule !== undefined) as [
375
+ string,
376
+ { to: string; status?: number }
377
+ ][]
378
+ );
379
+
380
+ const rulesMatcher = generateRulesMatcher(
381
+ rules,
382
+ ({ status, to }, replacements) => ({
383
+ status,
384
+ to: replacer(to, replacements),
385
+ })
386
+ );
387
+
388
+ return (request: Request) => {
389
+ const match = rulesMatcher({
390
+ request,
391
+ })[0];
392
+ if (match) return match;
393
+ };
394
+ } else {
395
+ return () => undefined;
396
+ }
397
+ }
398
+
399
+ function extractPathname(
400
+ path = "/",
401
+ includeSearch: boolean,
402
+ includeHash: boolean
403
+ ) {
404
+ if (!path.startsWith("/")) path = `/${path}`;
405
+ const url = new URL(`//${path}`, "relative://");
406
+ return `${url.pathname}${includeSearch ? url.search : ""}${
407
+ includeHash ? url.hash : ""
408
+ }`;
409
+ }
410
+
411
+ function validateURL(
412
+ token: string,
413
+ onlyRelative = false,
414
+ includeSearch = false,
415
+ includeHash = false
416
+ ) {
417
+ const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
418
+ if (host && host.groups && host.groups.host) {
419
+ if (onlyRelative) return;
420
+
421
+ return `https://${host.groups.host}${extractPathname(
422
+ host.groups.path,
423
+ includeSearch,
424
+ includeHash
425
+ )}`;
426
+ } else {
427
+ if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
428
+
429
+ const path = /^\//.exec(token);
430
+ if (path) {
431
+ try {
432
+ return extractPathname(token, includeSearch, includeHash);
433
+ } catch {}
434
+ }
435
+ }
436
+ return "";
437
+ }
438
+
439
+ function hasFileExtension(pathname: string) {
440
+ return /\/.+\.[a-z0-9]+$/i.test(pathname);
441
+ }
231
442
 
232
- const { port: proxyPort, exit } = proxy;
443
+ async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
444
+ // Defer importing miniflare until we really need it
445
+ const { Headers, Request, Response } = await import("@miniflare/core");
233
446
 
234
- let miniflareArgs: MiniflareOptions = {};
447
+ const headersFile = join(directory, "_headers");
448
+ const redirectsFile = join(directory, "_redirects");
449
+ const workerFile = join(directory, "_worker.js");
235
450
 
236
- if (usingFunctions) {
237
- const scriptPath = join(tmpdir(), "./functionsWorker.js");
238
- miniflareArgs = {
239
- scriptPath,
240
- buildWatchPaths: [functionsDirectory],
241
- buildCommand: `npx @cloudflare/pages-functions-compiler build ${functionsDirectory} --outfile ${scriptPath}`,
242
- };
451
+ const ignoredFiles = [headersFile, redirectsFile, workerFile];
452
+
453
+ const assetExists = (path: string) => {
454
+ path = join(directory, path);
455
+ return (
456
+ existsSync(path) &&
457
+ lstatSync(path).isFile() &&
458
+ !ignoredFiles.includes(path)
459
+ );
460
+ };
461
+
462
+ const getAsset = (path: string) => {
463
+ if (assetExists(path)) {
464
+ return join(directory, path);
465
+ }
466
+ };
467
+
468
+ let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
469
+ let headersMatcher = generateHeadersMatcher(headersFile);
470
+
471
+ watch([headersFile, redirectsFile], {
472
+ persistent: true,
473
+ }).on("change", (path) => {
474
+ switch (path) {
475
+ case headersFile: {
476
+ console.log("_headers modified. Re-evaluating...");
477
+ headersMatcher = generateHeadersMatcher(headersFile);
478
+ break;
479
+ }
480
+ case redirectsFile: {
481
+ console.log("_redirects modified. Re-evaluating...");
482
+ redirectsMatcher = generateRedirectsMatcher(redirectsFile);
483
+ break;
484
+ }
485
+ }
486
+ });
487
+
488
+ const serveAsset = (file: string) => {
489
+ return readFileSync(file);
490
+ };
491
+
492
+ const generateResponse = (request: Request) => {
493
+ const url = new URL(request.url);
494
+
495
+ const deconstructedResponse: {
496
+ status: number;
497
+ headers: Headers;
498
+ body?: Buffer;
499
+ } = {
500
+ status: 200,
501
+ headers: new Headers(),
502
+ body: undefined,
503
+ };
504
+
505
+ const match = redirectsMatcher(request);
506
+ if (match) {
507
+ const { status, to } = match;
508
+
509
+ let location = to;
510
+ let search;
511
+
512
+ if (to.startsWith("/")) {
513
+ search = new URL(location, "http://fakehost").search;
243
514
  } else {
244
- const scriptPath =
245
- directory !== undefined
246
- ? join(directory, singleWorkerScriptPath)
247
- : singleWorkerScriptPath;
515
+ search = new URL(location).search;
516
+ }
517
+
518
+ location = `${location}${search ? "" : url.search}`;
248
519
 
249
- if (!existsSync(scriptPath)) {
250
- return exit(
251
- `No Worker script found at ${scriptPath}. Please either create a functions directory or create a single Worker at ${scriptPath}.`
520
+ if (status && [301, 302, 303, 307, 308].includes(status)) {
521
+ deconstructedResponse.status = status;
522
+ } else {
523
+ deconstructedResponse.status = 302;
524
+ }
525
+
526
+ deconstructedResponse.headers.set("Location", location);
527
+ return deconstructedResponse;
528
+ }
529
+
530
+ if (!request.method?.match(/^(get|head)$/i)) {
531
+ deconstructedResponse.status = 405;
532
+ return deconstructedResponse;
533
+ }
534
+
535
+ const notFound = () => {
536
+ let cwd = url.pathname;
537
+ while (cwd) {
538
+ cwd = cwd.slice(0, cwd.lastIndexOf("/"));
539
+
540
+ if ((asset = getAsset(`${cwd}/404.html`))) {
541
+ deconstructedResponse.status = 404;
542
+ deconstructedResponse.body = serveAsset(asset);
543
+ deconstructedResponse.headers.set(
544
+ "Content-Type",
545
+ getType(asset) || "application/octet-stream"
252
546
  );
547
+ return deconstructedResponse;
253
548
  }
549
+ }
254
550
 
255
- miniflareArgs = {
256
- scriptPath,
257
- };
551
+ if ((asset = getAsset(`/index.html`))) {
552
+ deconstructedResponse.body = serveAsset(asset);
553
+ deconstructedResponse.headers.set(
554
+ "Content-Type",
555
+ getType(asset) || "application/octet-stream"
556
+ );
557
+ return deconstructedResponse;
258
558
  }
259
559
 
260
- const { Miniflare } = await import("miniflare");
261
- const { Request, Response, fetch } = await import("@miniflare/core");
262
- const miniflare = new Miniflare({
263
- watch: true,
264
- modules: true,
560
+ deconstructedResponse.status = 404;
561
+ return deconstructedResponse;
562
+ };
265
563
 
266
- kvNamespaces: kvs.map((kv) => kv.toString()),
564
+ let asset;
267
565
 
268
- durableObjects: Object.fromEntries(
269
- durableObjects.map((durableObject) =>
270
- durableObject.toString().split("=")
271
- )
272
- ),
566
+ if (url.pathname.endsWith("/")) {
567
+ if ((asset = getAsset(`${url.pathname}/index.html`))) {
568
+ deconstructedResponse.body = serveAsset(asset);
569
+ deconstructedResponse.headers.set(
570
+ "Content-Type",
571
+ getType(asset) || "application/octet-stream"
572
+ );
573
+ return deconstructedResponse;
574
+ } else if (
575
+ (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
576
+ ) {
577
+ deconstructedResponse.status = 301;
578
+ deconstructedResponse.headers.set(
579
+ "Location",
580
+ `${url.pathname.slice(0, -1)}${url.search}`
581
+ );
582
+ return deconstructedResponse;
583
+ }
584
+ }
273
585
 
274
- bindings: {
275
- // User bindings
276
- ...Object.fromEntries(
277
- bindings.map((binding) => binding.toString().split("="))
586
+ if (url.pathname.endsWith("/index")) {
587
+ deconstructedResponse.status = 301;
588
+ deconstructedResponse.headers.set(
589
+ "Location",
590
+ `${url.pathname.slice(0, -"index".length)}${url.search}`
591
+ );
592
+ return deconstructedResponse;
593
+ }
594
+
595
+ if ((asset = getAsset(url.pathname))) {
596
+ if (url.pathname.endsWith(".html")) {
597
+ const extensionlessPath = url.pathname.slice(0, -".html".length);
598
+ if (getAsset(extensionlessPath) || extensionlessPath === "/") {
599
+ deconstructedResponse.body = serveAsset(asset);
600
+ deconstructedResponse.headers.set(
601
+ "Content-Type",
602
+ getType(asset) || "application/octet-stream"
603
+ );
604
+ return deconstructedResponse;
605
+ } else {
606
+ deconstructedResponse.status = 301;
607
+ deconstructedResponse.headers.set(
608
+ "Location",
609
+ `${extensionlessPath}${url.search}`
610
+ );
611
+ return deconstructedResponse;
612
+ }
613
+ } else {
614
+ deconstructedResponse.body = serveAsset(asset);
615
+ deconstructedResponse.headers.set(
616
+ "Content-Type",
617
+ getType(asset) || "application/octet-stream"
618
+ );
619
+ return deconstructedResponse;
620
+ }
621
+ } else if (hasFileExtension(url.pathname)) {
622
+ notFound();
623
+ return deconstructedResponse;
624
+ }
625
+
626
+ if ((asset = getAsset(`${url.pathname}.html`))) {
627
+ deconstructedResponse.body = serveAsset(asset);
628
+ deconstructedResponse.headers.set(
629
+ "Content-Type",
630
+ getType(asset) || "application/octet-stream"
631
+ );
632
+ return deconstructedResponse;
633
+ }
634
+
635
+ if ((asset = getAsset(`${url.pathname}/index.html`))) {
636
+ deconstructedResponse.status = 301;
637
+ deconstructedResponse.headers.set(
638
+ "Location",
639
+ `${url.pathname}/${url.search}`
640
+ );
641
+ return deconstructedResponse;
642
+ } else {
643
+ notFound();
644
+ return deconstructedResponse;
645
+ }
646
+ };
647
+
648
+ const attachHeaders = (
649
+ request: Request,
650
+ deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
651
+ ) => {
652
+ const headers = deconstructedResponse.headers;
653
+ const newHeaders = new Headers({});
654
+ const matches = headersMatcher(request) || [];
655
+
656
+ matches.forEach((match) => {
657
+ Object.entries(match).forEach(([name, value]) => {
658
+ newHeaders.append(name, `${value}`);
659
+ });
660
+ });
661
+
662
+ const combinedHeaders = {
663
+ ...Object.fromEntries(headers.entries()),
664
+ ...Object.fromEntries(newHeaders.entries()),
665
+ };
666
+
667
+ deconstructedResponse.headers = new Headers({});
668
+ Object.entries(combinedHeaders).forEach(([name, value]) => {
669
+ if (value) deconstructedResponse.headers.set(name, value);
670
+ });
671
+ };
672
+
673
+ return async (input, init) => {
674
+ const request = new Request(input, init);
675
+ const deconstructedResponse = generateResponse(request);
676
+ attachHeaders(request, deconstructedResponse);
677
+
678
+ const headers = new Headers();
679
+
680
+ [...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
681
+ if (value) headers.set(name, value);
682
+ });
683
+
684
+ return new Response(deconstructedResponse.body, {
685
+ headers,
686
+ status: deconstructedResponse.status,
687
+ });
688
+ };
689
+ }
690
+
691
+ const RUNNING_BUILDERS: BuildResult[] = [];
692
+
693
+ async function buildFunctions({
694
+ scriptPath,
695
+ outputConfigPath,
696
+ functionsDirectory,
697
+ minify = false,
698
+ sourcemap = false,
699
+ fallbackService = "ASSETS",
700
+ watch = false,
701
+ onEnd,
702
+ }: {
703
+ scriptPath: string;
704
+ outputConfigPath?: string;
705
+ functionsDirectory: string;
706
+ minify?: boolean;
707
+ sourcemap?: boolean;
708
+ fallbackService?: string;
709
+ watch?: boolean;
710
+ onEnd?: () => void;
711
+ }) {
712
+ RUNNING_BUILDERS.forEach(
713
+ (runningBuilder) => runningBuilder.stop && runningBuilder.stop()
714
+ );
715
+
716
+ const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
717
+ const baseURL = toUrlPath("/");
718
+
719
+ const config: Config = await generateConfigFromFileTree({
720
+ baseDir: functionsDirectory,
721
+ baseURL,
722
+ });
723
+
724
+ if (outputConfigPath) {
725
+ writeFileSync(
726
+ outputConfigPath,
727
+ JSON.stringify({ ...config, baseURL }, null, 2)
728
+ );
729
+ }
730
+
731
+ await writeRoutesModule({
732
+ config,
733
+ srcDir: functionsDirectory,
734
+ outfile: routesModule,
735
+ });
736
+
737
+ RUNNING_BUILDERS.push(
738
+ await buildWorker({
739
+ routesModule,
740
+ outfile: scriptPath,
741
+ minify,
742
+ sourcemap,
743
+ fallbackService,
744
+ watch,
745
+ onEnd,
746
+ })
747
+ );
748
+ }
749
+
750
+ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
751
+ return yargs
752
+ .command(
753
+ "dev [directory] [-- command]",
754
+ "🧑‍💻 Develop your full-stack Pages application locally",
755
+ (yargs) => {
756
+ return yargs
757
+ .positional("directory", {
758
+ type: "string",
759
+ demandOption: undefined,
760
+ description: "The directory of static assets to serve",
761
+ })
762
+ .positional("command", {
763
+ type: "string",
764
+ demandOption: undefined,
765
+ description: "The proxy command to run",
766
+ })
767
+ .options({
768
+ local: {
769
+ type: "boolean",
770
+ default: true,
771
+ description: "Run on my machine",
772
+ },
773
+ port: {
774
+ type: "number",
775
+ default: 8788,
776
+ description: "The port to listen on (serve from)",
777
+ },
778
+ proxy: {
779
+ type: "number",
780
+ description:
781
+ "The port to proxy (where the static assets are served)",
782
+ },
783
+ "script-path": {
784
+ type: "string",
785
+ default: "_worker.js",
786
+ description:
787
+ "The location of the single Worker script if not using functions",
788
+ },
789
+ binding: {
790
+ type: "array",
791
+ description: "Bind variable/secret (KEY=VALUE)",
792
+ alias: "b",
793
+ },
794
+ kv: {
795
+ type: "array",
796
+ description: "KV namespace to bind",
797
+ alias: "k",
798
+ },
799
+ do: {
800
+ type: "array",
801
+ description: "Durable Object to bind (NAME=CLASS)",
802
+ alias: "o",
803
+ },
804
+ "live-reload": {
805
+ type: "boolean",
806
+ default: false,
807
+ description: "Auto reload HTML pages when change is detected",
808
+ },
809
+ // TODO: Miniflare user options
810
+ })
811
+ .epilogue(pagesBetaWarning);
812
+ },
813
+ async ({
814
+ local,
815
+ directory,
816
+ port,
817
+ proxy: requestedProxyPort,
818
+ "script-path": singleWorkerScriptPath,
819
+ binding: bindings = [],
820
+ kv: kvs = [],
821
+ do: durableObjects = [],
822
+ "live-reload": liveReload,
823
+ _: [_pages, _dev, ...remaining],
824
+ }) => {
825
+ // Beta message for `wrangler pages <commands>` usage
826
+ console.log(pagesBetaWarning);
827
+
828
+ if (!local) {
829
+ console.error("Only local mode is supported at the moment.");
830
+ return;
831
+ }
832
+
833
+ const functionsDirectory = "./functions";
834
+ const usingFunctions = existsSync(functionsDirectory);
835
+
836
+ const command = remaining as (string | number)[];
837
+
838
+ let proxyPort: number | void;
839
+
840
+ if (directory === undefined) {
841
+ proxyPort = await spawnProxyProcess({
842
+ port: requestedProxyPort,
843
+ command,
844
+ });
845
+ if (proxyPort === undefined) return undefined;
846
+ }
847
+
848
+ let miniflareArgs: MiniflareOptions = {};
849
+
850
+ let scriptReadyResolve: () => void;
851
+ const scriptReadyPromise = new Promise<void>(
852
+ (resolve) => (scriptReadyResolve = resolve)
853
+ );
854
+
855
+ if (usingFunctions) {
856
+ const scriptPath = join(tmpdir(), "./functionsWorker.js");
857
+
858
+ console.log(`Compiling worker to "${scriptPath}"...`);
859
+
860
+ try {
861
+ await buildFunctions({
862
+ scriptPath,
863
+ functionsDirectory,
864
+ sourcemap: true,
865
+ watch: true,
866
+ onEnd: () => scriptReadyResolve(),
867
+ });
868
+ } catch {}
869
+
870
+ watch([functionsDirectory], {
871
+ persistent: true,
872
+ ignoreInitial: true,
873
+ }).on("all", async () => {
874
+ await buildFunctions({
875
+ scriptPath,
876
+ functionsDirectory,
877
+ sourcemap: true,
878
+ watch: true,
879
+ onEnd: () => scriptReadyResolve(),
880
+ });
881
+ });
882
+
883
+ miniflareArgs = {
884
+ scriptPath,
885
+ };
886
+ } else {
887
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
888
+ scriptReadyResolve!();
889
+
890
+ const scriptPath =
891
+ directory !== undefined
892
+ ? join(directory, singleWorkerScriptPath)
893
+ : singleWorkerScriptPath;
894
+
895
+ if (existsSync(scriptPath)) {
896
+ miniflareArgs = {
897
+ scriptPath,
898
+ };
899
+ } else {
900
+ console.log("No functions. Shimming...");
901
+ miniflareArgs = {
902
+ // TODO: The fact that these request/response hacks are necessary is ridiculous.
903
+ // We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well)
904
+ script: `
905
+ export default {
906
+ async fetch(request, env, context) {
907
+ const response = await env.ASSETS.fetch(request.url, request)
908
+ return new Response(response.body, response)
909
+ }
910
+ }`,
911
+ };
912
+ }
913
+ }
914
+
915
+ // Defer importing miniflare until we really need it
916
+ const { Miniflare, Log, LogLevel } = await import("miniflare");
917
+ const { Response, fetch } = await import("@miniflare/core");
918
+
919
+ // Wait for esbuild to finish building before starting Miniflare.
920
+ // This must be before the call to `new Miniflare`, as that will
921
+ // asynchronously start loading the script. `await startServer()`
922
+ // internally just waits for that promise to resolve.
923
+ await scriptReadyPromise;
924
+
925
+ // `assetsFetch()` will only be called if there is `proxyPort` defined.
926
+ // We only define `proxyPort`, above, when there is no `directory` defined.
927
+ const assetsFetch =
928
+ directory !== undefined
929
+ ? await generateAssetsFetch(directory)
930
+ : invalidAssetsFetch;
931
+
932
+ const miniflare = new Miniflare({
933
+ port,
934
+ watch: true,
935
+ modules: true,
936
+
937
+ log: new Log(LogLevel.ERROR, { prefix: "pages" }),
938
+ logUnhandledRejections: true,
939
+ sourceMap: true,
940
+
941
+ kvNamespaces: kvs.map((kv) => kv.toString()),
942
+
943
+ durableObjects: Object.fromEntries(
944
+ durableObjects.map((durableObject) =>
945
+ durableObject.toString().split("=")
946
+ )
278
947
  ),
279
948
 
949
+ // User bindings
950
+ bindings: {
951
+ ...Object.fromEntries(
952
+ bindings
953
+ .map((binding) => binding.toString().split("="))
954
+ .map(([key, ...values]) => [key, values.join("=")])
955
+ ),
956
+ },
957
+
280
958
  // env.ASSETS.fetch
281
- ASSETS: {
282
- fetch: async (
283
- input: RequestInfo,
284
- init?: RequestInit | undefined
285
- ) => {
286
- try {
287
- let request = new Request(input, init);
288
- const url = new URL(request.url);
289
- url.host = `127.0.0.1:${proxyPort}`;
290
- request = new Request(url.toString(), request);
291
- return await fetch(request);
292
- } catch (thrown) {
293
- console.error(`Could not proxy request: ${thrown}`);
294
-
295
- // TODO: Pretty error page
296
- return new Response(
297
- `[wrangler] Could not proxy request: ${thrown}`,
298
- { status: 502 }
299
- );
959
+ serviceBindings: {
960
+ async ASSETS(request: Request) {
961
+ if (proxyPort) {
962
+ try {
963
+ const url = new URL(request.url);
964
+ url.host = `localhost:${proxyPort}`;
965
+ return await fetch(url, request);
966
+ } catch (thrown) {
967
+ console.error(`Could not proxy request: ${thrown}`);
968
+
969
+ // TODO: Pretty error page
970
+ return new Response(
971
+ `[wrangler] Could not proxy request: ${thrown}`,
972
+ { status: 502 }
973
+ );
974
+ }
975
+ } else {
976
+ try {
977
+ return await assetsFetch(request);
978
+ } catch (thrown) {
979
+ console.error(`Could not serve static asset: ${thrown}`);
980
+
981
+ // TODO: Pretty error page
982
+ return new Response(
983
+ `[wrangler] Could not serve static asset: ${thrown}`,
984
+ { status: 502 }
985
+ );
986
+ }
300
987
  }
301
988
  },
302
989
  },
303
- },
304
990
 
305
- kvPersist: true,
306
- durableObjectsPersist: true,
307
- cachePersist: true,
991
+ kvPersist: true,
992
+ durableObjectsPersist: true,
993
+ cachePersist: true,
994
+ liveReload,
308
995
 
309
- ...miniflareArgs,
310
- });
311
- const miniflareServer = await miniflare.createServer();
996
+ ...miniflareArgs,
997
+ });
998
+
999
+ try {
1000
+ // `startServer` might throw if user code contains errors
1001
+ const server = await miniflare.startServer();
1002
+ console.log(`Serving at http://localhost:${port}/`);
1003
+
1004
+ if (process.env.BROWSER !== "none") {
1005
+ await openInBrowser(`http://localhost:${port}/`);
1006
+ }
1007
+
1008
+ if (directory !== undefined && liveReload) {
1009
+ watch([directory], {
1010
+ persistent: true,
1011
+ ignoreInitial: true,
1012
+ }).on("all", async () => {
1013
+ await miniflare.reload();
1014
+ });
1015
+ }
1016
+
1017
+ CLEANUP_CALLBACKS.push(() => {
1018
+ server.close();
1019
+ miniflare.dispose().catch((err) => miniflare.log.error(err));
1020
+ });
1021
+ } catch (e) {
1022
+ miniflare.log.error(e as Error);
1023
+ CLEANUP();
1024
+ throw new FatalError("Could not start Miniflare.", 1);
1025
+ }
1026
+ }
1027
+ )
1028
+ .command("functions", false, (yargs) =>
1029
+ // we hide this command from help output because
1030
+ // it's not meant to be used directly right now
1031
+ yargs.command(
1032
+ "build [directory]",
1033
+ "Compile a folder of Cloudflare Pages Functions into a single Worker",
1034
+ (yargs) =>
1035
+ yargs
1036
+ .positional("directory", {
1037
+ type: "string",
1038
+ default: "functions",
1039
+ description: "The directory of Pages Functions",
1040
+ })
1041
+ .options({
1042
+ "script-path": {
1043
+ type: "string",
1044
+ default: "_worker.js",
1045
+ description: "The location of the output Worker script",
1046
+ },
1047
+ "output-config-path": {
1048
+ type: "string",
1049
+ description: "The location for the output config file",
1050
+ },
1051
+ minify: {
1052
+ type: "boolean",
1053
+ default: false,
1054
+ description: "Minify the output Worker script",
1055
+ },
1056
+ sourcemap: {
1057
+ type: "boolean",
1058
+ default: false,
1059
+ description:
1060
+ "Generate a sourcemap for the output Worker script",
1061
+ },
1062
+ "fallback-service": {
1063
+ type: "string",
1064
+ default: "ASSETS",
1065
+ description:
1066
+ "The service to fallback to at the end of the `next` chain. Setting to '' will fallback to the global `fetch`.",
1067
+ },
1068
+ watch: {
1069
+ type: "boolean",
1070
+ default: false,
1071
+ description:
1072
+ "Watch for changes to the functions and automatically rebuild the Worker script",
1073
+ },
1074
+ })
1075
+ .epilogue(pagesBetaWarning),
1076
+ async ({
1077
+ directory,
1078
+ "script-path": scriptPath,
1079
+ "output-config-path": outputConfigPath,
1080
+ minify,
1081
+ sourcemap,
1082
+ fallbackService,
1083
+ watch,
1084
+ }) => {
1085
+ // Beta message for `wrangler pages <commands>` usage
1086
+ console.log(pagesBetaWarning);
1087
+
1088
+ await buildFunctions({
1089
+ scriptPath,
1090
+ outputConfigPath,
1091
+ functionsDirectory: directory,
1092
+ minify,
1093
+ sourcemap,
1094
+ fallbackService,
1095
+ watch,
1096
+ });
1097
+ }
1098
+ )
1099
+ )
1100
+ .command("project", false, (yargs) =>
1101
+ yargs.command(
1102
+ "list",
1103
+ "List your Cloudflare Pages projects",
1104
+ () => {},
1105
+ async (args) => {
1106
+ const config = readConfig(args.config as ConfigPath, args);
1107
+ const accountId = await requireAuth(config);
1108
+
1109
+ const projects: Array<Project> = await listProjects({ accountId });
312
1110
 
313
- miniflareServer.listen(0, () => {
314
- const address = miniflareServer.address();
315
- if (typeof address === "string")
316
- return exit(
317
- "Could not determine Miniflare's port. Please report this issue to the Wrangler team."
1111
+ const data = projects.map((project) => {
1112
+ return {
1113
+ "Project Name": project.name,
1114
+ "Project Domains": `${project.domains.join(", ")}`,
1115
+ "Git Provider": project.source ? "Yes" : "No",
1116
+ "Last Modified": format(project.latest_deployment.modified_on),
1117
+ };
1118
+ });
1119
+ render(<Table data={data}></Table>);
1120
+ }
1121
+ )
1122
+ )
1123
+ .command("deployment", false, (yargs) =>
1124
+ yargs.command(
1125
+ "list",
1126
+ "List deployments in your Cloudflare Pages project",
1127
+ (yargs) =>
1128
+ yargs.options({
1129
+ project: {
1130
+ type: "string",
1131
+ demandOption: true,
1132
+ description:
1133
+ "The name of the project you would like to list deployments for",
1134
+ },
1135
+ }),
1136
+ async (args) => {
1137
+ const config = readConfig(args.config as ConfigPath, args);
1138
+ const accountId = await requireAuth(config);
1139
+
1140
+ const deployments: Array<Deployment> = await fetchResult(
1141
+ `/accounts/${accountId}/pages/projects/${args.project}/deployments`
318
1142
  );
319
1143
 
320
- const miniflarePort = address.port;
1144
+ const titleCase = (word: string) =>
1145
+ word.charAt(0).toUpperCase() + word.slice(1);
321
1146
 
322
- const app = express();
1147
+ const shortSha = (sha: string) => sha.slice(0, 7);
323
1148
 
324
- app.use(
325
- "/",
326
- httpProxyMiddleware.createProxyMiddleware({
327
- target: `http://127.0.0.1:${miniflarePort}`,
328
- })
329
- );
1149
+ const getStatus = (deployment: Deployment) => {
1150
+ // Return a pretty time since timestamp if successful otherwise the status
1151
+ if (deployment.latest_stage.status === `success`) {
1152
+ return format(deployment.latest_stage.ended_on);
1153
+ }
1154
+ return titleCase(deployment.latest_stage.status);
1155
+ };
330
1156
 
331
- app.use(
332
- "/",
333
- httpProxyMiddleware.createProxyMiddleware({
334
- target: `http://127.0.0.1:${proxyPort}`,
335
- })
336
- );
1157
+ const data = deployments.map((deployment) => {
1158
+ return {
1159
+ Environment: titleCase(deployment.environment),
1160
+ Branch: deployment.deployment_trigger.metadata.branch,
1161
+ Source: shortSha(
1162
+ deployment.deployment_trigger.metadata.commit_hash
1163
+ ),
1164
+ Deployment: deployment.url,
1165
+ Status: getStatus(deployment),
1166
+ // TODO: Use a url shortener
1167
+ Build: `https://dash.cloudflare.com/${accountId}/pages/view/${deployment.project_name}/${deployment.id}`,
1168
+ };
1169
+ });
1170
+ render(<Table data={data}></Table>);
1171
+ }
1172
+ )
1173
+ );
1174
+ };
337
1175
 
338
- app.listen(port, () => {
339
- console.log(`Serving at http://127.0.0.1:${port}/`);
340
- });
341
- });
342
- }
1176
+ const invalidAssetsFetch: typeof fetch = () => {
1177
+ throw new Error(
1178
+ "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
343
1179
  );
344
1180
  };
1181
+
1182
+ const listProjects = async ({
1183
+ accountId,
1184
+ }: {
1185
+ accountId: string;
1186
+ }): Promise<Array<Project>> => {
1187
+ const pageSize = 10;
1188
+ let page = 1;
1189
+ const results = [];
1190
+ while (results.length % pageSize === 0) {
1191
+ const json: Array<Project> = await fetchResult(
1192
+ `/accounts/${accountId}/pages/projects`,
1193
+ {},
1194
+ new URLSearchParams({
1195
+ per_page: pageSize.toString(),
1196
+ page: page.toString(),
1197
+ })
1198
+ );
1199
+ page++;
1200
+ results.push(...json);
1201
+ if (json.length < pageSize) {
1202
+ break;
1203
+ }
1204
+ }
1205
+ return results;
1206
+ };