wrangler 0.0.0-e2b7352 → 0.0.0-e2f9bb2

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 (86) hide show
  1. package/README.md +24 -13
  2. package/bin/wrangler.js +3 -0
  3. package/miniflare-dist/index.mjs +4828 -21
  4. package/package.json +29 -22
  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 +386 -81
  14. package/src/__tests__/dev.test.tsx +242 -21
  15. package/src/__tests__/guess-worker-format.test.ts +18 -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 +24 -0
  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 +25 -759
  26. package/src/__tests__/init.test.ts +1042 -0
  27. package/src/__tests__/jest.setup.ts +4 -4
  28. package/src/__tests__/kv.test.ts +130 -56
  29. package/src/__tests__/logger.test.ts +115 -0
  30. package/src/__tests__/pages.test.ts +290 -43
  31. package/src/__tests__/publish.test.ts +1699 -333
  32. package/src/__tests__/r2.test.ts +24 -8
  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 +97 -45
  36. package/src/__tests__/user.test.ts +131 -0
  37. package/src/__tests__/whoami.test.tsx +14 -9
  38. package/src/bundle.ts +15 -1
  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 +26 -3
  44. package/src/config/index.ts +2 -1
  45. package/src/config/validation-helpers.ts +26 -5
  46. package/src/config/validation.ts +233 -41
  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 +60 -34
  52. package/src/dev/local.tsx +101 -21
  53. package/src/dev/remote.tsx +23 -13
  54. package/src/dev/use-esbuild.ts +19 -5
  55. package/src/dialogs.tsx +16 -6
  56. package/src/entry.ts +38 -11
  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 +529 -303
  61. package/src/inspect.ts +17 -11
  62. package/src/logger.ts +66 -0
  63. package/src/miniflare-cli/index.ts +4 -0
  64. package/src/miniflare-cli/request-context.ts +40 -0
  65. package/src/module-collection.ts +7 -7
  66. package/src/open-in-browser.ts +5 -4
  67. package/src/package-manager.ts +9 -8
  68. package/src/pages.tsx +860 -55
  69. package/src/parse.ts +1 -1
  70. package/src/proxy.ts +25 -11
  71. package/src/publish.ts +260 -141
  72. package/src/sites.tsx +27 -14
  73. package/src/tail/index.ts +1 -1
  74. package/src/tail/printing.ts +13 -8
  75. package/src/update-check.ts +19 -0
  76. package/src/user.tsx +104 -38
  77. package/src/whoami.tsx +2 -1
  78. package/src/worker.ts +15 -6
  79. package/templates/gitignore +171 -0
  80. package/templates/static-asset-facade.js +1 -1
  81. package/wrangler-dist/cli.js +20948 -50169
  82. package/miniflare-dist/index.mjs.map +0 -7
  83. package/src/__tests__/logout.test.ts +0 -52
  84. package/src/__tests__/sentry.test.ts +0 -146
  85. package/src/reporting.ts +0 -131
  86. 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
 
