wrangler 0.0.0-e95e5a0 → 0.0.0-e98613f8

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 (305) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +26 -4
  3. package/bin/wrangler.js +166 -34
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +1456 -21
  6. package/package.json +191 -148
  7. package/src/__tests__/access.test.ts +25 -0
  8. package/src/__tests__/api-dev.test.ts +209 -0
  9. package/src/__tests__/api-devregistry.test.js +56 -0
  10. package/src/__tests__/api.test.ts +80 -0
  11. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  12. package/src/__tests__/config-cache.test.ts +30 -24
  13. package/src/__tests__/configuration.test.ts +3970 -3114
  14. package/src/__tests__/d1.test.ts +80 -0
  15. package/src/__tests__/delete.test.ts +263 -0
  16. package/src/__tests__/deployments.test.ts +91 -0
  17. package/src/__tests__/dev.test.tsx +1528 -737
  18. package/src/__tests__/dialogs.test.tsx +40 -0
  19. package/src/__tests__/generate.test.ts +235 -0
  20. package/src/__tests__/get-host-from-url.test.ts +16 -0
  21. package/src/__tests__/guess-worker-format.test.ts +68 -68
  22. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  23. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  24. package/src/__tests__/helpers/mock-bin.ts +20 -20
  25. package/src/__tests__/helpers/mock-cfetch.ts +216 -94
  26. package/src/__tests__/helpers/mock-console.ts +58 -39
  27. package/src/__tests__/helpers/mock-dialogs.ts +114 -51
  28. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  29. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  30. package/src/__tests__/helpers/mock-istty.ts +65 -18
  31. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  32. package/src/__tests__/helpers/mock-kv.ts +27 -27
  33. package/src/__tests__/helpers/mock-oauth-flow.ts +229 -228
  34. package/src/__tests__/helpers/mock-process.ts +39 -0
  35. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  36. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  37. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  38. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  39. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  40. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  41. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  42. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  43. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  44. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  45. package/src/__tests__/helpers/msw/index.ts +21 -0
  46. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  47. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  48. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  50. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  52. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  53. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  54. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  55. package/src/__tests__/https-options.test.ts +142 -109
  56. package/src/__tests__/index.test.ts +246 -231
  57. package/src/__tests__/init.test.ts +2887 -1488
  58. package/src/__tests__/jest.setup.ts +163 -30
  59. package/src/__tests__/kv.test.ts +1660 -1439
  60. package/src/__tests__/logger.test.ts +100 -74
  61. package/src/__tests__/logout.test.ts +47 -0
  62. package/src/__tests__/metrics.test.ts +450 -0
  63. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  64. package/src/__tests__/middleware.test.ts +726 -0
  65. package/src/__tests__/package-manager.test.ts +312 -165
  66. package/src/__tests__/pages-deployment-tail.test.ts +820 -0
  67. package/src/__tests__/pages.test.ts +2435 -322
  68. package/src/__tests__/parse.test.ts +253 -245
  69. package/src/__tests__/paths.test.ts +39 -0
  70. package/src/__tests__/publish.test.ts +7536 -4778
  71. package/src/__tests__/pubsub.test.ts +370 -0
  72. package/src/__tests__/queues.test.ts +522 -0
  73. package/src/__tests__/r2.test.ts +388 -209
  74. package/src/__tests__/route.test.ts +18 -18
  75. package/src/__tests__/secret.test.ts +624 -426
  76. package/src/__tests__/tail.test.ts +776 -567
  77. package/src/__tests__/test-old-node-version.js +31 -0
  78. package/src/__tests__/type-generation.test.ts +226 -0
  79. package/src/__tests__/user.test.ts +117 -119
  80. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  81. package/src/__tests__/validate-dev-props.test.ts +56 -0
  82. package/src/__tests__/version.test.ts +35 -0
  83. package/src/__tests__/whoami.test.tsx +264 -91
  84. package/src/__tests__/worker-namespace.test.ts +326 -0
  85. package/src/abort.d.ts +3 -0
  86. package/src/api/dev.ts +210 -0
  87. package/src/api/index.ts +2 -0
  88. package/src/bundle-reporter.tsx +68 -0
  89. package/src/bundle.ts +789 -135
  90. package/src/cfetch/index.ts +123 -67
  91. package/src/cfetch/internal.ts +216 -90
  92. package/src/cli.ts +23 -8
  93. package/src/config/config.ts +236 -195
  94. package/src/config/diagnostics.ts +61 -61
  95. package/src/config/environment.ts +506 -339
  96. package/src/config/index.ts +309 -38
  97. package/src/config/validation-helpers.ts +379 -357
  98. package/src/config/validation.ts +1942 -1263
  99. package/src/config-cache.ts +81 -41
  100. package/src/create-worker-preview.ts +239 -132
  101. package/src/create-worker-upload-form.ts +300 -224
  102. package/src/d1/backups.tsx +223 -0
  103. package/src/d1/constants.ts +2 -0
  104. package/src/d1/create.tsx +63 -0
  105. package/src/d1/delete.tsx +56 -0
  106. package/src/d1/execute.tsx +352 -0
  107. package/src/d1/formatTimeAgo.ts +14 -0
  108. package/src/d1/index.ts +101 -0
  109. package/src/d1/list.tsx +48 -0
  110. package/src/d1/migrations/apply.tsx +184 -0
  111. package/src/d1/migrations/create.tsx +77 -0
  112. package/src/d1/migrations/helpers.ts +147 -0
  113. package/src/d1/migrations/index.tsx +3 -0
  114. package/src/d1/migrations/list.tsx +79 -0
  115. package/src/d1/migrations/options.ts +18 -0
  116. package/src/d1/options.ts +22 -0
  117. package/src/d1/types.tsx +24 -0
  118. package/src/d1/utils.ts +48 -0
  119. package/src/delete.ts +108 -0
  120. package/src/deployments.ts +77 -0
  121. package/src/deprecated/index.ts +438 -0
  122. package/src/dev/dev-vars.ts +20 -17
  123. package/src/dev/dev.tsx +549 -353
  124. package/src/dev/get-local-persistence-path.tsx +31 -0
  125. package/src/dev/local.tsx +870 -292
  126. package/src/dev/remote.tsx +591 -201
  127. package/src/dev/start-server.ts +539 -0
  128. package/src/dev/use-esbuild.ts +183 -97
  129. package/src/dev/validate-dev-props.ts +31 -0
  130. package/src/dev-registry.tsx +201 -0
  131. package/src/dev.tsx +913 -0
  132. package/src/dialogs.tsx +146 -65
  133. package/src/dispatch-namespace.ts +207 -0
  134. package/src/durable.ts +102 -0
  135. package/src/entry.ts +248 -186
  136. package/src/environment-variables.ts +38 -23
  137. package/src/errors.ts +6 -6
  138. package/src/git-client.ts +135 -0
  139. package/src/global-wrangler-config-path.ts +26 -0
  140. package/src/https-options.ts +84 -80
  141. package/src/index.tsx +636 -2617
  142. package/src/init.ts +970 -0
  143. package/src/inspect.ts +706 -562
  144. package/src/intl-polyfill.d.ts +123 -123
  145. package/src/is-ci.ts +14 -0
  146. package/src/is-interactive.ts +16 -0
  147. package/src/kv/helpers.ts +430 -0
  148. package/src/kv/index.ts +596 -0
  149. package/src/logger.ts +67 -41
  150. package/src/metrics/index.ts +5 -0
  151. package/src/metrics/metrics-config.ts +239 -0
  152. package/src/metrics/metrics-dispatcher.ts +96 -0
  153. package/src/metrics/metrics-usage-headers.ts +24 -0
  154. package/src/metrics/send-event.ts +96 -0
  155. package/src/miniflare-cli/assets.ts +220 -0
  156. package/src/miniflare-cli/index.ts +205 -33
  157. package/src/miniflare-cli/request-context.ts +18 -18
  158. package/src/module-collection.ts +221 -212
  159. package/src/open-in-browser.ts +5 -14
  160. package/src/package-manager.ts +182 -90
  161. package/src/pages/build.tsx +270 -0
  162. package/src/pages/constants.ts +18 -0
  163. package/src/pages/deployment-tails.tsx +284 -0
  164. package/src/pages/deployments.tsx +84 -0
  165. package/src/pages/dev.tsx +706 -0
  166. package/src/pages/errors.ts +66 -0
  167. package/src/pages/functions/buildPlugin.ts +107 -0
  168. package/src/pages/functions/buildWorker.ts +166 -0
  169. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  170. package/src/pages/functions/filepath-routing.ts +189 -0
  171. package/src/pages/functions/identifiers.ts +78 -0
  172. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  173. package/src/pages/functions/routes-consolidation.ts +73 -0
  174. package/src/pages/functions/routes-transformation.test.ts +282 -0
  175. package/src/pages/functions/routes-transformation.ts +115 -0
  176. package/src/pages/functions/routes-validation.test.ts +403 -0
  177. package/src/pages/functions/routes-validation.ts +202 -0
  178. package/src/pages/functions/routes.ts +151 -0
  179. package/src/pages/functions.tsx +82 -0
  180. package/src/pages/hash.tsx +13 -0
  181. package/src/pages/index.tsx +102 -0
  182. package/src/pages/projects.tsx +169 -0
  183. package/src/pages/prompt-select-project.tsx +31 -0
  184. package/src/pages/publish.tsx +451 -0
  185. package/src/pages/types.ts +41 -0
  186. package/src/pages/upload.tsx +426 -0
  187. package/src/pages/utils.ts +23 -0
  188. package/src/parse.ts +223 -120
  189. package/src/paths.ts +53 -8
  190. package/src/proxy.ts +628 -383
  191. package/src/publish/index.ts +270 -0
  192. package/src/publish/publish.ts +1035 -0
  193. package/src/pubsub/index.ts +286 -0
  194. package/src/pubsub/pubsub-commands.tsx +624 -0
  195. package/src/queues/cli/commands/consumer/add.ts +71 -0
  196. package/src/queues/cli/commands/consumer/index.ts +22 -0
  197. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  198. package/src/queues/cli/commands/create.ts +25 -0
  199. package/src/queues/cli/commands/delete.ts +26 -0
  200. package/src/queues/cli/commands/index.ts +36 -0
  201. package/src/queues/cli/commands/list.ts +25 -0
  202. package/src/queues/client.ts +135 -0
  203. package/src/queues/utils.ts +18 -0
  204. package/src/r2/constants.ts +4 -0
  205. package/src/r2/helpers.ts +131 -0
  206. package/src/r2/index.ts +289 -0
  207. package/src/routes.ts +140 -0
  208. package/src/secret/index.ts +378 -0
  209. package/src/selfsigned.d.ts +23 -23
  210. package/src/sites.tsx +281 -202
  211. package/src/tail/createTail.ts +379 -0
  212. package/src/tail/filters.ts +108 -110
  213. package/src/tail/index.ts +211 -296
  214. package/src/tail/printing.ts +86 -46
  215. package/src/type-generation.ts +173 -0
  216. package/src/update-check.ts +11 -11
  217. package/src/user/access.ts +69 -0
  218. package/src/user/choose-account.tsx +69 -0
  219. package/src/user/env-vars.ts +46 -0
  220. package/src/user/generate-auth-url.ts +33 -0
  221. package/src/user/generate-random-state.ts +16 -0
  222. package/src/user/index.ts +3 -0
  223. package/src/user/user.tsx +1198 -0
  224. package/src/utils/collectKeyValues.ts +14 -0
  225. package/src/whoami.tsx +141 -42
  226. package/src/worker.ts +174 -101
  227. package/src/yargs-types.ts +24 -0
  228. package/src/zones.ts +191 -0
  229. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  230. package/templates/checked-fetch.js +17 -0
  231. package/templates/d1-beta-facade.js +205 -0
  232. package/templates/first-party-worker-module-facade.ts +18 -0
  233. package/templates/format-dev-errors.ts +32 -0
  234. package/templates/init-tests/test-jest-new-worker.js +25 -0
  235. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  236. package/templates/middleware/common.ts +62 -0
  237. package/templates/middleware/loader-modules.ts +84 -0
  238. package/templates/middleware/loader-sw.ts +227 -0
  239. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  240. package/templates/middleware/middleware-pretty-error.ts +40 -0
  241. package/templates/middleware/middleware-scheduled.ts +15 -0
  242. package/templates/new-worker-scheduled.js +17 -0
  243. package/templates/new-worker-scheduled.ts +32 -0
  244. package/templates/new-worker.js +3 -3
  245. package/templates/new-worker.ts +18 -3
  246. package/templates/no-op-worker.js +10 -0
  247. package/templates/pages-dev-pipeline.ts +28 -0
  248. package/templates/pages-dev-util.ts +52 -0
  249. package/templates/pages-shim.ts +9 -0
  250. package/templates/pages-template-plugin.ts +171 -0
  251. package/templates/pages-template-worker.ts +189 -0
  252. package/templates/serve-static-assets.ts +63 -0
  253. package/templates/service-bindings-module-facade.js +54 -0
  254. package/templates/service-bindings-sw-facade.js +42 -0
  255. package/templates/tsconfig.json +96 -95
  256. package/wrangler-dist/cli.d.ts +893 -0
  257. package/wrangler-dist/cli.js +95201 -44118
  258. package/pages/functions/buildPlugin.ts +0 -92
  259. package/pages/functions/buildWorker.ts +0 -138
  260. package/pages/functions/filepath-routing.ts +0 -189
  261. package/pages/functions/identifiers.ts +0 -78
  262. package/pages/functions/routes.ts +0 -156
  263. package/pages/functions/template-plugin.ts +0 -146
  264. package/pages/functions/template-worker.ts +0 -143
  265. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  266. package/src/kv.ts +0 -319
  267. package/src/miniflare-cli/enum-keys.ts +0 -17
  268. package/src/pages.tsx +0 -1866
  269. package/src/publish.ts +0 -469
  270. package/src/r2.ts +0 -50
  271. package/src/user.tsx +0 -1193
  272. package/templates/static-asset-facade.js +0 -47
  273. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  274. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  275. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  276. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  277. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  278. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  279. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  280. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  281. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  282. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  283. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  284. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  285. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  286. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  287. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  288. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  289. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  290. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  291. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  292. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  293. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  294. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  295. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  296. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  297. package/vendor/wrangler-mime/LICENSE +0 -21
  298. package/vendor/wrangler-mime/Mime.js +0 -97
  299. package/vendor/wrangler-mime/README.md +0 -187
  300. package/vendor/wrangler-mime/cli.js +0 -46
  301. package/vendor/wrangler-mime/index.js +0 -4
  302. package/vendor/wrangler-mime/lite.js +0 -4
  303. package/vendor/wrangler-mime/package.json +0 -52
  304. package/vendor/wrangler-mime/types/other.js +0 -1
  305. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/pages.tsx DELETED
