wrangler 0.0.0-e88a54e → 0.0.0-e95e5a0

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 (88) hide show
  1. package/README.md +25 -14
  2. package/bin/wrangler.js +13 -1
  3. package/miniflare-dist/index.mjs +4828 -21
  4. package/package.json +29 -24
  5. package/pages/functions/buildPlugin.ts +92 -0
  6. package/pages/functions/buildWorker.ts +80 -4
  7. package/pages/functions/filepath-routing.test.ts +11 -0
  8. package/pages/functions/filepath-routing.ts +8 -0
  9. package/pages/functions/routes.ts +6 -1
  10. package/pages/functions/template-plugin.ts +146 -0
  11. package/pages/functions/template-worker.ts +21 -8
  12. package/src/__tests__/config-cache.test.ts +36 -0
  13. package/src/__tests__/configuration.test.ts +530 -201
  14. package/src/__tests__/dev.test.tsx +284 -18
  15. package/src/__tests__/guess-worker-format.test.ts +28 -1
  16. package/src/__tests__/helpers/mock-cfetch.ts +5 -1
  17. package/src/__tests__/helpers/mock-console.ts +20 -3
  18. package/src/__tests__/helpers/mock-dialogs.ts +26 -1
  19. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  20. package/src/__tests__/helpers/mock-istty.ts +27 -0
  21. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  22. package/src/__tests__/helpers/run-in-tmp.ts +7 -0
  23. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  24. package/src/__tests__/https-options.test.ts +5 -2
  25. package/src/__tests__/index.test.ts +27 -769
  26. package/src/__tests__/init.test.ts +1516 -0
  27. package/src/__tests__/jest.setup.ts +4 -4
  28. package/src/__tests__/kv.test.ts +133 -61
  29. package/src/__tests__/logger.test.ts +115 -0
  30. package/src/__tests__/pages.test.ts +311 -26
  31. package/src/__tests__/publish.test.ts +2789 -618
  32. package/src/__tests__/r2.test.ts +26 -10
  33. package/src/__tests__/route.test.ts +4 -4
  34. package/src/__tests__/secret.test.ts +55 -34
  35. package/src/__tests__/tail.test.ts +146 -20
  36. package/src/__tests__/user.test.ts +131 -0
  37. package/src/__tests__/whoami.test.tsx +14 -9
  38. package/src/bundle.ts +30 -3
  39. package/src/cfetch/internal.ts +0 -2
  40. package/src/cli.ts +5 -11
  41. package/src/config/README.md +1 -1
  42. package/src/config/config.ts +20 -4
  43. package/src/config/environment.ts +32 -4
  44. package/src/config/index.ts +4 -3
  45. package/src/config/validation-helpers.ts +96 -7
  46. package/src/config/validation.ts +388 -54
  47. package/src/config-cache.ts +45 -0
  48. package/src/create-worker-preview.ts +22 -13
  49. package/src/create-worker-upload-form.ts +32 -9
  50. package/src/dev/dev-vars.ts +36 -0
  51. package/src/dev/dev.tsx +132 -78
  52. package/src/dev/local.tsx +101 -21
  53. package/src/dev/remote.tsx +23 -13
  54. package/src/dev/use-esbuild.ts +23 -5
  55. package/src/dialogs.tsx +16 -6
  56. package/src/entry.ts +83 -24
  57. package/src/environment-variables.ts +3 -1
  58. package/src/errors.ts +11 -0
  59. package/src/https-options.ts +3 -2
  60. package/src/index.tsx +689 -394
  61. package/src/inspect.ts +17 -11
  62. package/src/intl-polyfill.d.ts +139 -0
  63. package/src/logger.ts +66 -0
  64. package/src/miniflare-cli/index.ts +4 -0
  65. package/src/miniflare-cli/request-context.ts +40 -0
  66. package/src/module-collection.ts +7 -7
  67. package/src/open-in-browser.ts +5 -4
  68. package/src/package-manager.ts +9 -8
  69. package/src/pages.tsx +875 -56
  70. package/src/parse.ts +1 -1
  71. package/src/proxy.ts +28 -19
  72. package/src/publish.ts +263 -141
  73. package/src/sites.tsx +27 -14
  74. package/src/tail/index.ts +2 -2
  75. package/src/tail/printing.ts +13 -8
  76. package/src/update-check.ts +19 -0
  77. package/src/user.tsx +116 -41
  78. package/src/whoami.tsx +2 -1
  79. package/src/worker.ts +15 -6
  80. package/templates/gitignore +171 -0
  81. package/templates/static-asset-facade.js +1 -1
  82. package/wrangler-dist/cli.js +21162 -50227
  83. package/miniflare-dist/index.mjs.map +0 -7
  84. package/src/__tests__/dev2.test.tsx +0 -154
  85. package/src/__tests__/logout.test.ts +0 -52
  86. package/src/__tests__/sentry.test.ts +0 -146
  87. package/src/reporting.ts +0 -131
  88. package/wrangler-dist/cli.js.map +0 -7