@@ -92,7 +96,10 @@ describe("wrangler", () => {
92
96
  ).rejects.toThrowErrorMatchingInlineSnapshot(
93
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
- Unknown 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
 
@@ -168,7 +180,10 @@ describe("wrangler", () => {
168
180
  ).rejects.toThrowErrorMatchingInlineSnapshot(
169
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
- Unknown 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";
@@ -216,6 +217,8 @@ describe("tail", () => {
216
217
  });
217
218
 
218
219
  describe("printing", () => {
220
+ const { setIsTTY } = useMockIsTTY();
221
+
219
222
  it("logs request messages in JSON format", async () => {
220
223
  const api = mockWebsocketAPIs();
221
224
  await runWrangler("tail test-worker --format json");
@@ -260,14 +263,65 @@ describe("tail", () => {
260
263
  "[mock expiration date]"
261
264
  )
262
265
  ).toMatchInlineSnapshot(`
263
- "successfully created tail, expires at [mock expiration date]
266
+ "Successfully created tail, expires at [mock expiration date]
264
267
  Connected to test-worker, waiting for logs...
265
268
  GET https://example.org/ - Ok @ [mock event timestamp]"
266
269
  `);
267
270
  });
268
271
 
269
- it("defaults to logging in pretty format", async () => {
270
- // the same test as the one before, but without the --format flag
272
+ it("logs scheduled messages in pretty format", async () => {
273
+ const api = mockWebsocketAPIs();
274
+ await runWrangler("tail test-worker --format pretty");
275
+
276
+ const event = generateMockScheduledEvent();
277
+ const message = generateMockEventMessage({ event });
278
+ const serializedMessage = serialize(message);
279
+
280
+ api.ws.send(serializedMessage);
281
+ expect(
282
+ std.out
283
+ .replace(
284
+ new Date(mockEventTimestamp).toLocaleString(),
285
+ "[mock timestamp string]"
286
+ )
287
+ .replace(
288
+ mockTailExpiration.toLocaleString(),
289
+ "[mock expiration date]"
290
+ )
291
+ ).toMatchInlineSnapshot(`
292
+ "Successfully created tail, expires at [mock expiration date]
293
+ Connected to test-worker, waiting for logs...
294
+ \\"* * * * *\\" @ [mock timestamp string] - Ok"
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);
271
325
  const api = mockWebsocketAPIs();
272
326
  await runWrangler("tail test-worker");
273
327
 
@@ -287,13 +341,28 @@ describe("tail", () => {
287
341
  "[mock expiration date]"
288
342
  )
289
343
  ).toMatchInlineSnapshot(`
290
- "successfully created tail, expires at [mock expiration date]
344
+ "Successfully created tail, expires at [mock expiration date]
291
345
  Connected to test-worker, waiting for logs...
292
346
  GET https://example.org/ - Ok @ [mock event timestamp]"
293
347
  `);
294
348
  });
295
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
+
296
364
  it("logs console messages and exceptions", async () => {
365
+ setIsTTY(true);
297
366
  const api = mockWebsocketAPIs();
298
367
  await runWrangler("tail test-worker");
299
368
 
@@ -328,7 +397,7 @@ describe("tail", () => {
328
397
  "[mock expiration date]"
329
398
  )
330
399
  ).toMatchInlineSnapshot(`
331
- "successfully created tail, expires at [mock expiration date]
400
+ "Successfully created tail, expires at [mock expiration date]
332
401
  Connected to test-worker, waiting for logs...
333
402
  GET https://example.org/ - Ok @ [mock event timestamp]
334
403
  (log) some string
@@ -336,36 +405,14 @@ describe("tail", () => {
336
405
  (error) 1234"
337
406
  `);
338
407
  expect(std.err).toMatchInlineSnapshot(`
339
- " Error: some error
340
- Error: { complex: 'error' }"
341
- `);
342
- expect(std.warn).toMatchInlineSnapshot(`""`);
343
- });
408
+ "X [ERROR]  Error: some error
344
409
 
345
- it("logs scheduled messages in pretty format", async () => {
346
- const api = mockWebsocketAPIs();
347
- await runWrangler("tail test-worker --format pretty");
348
410
 
349
- const event = generateMockScheduledEvent();
350
- const message = generateMockEventMessage({ event });
351
- const serializedMessage = serialize(message);
411
+ X [ERROR]  Error: { complex: 'error' }
352
412
 
353
- api.ws.send(serializedMessage);
354
- expect(
355
- std.out
356
- .replace(
357
- new Date(mockEventTimestamp).toLocaleString(),
358
- "[mock timestamp string]"
359
- )
360
- .replace(
361
- mockTailExpiration.toLocaleString(),
362
- "[mock expiration date]"
363
- )
364
- ).toMatchInlineSnapshot(`
365
- "successfully created tail, expires at [mock expiration date]
366
- Connected to test-worker, waiting for logs...
367
- \\"* * * * *\\" @ [mock timestamp string] - Ok"
413
+ "
368
414
  `);
415
+ expect(std.warn).toMatchInlineSnapshot(`""`);
369
416
  });
370
417
  });
371
418
  });
@@ -392,7 +439,8 @@ function serialize(message: TailEventMessage): WebSocket.RawData {
392
439
  // This isn't a problem outside of testing since deserialization
393
440
  // works just fine and wrangler never _sends_ any event messages,
394
441
  // it only receives them.
395
- const request = (message.event as RequestEvent).request;
442
+ const request = ((message.event as RequestEvent | undefined | null) || {})
443
+ .request;
396
444
  const stringified = JSON.stringify(message, (key, value) => {
397
445
  if (key !== "request") {
398
446
  return value;
@@ -400,9 +448,9 @@ function serialize(message: TailEventMessage): WebSocket.RawData {
400
448
 
401
449
  return {
402
450
  ...request,
403
- url: request.url,
404
- headers: request.headers,
405
- method: request.method,
451
+ url: request?.url,
452
+ headers: request?.headers,
453
+ method: request?.method,
406
454
  };
407
455
  });
408
456
 
@@ -417,9 +465,9 @@ function serialize(message: TailEventMessage): WebSocket.RawData {
417
465
  * @returns whether event is a ScheduledEvent (true) or a RequestEvent
418
466
  */
419
467
  function isScheduled(
420
- event: ScheduledEvent | RequestEvent
468
+ event: ScheduledEvent | RequestEvent | undefined | null
421
469
  ): event is ScheduledEvent {
422
- return "cron" in event;
470
+ return Boolean(event && "cron" in event);
423
471
  }
424
472
 
425
473
  /**
@@ -585,15 +633,19 @@ function mockWebsocketAPIs(env?: string, legacyEnv = false): MockAPI {
585
633
  * @param opts Any specific parts of the message to use instead of defaults
586
634
  * @returns a `TailEventMessage` that wrangler can process and display
587
635
  */
588
- function generateMockEventMessage(
589
- opts?: Partial<TailEventMessage>
590
- ): TailEventMessage {
636
+ function generateMockEventMessage({
637
+ outcome = "ok",
638
+ exceptions = [],
639
+ logs = [],
640
+ eventTimestamp = mockEventTimestamp,
641
+ event = generateMockRequestEvent(),
642
+ }: Partial<TailEventMessage>): TailEventMessage {
591
643
  return {
592
- outcome: opts?.outcome || "ok",
593
- exceptions: opts?.exceptions || [],
594
- logs: opts?.logs || [],
595
- eventTimestamp: opts?.eventTimestamp || mockEventTimestamp,
596
- event: opts?.event || generateMockRequestEvent(),
644
+ outcome,
645
+ exceptions,
646
+ logs,
647
+ eventTimestamp,
648
+ event,
597
649
  };
598
650
  }
599
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
+ });