@@ -1,1866 +0,0 @@
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 { readdir, readFile, stat } from "node:fs/promises";
6
- import { tmpdir } from "node:os";
7
- import { dirname, join, sep } from "node:path";
8
- import { cwd } from "node:process";
9
- import { URL } from "node:url";
10
- import { hash } from "blake3-wasm";
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";
16
- import { getType } from "mime";
17
- import prettyBytes from "pretty-bytes";
18
- import React from "react";
19
- import { format as timeagoFormat } from "timeago.js";
20
- import { File, FormData } from "undici";
21
- import { buildPlugin } from "../pages/functions/buildPlugin";
22
- import { buildWorker } from "../pages/functions/buildWorker";
23
- import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
24
- import { writeRoutesModule } from "../pages/functions/routes";
25
- import { fetchResult } from "./cfetch";
26
- import { getConfigCache, saveToConfigCache } from "./config-cache";
27
- import { prompt } from "./dialogs";
28
- import { FatalError } from "./errors";
29
- import { logger } from "./logger";
30
- import { getRequestContextCheckOptions } from "./miniflare-cli/request-context";
31
- import openInBrowser from "./open-in-browser";
32
- import { toUrlPath } from "./paths";
33
- import { requireAuth } from "./user";
34
- import type { Config } from "../pages/functions/routes";
35
- import type { Headers, Request, fetch } from "@miniflare/core";
36
- import type { BuildResult } from "esbuild";
37
- import type { MiniflareOptions } from "miniflare";
38
- import type { BuilderCallback, CommandModule } from "yargs";
39
-
40
- export type Project = {
41
- name: string;
42
- subdomain: string;
43
- domains: Array<string>;
44
- source?: {
45
- type: string;
46
- };
47
- latest_deployment?: {
48
- modified_on: string;
49
- };
50
- created_on: string;
51
- production_branch: string;
52
- };
53
-
54
- export type Deployment = {
55
- id: string;
56
- environment: string;
57
- deployment_trigger: {
58
- metadata: {
59
- commit_hash: string;
60
- branch: string;
61
- };
62
- };
63
- url: string;
64
- latest_stage: {
65
- status: string;
66
- ended_on: string;
67
- };
68
- project_name: string;
69
- };
70
-
71
- interface PagesConfigCache {
72
- account_id?: string;
73
- project_name?: string;
74
- }
75
-
76
- const PAGES_CONFIG_CACHE_FILENAME = "pages.json";
77
-
78
- // Defer importing miniflare until we really need it. This takes ~0.5s
79
- // and also modifies some `stream/web` and `undici` prototypes, so we
80
- // don't want to do this if pages commands aren't being called.
81
-
82
- export const pagesBetaWarning =
83
- "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose";
84
-
85
- const CLEANUP_CALLBACKS: (() => void)[] = [];
86
- const CLEANUP = () => {
87
- CLEANUP_CALLBACKS.forEach((callback) => callback());
88
- RUNNING_BUILDERS.forEach((builder) => builder.stop?.());
89
- };
90
-
91
- process.on("SIGINT", () => {
92
- CLEANUP();
93
- process.exit();
94
- });
95
- process.on("SIGTERM", () => {
96
- CLEANUP();
97
- process.exit();
98
- });
99
-
100
- function isWindows() {
101
- return process.platform === "win32";
102
- }
103
-
104
- const SECONDS_TO_WAIT_FOR_PROXY = 5;
105
-
106
- async function sleep(ms: number) {
107
- await new Promise((resolve) => setTimeout(resolve, ms));
108
- }
109
-
110
- function getPids(pid: number) {
111
- const pids: number[] = [pid];
112
- let command: string, regExp: RegExp;
113
-
114
- if (isWindows()) {
115
- command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
116
- regExp = new RegExp(/(\d+)/);
117
- } else {
118
- command = `pgrep -P ${pid}`;
119
- regExp = new RegExp(/(\d+)/);
120
- }
121
-
122
- try {
123
- const newPids = (
124
- execSync(command)
125
- .toString()
126
- .split("\n")
127
- .map((line) => line.match(regExp))
128
- .filter((line) => line !== null) as RegExpExecArray[]
129
- ).map((match) => parseInt(match[1]));
130
-
131
- pids.push(...newPids.map(getPids).flat());
132
- } catch {}
133
-
134
- return pids;
135
- }
136
-
137
- function getPort(pid: number) {
138
- let command: string, regExp: RegExp;
139
-
140
- if (isWindows()) {
141
- command = "\\windows\\system32\\netstat.exe -nao";
142
- regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
143
- } else {
144
- command = "lsof -nPi";
145
- regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
146
- }
147
-
148
- try {
149
- const matches = execSync(command)
150
- .toString()
151
- .split("\n")
152
- .map((line) => line.match(regExp))
153
- .filter((line) => line !== null) as RegExpExecArray[];
154
-
155
- const match = matches[0];
156
- if (match) return parseInt(match[1]);
157
- } catch (thrown) {
158
- logger.error(
159
- `Error scanning for ports of process with PID ${pid}: ${thrown}`
160
- );
161
- }
162
- }
163
-
164
- async function spawnProxyProcess({
165
- port,
166
- command,
167
- }: {
168
- port?: number;
169
- command: (string | number)[];
170
- }): Promise<void | number> {
171
- if (command.length === 0) {
172
- CLEANUP();
173
- throw new FatalError(
174
- "Must specify a directory of static assets to serve or a command to run.",
175
- 1
176
- );
177
- }
178
-
179
- logger.log(`Running ${command.join(" ")}...`);
180
- const proxy = spawn(
181
- command[0].toString(),
182
- command.slice(1).map((value) => value.toString()),
183
- {
184
- shell: isWindows(),
185
- env: {
186
- BROWSER: "none",
187
- ...process.env,
188
- },
189
- }
190
- );
191
- CLEANUP_CALLBACKS.push(() => {
192
- proxy.kill();
193
- });
194
-
195
- proxy.stdout.on("data", (data) => {
196
- logger.log(`[proxy]: ${data}`);
197
- });
198
-
199
- proxy.stderr.on("data", (data) => {
200
- logger.error(`[proxy]: ${data}`);
201
- });
202
-
203
- proxy.on("close", (code) => {
204
- logger.error(`Proxy exited with status ${code}.`);
205
- });
206
-
207
- // Wait for proxy process to start...
208
- while (!proxy.pid) {}
209
-
210
- if (port === undefined) {
211
- logger.log(
212
- `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
213
- );
214
- logger.log("To skip, specify the proxy port with --proxy.");
215
- await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
216
-
217
- port = getPids(proxy.pid)
218
- .map(getPort)
219
- .filter((port) => port !== undefined)[0];
220
-
221
- if (port === undefined) {
222
- CLEANUP();
223
- throw new FatalError(
224
- "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
225
- 1
226
- );
227
- } else {
228
- logger.log(`Automatically determined the proxy port to be ${port}.`);
229
- }
230
- }
231
-
232
- return port;
233
- }
234
-
235
- function escapeRegex(str: string) {
236
- return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
237
- }
238
-
239
- type Replacements = Record<string, string>;
240
-
241
- function replacer(str: string, replacements: Replacements) {
242
- for (const [replacement, value] of Object.entries(replacements)) {
243
- str = str.replace(`:${replacement}`, value);
244
- }
245
- return str;
246
- }
247
-
248
- function generateRulesMatcher<T>(
249
- rules?: Record<string, T>,
250
- replacer: (match: T, replacements: Replacements) => T = (match) => match
251
- ) {
252
- // TODO: How can you test cross-host rules?
253
- if (!rules) return () => [];
254
-
255
- const compiledRules = Object.entries(rules)
256
- .map(([rule, match]) => {
257
- const crossHost = rule.startsWith("https://");
258
-
259
- rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
260
-
261
- const host_matches = rule.matchAll(
262
- /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
263
- );
264
- for (const match of host_matches) {
265
- rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`);
266
- }
267
-
268
- const path_matches = rule.matchAll(/:(\w+)/g);
269
- for (const match of path_matches) {
270
- rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);
271
- }
272
-
273
- rule = "^" + rule + "$";
274
-
275
- try {
276
- const regExp = new RegExp(rule);
277
- return [{ crossHost, regExp }, match];
278
- } catch {}
279
- })
280
- .filter((value) => value !== undefined) as [
281
- { crossHost: boolean; regExp: RegExp },
282
- T
283
- ][];
284
-
285
- return ({ request }: { request: Request }) => {
286
- const { pathname, host } = new URL(request.url);
287
-
288
- return compiledRules
289
- .map(([{ crossHost, regExp }, match]) => {
290
- const test = crossHost ? `https://${host}${pathname}` : pathname;
291
- const result = regExp.exec(test);
292
- if (result) {
293
- return replacer(match, result.groups || {});
294
- }
295
- })
296
- .filter((value) => value !== undefined) as T[];
297
- };
298
- }
299
-
300
- function generateHeadersMatcher(headersFile: string) {
301
- if (existsSync(headersFile)) {
302
- const contents = readFileSync(headersFile).toString();
303
-
304
- // TODO: Log errors
305
- const lines = contents
306
- .split("\n")
307
- .map((line) => line.trim())
308
- .filter((line) => !line.startsWith("#") && line !== "");
309
-
310
- const rules: Record<string, Record<string, string>> = {};
311
- let rule: { path: string; headers: Record<string, string> } | undefined =
312
- undefined;
313
-
314
- for (const line of lines) {
315
- if (/^([^\s]+:\/\/|^\/)/.test(line)) {
316
- if (rule && Object.keys(rule.headers).length > 0) {
317
- rules[rule.path] = rule.headers;
318
- }
319
-
320
- const path = validateURL(line);
321
- if (path) {
322
- rule = {
323
- path,
324
- headers: {},
325
- };
326
- continue;
327
- }
328
- }
329
-
330
- if (!line.includes(":")) continue;
331
-
332
- const [rawName, ...rawValue] = line.split(":");
333
- const name = rawName.trim().toLowerCase();
334
- const value = rawValue.join(":").trim();
335
-
336
- if (name === "") continue;
337
- if (!rule) continue;
338
-
339
- const existingValues = rule.headers[name];
340
- rule.headers[name] = existingValues
341
- ? `${existingValues}, ${value}`
342
- : value;
343
- }
344
-
345
- if (rule && Object.keys(rule.headers).length > 0) {
346
- rules[rule.path] = rule.headers;
347
- }
348
-
349
- const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
350
- Object.fromEntries(
351
- Object.entries(match).map(([name, value]) => [
352
- name,
353
- replacer(value, replacements),
354
- ])
355
- )
356
- );
357
-
358
- return (request: Request) => {
359
- const matches = rulesMatcher({
360
- request,
361
- });
362
- if (matches) return matches;
363
- };
364
- } else {
365
- return () => undefined;
366
- }
367
- }
368
-
369
- function generateRedirectsMatcher(redirectsFile: string) {
370
- if (existsSync(redirectsFile)) {
371
- const contents = readFileSync(redirectsFile).toString();
372
-
373
- // TODO: Log errors
374
- const lines = contents
375
- .split("\n")
376
- .map((line) => line.trim())
377
- .filter((line) => !line.startsWith("#") && line !== "");
378
-
379
- const rules = Object.fromEntries(
380
- lines
381
- .map((line) => line.split(" "))
382
- .filter((tokens) => tokens.length === 2 || tokens.length === 3)
383
- .map((tokens) => {
384
- const from = validateURL(tokens[0], true, false, false);
385
- const to = validateURL(tokens[1], false, true, true);
386
- let status: number | undefined = parseInt(tokens[2]) || 302;
387
- status = [301, 302, 303, 307, 308].includes(status)
388
- ? status
389
- : undefined;
390
-
391
- return from && to && status ? [from, { to, status }] : undefined;
392
- })
393
- .filter((rule) => rule !== undefined) as [
394
- string,
395
- { to: string; status?: number }
396
- ][]
397
- );
398
-
399
- const rulesMatcher = generateRulesMatcher(
400
- rules,
401
- ({ status, to }, replacements) => ({
402
- status,
403
- to: replacer(to, replacements),
404
- })
405
- );
406
-
407
- return (request: Request) => {
408
- const match = rulesMatcher({
409
- request,
410
- })[0];
411
- if (match) return match;
412
- };
413
- } else {
414
- return () => undefined;
415
- }
416
- }
417
-
418
- function extractPathname(
419
- path = "/",
420
- includeSearch: boolean,
421
- includeHash: boolean
422
- ) {
423
- if (!path.startsWith("/")) path = `/${path}`;
424
- const url = new URL(`//${path}`, "relative://");
425
- return `${url.pathname}${includeSearch ? url.search : ""}${
426
- includeHash ? url.hash : ""
427
- }`;
428
- }
429
-
430
- function validateURL(
431
- token: string,
432
- onlyRelative = false,
433
- includeSearch = false,
434
- includeHash = false
435
- ) {
436
- const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
437
- if (host && host.groups && host.groups.host) {
438
- if (onlyRelative) return;
439
-
440
- return `https://${host.groups.host}${extractPathname(
441
- host.groups.path,
442
- includeSearch,
443
- includeHash
444
- )}`;
445
- } else {
446
- if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
447
-
448
- const path = /^\//.exec(token);
449
- if (path) {
450
- try {
451
- return extractPathname(token, includeSearch, includeHash);
452
- } catch {}
453
- }
454
- }
455
- return "";
456
- }
457
-
458
- function hasFileExtension(pathname: string) {
459
- return /\/.+\.[a-z0-9]+$/i.test(pathname);
460
- }
461
-
462
- async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
463
- // Defer importing miniflare until we really need it
464
- const { Headers, Request, Response } = await import("@miniflare/core");
465
-
466
- const headersFile = join(directory, "_headers");
467
- const redirectsFile = join(directory, "_redirects");
468
- const workerFile = join(directory, "_worker.js");
469
-
470
- const ignoredFiles = [headersFile, redirectsFile, workerFile];
471
-
472
- const assetExists = (path: string) => {
473
- path = join(directory, path);
474
- return (
475
- existsSync(path) &&
476
- lstatSync(path).isFile() &&
477
- !ignoredFiles.includes(path)
478
- );
479
- };
480
-
481
- const getAsset = (path: string) => {
482
- if (assetExists(path)) {
483
- return join(directory, path);
484
- }
485
- };
486
-
487
- let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
488
- let headersMatcher = generateHeadersMatcher(headersFile);
489
-
490
- watch([headersFile, redirectsFile], {
491
- persistent: true,
492
- }).on("change", (path) => {
493
- switch (path) {
494
- case headersFile: {
495
- logger.log("_headers modified. Re-evaluating...");
496
- headersMatcher = generateHeadersMatcher(headersFile);
497
- break;
498
- }
499
- case redirectsFile: {
500
- logger.log("_redirects modified. Re-evaluating...");
501
- redirectsMatcher = generateRedirectsMatcher(redirectsFile);
502
- break;
503
- }
504
- }
505
- });
506
-
507
- const serveAsset = (file: string) => {
508
- return readFileSync(file);
509
- };
510
-
511
- const generateResponse = (request: Request) => {
512
- const url = new URL(request.url);
513
-
514
- const deconstructedResponse: {
515
- status: number;
516
- headers: Headers;
517
- body?: Buffer;
518
- } = {
519
- status: 200,
520
- headers: new Headers(),
521
- body: undefined,
522
- };
523
-
524
- const match = redirectsMatcher(request);
525
- if (match) {
526
- const { status, to } = match;
527
-
528
- let location = to;
529
- let search;
530
-
531
- if (to.startsWith("/")) {
532
- search = new URL(location, "http://fakehost").search;
533
- } else {
534
- search = new URL(location).search;
535
- }
536
-
537
- location = `${location}${search ? "" : url.search}`;
538
-
539
- if (status && [301, 302, 303, 307, 308].includes(status)) {
540
- deconstructedResponse.status = status;
541
- } else {
542
- deconstructedResponse.status = 302;
543
- }
544
-
545
- deconstructedResponse.headers.set("Location", location);
546
- return deconstructedResponse;
547
- }
548
-
549
- if (!request.method?.match(/^(get|head)$/i)) {
550
- deconstructedResponse.status = 405;
551
- return deconstructedResponse;
552
- }
553
-
554
- const notFound = () => {
555
- let cwd = url.pathname;
556
- while (cwd) {
557
- cwd = cwd.slice(0, cwd.lastIndexOf("/"));
558
-
559
- if ((asset = getAsset(`${cwd}/404.html`))) {
560
- deconstructedResponse.status = 404;
561
- deconstructedResponse.body = serveAsset(asset);
562
- deconstructedResponse.headers.set(
563
- "Content-Type",
564
- getType(asset) || "application/octet-stream"
565
- );
566
- return deconstructedResponse;
567
- }
568
- }
569
-
570
- if ((asset = getAsset(`/index.html`))) {
571
- deconstructedResponse.body = serveAsset(asset);
572
- deconstructedResponse.headers.set(
573
- "Content-Type",
574
- getType(asset) || "application/octet-stream"
575
- );
576
- return deconstructedResponse;
577
- }
578
-
579
- deconstructedResponse.status = 404;
580
- return deconstructedResponse;
581
- };
582
-
583
- let asset;
584
-
585
- if (url.pathname.endsWith("/")) {
586
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
587
- deconstructedResponse.body = serveAsset(asset);
588
- deconstructedResponse.headers.set(
589
- "Content-Type",
590
- getType(asset) || "application/octet-stream"
591
- );
592
- return deconstructedResponse;
593
- } else if (
594
- (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
595
- ) {
596
- deconstructedResponse.status = 301;
597
- deconstructedResponse.headers.set(
598
- "Location",
599
- `${url.pathname.slice(0, -1)}${url.search}`
600
- );
601
- return deconstructedResponse;
602
- }
603
- }
604
-
605
- if (url.pathname.endsWith("/index")) {
606
- deconstructedResponse.status = 301;
607
- deconstructedResponse.headers.set(
608
- "Location",
609
- `${url.pathname.slice(0, -"index".length)}${url.search}`
610
- );
611
- return deconstructedResponse;
612
- }
613
-
614
- if ((asset = getAsset(url.pathname))) {
615
- if (url.pathname.endsWith(".html")) {
616
- const extensionlessPath = url.pathname.slice(0, -".html".length);
617
- if (getAsset(extensionlessPath) || extensionlessPath === "/") {
618
- deconstructedResponse.body = serveAsset(asset);
619
- deconstructedResponse.headers.set(
620
- "Content-Type",
621
- getType(asset) || "application/octet-stream"
622
- );
623
- return deconstructedResponse;
624
- } else {
625
- deconstructedResponse.status = 301;
626
- deconstructedResponse.headers.set(
627
- "Location",
628
- `${extensionlessPath}${url.search}`
629
- );
630
- return deconstructedResponse;
631
- }
632
- } else {
633
- deconstructedResponse.body = serveAsset(asset);
634
- deconstructedResponse.headers.set(
635
- "Content-Type",
636
- getType(asset) || "application/octet-stream"
637
- );
638
- return deconstructedResponse;
639
- }
640
- } else if (hasFileExtension(url.pathname)) {
641
- notFound();
642
- return deconstructedResponse;
643
- }
644
-
645
- if ((asset = getAsset(`${url.pathname}.html`))) {
646
- deconstructedResponse.body = serveAsset(asset);
647
- deconstructedResponse.headers.set(
648
- "Content-Type",
649
- getType(asset) || "application/octet-stream"
650
- );
651
- return deconstructedResponse;
652
- }
653
-
654
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
655
- deconstructedResponse.status = 301;
656
- deconstructedResponse.headers.set(
657
- "Location",
658
- `${url.pathname}/${url.search}`
659
- );
660
- return deconstructedResponse;
661
- } else {
662
- notFound();
663
- return deconstructedResponse;
664
- }
665
- };
666
-
667
- const attachHeaders = (
668
- request: Request,
669
- deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
670
- ) => {
671
- const headers = deconstructedResponse.headers;
672
- const newHeaders = new Headers({});
673
- const matches = headersMatcher(request) || [];
674
-
675
- matches.forEach((match) => {
676
- Object.entries(match).forEach(([name, value]) => {
677
- newHeaders.append(name, `${value}`);
678
- });
679
- });
680
-
681
- const combinedHeaders = {
682
- ...Object.fromEntries(headers.entries()),
683
- ...Object.fromEntries(newHeaders.entries()),
684
- };
685
-
686
- deconstructedResponse.headers = new Headers({});
687
- Object.entries(combinedHeaders).forEach(([name, value]) => {
688
- if (value) deconstructedResponse.headers.set(name, value);
689
- });
690
- };
691
-
692
- return async (input, init) => {
693
- const request = new Request(input, init);
694
- const deconstructedResponse = generateResponse(request);
695
- attachHeaders(request, deconstructedResponse);
696
-
697
- const headers = new Headers();
698
-
699
- [...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
700
- if (value) headers.set(name, value);
701
- });
702
-
703
- return new Response(deconstructedResponse.body, {
704
- headers,
705
- status: deconstructedResponse.status,
706
- });
707
- };
708
- }
709
-
710
- const RUNNING_BUILDERS: BuildResult[] = [];
711
-
712
- async function buildFunctions({
713
- outfile,
714
- outputConfigPath,
715
- functionsDirectory,
716
- minify = false,
717
- sourcemap = false,
718
- fallbackService = "ASSETS",
719
- watch = false,
720
- onEnd,
721
- plugin = false,
722
- buildOutputDirectory,
723
- }: {
724
- outfile: string;
725
- outputConfigPath?: string;
726
- functionsDirectory: string;
727
- minify?: boolean;
728
- sourcemap?: boolean;
729
- fallbackService?: string;
730
- watch?: boolean;
731
- onEnd?: () => void;
732
- plugin?: boolean;
733
- buildOutputDirectory?: string;
734
- }) {
735
- RUNNING_BUILDERS.forEach(
736
- (runningBuilder) => runningBuilder.stop && runningBuilder.stop()
737
- );
738
-
739
- const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
740
- const baseURL = toUrlPath("/");
741
-
742
- const config: Config = await generateConfigFromFileTree({
743
- baseDir: functionsDirectory,
744
- baseURL,
745
- });
746
-
747
- if (outputConfigPath) {
748
- writeFileSync(
749
- outputConfigPath,
750
- JSON.stringify({ ...config, baseURL }, null, 2)
751
- );
752
- }
753
-
754
- await writeRoutesModule({
755
- config,
756
- srcDir: functionsDirectory,
757
- outfile: routesModule,
758
- });
759
-
760
- if (plugin) {
761
- RUNNING_BUILDERS.push(
762
- await buildPlugin({
763
- routesModule,
764
- outfile,
765
- minify,
766
- sourcemap,
767
- watch,
768
- onEnd,
769
- })
770
- );
771
- } else {
772
- RUNNING_BUILDERS.push(
773
- await buildWorker({
774
- routesModule,
775
- outfile,
776
- minify,
777
- sourcemap,
778
- fallbackService,
779
- watch,
780
- onEnd,
781
- buildOutputDirectory,
782
- })
783
- );
784
- }
785
- }
786
-
787
- interface CreateDeploymentArgs {
788
- directory: string;
789
- projectName?: string;
790
- branch?: string;
791
- commitHash?: string;
792
- commitMessage?: string;
793
- commitDirty?: boolean;
794
- }
795
-
796
- const createDeployment: CommandModule<
797
- CreateDeploymentArgs,
798
- CreateDeploymentArgs
799
- > = {
800
- describe: "🆙 Publish a directory of static assets as a Pages deployment",
801
- builder: (yargs) => {
802
- return yargs
803
- .positional("directory", {
804
- type: "string",
805
- default: "functions",
806
- description: "The directory of Pages Functions",
807
- })
808
- .options({
809
- "project-name": {
810
- type: "string",
811
- description:
812
- "The name of the project you want to list deployments for",
813
- },
814
- branch: {
815
- type: "string",
816
- description:
817
- "The branch of the project you want to list deployments for",
818
- },
819
- "commit-hash": {
820
- type: "string",
821
- description:
822
- "The branch of the project you want to list deployments for",
823
- },
824
- "commit-message": {
825
- type: "string",
826
- description:
827
- "The branch of the project you want to list deployments for",
828
- },
829
- "commit-dirty": {
830
- type: "boolean",
831
- description:
832
- "The branch of the project you want to list deployments for",
833
- },
834
- })
835
- .epilogue(pagesBetaWarning);
836
- },
837
- handler: async ({
838
- directory,
839
- projectName,
840
- branch,
841
- commitHash,
842
- commitMessage,
843
- commitDirty,
844
- }) => {
845
- const config = getConfigCache<PagesConfigCache>(
846
- PAGES_CONFIG_CACHE_FILENAME
847
- );
848
- const accountId = await requireAuth(config);
849
-
850
- projectName ??= config.project_name;
851
-
852
- const isInteractive = process.stdin.isTTY;
853
- if (!projectName && isInteractive) {
854
- const existingOrNew = await new Promise<"new" | "existing">((resolve) => {
855
- const { unmount } = render(
856
- <>
857
- <Text>
858
- No project selected. Would you like to create one or use an
859
- existing project?
860
- </Text>
861
- <SelectInput
862
- items={[
863
- {
864
- key: "new",
865
- label: "Create a new project",
866
- value: "new",
867
- },
868
- {
869
- key: "existing",
870
- label: "Use an existing project",
871
- value: "existing",
872
- },
873
- ]}
874
- onSelect={async (selected) => {
875
- resolve(selected.value as "new" | "existing");
876
- unmount();
877
- }}
878
- />
879
- </>
880
- );
881
- });
882
-
883
- switch (existingOrNew) {
884
- case "existing": {
885
- const projects = (await listProjects({ accountId })).filter(
886
- (project) => !project.source
887
- );
888
- projectName = await new Promise((resolve) => {
889
- const { unmount } = render(
890
- <>
891
- <Text>Select a project:</Text>
892
- <SelectInput
893
- items={projects.map((project) => ({
894
- key: project.name,
895
- label: project.name,
896
- value: project,
897
- }))}
898
- onSelect={async (selected) => {
899
- resolve(selected.value.name);
900
- unmount();
901
- }}
902
- />
903
- </>
904
- );
905
- });
906
- break;
907
- }
908
- case "new": {
909
- projectName = await prompt("Enter the name of your new project:");
910
-
911
- if (!projectName) {
912
- throw new FatalError("Must specify a project name.", 1);
913
- }
914
-
915
- let isGitDir = true;
916
- try {
917
- execSync(`git rev-parse --is-inside-work-tree`, {
918
- stdio: "ignore",
919
- });
920
- } catch (err) {
921
- isGitDir = false;
922
- }
923
-
924
- const productionBranch = await prompt(
925
- "Enter the production branch name:",
926
- "text",
927
- isGitDir
928
- ? execSync(`git rev-parse --abbrev-ref HEAD`).toString().trim()
929
- : "production"
930
- );
931
-
932
- if (!productionBranch) {
933
- throw new FatalError("Must specify a production branch.", 1);
934
- }
935
-
936
- await fetchResult<Project>(`/accounts/${accountId}/pages/projects`, {
937
- method: "POST",
938
- body: JSON.stringify({
939
- name: projectName,
940
- production_branch: productionBranch,
941
- }),
942
- });
943
-
944
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
945
- account_id: accountId,
946
- project_name: projectName,
947
- });
948
-
949
- logger.log(`✨ Successfully created the '${projectName}' project.`);
950
- break;
951
- }
952
- }
953
- }
954
-
955
- if (!projectName) {
956
- throw new FatalError("Must specify a project name.", 1);
957
- }
958
-
959
- // We infer git info by default is not passed in
960
-
961
- let isGitDir = true;
962
- try {
963
- execSync(`git rev-parse --is-inside-work-tree`, {
964
- stdio: "ignore",
965
- });
966
- } catch (err) {
967
- isGitDir = false;
968
- }
969
-
970
- let isGitDirty = false;
971
-
972
- if (isGitDir) {
973
- try {
974
- isGitDirty = Boolean(
975
- execSync(`git status --porcelain`).toString().length
976
- );
977
-
978
- if (!branch) {
979
- branch = execSync(`git rev-parse --abbrev-ref HEAD`)
980
- .toString()
981
- .trim();
982
- }
983
-
984
- if (!commitHash) {
985
- commitHash = execSync(`git rev-parse HEAD`).toString().trim();
986
- }
987
-
988
- if (!commitMessage) {
989
- commitMessage = execSync(`git show -s --format=%B ${commitHash}`)
990
- .toString()
991
- .trim();
992
- }
993
- } catch (err) {}
994
-
995
- if (isGitDirty && !commitDirty) {
996
- logger.warn(
997
- `Warning: Your working directory is a git repo and has uncommitted changes\nTo silense this warning, pass in --commit-dirty=true`
998
- );
999
- }
1000
-
1001
- if (commitDirty === undefined) {
1002
- commitDirty = isGitDirty;
1003
- }
1004
- }
1005
-
1006
- let builtFunctions: string | undefined = undefined;
1007
- const functionsDirectory = join(cwd(), "functions");
1008
- if (existsSync(functionsDirectory)) {
1009
- const outfile = join(tmpdir(), "./functionsWorker.js");
1010
-
1011
- await new Promise((resolve) =>
1012
- buildFunctions({
1013
- outfile,
1014
- functionsDirectory,
1015
- onEnd: () => resolve(null),
1016
- buildOutputDirectory: dirname(outfile),
1017
- })
1018
- );
1019
-
1020
- builtFunctions = readFileSync(outfile, "utf-8");
1021
- }
1022
-
1023
- type File = {
1024
- content: Buffer;
1025
- metadata: Metadata;
1026
- };
1027
-
1028
- type Metadata = {
1029
- sizeInBytes: number;
1030
- hash: string;
1031
- };
1032
-
1033
- const IGNORE_LIST = [
1034
- "_worker.js",
1035
- "_redirects",
1036
- "_headers",
1037
- ".DS_Store",
1038
- "node_modules",
1039
- ];
1040
-
1041
- const walk = async (
1042
- dir: string,
1043
- fileMap: Map<string, File> = new Map(),
1044
- depth = 0
1045
- ) => {
1046
- const files = await readdir(dir);
1047
-
1048
- await Promise.all(
1049
- files.map(async (file) => {
1050
- const filepath = join(dir, file);
1051
- const filestat = await stat(filepath);
1052
-
1053
- if (IGNORE_LIST.includes(file)) {
1054
- return;
1055
- }
1056
-
1057
- if (filestat.isSymbolicLink()) {
1058
- return;
1059
- }
1060
-
1061
- if (filestat.isDirectory()) {
1062
- fileMap = await walk(filepath, fileMap, depth + 1);
1063
- } else {
1064
- let name;
1065
- if (depth) {
1066
- name = filepath.split(sep).slice(1).join("/");
1067
- } else {
1068
- name = file;
1069
- }
1070
-
1071
- // TODO: Move this to later so we don't hold as much in memory
1072
- const fileContent = await readFile(filepath);
1073
-
1074
- const base64Content = fileContent.toString("base64");
1075
- const extension =
1076
- name.split(".").length > 1 ? name.split(".").at(-1) || "" : "";
1077
-
1078
- const content = base64Content + extension;
1079
-
1080
- if (filestat.size > 25 * 1024 * 1024) {
1081
- throw new Error(
1082
- `Error: Pages only supports files up to ${prettyBytes(
1083
- 25 * 1024 * 1024
1084
- )} in size\n${name} is ${prettyBytes(filestat.size)} in size`
1085
- );
1086
- }
1087
-
1088
- fileMap.set(name, {
1089
- content: fileContent,
1090
- metadata: {
1091
- sizeInBytes: filestat.size,
1092
- hash: hash(content).toString("hex").slice(0, 32),
1093
- },
1094
- });
1095
- }
1096
- })
1097
- );
1098
-
1099
- return fileMap;
1100
- };
1101
-
1102
- const fileMap = await walk(directory);
1103
-
1104
- const start = Date.now();
1105
-
1106
- const files: Array<Promise<void>> = [];
1107
-
1108
- if (fileMap.size > 1000) {
1109
- throw new Error(
1110
- `Error: Pages only supports up to 1,000 files in a deployment at the moment.\nTry a smaller project perhaps?`
1111
- );
1112
- }
1113
-
1114
- let counter = 0;
1115
-
1116
- const { rerender, unmount } = render(
1117
- <Progress done={counter} total={fileMap.size} />
1118
- );
1119
-
1120
- fileMap.forEach((file: File, name: string) => {
1121
- const form = new FormData();
1122
- form.append(
1123
- "file",
1124
- new File([new Uint8Array(file.content.buffer)], name)
1125
- );
1126
-
1127
- // TODO: Consider a retry
1128
-
1129
- const promise = fetchResult<{ id: string }>(
1130
- `/accounts/${accountId}/pages/projects/${projectName}/file`,
1131
- {
1132
- method: "POST",
1133
- body: form,
1134
- }
1135
- ).then((response) => {
1136
- counter++;
1137
- rerender(<Progress done={counter} total={fileMap.size} />);
1138
- if (response.id != file.metadata.hash) {
1139
- throw new Error(
1140
- `Looks like there was an issue uploading '${name}'. Try again perhaps?`
1141
- );
1142
- }
1143
- });
1144
-
1145
- files.push(promise);
1146
- });
1147
-
1148
- await Promise.all(files);
1149
-
1150
- unmount();
1151
-
1152
- const uploadMs = Date.now() - start;
1153
-
1154
- logger.log(
1155
- `✨ Success! Uploaded ${fileMap.size} files ${formatTime(uploadMs)}\n`
1156
- );
1157
-
1158
- const formData = new FormData();
1159
-
1160
- formData.append(
1161
- "manifest",
1162
- JSON.stringify(
1163
- Object.fromEntries(
1164
- [...fileMap.entries()].map(([fileName, file]) => [
1165
- `/${fileName}`,
1166
- file.metadata.hash,
1167
- ])
1168
- )
1169
- )
1170
- );
1171
-
1172
- if (branch) {
1173
- formData.append("branch", branch);
1174
- }
1175
-
1176
- if (commitMessage) {
1177
- formData.append("commit_message", commitMessage);
1178
- }
1179
-
1180
- if (commitHash) {
1181
- formData.append("commit_hash", commitHash);
1182
- }
1183
-
1184
- if (commitDirty !== undefined) {
1185
- formData.append("commit_dirty", commitDirty);
1186
- }
1187
-
1188
- let _headers: string | undefined,
1189
- _redirects: string | undefined,
1190
- _workerJS: string | undefined;
1191
-
1192
- try {
1193
- _headers = readFileSync(join(directory, "_headers"), "utf-8");
1194
- } catch {}
1195
-
1196
- try {
1197
- _redirects = readFileSync(join(directory, "_redirects"), "utf-8");
1198
- } catch {}
1199
-
1200
- try {
1201
- _workerJS = readFileSync(join(directory, "_worker.js"), "utf-8");
1202
- } catch {}
1203
-
1204
- if (_headers) {
1205
- formData.append("_headers", new File([_headers], "_headers"));
1206
- }
1207
-
1208
- if (_redirects) {
1209
- formData.append("_redirects", new File([_redirects], "_redirects"));
1210
- }
1211
-
1212
- if (builtFunctions) {
1213
- formData.append("_worker.js", new File([builtFunctions], "_worker.js"));
1214
- } else if (_workerJS) {
1215
- formData.append("_worker.js", new File([_workerJS], "_worker.js"));
1216
- }
1217
-
1218
- const deploymentResponse = await fetchResult<Deployment>(
1219
- `/accounts/${accountId}/pages/projects/${projectName}/deployments`,
1220
- {
1221
- method: "POST",
1222
- body: formData,
1223
- }
1224
- );
1225
-
1226
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1227
- account_id: accountId,
1228
- project_name: projectName,
1229
- });
1230
-
1231
- logger.log(
1232
- `✨ Deployment complete! Take a peek over at ${deploymentResponse.url}`
1233
- );
1234
- },
1235
- };
1236
-
1237
- export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1238
- return yargs
1239
- .command(
1240
- "dev [directory] [-- command]",
1241
- "🧑‍💻 Develop your full-stack Pages application locally",
1242
- (yargs) => {
1243
- return yargs
1244
- .positional("directory", {
1245
- type: "string",
1246
- demandOption: undefined,
1247
- description: "The directory of static assets to serve",
1248
- })
1249
- .positional("command", {
1250
- type: "string",
1251
- demandOption: undefined,
1252
- description: "The proxy command to run",
1253
- })
1254
- .options({
1255
- local: {
1256
- type: "boolean",
1257
- default: true,
1258
- description: "Run on my machine",
1259
- },
1260
- port: {
1261
- type: "number",
1262
- default: 8788,
1263
- description: "The port to listen on (serve from)",
1264
- },
1265
- proxy: {
1266
- type: "number",
1267
- description:
1268
- "The port to proxy (where the static assets are served)",
1269
- },
1270
- "script-path": {
1271
- type: "string",
1272
- default: "_worker.js",
1273
- description:
1274
- "The location of the single Worker script if not using functions",
1275
- },
1276
- binding: {
1277
- type: "array",
1278
- description: "Bind variable/secret (KEY=VALUE)",
1279
- alias: "b",
1280
- },
1281
- kv: {
1282
- type: "array",
1283
- description: "KV namespace to bind",
1284
- alias: "k",
1285
- },
1286
- do: {
1287
- type: "array",
1288
- description: "Durable Object to bind (NAME=CLASS)",
1289
- alias: "o",
1290
- },
1291
- "live-reload": {
1292
- type: "boolean",
1293
- default: false,
1294
- description: "Auto reload HTML pages when change is detected",
1295
- },
1296
- // TODO: Miniflare user options
1297
- })
1298
- .epilogue(pagesBetaWarning);
1299
- },
1300
- async ({
1301
- local,
1302
- directory,
1303
- port,
1304
- proxy: requestedProxyPort,
1305
- "script-path": singleWorkerScriptPath,
1306
- binding: bindings = [],
1307
- kv: kvs = [],
1308
- do: durableObjects = [],
1309
- "live-reload": liveReload,
1310
- _: [_pages, _dev, ...remaining],
1311
- }) => {
1312
- // Beta message for `wrangler pages <commands>` usage
1313
- logger.log(pagesBetaWarning);
1314
-
1315
- if (!local) {
1316
- logger.error("Only local mode is supported at the moment.");
1317
- return;
1318
- }
1319
-
1320
- const functionsDirectory = "./functions";
1321
- const usingFunctions = existsSync(functionsDirectory);
1322
-
1323
- const command = remaining as (string | number)[];
1324
-
1325
- let proxyPort: number | void;
1326
-
1327
- if (directory === undefined) {
1328
- proxyPort = await spawnProxyProcess({
1329
- port: requestedProxyPort,
1330
- command,
1331
- });
1332
- if (proxyPort === undefined) return undefined;
1333
- }
1334
-
1335
- let miniflareArgs: MiniflareOptions = {};
1336
-
1337
- let scriptReadyResolve: () => void;
1338
- const scriptReadyPromise = new Promise<void>(
1339
- (resolve) => (scriptReadyResolve = resolve)
1340
- );
1341
-
1342
- if (usingFunctions) {
1343
- const outfile = join(tmpdir(), "./functionsWorker.js");
1344
-
1345
- logger.log(`Compiling worker to "${outfile}"...`);
1346
-
1347
- try {
1348
- await buildFunctions({
1349
- outfile,
1350
- functionsDirectory,
1351
- sourcemap: true,
1352
- watch: true,
1353
- onEnd: () => scriptReadyResolve(),
1354
- buildOutputDirectory: directory,
1355
- });
1356
- } catch {}
1357
-
1358
- watch([functionsDirectory], {
1359
- persistent: true,
1360
- ignoreInitial: true,
1361
- }).on("all", async () => {
1362
- await buildFunctions({
1363
- outfile,
1364
- functionsDirectory,
1365
- sourcemap: true,
1366
- watch: true,
1367
- onEnd: () => scriptReadyResolve(),
1368
- buildOutputDirectory: directory,
1369
- });
1370
- });
1371
-
1372
- miniflareArgs = {
1373
- scriptPath: outfile,
1374
- };
1375
- } else {
1376
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1377
- scriptReadyResolve!();
1378
-
1379
- const scriptPath =
1380
- directory !== undefined
1381
- ? join(directory, singleWorkerScriptPath)
1382
- : singleWorkerScriptPath;
1383
-
1384
- if (existsSync(scriptPath)) {
1385
- miniflareArgs = {
1386
- scriptPath,
1387
- };
1388
- } else {
1389
- logger.log("No functions. Shimming...");
1390
- miniflareArgs = {
1391
- // TODO: The fact that these request/response hacks are necessary is ridiculous.
1392
- // We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well)
1393
- script: `
1394
- export default {
1395
- async fetch(request, env, context) {
1396
- const response = await env.ASSETS.fetch(request.url, request)
1397
- return new Response(response.body, response)
1398
- }
1399
- }`,
1400
- };
1401
- }
1402
- }
1403
-
1404
- // Defer importing miniflare until we really need it
1405
- const { Miniflare, Log, LogLevel } = await import("miniflare");
1406
- const { Response, fetch } = await import("@miniflare/core");
1407
-
1408
- // Wait for esbuild to finish building before starting Miniflare.
1409
- // This must be before the call to `new Miniflare`, as that will
1410
- // asynchronously start loading the script. `await startServer()`
1411
- // internally just waits for that promise to resolve.
1412
- await scriptReadyPromise;
1413
-
1414
- // `assetsFetch()` will only be called if there is `proxyPort` defined.
1415
- // We only define `proxyPort`, above, when there is no `directory` defined.
1416
- const assetsFetch =
1417
- directory !== undefined
1418
- ? await generateAssetsFetch(directory)
1419
- : invalidAssetsFetch;
1420
-
1421
- const requestContextCheckOptions =
1422
- await getRequestContextCheckOptions();
1423
-
1424
- const miniflare = new Miniflare({
1425
- port,
1426
- watch: true,
1427
- modules: true,
1428
-
1429
- log: new Log(LogLevel.ERROR, { prefix: "pages" }),
1430
- logUnhandledRejections: true,
1431
- sourceMap: true,
1432
-
1433
- kvNamespaces: kvs.map((kv) => kv.toString()),
1434
-
1435
- durableObjects: Object.fromEntries(
1436
- durableObjects.map((durableObject) =>
1437
- durableObject.toString().split("=")
1438
- )
1439
- ),
1440
-
1441
- // User bindings
1442
- bindings: {
1443
- ...Object.fromEntries(
1444
- bindings
1445
- .map((binding) => binding.toString().split("="))
1446
- .map(([key, ...values]) => [key, values.join("=")])
1447
- ),
1448
- },
1449
-
1450
- // env.ASSETS.fetch
1451
- serviceBindings: {
1452
- async ASSETS(request: Request) {
1453
- if (proxyPort) {
1454
- try {
1455
- const url = new URL(request.url);
1456
- url.host = `localhost:${proxyPort}`;
1457
- return await fetch(url, request);
1458
- } catch (thrown) {
1459
- logger.error(`Could not proxy request: ${thrown}`);
1460
-
1461
- // TODO: Pretty error page
1462
- return new Response(
1463
- `[wrangler] Could not proxy request: ${thrown}`,
1464
- { status: 502 }
1465
- );
1466
- }
1467
- } else {
1468
- try {
1469
- return await assetsFetch(request);
1470
- } catch (thrown) {
1471
- logger.error(`Could not serve static asset: ${thrown}`);
1472
-
1473
- // TODO: Pretty error page
1474
- return new Response(
1475
- `[wrangler] Could not serve static asset: ${thrown}`,
1476
- { status: 502 }
1477
- );
1478
- }
1479
- }
1480
- },
1481
- },
1482
-
1483
- kvPersist: true,
1484
- durableObjectsPersist: true,
1485
- cachePersist: true,
1486
- liveReload,
1487
-
1488
- ...requestContextCheckOptions,
1489
- ...miniflareArgs,
1490
- });
1491
-
1492
- try {
1493
- // `startServer` might throw if user code contains errors
1494
- const server = await miniflare.startServer();
1495
- logger.log(`Serving at http://localhost:${port}/`);
1496
-
1497
- if (process.env.BROWSER !== "none") {
1498
- await openInBrowser(`http://localhost:${port}/`);
1499
- }
1500
-
1501
- if (directory !== undefined && liveReload) {
1502
- watch([directory], {
1503
- persistent: true,
1504
- ignoreInitial: true,
1505
- }).on("all", async () => {
1506
- await miniflare.reload();
1507
- });
1508
- }
1509
-
1510
- CLEANUP_CALLBACKS.push(() => {
1511
- server.close();
1512
- miniflare.dispose().catch((err) => miniflare.log.error(err));
1513
- });
1514
- } catch (e) {
1515
- miniflare.log.error(e as Error);
1516
- CLEANUP();
1517
- throw new FatalError("Could not start Miniflare.", 1);
1518
- }
1519
- }
1520
- )
1521
- .command("functions", false, (yargs) =>
1522
- // we hide this command from help output because
1523
- // it's not meant to be used directly right now
1524
- yargs.command(
1525
- "build [directory]",
1526
- "Compile a folder of Cloudflare Pages Functions into a single Worker",
1527
- (yargs) =>
1528
- yargs
1529
- .positional("directory", {
1530
- type: "string",
1531
- default: "functions",
1532
- description: "The directory of Pages Functions",
1533
- })
1534
- .options({
1535
- outfile: {
1536
- type: "string",
1537
- default: "_worker.js",
1538
- description: "The location of the output Worker script",
1539
- },
1540
- "output-config-path": {
1541
- type: "string",
1542
- description: "The location for the output config file",
1543
- },
1544
- minify: {
1545
- type: "boolean",
1546
- default: false,
1547
- description: "Minify the output Worker script",
1548
- },
1549
- sourcemap: {
1550
- type: "boolean",
1551
- default: false,
1552
- description:
1553
- "Generate a sourcemap for the output Worker script",
1554
- },
1555
- "fallback-service": {
1556
- type: "string",
1557
- default: "ASSETS",
1558
- description:
1559
- "The service to fallback to at the end of the `next` chain. Setting to '' will fallback to the global `fetch`.",
1560
- },
1561
- watch: {
1562
- type: "boolean",
1563
- default: false,
1564
- description:
1565
- "Watch for changes to the functions and automatically rebuild the Worker script",
1566
- },
1567
- plugin: {
1568
- type: "boolean",
1569
- default: false,
1570
- description: "Build a plugin rather than a Worker script",
1571
- },
1572
- })
1573
- .epilogue(pagesBetaWarning),
1574
- async ({
1575
- directory,
1576
- outfile,
1577
- "output-config-path": outputConfigPath,
1578
- minify,
1579
- sourcemap,
1580
- fallbackService,
1581
- watch,
1582
- plugin,
1583
- }) => {
1584
- // Beta message for `wrangler pages <commands>` usage
1585
- logger.log(pagesBetaWarning);
1586
-
1587
- await buildFunctions({
1588
- outfile,
1589
- outputConfigPath,
1590
- functionsDirectory: directory,
1591
- minify,
1592
- sourcemap,
1593
- fallbackService,
1594
- watch,
1595
- plugin,
1596
- buildOutputDirectory: dirname(outfile),
1597
- });
1598
- }
1599
- )
1600
- )
1601
- .command("project", "⚡️ Interact with your Pages projects", (yargs) =>
1602
- yargs
1603
- .command(
1604
- "list",
1605
- "List your Cloudflare Pages projects",
1606
- (yargs) => yargs.epilogue(pagesBetaWarning),
1607
- async () => {
1608
- const config = getConfigCache<PagesConfigCache>(
1609
- PAGES_CONFIG_CACHE_FILENAME
1610
- );
1611
-
1612
- const accountId = await requireAuth(config);
1613
-
1614
- const projects: Array<Project> = await listProjects({ accountId });
1615
-
1616
- const data = projects.map((project) => {
1617
- return {
1618
- "Project Name": project.name,
1619
- "Project Domains": `${project.domains.join(", ")}`,
1620
- "Git Provider": project.source ? "Yes" : "No",
1621
- "Last Modified": project.latest_deployment
1622
- ? timeagoFormat(project.latest_deployment.modified_on)
1623
- : timeagoFormat(project.created_on),
1624
- };
1625
- });
1626
-
1627
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1628
- account_id: accountId,
1629
- });
1630
-
1631
- render(<Table data={data}></Table>);
1632
- }
1633
- )
1634
- .command(
1635
- "create [project-name]",
1636
- "Create a new Cloudflare Pages project",
1637
- (yargs) =>
1638
- yargs
1639
- .positional("project-name", {
1640
- type: "string",
1641
- demandOption: true,
1642
- description: "The name of your Pages project",
1643
- })
1644
- .options({
1645
- "production-branch": {
1646
- type: "string",
1647
- description:
1648
- "The name of the production branch of your project",
1649
- },
1650
- })
1651
- .epilogue(pagesBetaWarning),
1652
- async ({ productionBranch, projectName }) => {
1653
- const config = getConfigCache<PagesConfigCache>(
1654
- PAGES_CONFIG_CACHE_FILENAME
1655
- );
1656
- const accountId = await requireAuth(config);
1657
-
1658
- const isInteractive = process.stdin.isTTY;
1659
- if (!projectName && isInteractive) {
1660
- projectName = await prompt("Enter the name of your new project:");
1661
- }
1662
-
1663
- if (!projectName) {
1664
- throw new FatalError("Must specify a project name.", 1);
1665
- }
1666
-
1667
- if (!productionBranch && isInteractive) {
1668
- let isGitDir = true;
1669
- try {
1670
- execSync(`git rev-parse --is-inside-work-tree`, {
1671
- stdio: "ignore",
1672
- });
1673
- } catch (err) {
1674
- isGitDir = false;
1675
- }
1676
-
1677
- productionBranch = await prompt(
1678
- "Enter the production branch name:",
1679
- "text",
1680
- isGitDir
1681
- ? execSync(`git rev-parse --abbrev-ref HEAD`)
1682
- .toString()
1683
- .trim()
1684
- : "production"
1685
- );
1686
- }
1687
-
1688
- if (!productionBranch) {
1689
- throw new FatalError("Must specify a production branch.", 1);
1690
- }
1691
-
1692
- const { subdomain } = await fetchResult<Project>(
1693
- `/accounts/${accountId}/pages/projects`,
1694
- {
1695
- method: "POST",
1696
- body: JSON.stringify({
1697
- name: projectName,
1698
- production_branch: productionBranch,
1699
- }),
1700
- }
1701
- );
1702
-
1703
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1704
- account_id: accountId,
1705
- project_name: projectName,
1706
- });
1707
-
1708
- logger.log(
1709
- `✨ Successfully created the '${projectName}' project. It will be available at https://${subdomain}/ once you create your first deployment.`
1710
- );
1711
- logger.log(
1712
- `To deploy a folder of assets, run 'wrangler pages publish [directory]'.`
1713
- );
1714
- }
1715
- )
1716
- .epilogue(pagesBetaWarning)
1717
- )
1718
- .command(
1719
- "deployment",
1720
- "🚀 Interact with the deployments of a project",
1721
- (yargs) =>
1722
- yargs
1723
- .command(
1724
- "list",
1725
- "List deployments in your Cloudflare Pages project",
1726
- (yargs) =>
1727
- yargs
1728
- .options({
1729
- "project-name": {
1730
- type: "string",
1731
- description:
1732
- "The name of the project you would like to list deployments for",
1733
- },
1734
- })
1735
- .epilogue(pagesBetaWarning),
1736
- async ({ projectName }) => {
1737
- const config = getConfigCache<PagesConfigCache>(
1738
- PAGES_CONFIG_CACHE_FILENAME
1739
- );
1740
- const accountId = await requireAuth(config);
1741
-
1742
- projectName ??= config.project_name;
1743
-
1744
- const isInteractive = process.stdin.isTTY;
1745
- if (!projectName && isInteractive) {
1746
- const projects = await listProjects({ accountId });
1747
- projectName = await new Promise((resolve) => {
1748
- const { unmount } = render(
1749
- <>
1750
- <Text>Select a project:</Text>
1751
- <SelectInput
1752
- items={projects.map((project) => ({
1753
- key: project.name,
1754
- label: project.name,
1755
- value: project,
1756
- }))}
1757
- onSelect={async (selected) => {
1758
- resolve(selected.value.name);
1759
- unmount();
1760
- }}
1761
- />
1762
- </>
1763
- );
1764
- });
1765
- }
1766
-
1767
- if (!projectName) {
1768
- throw new FatalError("Must specify a project name.", 1);
1769
- }
1770
-
1771
- const deployments: Array<Deployment> = await fetchResult(
1772
- `/accounts/${accountId}/pages/projects/${projectName}/deployments`
1773
- );
1774
-
1775
- const titleCase = (word: string) =>
1776
- word.charAt(0).toUpperCase() + word.slice(1);
1777
-
1778
- const shortSha = (sha: string) => sha.slice(0, 7);
1779
-
1780
- const getStatus = (deployment: Deployment) => {
1781
- // Return a pretty time since timestamp if successful otherwise the status
1782
- if (deployment.latest_stage.status === `success`) {
1783
- return timeagoFormat(deployment.latest_stage.ended_on);
1784
- }
1785
- return titleCase(deployment.latest_stage.status);
1786
- };
1787
-
1788
- const data = deployments.map((deployment) => {
1789
- return {
1790
- Environment: titleCase(deployment.environment),
1791
- Branch: deployment.deployment_trigger.metadata.branch,
1792
- Source: shortSha(
1793
- deployment.deployment_trigger.metadata.commit_hash
1794
- ),
1795
- Deployment: deployment.url,
1796
- Status: getStatus(deployment),
1797
- // TODO: Use a url shortener
1798
- Build: `https://dash.cloudflare.com/${accountId}/pages/view/${deployment.project_name}/${deployment.id}`,
1799
- };
1800
- });
1801
-
1802
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1803
- account_id: accountId,
1804
- });
1805
-
1806
- render(<Table data={data}></Table>);
1807
- }
1808
- )
1809
- .command({
1810
- command: "create [directory]",
1811
- ...createDeployment,
1812
- } as CommandModule)
1813
- .epilogue(pagesBetaWarning)
1814
- )
1815
- .command({
1816
- command: "publish [directory]",
1817
- ...createDeployment,
1818
- } as CommandModule);
1819
- };
1820
-
1821
- const invalidAssetsFetch: typeof fetch = () => {
1822
- throw new Error(
1823
- "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
1824
- );
1825
- };
1826
-
1827
- const listProjects = async ({
1828
- accountId,
1829
- }: {
1830
- accountId: string;
1831
- }): Promise<Array<Project>> => {
1832
- const pageSize = 10;
1833
- let page = 1;
1834
- const results = [];
1835
- while (results.length % pageSize === 0) {
1836
- const json: Array<Project> = await fetchResult(
1837
- `/accounts/${accountId}/pages/projects`,
1838
- {},
1839
- new URLSearchParams({
1840
- per_page: pageSize.toString(),
1841
- page: page.toString(),
1842
- })
1843
- );
1844
- page++;
1845
- results.push(...json);
1846
- if (json.length < pageSize) {
1847
- break;
1848
- }
1849
- }
1850
- return results;
1851
- };
1852
-
1853
- function formatTime(duration: number) {
1854
- return `(${(duration / 1000).toFixed(2)} sec)`;
1855
- }
1856
-
1857
- function Progress({ done, total }: { done: number; total: number }) {
1858
- return (
1859
- <>
1860
- <Text>
1861
- <Spinner type="earth" />
1862
- {` Uploading... (${done}/${total})\n`}
1863
- </Text>
1864
- </>
1865
- );
1866
- }