wrangler 0.0.0-e64812e → 0.0.0-e6488257

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