wrangler 2.0.18 → 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.
package/bin/wrangler.js CHANGED
@@ -3,7 +3,6 @@ const { spawn } = require("child_process");
3
3
  const path = require("path");
4
4
  const fs = require("fs");
5
5
  const os = require("os");
6
- const semiver = require("semiver");
7
6
 
8
7
  const MIN_NODE_VERSION = "16.7.0";
9
8
  const debug =
@@ -21,8 +20,8 @@ function runWrangler() {
21
20
  // Note Volta and nvm are also recommended in the official docs:
22
21
  // https://developers.cloudflare.com/workers/get-started/guide#2-install-the-workers-cli
23
22
  console.error(
24
- `Wrangler requires at least Node.js v${MIN_NODE_VERSION}. You are using v${process.versions.node}.
25
- You should use the latest Node.js version if possible, as Cloudflare Workers use a very up-to-date version of V8.
23
+ `Wrangler requires at least node.js v${MIN_NODE_VERSION}. You are using v${process.versions.node}. Please update your version of node.js.
24
+
26
25
  Consider using a Node.js version manager such as https://volta.sh/ or https://github.com/nvm-sh/nvm.`
27
26
  );
28
27
  process.exitCode = 1;
@@ -128,10 +127,42 @@ async function main() {
128
127
  }
129
128
 
130
129
  process.on("SIGINT", () => {
131
- wranglerProcess?.kill();
130
+ wranglerProcess && wranglerProcess.kill();
132
131
  });
133
132
  process.on("SIGTERM", () => {
134
- wranglerProcess?.kill();
133
+ wranglerProcess && wranglerProcess.kill();
135
134
  });
136
135
 
136
+ // semiver implementation via https://github.com/lukeed/semiver/blob/ae7eebe6053c96be63032b14fb0b68e2553fcac4/src/index.js
137
+
138
+ /**
139
+ MIT License
140
+
141
+ Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)
142
+
143
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
144
+
145
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
146
+
147
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
148
+
149
+ */
150
+
151
+ var fn = new Intl.Collator(0, { numeric: 1 }).compare;
152
+
153
+ function semiver(a, b, bool) {
154
+ a = a.split(".");
155
+ b = b.split(".");
156
+
157
+ return (
158
+ fn(a[0], b[0]) ||
159
+ fn(a[1], b[1]) ||
160
+ ((b[2] = b.slice(2).join(".")),
161
+ (bool = /[.-]/.test((a[2] = a.slice(2).join(".")))),
162
+ bool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1)
163
+ );
164
+ }
165
+
166
+ // end semiver implementation
167
+
137
168
  void main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "2.0.18",
3
+ "version": "2.0.19",
4
4
  "description": "Command-line interface for all things Cloudflare Workers",
5
5
  "keywords": [
6
6
  "wrangler",
@@ -93,7 +93,6 @@
93
93
  "nanoid": "^3.3.3",
94
94
  "path-to-regexp": "^6.2.0",
95
95
  "selfsigned": "^2.0.1",
96
- "semiver": "^1.1.0",
97
96
  "xxhash-wasm": "^1.0.1"
98
97
  },
99
98
  "devDependencies": {
@@ -40,6 +40,7 @@ describe("normalizeAndValidateConfig()", () => {
40
40
  tsconfig: undefined,
41
41
  kv_namespaces: [],
42
42
  legacy_env: true,
43
+ send_metrics: undefined,
43
44
  main: undefined,
44
45
  migrations: [],
45
46
  name: undefined,
@@ -76,6 +77,7 @@ describe("normalizeAndValidateConfig()", () => {
76
77
  it("should override config defaults with provided values", () => {
77
78
  const expectedConfig: Partial<ConfigFields<RawDevConfig>> = {
78
79
  legacy_env: true,
80
+ send_metrics: false,
79
81
  dev: {
80
82
  ip: "255.255.255.255",
81
83
  port: 9999,
@@ -98,6 +100,7 @@ describe("normalizeAndValidateConfig()", () => {
98
100
  it("should error on invalid top level fields", () => {
99
101
  const expectedConfig = {
100
102
  legacy_env: "FOO",
103
+ send_metrics: "BAD",
101
104
  dev: {
102
105
  ip: 222,
103
106
  port: "FOO",
@@ -117,13 +120,14 @@ describe("normalizeAndValidateConfig()", () => {
117
120
  );
118
121
  expect(diagnostics.hasWarnings()).toBe(false);
119
122
  expect(diagnostics.renderErrors()).toMatchInlineSnapshot(`
120
- "Processing wrangler configuration:
121
- - Expected \\"legacy_env\\" to be of type boolean but got \\"FOO\\".
122
- - Expected \\"dev.ip\\" to be of type string but got 222.
123
- - Expected \\"dev.port\\" to be of type number but got \\"FOO\\".
124
- - Expected \\"dev.local_protocol\\" field to be one of [\\"http\\",\\"https\\"] but got \\"wss\\".
125
- - Expected \\"dev.upstream_protocol\\" field to be one of [\\"http\\",\\"https\\"] but got \\"ws\\"."
126
- `);
123
+ "Processing wrangler configuration:
124
+ - Expected \\"legacy_env\\" to be of type boolean but got \\"FOO\\".
125
+ - Expected \\"send_metrics\\" to be of type boolean but got \\"BAD\\".
126
+ - Expected \\"dev.ip\\" to be of type string but got 222.
127
+ - Expected \\"dev.port\\" to be of type number but got \\"FOO\\".
128
+ - Expected \\"dev.local_protocol\\" field to be one of [\\"http\\",\\"https\\"] but got \\"wss\\".
129
+ - Expected \\"dev.upstream_protocol\\" field to be one of [\\"http\\",\\"https\\"] but got \\"ws\\"."
130
+ `);
127
131
  });
128
132
 
129
133
  it("should warn on and remove unexpected top level fields", () => {
@@ -6,7 +6,7 @@ import { reinitialiseAuthTokens } from "../../user";
6
6
  const originalCwd = process.cwd();
7
7
 
8
8
  export function runInTempDir({ homedir } = { homedir: "./home" }) {
9
- let tmpDir: string | undefined;
9
+ let tmpDir: string;
10
10
 
11
11
  beforeEach(() => {
12
12
  // Use realpath because the temporary path can point to a symlink rather than the actual path.
@@ -30,7 +30,7 @@ export function runInTempDir({ homedir } = { homedir: "./home" }) {
30
30
  });
31
31
 
32
32
  afterEach(() => {
33
- if (tmpDir && fs.existsSync(tmpDir)) {
33
+ if (fs.existsSync(tmpDir)) {
34
34
  process.chdir(originalCwd);
35
35
  fs.rmSync(tmpDir, { recursive: true });
36
36
  }
@@ -0,0 +1,415 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import fetchMock from "jest-fetch-mock";
3
+ import { version as wranglerVersion } from "../../package.json";
4
+ import { purgeConfigCaches, saveToConfigCache } from "../config-cache";
5
+ import { logger } from "../logger";
6
+ import { getMetricsDispatcher, getMetricsConfig } from "../metrics";
7
+ import {
8
+ CURRENT_METRICS_DATE,
9
+ readMetricsConfig,
10
+ USER_ID_CACHE_PATH,
11
+ writeMetricsConfig,
12
+ } from "../metrics/metrics-config";
13
+ import { writeAuthConfigFile } from "../user";
14
+ import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch";
15
+ import { mockConsoleMethods } from "./helpers/mock-console";
16
+ import { mockConfirm } from "./helpers/mock-dialogs";
17
+ import { useMockIsTTY } from "./helpers/mock-istty";
18
+ import { runInTempDir } from "./helpers/run-in-tmp";
19
+
20
+ declare const global: { SPARROW_SOURCE_KEY: string | undefined };
21
+
22
+ describe("metrics", () => {
23
+ const ORIGINAL_SPARROW_SOURCE_KEY = global.SPARROW_SOURCE_KEY;
24
+ const std = mockConsoleMethods();
25
+ runInTempDir();
26
+
27
+ beforeEach(() => {
28
+ global.SPARROW_SOURCE_KEY = "MOCK_KEY";
29
+ logger.loggerLevel = "debug";
30
+ // Create a node_modules directory to store config-cache files
31
+ mkdirSync("node_modules");
32
+ });
33
+ afterEach(() => {
34
+ global.SPARROW_SOURCE_KEY = ORIGINAL_SPARROW_SOURCE_KEY;
35
+ fetchMock.resetMocks();
36
+ unsetAllMocks();
37
+ purgeConfigCaches();
38
+ });
39
+
40
+ describe("getMetricsDispatcher()", () => {
41
+ const MOCK_DISPATCHER_OPTIONS = {
42
+ // By setting this to true we avoid the `getMetricsConfig()` logic in these tests.
43
+ sendMetrics: true,
44
+ offline: false,
45
+ };
46
+
47
+ // These tests should never hit the `/user` API endpoint.
48
+ const userRequests = mockUserRequest();
49
+ afterEach(() => {
50
+ expect(userRequests.count).toBe(0);
51
+ });
52
+
53
+ describe("identify()", () => {
54
+ it("should send a request to the default URL", async () => {
55
+ const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
56
+ fetchMock.mockResponse("");
57
+ await dispatcher.identify({ a: 1, b: 2 });
58
+ expect(fetchMock).toHaveBeenCalledTimes(1);
59
+ const [url, { body, headers }] = fetchMock.mock.calls[0];
60
+ expect(url).toEqual("https://sparrow.cloudflare.com/api/v1/identify");
61
+ expect(JSON.parse(body)).toEqual(
62
+ expect.objectContaining({
63
+ event: "identify",
64
+ properties: {
65
+ category: "Workers",
66
+ wranglerVersion,
67
+ a: 1,
68
+ b: 2,
69
+ },
70
+ })
71
+ );
72
+ expect(headers).toEqual(
73
+ expect.objectContaining({
74
+ "Sparrow-Source-Key": "MOCK_KEY",
75
+ })
76
+ );
77
+ expect(std.debug).toMatchInlineSnapshot(
78
+ `"Metrics dispatcher: Posting data {\\"type\\":\\"identify\\",\\"name\\":\\"identify\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}"`
79
+ );
80
+ expect(std.out).toMatchInlineSnapshot(`""`);
81
+ expect(std.warn).toMatchInlineSnapshot(`""`);
82
+ expect(std.err).toMatchInlineSnapshot(`""`);
83
+ });
84
+
85
+ it("should write a debug log if the dispatcher is disabled", async () => {
86
+ const dispatcher = await getMetricsDispatcher({
87
+ ...MOCK_DISPATCHER_OPTIONS,
88
+ sendMetrics: false,
89
+ });
90
+ await dispatcher.identify({ a: 1, b: 2 });
91
+ expect(fetchMock).toHaveBeenCalledTimes(0);
92
+ expect(std.debug).toMatchInlineSnapshot(
93
+ `"Metrics dispatcher: Dispatching disabled - would have sent {\\"type\\":\\"identify\\",\\"name\\":\\"identify\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}."`
94
+ );
95
+ expect(std.out).toMatchInlineSnapshot(`""`);
96
+ expect(std.warn).toMatchInlineSnapshot(`""`);
97
+ expect(std.err).toMatchInlineSnapshot(`""`);
98
+ });
99
+
100
+ it("should write a debug log if the request fails", async () => {
101
+ const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
102
+ fetchMock.mockReject(new Error("BAD REQUEST"));
103
+ await dispatcher.identify({ a: 1, b: 2 });
104
+ expect(std.debug).toMatchInlineSnapshot(`
105
+ "Metrics dispatcher: Posting data {\\"type\\":\\"identify\\",\\"name\\":\\"identify\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}
106
+ Metrics dispatcher: Failed to send request: BAD REQUEST"
107
+ `);
108
+ expect(std.out).toMatchInlineSnapshot(`""`);
109
+ expect(std.warn).toMatchInlineSnapshot(`""`);
110
+ expect(std.err).toMatchInlineSnapshot(`""`);
111
+ });
112
+
113
+ it("should write a warning log if no source key has been provided", async () => {
114
+ global.SPARROW_SOURCE_KEY = undefined;
115
+ const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
116
+ await dispatcher.identify({ a: 1, b: 2 });
117
+ expect(fetchMock).toHaveBeenCalledTimes(0);
118
+ expect(std.debug).toMatchInlineSnapshot(
119
+ `"Metrics dispatcher: Source Key not provided. Be sure to initialize before sending events. { type: 'identify', name: 'identify', properties: { a: 1, b: 2 } }"`
120
+ );
121
+ expect(std.out).toMatchInlineSnapshot(`""`);
122
+ expect(std.warn).toMatchInlineSnapshot(`""`);
123
+ expect(std.err).toMatchInlineSnapshot(`""`);
124
+ });
125
+ });
126
+
127
+ describe("sendEvent()", () => {
128
+ it("should send a request to the default URL", async () => {
129
+ const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
130
+ fetchMock.mockResponse("");
131
+ await dispatcher.sendEvent("some-event", { a: 1, b: 2 });
132
+ expect(fetchMock).toHaveBeenCalledTimes(1);
133
+ const [url, { body, headers }] = fetchMock.mock.calls[0];
134
+ expect(url).toEqual("https://sparrow.cloudflare.com/api/v1/event");
135
+ expect(JSON.parse(body)).toEqual(
136
+ expect.objectContaining({
137
+ event: "some-event",
138
+ properties: {
139
+ category: "Workers",
140
+ wranglerVersion,
141
+ a: 1,
142
+ b: 2,
143
+ },
144
+ })
145
+ );
146
+ expect(headers).toEqual(
147
+ expect.objectContaining({
148
+ "Sparrow-Source-Key": "MOCK_KEY",
149
+ })
150
+ );
151
+ expect(std.debug).toMatchInlineSnapshot(
152
+ `"Metrics dispatcher: Posting data {\\"type\\":\\"event\\",\\"name\\":\\"some-event\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}"`
153
+ );
154
+ expect(std.out).toMatchInlineSnapshot(`""`);
155
+ expect(std.warn).toMatchInlineSnapshot(`""`);
156
+ expect(std.err).toMatchInlineSnapshot(`""`);
157
+ });
158
+
159
+ it("should write a debug log if the dispatcher is disabled", async () => {
160
+ const dispatcher = await getMetricsDispatcher({
161
+ ...MOCK_DISPATCHER_OPTIONS,
162
+ sendMetrics: false,
163
+ });
164
+ await dispatcher.sendEvent("some-event", { a: 1, b: 2 });
165
+ expect(fetchMock).toHaveBeenCalledTimes(0);
166
+ expect(std.debug).toMatchInlineSnapshot(
167
+ `"Metrics dispatcher: Dispatching disabled - would have sent {\\"type\\":\\"event\\",\\"name\\":\\"some-event\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}."`
168
+ );
169
+ expect(std.out).toMatchInlineSnapshot(`""`);
170
+ expect(std.warn).toMatchInlineSnapshot(`""`);
171
+ expect(std.err).toMatchInlineSnapshot(`""`);
172
+ });
173
+
174
+ it("should write a debug log if the request fails", async () => {
175
+ const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
176
+ fetchMock.mockReject(new Error("BAD REQUEST"));
177
+ await dispatcher.sendEvent("some-event", { a: 1, b: 2 });
178
+ expect(std.debug).toMatchInlineSnapshot(`
179
+ "Metrics dispatcher: Posting data {\\"type\\":\\"event\\",\\"name\\":\\"some-event\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}
180
+ Metrics dispatcher: Failed to send request: BAD REQUEST"
181
+ `);
182
+ expect(std.out).toMatchInlineSnapshot(`""`);
183
+ expect(std.warn).toMatchInlineSnapshot(`""`);
184
+ expect(std.err).toMatchInlineSnapshot(`""`);
185
+ });
186
+
187
+ it("should write a warning log if no source key has been provided", async () => {
188
+ global.SPARROW_SOURCE_KEY = undefined;
189
+ const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
190
+ await dispatcher.sendEvent("some-event", { a: 1, b: 2 });
191
+ expect(fetchMock).toHaveBeenCalledTimes(0);
192
+ expect(std.debug).toMatchInlineSnapshot(
193
+ `"Metrics dispatcher: Source Key not provided. Be sure to initialize before sending events. { type: 'event', name: 'some-event', properties: { a: 1, b: 2 } }"`
194
+ );
195
+ expect(std.out).toMatchInlineSnapshot(`""`);
196
+ expect(std.warn).toMatchInlineSnapshot(`""`);
197
+ expect(std.err).toMatchInlineSnapshot(`""`);
198
+ });
199
+ });
200
+ });
201
+
202
+ describe("getMetricsConfig()", () => {
203
+ const { setIsTTY } = useMockIsTTY();
204
+ beforeEach(() => {
205
+ // Default the mock TTY to interactive for all these tests.
206
+ setIsTTY(true);
207
+ });
208
+
209
+ describe("enabled", () => {
210
+ it("should return the sendMetrics argument for enabled if it is defined", async () => {
211
+ expect(
212
+ await getMetricsConfig({ sendMetrics: false, offline: false })
213
+ ).toMatchObject({
214
+ enabled: false,
215
+ });
216
+ expect(
217
+ await getMetricsConfig({ sendMetrics: true, offline: false })
218
+ ).toMatchObject({
219
+ enabled: true,
220
+ });
221
+ });
222
+
223
+ it("should return enabled false if the process is not interactive", async () => {
224
+ setIsTTY(false);
225
+ expect(
226
+ await getMetricsConfig({
227
+ sendMetrics: undefined,
228
+ offline: false,
229
+ })
230
+ ).toMatchObject({
231
+ enabled: false,
232
+ });
233
+ });
234
+
235
+ it("should return enabled true if the user on this device previously agreed to send metrics", async () => {
236
+ await writeMetricsConfig({
237
+ permission: {
238
+ enabled: true,
239
+ date: new Date(2022, 6, 4),
240
+ },
241
+ });
242
+ expect(
243
+ await getMetricsConfig({
244
+ sendMetrics: undefined,
245
+ offline: false,
246
+ })
247
+ ).toMatchObject({
248
+ enabled: true,
249
+ });
250
+ });
251
+
252
+ it("should return enabled false if the user on this device previously refused to send metrics", async () => {
253
+ await writeMetricsConfig({
254
+ permission: {
255
+ enabled: false,
256
+ date: new Date(2022, 6, 4),
257
+ },
258
+ });
259
+ expect(
260
+ await getMetricsConfig({
261
+ sendMetrics: undefined,
262
+ offline: false,
263
+ })
264
+ ).toMatchObject({
265
+ enabled: false,
266
+ });
267
+ });
268
+
269
+ it("should accept and store permission granting to send metrics if the user agrees", async () => {
270
+ const checkConfirmations = mockConfirm({
271
+ text: "Would you like to help improve Wrangler by sending usage metrics to Cloudflare?",
272
+ result: true,
273
+ });
274
+ expect(
275
+ await getMetricsConfig({
276
+ sendMetrics: undefined,
277
+ offline: false,
278
+ })
279
+ ).toMatchObject({
280
+ enabled: true,
281
+ });
282
+ checkConfirmations();
283
+ expect((await readMetricsConfig()).permission).toMatchObject({
284
+ enabled: true,
285
+ });
286
+ });
287
+
288
+ it("should accept and store permission declining to send metrics if the user declines", async () => {
289
+ const checkConfirmations = mockConfirm({
290
+ text: "Would you like to help improve Wrangler by sending usage metrics to Cloudflare?",
291
+ result: false,
292
+ });
293
+ expect(
294
+ await getMetricsConfig({
295
+ sendMetrics: undefined,
296
+ offline: false,
297
+ })
298
+ ).toMatchObject({
299
+ enabled: false,
300
+ });
301
+ checkConfirmations();
302
+ expect((await readMetricsConfig()).permission).toMatchObject({
303
+ enabled: false,
304
+ });
305
+ });
306
+
307
+ it("should ignore the config if the permission date is older than the current metrics date", async () => {
308
+ const checkConfirmations = mockConfirm({
309
+ text: "Would you like to help improve Wrangler by sending usage metrics to Cloudflare?",
310
+ result: false,
311
+ });
312
+ const OLD_DATE = new Date(2000);
313
+ await writeMetricsConfig({
314
+ permission: { enabled: true, date: OLD_DATE },
315
+ });
316
+ expect(
317
+ await getMetricsConfig({
318
+ sendMetrics: undefined,
319
+ offline: false,
320
+ })
321
+ ).toMatchObject({
322
+ enabled: false,
323
+ });
324
+ checkConfirmations();
325
+ const { permission } = await readMetricsConfig();
326
+ expect(permission?.enabled).toBe(false);
327
+ // The date should be updated to today's date
328
+ expect(permission?.date).toEqual(CURRENT_METRICS_DATE);
329
+
330
+ expect(std.out).toMatchInlineSnapshot(`
331
+ "Usage metrics tracking has changed since you last granted permission.
332
+ Your choice has been saved in the following file: home/.wrangler/config/metrics.json.
333
+
334
+ You can override the user level setting for a project in \`wrangler.toml\`:
335
+
336
+ - to disable sending metrics for a project: \`send_metrics = false\`
337
+ - to enable sending metrics for a project: \`send_metrics = true\`"
338
+ `);
339
+ });
340
+ });
341
+
342
+ describe("deviceId", () => {
343
+ it("should return a deviceId found in the config file", async () => {
344
+ await writeMetricsConfig({ deviceId: "XXXX-YYYY-ZZZZ" });
345
+ const { deviceId } = await getMetricsConfig({
346
+ sendMetrics: true,
347
+ offline: false,
348
+ });
349
+ expect(deviceId).toEqual("XXXX-YYYY-ZZZZ");
350
+ expect((await readMetricsConfig()).deviceId).toEqual(deviceId);
351
+ });
352
+
353
+ it("should create and store a new deviceId if none is found in the config file", async () => {
354
+ await writeMetricsConfig({});
355
+ const { deviceId } = await getMetricsConfig({
356
+ sendMetrics: true,
357
+ offline: false,
358
+ });
359
+ expect(deviceId).toMatch(
360
+ /[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}/
361
+ );
362
+ expect((await readMetricsConfig()).deviceId).toEqual(deviceId);
363
+ });
364
+ });
365
+
366
+ describe("userId", () => {
367
+ const userRequests = mockUserRequest();
368
+ it("should return a userId found in a cache file", async () => {
369
+ await saveToConfigCache(USER_ID_CACHE_PATH, {
370
+ userId: "CACHED_USER_ID",
371
+ });
372
+ const { userId } = await getMetricsConfig({
373
+ sendMetrics: true,
374
+ offline: false,
375
+ });
376
+ expect(userId).toEqual("CACHED_USER_ID");
377
+ expect(userRequests.count).toBe(0);
378
+ });
379
+
380
+ it("should fetch the userId from Cloudflare and store it in a cache file", async () => {
381
+ writeAuthConfigFile({ oauth_token: "DUMMY_TOKEN" });
382
+ const { userId } = await getMetricsConfig({
383
+ sendMetrics: true,
384
+ offline: false,
385
+ });
386
+ expect(userId).toEqual("MOCK_USER_ID");
387
+ expect(userRequests.count).toBe(1);
388
+ });
389
+
390
+ it("should not fetch the userId from Cloudflare if running in `offline` mode", async () => {
391
+ writeAuthConfigFile({ oauth_token: "DUMMY_TOKEN" });
392
+ const { userId } = await getMetricsConfig({
393
+ sendMetrics: true,
394
+ offline: true,
395
+ });
396
+ expect(userId).toBe(undefined);
397
+ expect(userRequests.count).toBe(0);
398
+ });
399
+ });
400
+ });
401
+ });
402
+
403
+ function mockUserRequest() {
404
+ const requests = { count: 0 };
405
+ beforeEach(() => {
406
+ setMockResponse("/user", () => {
407
+ requests.count++;
408
+ return { id: "MOCK_USER_ID" };
409
+ });
410
+ });
411
+ afterEach(() => {
412
+ requests.count = 0;
413
+ });
414
+ return requests;
415
+ }
@@ -0,0 +1,31 @@
1
+ // this test has to be run with a version of node.js older than 16.7 to pass
2
+
3
+ const { spawn } = require("child_process");
4
+ const path = require("path");
5
+
6
+ const assert = require("assert");
7
+
8
+ const wranglerProcess = spawn(
9
+ "node",
10
+ [path.join(__dirname, "../../bin/wrangler.js")],
11
+ { stdio: "pipe" }
12
+ );
13
+
14
+ const messageToMatch = "Wrangler requires at least node.js v16.7.0";
15
+
16
+ wranglerProcess.once("exit", (code) => {
17
+ try {
18
+ const errorMessage = wranglerProcess.stderr.read().toString();
19
+
20
+ assert(code === 1, "Expected exit code 1");
21
+ assert(
22
+ errorMessage.includes(messageToMatch),
23
+ `Expected error message to include "${messageToMatch}"`
24
+ );
25
+ } catch (err) {
26
+ console.error("Error:", err);
27
+ throw new Error(
28
+ "This test has to be run with a version of node.js under 16.7 to pass"
29
+ );
30
+ }
31
+ });
@@ -38,6 +38,14 @@ export interface ConfigFields<Dev extends RawDevConfig> {
38
38
  */
39
39
  legacy_env: boolean;
40
40
 
41
+ /**
42
+ * Whether Wrangler should send usage metrics to Cloudflare for this project.
43
+ *
44
+ * When defined this will override any user settings.
45
+ * Otherwise, Wrangler will use the user's preference.
46
+ */
47
+ send_metrics: boolean | undefined;
48
+
41
49
  /**
42
50
  * Options to configure the development server that your worker will use.
43
51
  */
@@ -94,6 +94,14 @@ export function normalizeAndValidateConfig(
94
94
  "boolean"
95
95
  );
96
96
 
97
+ validateOptionalProperty(
98
+ diagnostics,
99
+ "",
100
+ "send_metrics",
101
+ rawConfig.send_metrics,
102
+ "boolean"
103
+ );
104
+
97
105
  // TODO: set the default to false to turn on service environments as the default
98
106
  const isLegacyEnv =
99
107
  (args as { "legacy-env": boolean | undefined })["legacy-env"] ??
@@ -173,6 +181,7 @@ export function normalizeAndValidateConfig(
173
181
  const config: Config = {
174
182
  configPath,
175
183
  legacy_env: isLegacyEnv,
184
+ send_metrics: rawConfig.send_metrics,
176
185
  ...activeEnv,
177
186
  dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}),
178
187
  migrations: normalizeAndValidateMigrations(
@@ -6,7 +6,7 @@ import { logger } from "./logger";
6
6
 
7
7
  let cacheMessageShown = false;
8
8
 
9
- let __cacheFolder: string | null;
9
+ let __cacheFolder: string | null | undefined;
10
10
  function getCacheFolder() {
11
11
  if (__cacheFolder || __cacheFolder === null) return __cacheFolder;
12
12
 
@@ -80,4 +80,5 @@ export function purgeConfigCaches() {
80
80
  if (cacheFolder) {
81
81
  rmSync(cacheFolder, { recursive: true, force: true });
82
82
  }
83
+ __cacheFolder = undefined;
83
84
  }
package/src/dev/local.tsx CHANGED
@@ -195,9 +195,10 @@ function useLocalWorker({
195
195
  ),
196
196
  ...(localPersistencePath
197
197
  ? {
198
- kvPersist: path.join(localPersistencePath, "kv"),
199
- durableObjectsPersist: path.join(localPersistencePath, "do"),
200
198
  cachePersist: path.join(localPersistencePath, "cache"),
199
+ durableObjectsPersist: path.join(localPersistencePath, "do"),
200
+ kvPersist: path.join(localPersistencePath, "kv"),
201
+ r2Persist: path.join(localPersistencePath, "r2"),
201
202
  }
202
203
  : {
203
204
  // We mark these as true, so that they'll
@@ -205,9 +206,10 @@ function useLocalWorker({
205
206
  // This means they'll persist across a dev session,
206
207
  // even if we change source and reload,
207
208
  // and be deleted when the dev session ends
208
- durableObjectsPersist: true,
209
209
  cachePersist: true,
210
+ durableObjectsPersist: true,
210
211
  kvPersist: true,
212
+ r2Persist: true,
211
213
  }),
212
214
 
213
215
  sitePath: assetPaths?.assetDirectory