@@ -67,7 +67,10 @@ describe("wrangler", () => {
67
67
  ).rejects.toThrowErrorMatchingInlineSnapshot(
68
68
  `"Not enough non-option arguments: got 0, need at least 1"`
69
69
  );
70
- expect(std.out).toMatchInlineSnapshot(`""`);
70
+ expect(std.out).toMatchInlineSnapshot(`
71
+ "
72
+ "
73
+ `);
71
74
  expect(std.err).toMatchInlineSnapshot(`
72
75
  "wrangler r2 bucket create <name>
73
76
 
@@ -81,8 +84,9 @@ describe("wrangler", () => {
81
84
  -h, --help Show help [boolean]
82
85
  -v, --version Show version number [boolean]
83
86
  --legacy-env Use legacy environments [boolean]
87
+ X [ERROR] Not enough non-option arguments: got 0, need at least 1
84
88
 
85
- Not enough non-option arguments: got 0, need at least 1"
89
+ "
86
90
  `);
87
91
  });
88
92
 
@@ -90,9 +94,12 @@ describe("wrangler", () => {
90
94
  await expect(
91
95
  runWrangler("r2 bucket create abc def ghi")
92
96
  ).rejects.toThrowErrorMatchingInlineSnapshot(
93
- `"Unexpected additional positional arguments \\"def ghi\\"."`
97
+ `"Unknown arguments: def, ghi"`
94
98
  );
95
- expect(std.out).toMatchInlineSnapshot(`""`);
99
+ expect(std.out).toMatchInlineSnapshot(`
100
+ "
101
+ "
102
+ `);
96
103
  expect(std.err).toMatchInlineSnapshot(`
97
104
  "wrangler r2 bucket create <name>
98
105
 
@@ -106,8 +113,9 @@ describe("wrangler", () => {
106
113
  -h, --help Show help [boolean]
107
114
  -v, --version Show version number [boolean]
108
115
  --legacy-env Use legacy environments [boolean]
116
+ X [ERROR] Unknown arguments: def, ghi
109
117
 
110
- Unexpected additional positional arguments \\"def ghi\\"."
118
+ "
111
119
  `);
112
120
  });
113
121
 
@@ -143,7 +151,10 @@ describe("wrangler", () => {
143
151
  ).rejects.toThrowErrorMatchingInlineSnapshot(
144
152
  `"Not enough non-option arguments: got 0, need at least 1"`
145
153
  );
146
- expect(std.out).toMatchInlineSnapshot(`""`);
154
+ expect(std.out).toMatchInlineSnapshot(`
155
+ "
156
+ "
157
+ `);
147
158
  expect(std.err).toMatchInlineSnapshot(`
148
159
  "wrangler r2 bucket delete <name>
149
160
 
@@ -157,8 +168,9 @@ describe("wrangler", () => {
157
168
  -h, --help Show help [boolean]
158
169
  -v, --version Show version number [boolean]
159
170
  --legacy-env Use legacy environments [boolean]
171
+ X [ERROR] Not enough non-option arguments: got 0, need at least 1
160
172
 
161
- Not enough non-option arguments: got 0, need at least 1"
173
+ "
162
174
  `);
163
175
  });
