wrangler 2.0.16 → 2.0.19

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 (51) hide show
  1. package/bin/wrangler.js +42 -8
  2. package/miniflare-dist/index.mjs +1 -0
  3. package/package.json +65 -63
  4. package/src/__tests__/configuration.test.ts +11 -7
  5. package/src/__tests__/helpers/run-in-tmp.ts +22 -23
  6. package/src/__tests__/https-options.test.ts +51 -18
  7. package/src/__tests__/index.test.ts +13 -13
  8. package/src/__tests__/jest.setup.ts +13 -0
  9. package/src/__tests__/kv.test.ts +33 -2
  10. package/src/__tests__/metrics.test.ts +415 -0
  11. package/src/__tests__/pages.test.ts +15 -8
  12. package/src/__tests__/publish.test.ts +49 -23
  13. package/src/__tests__/secret.test.ts +84 -78
  14. package/src/__tests__/tail.test.ts +8 -0
  15. package/src/__tests__/test-old-node-version.js +31 -0
  16. package/src/__tests__/user.test.ts +7 -7
  17. package/src/__tests__/whoami.test.tsx +11 -1
  18. package/src/api/dev.ts +4 -1
  19. package/src/cli.ts +1 -1
  20. package/src/config/config.ts +8 -0
  21. package/src/config/validation.ts +9 -0
  22. package/src/config-cache.ts +2 -1
  23. package/src/dev/local.tsx +31 -25
  24. package/src/dev/remote.tsx +2 -2
  25. package/src/dev.tsx +6 -0
  26. package/src/entry.ts +1 -1
  27. package/src/{__tests__/helpers/faye-websocket.d.ts → faye-websocket.d.ts} +0 -0
  28. package/src/global-wrangler-config-path.ts +26 -0
  29. package/src/https-options.ts +8 -4
  30. package/src/index.tsx +120 -22
  31. package/src/kv.ts +23 -1
  32. package/src/metrics/index.ts +4 -0
  33. package/src/metrics/metrics-config.ts +222 -0
  34. package/src/metrics/metrics-dispatcher.ts +93 -0
  35. package/src/metrics/send-event.ts +80 -0
  36. package/src/miniflare-cli/index.ts +1 -0
  37. package/src/package-manager.ts +45 -0
  38. package/src/pages/build.tsx +2 -0
  39. package/src/pages/deployments.tsx +2 -0
  40. package/src/pages/dev.tsx +4 -0
  41. package/src/pages/projects.tsx +3 -0
  42. package/src/pages/publish.tsx +3 -0
  43. package/src/pages/upload.tsx +26 -14
  44. package/src/publish.ts +28 -15
  45. package/src/pubsub/pubsub-commands.tsx +43 -0
  46. package/src/user/user.tsx +29 -20
  47. package/src/worker-namespace.ts +16 -0
  48. package/templates/static-asset-facade.js +11 -5
  49. package/templates/tsconfig.json +2 -2
  50. package/wrangler-dist/cli.d.ts +298 -0
  51. package/wrangler-dist/cli.js +2589 -1659