164
176
 
@@ -166,9 +178,12 @@ describe("wrangler", () => {
166
178
  await expect(
167
179
  runWrangler("r2 bucket delete abc def ghi")
168
180
  ).rejects.toThrowErrorMatchingInlineSnapshot(
169
- `"Unexpected additional positional arguments \\"def ghi\\"."`
181
+ `"Unknown arguments: def, ghi"`
170
182
  );
171
- expect(std.out).toMatchInlineSnapshot(`""`);
183
+ expect(std.out).toMatchInlineSnapshot(`
184
+ "
185
+ "
186
+ `);
172
187
  expect(std.err).toMatchInlineSnapshot(`
173
188
  "wrangler r2 bucket delete <name>
174
189
 
@@ -182,8 +197,9 @@ describe("wrangler", () => {
182
197
  -h, --help Show help [boolean]
183
198
  -v, --version Show version number [boolean]
184
199
  --legacy-env Use legacy environments [boolean]
200
+ X [ERROR] Unknown arguments: def, ghi
185
201
 
186
- Unexpected additional positional arguments \\"def ghi\\"."
202
+ "
187
203
  `);
188
204
  });
189
205
 
@@ -9,7 +9,7 @@ describe("wrangler route", () => {
9
9
  it("shows a deprecation notice when `wrangler route` is run", async () => {
10
10
  await expect(runWrangler("route")).rejects
11
11
  .toThrowErrorMatchingInlineSnapshot(`
12
- "DEPRECATION WARNING:
12
+ "Deprecation:
13
13
  \`wrangler route\` has been deprecated.
14
14
  Please use wrangler.toml and/or \`wrangler publish --routes\` to modify routes"
15
15
  `);
@@ -18,7 +18,7 @@ describe("wrangler route", () => {
18
18
  it("shows a deprecation notice when `wrangler route delete` is run", async () => {
19
19
  await expect(runWrangler("route delete")).rejects
20
20
  .toThrowErrorMatchingInlineSnapshot(`
21
- "DEPRECATION WARNING:
21
+ "Deprecation:
22
22
  \`wrangler route delete\` has been deprecated.
23
23
  Remove the unwanted route(s) from wrangler.toml and run \`wrangler publish\` to remove your worker from those routes."
24
24
  `);
@@ -27,7 +27,7 @@ describe("wrangler route", () => {
27
27
  it("shows a deprecation notice when `wrangler route delete <id>` is run", async () => {
28
28
  await expect(runWrangler("route delete some-zone-id")).rejects
29
29
  .toThrowErrorMatchingInlineSnapshot(`
30
- "DEPRECATION WARNING:
30
+ "Deprecation:
31
31
  \`wrangler route delete\` has been deprecated.
32
32
  Remove the unwanted route(s) from wrangler.toml and run \`wrangler publish\` to remove your worker from those routes."
33
33
  `);
@@ -36,7 +36,7 @@ describe("wrangler route", () => {
36
36
  it("shows a deprecation notice when `wrangler route list` is run", async () => {
37
37
  await expect(runWrangler("route list")).rejects
38
38
  .toThrowErrorMatchingInlineSnapshot(`
39
- "DEPRECATION WARNING:
39
+ "Deprecation:
40
40
  \`wrangler route list\` has been deprecated.
41
41
  Refer to wrangler.toml for a list of routes the worker will be deployed to upon publishing.
42
42
  Refer to the Cloudflare Dashboard to see the routes this worker is currently running on."
@@ -1,22 +1,31 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as TOML from "@iarna/toml";
3
- import fetchMock from "jest-fetch-mock";
4
3
  import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
5
4
  import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch";
6
5
  import { mockConsoleMethods } from "./helpers/mock-console";
7
- import { mockConfirm, mockPrompt } from "./helpers/mock-dialogs";
6
+ import {
7
+ mockConfirm,
8
+ mockPrompt,
9
+ clearConfirmMocks,
10
+ clearPromptMocks,
11
+ } from "./helpers/mock-dialogs";
12
+ import { mockOAuthFlow } from "./helpers/mock-oauth-flow";
8
13
  import { useMockStdin } from "./helpers/mock-stdin";
9
14
  import { runInTempDir } from "./helpers/run-in-tmp";
10
15
  import { runWrangler } from "./helpers/run-wrangler";
11
16
 
12
17
  describe("wrangler secret", () => {
13
18
  const std = mockConsoleMethods();
19
+ const { mockGetMemberships } = mockOAuthFlow();
20
+
14
21
  runInTempDir();
15
22
  mockAccountId();
16
23
  mockApiToken();
17
24
 
18
25
  afterEach(() => {
19
26
  unsetAllMocks();
27
+ clearConfirmMocks();
28
+ clearPromptMocks();
20
29
  });
21
30
 
22
31
  describe("put", () => {
@@ -121,11 +130,14 @@ describe("wrangler secret", () => {
121
130
  } catch (e) {
122
131
  error = e as Error;
123
132
  }
124
- expect(std.out).toMatchInlineSnapshot(`""`);
133
+ expect(std.out).toMatchInlineSnapshot(`
134
+ "
135
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
136
+ `);
125
137
  expect(std.err).toMatchInlineSnapshot(`
126
- "Missing script name
138
+ "X [ERROR] Missing script name
127
139
 
128
- %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
140
+ "
129
141
  `);
130
142
  expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
131
143
  });
@@ -155,7 +167,10 @@ describe("wrangler secret", () => {
155
167
  runWrangler("secret put the-key --name script-name")
156
168
  ).rejects.toThrowErrorMatchingInlineSnapshot(`"Error in stdin stream"`);
157
169
 
158
- expect(std.out).toMatchInlineSnapshot(`""`);
170
+ expect(std.out).toMatchInlineSnapshot(`
171
+ "
172
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
173
+ `);
159
174
  expect(std.warn).toMatchInlineSnapshot(`""`);
160
175
  });
161
176
 
@@ -163,10 +178,14 @@ describe("wrangler secret", () => {
163
178
  mockAccountId({ accountId: null });
164
179
 
165
180
  it("should error if a user has no account", async () => {
181
+ mockGetMemberships({
182
+ success: false,
183
+ result: [],
184
+ });
166
185
  await expect(
167
186
  runWrangler("secret put the-key --name script-name")
168
187
  ).rejects.toThrowErrorMatchingInlineSnapshot(
169
- `"No account id found, quitting..."`
188
+ `"Failed to automatically retrieve account IDs for the logged in user. In a non-interactive environment, it is mandatory to specify an account ID, either by assigning its value to CLOUDFLARE_ACCOUNT_ID, or as \`account_id\` in your \`wrangler.toml\` file."`
170
189
  );
171
190
  });
172
191
 
@@ -190,28 +209,24 @@ describe("wrangler secret", () => {
190
209
  });
191
210
 
192
211
  it("should error if a user has multiple accounts, and has not specified an account in wrangler.toml", async () => {
193
- // This is a mock response for the request to the CF API memberships of the current user.
194
- fetchMock.doMockOnce(async () => {
195
- return {
196
- body: JSON.stringify({
197
- success: true,
198
- result: [
199
- {
200
- id: "1",
201
- account: { id: "account-id-1", name: "account-name-1" },
202
- },
203
- {
204
- id: "2",
205
- account: { id: "account-id-2", name: "account-name-2" },
206
- },
207
- {
208
- id: "3",
209
- account: { id: "account-id-3", name: "account-name-3" },
210
- },
211
- ],
212
- }),
213
- };
212
+ mockGetMemberships({
213
+ success: true,
214
+ result: [
215
+ {
216
+ id: "1",
217
+ account: { id: "account-id-1", name: "account-name-1" },
218
+ },
219
+ {
220
+ id: "2",
221
+ account: { id: "account-id-2", name: "account-name-2" },
222
+ },
223
+ {
224
+ id: "3",
225
+ account: { id: "account-id-3", name: "account-name-3" },
226
+ },
227
+ ],
214
228
  });
229
+
215
230
  await expect(runWrangler("secret put the-key --name script-name"))
216
231
  .rejects.toThrowErrorMatchingInlineSnapshot(`
217
232
  "More than one account available but unable to select one in non-interactive mode.
@@ -320,11 +335,14 @@ describe("wrangler secret", () => {
320
335
  } catch (e) {
321
336
  error = e as Error;
322
337
  }
323
- expect(std.out).toMatchInlineSnapshot(`""`);
338
+ expect(std.out).toMatchInlineSnapshot(`
339
+ "
340
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
341
+ `);
324
342
  expect(std.err).toMatchInlineSnapshot(`
325
- "Missing script name
343
+ "X [ERROR] Missing script name
326
344
 
327
- %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
345
+ "
328
346
  `);
329
347
  expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
330
348
  });
@@ -413,11 +431,14 @@ describe("wrangler secret", () => {
413
431
  } catch (e) {
414
432
  error = e as Error;
415
433
  }
416
- expect(std.out).toMatchInlineSnapshot(`""`);
434
+ expect(std.out).toMatchInlineSnapshot(`
435
+ "
436
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
437
+ `);
417
438
  expect(std.err).toMatchInlineSnapshot(`
418
- "Missing script name
439
+ "X [ERROR] Missing script name
419
440
 
420
- %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
441
+ "
421
442
  `);
422
443
  expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
423
444
  });
@@ -3,6 +3,7 @@ import { Headers, Request } from "undici";
3
3
  import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
4
4
  import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch";
5
5
  import { mockConsoleMethods } from "./helpers/mock-console";
6
+ import { useMockIsTTY } from "./helpers/mock-istty";
6
7
  import { runInTempDir } from "./helpers/run-in-tmp";
7
8
  import { runWrangler } from "./helpers/run-wrangler";
8
9
  import type { TailEventMessage, RequestEvent, ScheduledEvent } from "../tail";
@@ -134,7 +135,7 @@ describe("tail", () => {
134
135
 
135
136
  it("sends header filters without a query", async () => {
136
137
  const api = mockWebsocketAPIs();
137
- await runWrangler("tail test-worker --header X-CUSTOM-HEADER ");
138
+ await runWrangler("tail test-worker --header X-CUSTOM-HEADER");
138
139
  await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
139
140
  { header: { key: "X-CUSTOM-HEADER" } },
140
141
  ]);
@@ -142,9 +143,7 @@ describe("tail", () => {
142
143
 
143
144
  it("sends header filters with a query", async () => {
144
145
  const api = mockWebsocketAPIs();
145
- await runWrangler(
146
- "tail test-worker --header X-CUSTOM-HEADER:some-value "
147
- );
146
+ await runWrangler("tail test-worker --header X-CUSTOM-HEADER:some-value");
148
147
  await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
149
148
  { header: { key: "X-CUSTOM-HEADER", query: "some-value" } },
150
149
  ]);
@@ -218,6 +217,8 @@ describe("tail", () => {
218
217
  });
219
218
 
220
219
  describe("printing", () => {
220
+ const { setIsTTY } = useMockIsTTY();
221
+
221
222
  it("logs request messages in JSON format", async () => {
222
223
  const api = mockWebsocketAPIs();
223
224
  await runWrangler("tail test-worker --format json");
@@ -262,7 +263,7 @@ describe("tail", () => {
262
263
  "[mock expiration date]"
263
264
  )
264
265
  ).toMatchInlineSnapshot(`
265
- "successfully created tail, expires at [mock expiration date]
266
+ "Successfully created tail, expires at [mock expiration date]
266
267
  Connected to test-worker, waiting for logs...
267
268
  GET https://example.org/ - Ok @ [mock event timestamp]"
268
269
  `);
@@ -288,11 +289,131 @@ describe("tail", () => {
288
289
  "[mock expiration date]"
289
290
  )
290
291
  ).toMatchInlineSnapshot(`
291
- "successfully created tail, expires at [mock expiration date]
292
+ "Successfully created tail, expires at [mock expiration date]
292
293
  Connected to test-worker, waiting for logs...
293
294
  \\"* * * * *\\" @ [mock timestamp string] - Ok"
294
295
  `);
295
296
  });
297
+
298
+ it("should not crash when the tail message has a void event", async () => {
299
+ const api = mockWebsocketAPIs();
300
+ await runWrangler("tail test-worker --format pretty");
301
+
302
+ const message = generateMockEventMessage({ event: null });
303
+ const serializedMessage = serialize(message);
304
+
305
+ api.ws.send(serializedMessage);
306
+ expect(
307
+ std.out
308
+ .replace(
309
+ new Date(mockEventTimestamp).toLocaleString(),
310
+ "[mock timestamp string]"
311
+ )
312
+ .replace(
313
+ mockTailExpiration.toLocaleString(),
314
+ "[mock expiration date]"
315
+ )
316
+ ).toMatchInlineSnapshot(`
317
+ "Successfully created tail, expires at [mock expiration date]
318
+ Connected to test-worker, waiting for logs...
319
+ [missing request] - Ok @ [mock timestamp string]"
320
+ `);
321
+ });
322
+
323
+ it("defaults to logging in pretty format when the output is a TTY", async () => {
324
+ setIsTTY(true);
325
+ const api = mockWebsocketAPIs();
326
+ await runWrangler("tail test-worker");
327
+
328
+ const event = generateMockRequestEvent();
329
+ const message = generateMockEventMessage({ event });
330
+ const serializedMessage = serialize(message);
331
+
332
+ api.ws.send(serializedMessage);
333
+ expect(
334
+ std.out
335
+ .replace(
336
+ new Date(mockEventTimestamp).toLocaleString(),
337
+ "[mock event timestamp]"
338
+ )
339
+ .replace(
340
+ mockTailExpiration.toLocaleString(),
341
+ "[mock expiration date]"
342
+ )
343
+ ).toMatchInlineSnapshot(`
344
+ "Successfully created tail, expires at [mock expiration date]
345
+ Connected to test-worker, waiting for logs...
346
+ GET https://example.org/ - Ok @ [mock event timestamp]"
347
+ `);
348
+ });
349
+
350
+ it("defaults to logging in json format when the output is not a TTY", async () => {
351
+ setIsTTY(false);
352
+
353
+ const api = mockWebsocketAPIs();
354
+ await runWrangler("tail test-worker");
355
+
356
+ const event = generateMockRequestEvent();
357
+ const message = generateMockEventMessage({ event });
358
+ const serializedMessage = serialize(message);
359
+
360
+ api.ws.send(serializedMessage);
361
+ expect(std.out).toMatch(deserializeToJson(serializedMessage));
362
+ });
363
+
364
+ it("logs console messages and exceptions", async () => {
365
+ setIsTTY(true);
366
+ const api = mockWebsocketAPIs();
367
+ await runWrangler("tail test-worker");
368
+
369
+ const event = generateMockRequestEvent();
370
+ const message = generateMockEventMessage({
371
+ event,
372
+ logs: [
373
+ { message: ["some string"], level: "log", timestamp: 1234561 },
374
+ {
375
+ message: [{ complex: "object" }],
376
+ level: "log",
377
+ timestamp: 1234562,
378
+ },
379
+ { message: [1234], level: "error", timestamp: 1234563 },
380
+ ],
381
+ exceptions: [
382
+ { name: "Error", message: "some error", timestamp: 1234564 },
383
+ { name: "Error", message: { complex: "error" }, timestamp: 1234564 },
384
+ ],
385
+ });
386
+ const serializedMessage = serialize(message);
387
+
388
+ api.ws.send(serializedMessage);
389
+ expect(
390
+ std.out
391
+ .replace(
392
+ new Date(mockEventTimestamp).toLocaleString(),
393
+ "[mock event timestamp]"
394
+ )
395
+ .replace(
396
+ mockTailExpiration.toLocaleString(),
397
+ "[mock expiration date]"
398
+ )
399
+ ).toMatchInlineSnapshot(`
400
+ "Successfully created tail, expires at [mock expiration date]
401
+ Connected to test-worker, waiting for logs...
402
+ GET https://example.org/ - Ok @ [mock event timestamp]
403
+ (log) some string
404
+ (log) { complex: 'object' }
405
+ (error) 1234"
406
+ `);
407
+ expect(std.err).toMatchInlineSnapshot(`
408
+ "X [ERROR]  Error: some error
409
+
410
+
411
+ X [ERROR]  Error: { complex: 'error' }
412
+
413
+ "
414
+ `);
415
+ expect(std.warn).toMatchInlineSnapshot(`""`);
416
+ });
296
417
  });
297
418
  });
298
419
 
@@ -318,7 +439,8 @@ function serialize(message: TailEventMessage): WebSocket.RawData {
318
439
  // This isn't a problem outside of testing since deserialization
319
440
  // works just fine and wrangler never _sends_ any event messages,
320
441
  // it only receives them.
321
- const request = (message.event as RequestEvent).request;
442
+ const request = ((message.event as RequestEvent | undefined | null) || {})
443
+ .request;
322
444
  const stringified = JSON.stringify(message, (key, value) => {
323
445
  if (key !== "request") {
324
446
  return value;
@@ -326,9 +448,9 @@ function serialize(message: TailEventMessage): WebSocket.RawData {
326
448
 
327
449
  return {
328
450
  ...request,
329
- url: request.url,
330
- headers: request.headers,
331
- method: request.method,
451
+ url: request?.url,
452
+ headers: request?.headers,
453
+ method: request?.method,
332
454
  };
333
455
  });
334
456
 
@@ -343,9 +465,9 @@ function serialize(message: TailEventMessage): WebSocket.RawData {
343
465
  * @returns whether event is a ScheduledEvent (true) or a RequestEvent
344
466
  */
345
467
  function isScheduled(
346
- event: ScheduledEvent | RequestEvent
468
+ event: ScheduledEvent | RequestEvent | undefined | null
347
469
  ): event is ScheduledEvent {
348
- return "cron" in event;
470
+ return Boolean(event && "cron" in event);
349
471
  }
350
472
 
351
473
  /**
@@ -511,15 +633,19 @@ function mockWebsocketAPIs(env?: string, legacyEnv = false): MockAPI {
511
633
  * @param opts Any specific parts of the message to use instead of defaults
512
634
  * @returns a `TailEventMessage` that wrangler can process and display
513
635
  */
514
- function generateMockEventMessage(
515
- opts?: Partial<TailEventMessage>
516
- ): TailEventMessage {
636
+ function generateMockEventMessage({
637
+ outcome = "ok",
638
+ exceptions = [],
639
+ logs = [],
640
+ eventTimestamp = mockEventTimestamp,
641
+ event = generateMockRequestEvent(),
642
+ }: Partial<TailEventMessage>): TailEventMessage {
517
643
  return {
518
- outcome: opts?.outcome || "ok",
519
- exceptions: opts?.exceptions || [],
520
- logs: opts?.logs || [],
521
- eventTimestamp: opts?.eventTimestamp || mockEventTimestamp,
522
- event: opts?.event || generateMockRequestEvent(),
644
+ outcome,
645
+ exceptions,
646
+ logs,
647
+ eventTimestamp,
648
+ event,
523
649
  };
524
650
  }
525
651
 
@@ -0,0 +1,131 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import fetchMock from "jest-fetch-mock";
5
+ import {
6
+ readAuthConfigFile,
7
+ requireAuth,
8
+ USER_AUTH_CONFIG_FILE,
9
+ writeAuthConfigFile,
10
+ } from "../user";
11
+ import { mockConsoleMethods } from "./helpers/mock-console";
12
+ import { useMockIsTTY } from "./helpers/mock-istty";
13
+ import { mockOAuthFlow } from "./helpers/mock-oauth-flow";
14
+ import { runInTempDir } from "./helpers/run-in-tmp";
15
+ import { runWrangler } from "./helpers/run-wrangler";
16
+ import type { Config } from "../config";
17
+ import type { UserAuthConfig } from "../user";
18
+
19
+ describe("User", () => {
20
+ runInTempDir({ homedir: "./home" });
21
+ const std = mockConsoleMethods();
22
+ const {
23
+ mockOAuthServerCallback,
24
+ mockGrantAccessToken,
25
+ mockGrantAuthorization,
26
+ mockRevokeAuthorization,
27
+ mockExchangeRefreshTokenForAccessToken,
28
+ } = mockOAuthFlow();
29
+
30
+ const { setIsTTY } = useMockIsTTY();
31
+
32
+ describe("login", () => {
33
+ it("should login a user when `wrangler login` is run", async () => {
34
+ mockOAuthServerCallback();
35
+ const accessTokenRequest = mockGrantAccessToken({ respondWith: "ok" });
36
+ mockGrantAuthorization({ respondWith: "success" });
37
+
38
+ await runWrangler("login");
39
+
40
+ expect(accessTokenRequest.actual.url).toEqual(
41
+ accessTokenRequest.expected.url
42
+ );
43
+ expect(accessTokenRequest.actual.method).toEqual(
44
+ accessTokenRequest.expected.method
45
+ );
46
+
47
+ expect(std.out).toMatchInlineSnapshot(`
48
+ "Attempting to login via OAuth...
49
+ Successfully logged in."
50
+ `);
51
+
52
+ expect(readAuthConfigFile()).toEqual<UserAuthConfig>({
53
+ api_token: undefined,
54
+ oauth_token: "test-access-token",
55
+ refresh_token: "test-refresh-token",
56
+ expiration_time: expect.any(String),
57
+ });
58
+ });
59
+ });
60
+
61
+ describe("logout", () => {
62
+ it("should exit with a message stating the user is not logged in", async () => {
63
+ await runWrangler("logout");
64
+ expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
65
+ });
66
+
67
+ it("should logout user that has been properly logged in", async () => {
68
+ writeAuthConfigFile({
69
+ oauth_token: "some-oauth-tok",
70
+ refresh_token: "some-refresh-tok",
71
+ });
72
+ const outcome = mockRevokeAuthorization();
73
+
74
+ await runWrangler("logout");
75
+
76
+ expect(outcome.actual.url).toEqual(
77
+ "https://dash.cloudflare.com/oauth2/revoke"
78
+ );
79
+ expect(outcome.actual.method).toEqual("POST");
80
+
81
+ expect(std.out).toMatchInlineSnapshot(`"Successfully logged out."`);
82
+
83
+ // Make sure that we made the request to logout.
84
+ expect(fetchMock).toHaveBeenCalledTimes(1);
85
+
86
+ // Make sure that logout removed the config file containing the auth tokens.
87
+ const config = path.join(os.homedir(), USER_AUTH_CONFIG_FILE);
88
+ expect(fs.existsSync(config)).toBeFalsy();
89
+ });
90
+ });
91
+
92
+ // TODO: Improve OAuth mocking to handle `/token` endpoints from different calls
93
+ it("should handle errors for failed token refresh", async () => {
94
+ setIsTTY(false);
95
+ mockOAuthServerCallback();
96
+ writeAuthConfigFile({
97
+ oauth_token: "hunter2",
98
+ refresh_token: "Order 66",
99
+ });
100
+ mockGrantAuthorization({ respondWith: "success" });
101
+
102
+ mockExchangeRefreshTokenForAccessToken({
103
+ respondWith: "badResponse",
104
+ });
105
+
106
+ // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
107
+ await expect(
108
+ requireAuth({} as Config)
109
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
110
+ `"Did not login, quitting..."`
111
+ );
112
+ });
113
+
114
+ it("should confirm no error message when refresh is successful", async () => {
115
+ setIsTTY(false);
116
+ mockOAuthServerCallback();
117
+ writeAuthConfigFile({
118
+ oauth_token: "hunter2",
119
+ refresh_token: "Order 66",
120
+ });
121
+ mockGrantAuthorization({ respondWith: "success" });
122
+
123
+ mockExchangeRefreshTokenForAccessToken({
124
+ respondWith: "refreshSuccess",
125
+ });
126
+
127
+ // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
128
+ await expect(requireAuth({} as Config)).rejects.toThrowError();
129
+ expect(std.err).toContain("");
130
+ });
131
+ });