@@ -0,0 +1,222 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { fetchResult } from "../cfetch";
6
+ import { getConfigCache, saveToConfigCache } from "../config-cache";
7
+ import { confirm } from "../dialogs";
8
+ import isInteractive from "../is-interactive";
9
+ import { logger } from "../logger";
10
+ import { getAPIToken } from "../user";
11
+
12
+ /**
13
+ * The date that the metrics being gathered was last updated in a way that would require
14
+ * the user to give their permission again.
15
+ *
16
+ * When reading from a config file, we check the recorded date in the config file against
17
+ * this one here. We ignore the permissions set in the the file if the recorded date is older.
18
+ * This allows us to prompt the user to re-opt-in when we make substantive changes to our metrics
19
+ * gathering.
20
+ */
21
+ export const CURRENT_METRICS_DATE = new Date(2022, 6, 4);
22
+ export const USER_ID_CACHE_PATH = "user-id.json";
23
+
24
+ export interface MetricsConfigOptions {
25
+ /**
26
+ * Defines whether to send metrics to Cloudflare:
27
+ * If defined, then use this value for whether the dispatch is enabled.
28
+ * Otherwise, infer the enabled value from the user configuration.
29
+ */
30
+ sendMetrics?: boolean;
31
+ /**
32
+ * When true, do not make any CF API requests.
33
+ */
34
+ offline?: boolean;
35
+ }
36
+
37
+ /**
38
+ * The information needed to set up the MetricsDispatcher.
39
+ */
40
+ export interface MetricsConfig {
41
+ /** True if usage tracking is enabled. */
42
+ enabled: boolean;
43
+ /** A UID that identifies this user and machine pair for Wrangler. */
44
+ deviceId: string;
45
+ /** The currently logged in user - undefined if not logged in. */
46
+ userId: string | undefined;
47
+ }
48
+
49
+ /**
50
+ * Get hold of the permissions and device-id for metrics dispatch.
51
+ *
52
+ * The device-id is just a unique identifier sent along with events to help
53
+ * to collate metrics. Once generated, this id is cached in the metrics config file.
54
+ *
55
+ * The permissions define whether we can send metrics or not. They can come from a variety of places:
56
+ * - the `send_metrics` setting in `wrangler.toml`
57
+ * - a cached response from the current user
58
+ * - prompting the user to opt-in to metrics
59
+ *
60
+ * If the user was prompted to opt-in, then their response is cached in the metrics config file.
61
+ *
62
+ * If the current process is not interactive then we will cannot prompt the user and just assume
63
+ * we cannot send metrics if there is no cached or project-level preference available.
64
+ */
65
+ export async function getMetricsConfig({
66
+ sendMetrics,
67
+ offline = false,
68
+ }: MetricsConfigOptions): Promise<MetricsConfig> {
69
+ const config = await readMetricsConfig();
70
+ const deviceId = await getDeviceId(config);
71
+ const userId = await getUserId(offline);
72
+
73
+ // If the project is explicitly set the `send_metrics` options in `wrangler.toml`
74
+ // then use that and ignore any user preference.
75
+ if (sendMetrics !== undefined) {
76
+ return { enabled: sendMetrics, deviceId, userId };
77
+ }
78
+
79
+ // Get the user preference from the metrics config.
80
+ const permission = config.permission;
81
+ if (permission !== undefined) {
82
+ if (new Date(permission.date) >= CURRENT_METRICS_DATE) {
83
+ return { enabled: permission.enabled, deviceId, userId };
84
+ } else if (permission.enabled) {
85
+ logger.log(
86
+ "Usage metrics tracking has changed since you last granted permission."
87
+ );
88
+ }
89
+ }
90
+
91
+ // We couldn't get the metrics permission from the project-level nor the user-level config.
92
+ // If we are not interactive then just bail out.
93
+ if (!isInteractive()) {
94
+ return { enabled: false, deviceId, userId };
95
+ }
96
+
97
+ // Otherwise, let's ask the user and store the result in the metrics config.
98
+ const enabled = await confirm(
99
+ "Would you like to help improve Wrangler by sending usage metrics to Cloudflare?"
100
+ );
101
+ logger.log(
102
+ `Your choice has been saved in the following file: ${path.relative(
103
+ process.cwd(),
104
+ getMetricsConfigPath()
105
+ )}.\n\n` +
106
+ " You can override the user level setting for a project in `wrangler.toml`:\n\n" +
107
+ " - to disable sending metrics for a project: `send_metrics = false`\n" +
108
+ " - to enable sending metrics for a project: `send_metrics = true`"
109
+ );
110
+ await writeMetricsConfig({
111
+ permission: {
112
+ enabled,
113
+ date: CURRENT_METRICS_DATE,
114
+ },
115
+ deviceId,
116
+ });
117
+ return { enabled, deviceId, userId };
118
+ }
119
+
120
+ /**
121
+ * Stringify and write the given info to the metrics config file.
122
+ */
123
+ export async function writeMetricsConfig(config: MetricsConfigFile) {
124
+ await mkdir(path.dirname(getMetricsConfigPath()), { recursive: true });
125
+ await writeFile(
126
+ getMetricsConfigPath(),
127
+ JSON.stringify(
128
+ config,
129
+ (_key, value) => (value instanceof Date ? value.toISOString() : value),
130
+ "\t"
131
+ )
132
+ );
133
+ }
134
+
135
+ /**
136
+ * Read and parse the metrics config file.
137
+ */
138
+ export async function readMetricsConfig(): Promise<MetricsConfigFile> {
139
+ try {
140
+ return JSON.parse(
141
+ await readFile(getMetricsConfigPath(), "utf8"),
142
+ (key, value) => (key === "date" ? new Date(value) : value)
143
+ );
144
+ } catch {
145
+ return {};
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Get the path to the metrics config file.
151
+ */
152
+ function getMetricsConfigPath(): string {
153
+ return path.resolve(os.homedir(), ".wrangler/config/metrics.json");
154
+ }
155
+
156
+ /**
157
+ * The format of the metrics config file.
158
+ */
159
+ export interface MetricsConfigFile {
160
+ permission?: {
161
+ /** True if Wrangler should send metrics to Cloudflare. */
162
+ enabled: boolean;
163
+ /** The date that this permission was set. */
164
+ date: Date;
165
+ };
166
+ /** A unique UUID that identifies this device for metrics purposes. */
167
+ deviceId?: string;
168
+ }
169
+
170
+ /**
171
+ * Returns an ID that uniquely identifies Wrangler on this device to help collate events.
172
+ *
173
+ * Once created this ID is stored in the metrics config file.
174
+ */
175
+ async function getDeviceId(config: MetricsConfigFile) {
176
+ // Get or create the deviceId.
177
+ const deviceId = config.deviceId ?? randomUUID();
178
+ if (config.deviceId === undefined) {
179
+ // We had to create a new deviceID so store it now.
180
+ await writeMetricsConfig({ ...config, deviceId });
181
+ }
182
+ return deviceId;
183
+ }
184
+
185
+ /**
186
+ * Returns the ID of the current user, which will be sent with each event.
187
+ *
188
+ * The ID is retrieved from the CF API `/user` endpoint if the user is authenticated and then
189
+ * stored in the `node_modules/.cache`.
190
+ *
191
+ * If it is not possible to retrieve the ID (perhaps the user is not logged in) then we just use
192
+ * `undefined`.
193
+ */
194
+ async function getUserId(offline: boolean) {
195
+ // Get the userId from the cache.
196
+ // If it has not been found in the cache and we are not offline then make an API call to get it.
197
+ // If we can't work in out then just use `anonymous`.
198
+ let userId = getConfigCache<{ userId: string }>(USER_ID_CACHE_PATH).userId;
199
+ if (userId === undefined && !offline) {
200
+ userId = await fetchUserId();
201
+ if (userId !== undefined) {
202
+ saveToConfigCache(USER_ID_CACHE_PATH, { userId });
203
+ }
204
+ }
205
+ return userId;
206
+ }
207
+
208
+ /**
209
+ * Ask the Cloudflare API for the User ID of the current user.
210
+ *
211
+ * We will only do this if we are not "offline", e.g. not running `wrangler dev --local`.
212
+ * Quietly return undefined if anything goes wrong.
213
+ */
214
+ async function fetchUserId(): Promise<string | undefined> {
215
+ try {
216
+ return getAPIToken()
217
+ ? (await fetchResult<{ id: string }>("/user")).id
218
+ : undefined;
219
+ } catch (e) {
220
+ return undefined;
221
+ }
222
+ }
@@ -0,0 +1,93 @@
1
+ import { fetch } from "undici";
2
+ import { version as wranglerVersion } from "../../package.json";
3
+ import { logger } from "../logger";
4
+ import { getMetricsConfig } from "./metrics-config";
5
+ import type { MetricsConfigOptions } from "./metrics-config";
6
+
7
+ // The SPARROW_SOURCE_KEY is provided at esbuild time as a `define` for production and beta
8
+ // releases. Otherwise it is left undefined, which automatically disables metrics requests.
9
+ declare const SPARROW_SOURCE_KEY: string;
10
+ const SPARROW_URL = "https://sparrow.cloudflare.com";
11
+
12
+ export async function getMetricsDispatcher(options: MetricsConfigOptions) {
13
+ return {
14
+ /**
15
+ * Dispatch a event to the analytics target.
16
+ *
17
+ * The event should follow these conventions
18
+ * - name is of the form `[action] [object]` (lower case)
19
+ * - additional properties are camelCased
20
+ */
21
+ async sendEvent(name: string, properties: Properties = {}): Promise<void> {
22
+ await dispatch({ type: "event", name, properties });
23
+ },
24
+
25
+ /**
26
+ * Dispatch a user profile information to the analytics target.
27
+ *
28
+ * This call can be used to inform the analytics target of relevant properties associated
29
+ * with the current user.
30
+ */
31
+ async identify(properties: Properties): Promise<void> {
32
+ await dispatch({ type: "identify", name: "identify", properties });
33
+ },
34
+ };
35
+
36
+ async function dispatch(event: {
37
+ type: "identify" | "event";
38
+ name: string;
39
+ properties: Properties;
40
+ }): Promise<void> {
41
+ if (!SPARROW_SOURCE_KEY) {
42
+ logger.debug(
43
+ "Metrics dispatcher: Source Key not provided. Be sure to initialize before sending events.",
44
+ event
45
+ );
46
+ return;
47
+ }
48
+
49
+ // Lazily get the config for this dispatcher only when an event is being dispatched.
50
+ const metricsConfig = await getMetricsConfig(options);
51
+ if (!metricsConfig.enabled) {
52
+ logger.debug(
53
+ `Metrics dispatcher: Dispatching disabled - would have sent ${JSON.stringify(
54
+ event
55
+ )}.`
56
+ );
57
+ return;
58
+ }
59
+
60
+ try {
61
+ logger.debug(`Metrics dispatcher: Posting data ${JSON.stringify(event)}`);
62
+ const body = JSON.stringify({
63
+ deviceId: metricsConfig.deviceId,
64
+ userId: metricsConfig.userId,
65
+ event: event.name,
66
+ properties: {
67
+ category: "Workers",
68
+ wranglerVersion,
69
+ ...event.properties,
70
+ },
71
+ });
72
+
73
+ await fetch(`${SPARROW_URL}/api/v1/${event.type}`, {
74
+ method: "POST",
75
+ headers: {
76
+ Accept: "*/*",
77
+ "Content-Type": "application/json",
78
+ "Sparrow-Source-Key": SPARROW_SOURCE_KEY,
79
+ },
80
+ mode: "cors",
81
+ keepalive: true,
82
+ body,
83
+ });
84
+ } catch (e) {
85
+ logger.debug(
86
+ "Metrics dispatcher: Failed to send request:",
87
+ (e as Error).message
88
+ );
89
+ }
90
+ }
91
+ }
92
+
93
+ export type Properties = Record<string, unknown>;
@@ -0,0 +1,80 @@
1
+ import { logger } from "../logger";
2
+ import { getMetricsDispatcher } from "./metrics-dispatcher";
3
+ import type { MetricsConfigOptions } from "./metrics-config";
4
+ import type { Properties } from "./metrics-dispatcher";
5
+
6
+ /** These are event names used by this wrangler client. */
7
+ export type EventNames =
8
+ | "view accounts"
9
+ | "deploy worker script"
10
+ | "begin log stream"
11
+ | "end log stream"
12
+ | "create encrypted variable"
13
+ | "delete encrypted variable"
14
+ | "list encrypted variables"
15
+ | "create kv namespace"
16
+ | "list kv namespaces"
17
+ | "delete kv namespace"
18
+ | "write kv key-value"
19
+ | "list kv keys"
20
+ | "read kv value"
21
+ | "delete kv key-value"
22
+ | "write kv key-values (bulk)"
23
+ | "delete kv key-values (bulk)"
24
+ | "create r2 bucket"
25
+ | "list r2 buckets"
26
+ | "delete r2 bucket"
27
+ | "login user"
28
+ | "logout user"
29
+ | "create pubsub namespace"
30
+ | "list pubsub namespaces"
31
+ | "delete pubsub namespace"
32
+ | "view pubsub namespace"
33
+ | "create pubsub broker"
34
+ | "update pubsub broker"
35
+ | "list pubsub brokers"
36
+ | "delete pubsub broker"
37
+ | "view pubsub broker"
38
+ | "issue pubsub broker credentials"
39
+ | "revoke pubsub broker credentials"
40
+ | "unrevoke pubsub broker credentials"
41
+ | "list pubsub broker revoked credentials"
42
+ | "list pubsub broker public-keys"
43
+ | "list worker namespaces"
44
+ | "view worker namespace"
45
+ | "create worker namespace"
46
+ | "delete worker namespace"
47
+ | "rename worker namespace"
48
+ | "create pages project"
49
+ | "list pages projects"
50
+ | "deploy pages project"
51
+ | "list pages projects deployments"
52
+ | "build pages functions"
53
+ | "run dev"
54
+ | "run pages dev";
55
+
56
+ export function sendMetricsEvent(event: EventNames): void;
57
+ export function sendMetricsEvent(
58
+ event: EventNames,
59
+ options: MetricsConfigOptions
60
+ ): void;
61
+ export function sendMetricsEvent(
62
+ event: EventNames,
63
+ properties: Properties,
64
+ options: MetricsConfigOptions
65
+ ): void;
66
+ /**
67
+ * Send a metrics event to Cloudflare, if usage tracking is enabled.
68
+ */
69
+ export function sendMetricsEvent(
70
+ event: EventNames,
71
+ ...args: [] | [MetricsConfigOptions] | [Properties, MetricsConfigOptions]
72
+ ): void {
73
+ const options = args.pop() ?? {};
74
+ const properties = (args.pop() ?? {}) as Properties;
75
+ getMetricsDispatcher(options)
76
+ .then((metricsDispatcher) => metricsDispatcher.sendEvent(event, properties))
77
+ .catch((err) => {
78
+ logger.debug("Error sending metrics event", err);
79
+ });
80
+ }
@@ -41,6 +41,7 @@ async function main() {
41
41
  // Start Miniflare development server
42
42
  await mf.startServer();
43
43
  await mf.startScheduler();
44
+ process.send && process.send("ready");
44
45
  } catch (e) {
45
46
  mf.log.error(e as Error);
46
47
  process.exitCode = 1;
@@ -1,5 +1,6 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { env } from "node:process";
3
4
  import { execa, execaCommandSync } from "execa";
4
5
  import { logger } from "./logger";
5
6
 
@@ -19,7 +20,9 @@ export async function getPackageManager(cwd: string): Promise<PackageManager> {
19
20
  const hasYarnLock = existsSync(join(cwd, "yarn.lock"));
20
21
  const hasNpmLock = existsSync(join(cwd, "package-lock.json"));
21
22
  const hasPnpmLock = existsSync(join(cwd, "pnpm-lock.yaml"));
23
+ const userAgent = sniffUserAgent();
22
24
 
25
+ // check for lockfiles
23
26
  if (hasNpmLock) {
24
27
  if (hasNpm) {
25
28
  logger.log(
@@ -60,6 +63,19 @@ export async function getPackageManager(cwd: string): Promise<PackageManager> {
60
63
  }
61
64
  }
62
65
 
66
+ // check the user agent
67
+ if (userAgent === "npm" && hasNpm) {
68
+ logger.log("Using npm as package manager.");
69
+ return { ...NpmPackageManager, cwd };
70
+ } else if (userAgent === "pnpm" && hasPnpm) {
71
+ logger.log("Using pnpm as package manager.");
72
+ return { ...PnpmPackageManager, cwd };
73
+ } else if (userAgent === "yarn" && hasYarn) {
74
+ logger.log("Using yarn as package manager.");
75
+ return { ...YarnPackageManager, cwd };
76
+ }
77
+
78
+ // lastly, check what's installed
63
79
  if (hasNpm) {
64
80
  logger.log("Using npm as package manager.");
65
81
  return { ...NpmPackageManager, cwd };
@@ -172,3 +188,32 @@ function supportsNpm(): Promise<boolean> {
172
188
  function supportsPnpm(): Promise<boolean> {
173
189
  return supports("pnpm");
174
190
  }
191
+
192
+ /**
193
+ * The environment variable `npm_config_user_agent` can be used to
194
+ * guess the package manager that was used to execute wrangler.
195
+ * It's imperfect (just like regular user agent sniffing!)
196
+ * but the package managers we support all set this property:
197
+ *
198
+ * - [npm](https://github.com/npm/cli/blob/1415b4bdeeaabb6e0ba12b6b1b0cc56502bd64ab/lib/utils/config/definitions.js#L1945-L1979)
199
+ * - [pnpm](https://github.com/pnpm/pnpm/blob/cd4f9341e966eb8b411462b48ff0c0612e0a51a7/packages/plugin-commands-script-runners/src/makeEnv.ts#L14)
200
+ * - [yarn](https://yarnpkg.com/advanced/lifecycle-scripts#environment-variables)
201
+ */
202
+ function sniffUserAgent(): "npm" | "pnpm" | "yarn" | undefined {
203
+ const userAgent = env.npm_config_user_agent;
204
+ if (userAgent === undefined) {
205
+ return undefined;
206
+ }
207
+
208
+ if (userAgent.includes("yarn")) {
209
+ return "yarn";
210
+ }
211
+
212
+ if (userAgent.includes("pnpm")) {
213
+ return "pnpm";
214
+ }
215
+
216
+ if (userAgent.includes("npm")) {
217
+ return "npm";
218
+ }
219
+ }
@@ -2,6 +2,7 @@ import { writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
  import { logger } from "../logger";
5
+ import * as metrics from "../metrics";
5
6
  import { toUrlPath } from "../paths";
6
7
  import { isInPagesCI } from "./constants";
7
8
  import { buildPlugin } from "./functions/buildPlugin";
@@ -120,6 +121,7 @@ export const Handler = async ({
120
121
  buildOutputDirectory,
121
122
  nodeCompat,
122
123
  });
124
+ metrics.sendMetricsEvent("build pages functions");
123
125
  };
124
126
 
125
127
  export async function buildFunctions({
@@ -6,6 +6,7 @@ import { format as timeagoFormat } from "timeago.js";
6
6
  import { fetchResult } from "../cfetch";
7
7
  import { getConfigCache, saveToConfigCache } from "../config-cache";
8
8
  import { FatalError } from "../errors";
9
+ import * as metrics from "../metrics";
9
10
  import { requireAuth } from "../user";
10
11
  import { PAGES_CONFIG_CACHE_FILENAME } from "./constants";
11
12
  import { listProjects } from "./projects";
@@ -98,4 +99,5 @@ export async function ListHandler({
98
99
  });
99
100
 
100
101
  render(<Table data={data}></Table>, { patchConsole: false });
102
+ metrics.sendMetricsEvent("list pages projects deployments");
101
103
  }
package/src/pages/dev.tsx CHANGED
@@ -8,6 +8,7 @@ import { getType } from "mime";
8
8
  import { getVarsForDev } from "../dev/dev-vars";
9
9
  import { FatalError } from "../errors";
10
10
  import { logger } from "../logger";
11
+ import * as metrics from "../metrics";
11
12
  import { getRequestContextCheckOptions } from "../miniflare-cli/request-context";
12
13
  import openInBrowser from "../open-in-browser";
13
14
  import { buildFunctions } from "./build";
@@ -172,6 +173,7 @@ export const Handler = async ({
172
173
  buildOutputDirectory: directory,
173
174
  nodeCompat,
174
175
  });
176
+ metrics.sendMetricsEvent("build pages functions");
175
177
  } catch {}
176
178
 
177
179
  watch([functionsDirectory], {
@@ -187,6 +189,7 @@ export const Handler = async ({
187
189
  buildOutputDirectory: directory,
188
190
  nodeCompat,
189
191
  });
192
+ metrics.sendMetricsEvent("build pages functions");
190
193
  });
191
194
 
192
195
  miniflareArgs = {
@@ -318,6 +321,7 @@ export const Handler = async ({
318
321
  // `startServer` might throw if user code contains errors
319
322
  const server = await miniflare.startServer();
320
323
  logger.log(`Serving at http://localhost:${port}/`);
324
+ metrics.sendMetricsEvent("run pages dev");
321
325
 
322
326
  if (process.env.BROWSER !== "none") {
323
327
  await openInBrowser(`http://localhost:${port}/`);
@@ -8,6 +8,7 @@ import { getConfigCache, saveToConfigCache } from "../config-cache";
8
8
  import { prompt } from "../dialogs";
9
9
  import { FatalError } from "../errors";
10
10
  import { logger } from "../logger";
11
+ import * as metrics from "../metrics";
11
12
  import { requireAuth } from "../user";
12
13
  import { PAGES_CONFIG_CACHE_FILENAME } from "./constants";
13
14
  import { pagesBetaWarning } from "./utils";
@@ -44,6 +45,7 @@ export async function ListHandler() {
44
45
  });
45
46
 
46
47
  render(<Table data={data}></Table>, { patchConsole: false });
48
+ metrics.sendMetricsEvent("list pages projects");
47
49
  }
48
50
 
49
51
  export const listProjects = async ({
@@ -154,4 +156,5 @@ export async function CreateHandler({
154
156
  logger.log(
155
157
  `To deploy a folder of assets, run 'wrangler pages publish [directory]'.`
156
158
  );
159
+ metrics.sendMetricsEvent("create pages project");
157
160
  }
@@ -12,6 +12,7 @@ import { getConfigCache, saveToConfigCache } from "../config-cache";
12
12
  import { prompt } from "../dialogs";
13
13
  import { FatalError } from "../errors";
14
14
  import { logger } from "../logger";
15
+ import * as metrics from "../metrics";
15
16
  import { requireAuth } from "../user";
16
17
  import { buildFunctions } from "./build";
17
18
  import { PAGES_CONFIG_CACHE_FILENAME } from "./constants";
@@ -193,6 +194,7 @@ export const Handler = async ({
193
194
  });
194
195
 
195
196
  logger.log(`✨ Successfully created the '${projectName}' project.`);
197
+ metrics.sendMetricsEvent("create pages project");
196
198
  break;
197
199
  }
198
200
  }
@@ -332,4 +334,5 @@ export const Handler = async ({
332
334
  logger.log(
333
335
  `✨ Deployment complete! Take a peek over at ${deploymentResponse.url}`
334
336
  );
337
+ metrics.sendMetricsEvent("deploy pages project");
335
338
  };
@@ -95,7 +95,7 @@ export const upload = async (
95
95
  }
96
96
 
97
97
  type FileContainer = {
98
- content: string;
98
+ path: string;
99
99
  contentType: string;
100
100
  sizeInBytes: number;
101
101
  hash: string;
@@ -112,6 +112,14 @@ export const upload = async (
112
112
 
113
113
  const directory = resolve(args.directory);
114
114
 
115
+ // TODO(future): Use this to more efficiently load files in and speed up uploading
116
+ // Limit memory to 1 GB unless more is specified
117
+ // let maxMemory = 1_000_000_000;
118
+ // if (process.env.NODE_OPTIONS && (process.env.NODE_OPTIONS.includes('--max-old-space-size=') || process.env.NODE_OPTIONS.includes('--max_old_space_size='))) {
119
+ // const parsed = parser(process.env.NODE_OPTIONS);
120
+ // maxMemory = (parsed['max-old-space-size'] ? parsed['max-old-space-size'] : parsed['max_old_space_size']) * 1000 * 1000; // Turn MB into bytes
121
+ // }
122
+
115
123
  const walk = async (
116
124
  dir: string,
117
125
  fileMap: Map<string, FileContainer> = new Map(),
@@ -137,7 +145,6 @@ export const upload = async (
137
145
  } else {
138
146
  const name = relative(startingDir, filepath).split(sep).join("/");
139
147
 
140
- // TODO: Move this to later so we don't hold as much in memory
141
148
  const fileContent = await readFile(filepath);
142
149
 
143
150
  const base64Content = fileContent.toString("base64");
@@ -152,8 +159,9 @@ export const upload = async (
152
159
  );
153
160
  }
154
161
 
162
+ // We don't want to hold the content in memory. We instead only want to read it when it's needed
155
163
  fileMap.set(name, {
156
- content: base64Content,
164
+ path: filepath,
157
165
  contentType: getType(name) || "application/octet-stream",
158
166
  sizeInBytes: filestat.size,
159
167
  hash: blake3hash(base64Content + extension)
@@ -248,17 +256,21 @@ export const upload = async (
248
256
  // Don't upload empty buckets (can happen for tiny projects)
249
257
  if (bucket.files.length === 0) continue;
250
258
 
251
- const payload: UploadPayloadFile[] = bucket.files.map((file) => ({
252
- key: file.hash,
253
- value: file.content,
254
- metadata: {
255
- contentType: file.contentType,
256
- },
257
- base64: true,
258
- }));
259
-
260
259
  let attempts = 0;
261
260
  const doUpload = async (): Promise<void> => {
261
+ // Populate the payload only when actually uploading (this is limited to 3 concurrent uploads at 50 MiB per bucket meaning we'd only load in a max of ~150 MiB)
262
+ // This is so we don't run out of memory trying to upload the files.
263
+ const payload: UploadPayloadFile[] = await Promise.all(
264
+ bucket.files.map(async (file) => ({
265
+ key: file.hash,
266
+ value: (await readFile(file.path)).toString("base64"),
267
+ metadata: {
268
+ contentType: file.contentType,
269
+ },
270
+ base64: true,
271
+ }))
272
+ );
273
+
262
274
  try {
263
275
  return await fetchResult(`/pages/assets/upload`, {
264
276
  method: "POST",
@@ -270,9 +282,9 @@ export const upload = async (
270
282
  });
271
283
  } catch (e) {
272
284
  if (attempts < MAX_UPLOAD_ATTEMPTS) {
273
- // Linear backoff, 0 second first time, then 1 second etc.
285
+ // Exponential backoff, 1 second first time, then 2 second, then 4 second etc.
274
286
  await new Promise((resolvePromise) =>
275
- setTimeout(resolvePromise, attempts++ * 1000)
287
+ setTimeout(resolvePromise, Math.pow(2, attempts++) * 1000)
276
288
  );
277
289
 
278
290
  if ((e as { code: number }).code === 8000013) {