wrangler 0.0.0-ece06ea → 0.0.0-ed4f2ef

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 (109) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +12 -3
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +49 -22
  6. package/pages/functions/buildWorker.ts +62 -0
  7. package/pages/functions/filepath-routing.test.ts +223 -0
  8. package/pages/functions/filepath-routing.ts +181 -0
  9. package/pages/functions/identifiers.ts +78 -0
  10. package/pages/functions/routes.ts +151 -0
  11. package/pages/functions/template-worker.ts +130 -0
  12. package/src/__tests__/configuration.test.ts +2874 -0
  13. package/src/__tests__/dev.test.tsx +588 -0
  14. package/src/__tests__/guess-worker-format.test.ts +83 -0
  15. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  16. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  17. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  18. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  19. package/src/__tests__/helpers/mock-bin.ts +36 -0
  20. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  21. package/src/__tests__/helpers/mock-console.ts +70 -0
  22. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  23. package/src/__tests__/helpers/mock-kv.ts +33 -0
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +178 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +127 -0
  31. package/src/__tests__/index.test.ts +953 -119
  32. package/src/__tests__/jest.setup.ts +74 -0
  33. package/src/__tests__/kv.test.ts +1380 -0
  34. package/src/__tests__/package-manager.test.ts +206 -0
  35. package/src/__tests__/pages.test.ts +180 -0
  36. package/src/__tests__/parse.test.ts +322 -0
  37. package/src/__tests__/publish.test.ts +3946 -0
  38. package/src/__tests__/r2.test.ts +198 -0
  39. package/src/__tests__/route.test.ts +45 -0
  40. package/src/__tests__/secret.test.ts +425 -0
  41. package/src/__tests__/sentry.test.ts +146 -0
  42. package/src/__tests__/tail.test.ts +638 -0
  43. package/src/__tests__/user.test.ts +83 -0
  44. package/src/__tests__/whoami.test.tsx +95 -0
  45. package/src/bundle.ts +155 -0
  46. package/src/cfetch/index.ts +104 -0
  47. package/src/cfetch/internal.ts +139 -0
  48. package/src/cli.ts +18 -7
  49. package/src/config/README.md +107 -0
  50. package/src/config/config.ts +229 -0
  51. package/src/config/diagnostics.ts +80 -0
  52. package/src/config/environment.ts +371 -0
  53. package/src/config/index.ts +62 -0
  54. package/src/config/validation-helpers.ts +557 -0
  55. package/src/config/validation.ts +1240 -0
  56. package/src/create-worker-preview.ts +173 -0
  57. package/src/create-worker-upload-form.ts +240 -0
  58. package/src/dev/dev.tsx +413 -0
  59. package/src/dev/local.tsx +287 -0
  60. package/src/dev/remote.tsx +209 -0
  61. package/src/dev/use-esbuild.ts +109 -0
  62. package/src/dialogs.tsx +6 -14
  63. package/src/entry.ts +256 -0
  64. package/src/environment-variables.ts +33 -0
  65. package/src/errors.ts +11 -0
  66. package/src/https-options.ts +122 -0
  67. package/src/index.tsx +1503 -959
  68. package/src/inspect.ts +624 -0
  69. package/src/intl-polyfill.d.ts +139 -0
  70. package/src/kv.ts +319 -0
  71. package/src/miniflare-cli/README.md +30 -0
  72. package/src/miniflare-cli/enum-keys.ts +17 -0
  73. package/src/miniflare-cli/index.ts +38 -0
  74. package/src/module-collection.ts +257 -0
  75. package/src/open-in-browser.ts +25 -0
  76. package/src/package-manager.ts +126 -0
  77. package/src/pages.tsx +1074 -212
  78. package/src/parse.ts +183 -0
  79. package/src/paths.ts +26 -0
  80. package/src/proxy.ts +455 -0
  81. package/src/publish.ts +326 -295
  82. package/src/r2.ts +50 -0
  83. package/src/reporting.ts +131 -0
  84. package/src/selfsigned.d.ts +29 -0
  85. package/src/sites.tsx +224 -59
  86. package/src/tail/filters.ts +279 -0
  87. package/src/tail/index.ts +299 -0
  88. package/src/tail/printing.ts +62 -0
  89. package/src/user.tsx +340 -203
  90. package/src/whoami.tsx +69 -0
  91. package/src/worker.ts +172 -0
  92. package/templates/new-worker.js +15 -0
  93. package/templates/new-worker.ts +15 -0
  94. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  95. package/templates/tsconfig.json +105 -0
  96. package/wrangler-dist/cli.js +136988 -131174
  97. package/wrangler-dist/cli.js.map +3 -3
  98. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  99. package/src/__tests__/mock-cfetch.js +0 -46
  100. package/src/api/form_data.ts +0 -158
  101. package/src/api/inspect.ts +0 -441
  102. package/src/api/preview.ts +0 -123
  103. package/src/api/worker.ts +0 -161
  104. package/src/cfetch.ts +0 -72
  105. package/src/config.ts +0 -124
  106. package/src/dev.tsx +0 -736
  107. package/src/kv.tsx +0 -211
  108. package/src/tail.tsx +0 -71
  109. package/src/util/fetch.ts +0 -74
@@ -0,0 +1,638 @@
1
+ import MockWebSocket from "jest-websocket-mock";
2
+ import { Headers, Request } from "undici";
3
+ import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
4
+ import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch";
5
+ import { mockConsoleMethods } from "./helpers/mock-console";
6
+ import { runInTempDir } from "./helpers/run-in-tmp";
7
+ import { runWrangler } from "./helpers/run-wrangler";
8
+ import type { TailEventMessage, RequestEvent, ScheduledEvent } from "../tail";
9
+ import type WebSocket from "ws";
10
+
11
+ describe("tail", () => {
12
+ runInTempDir();
13
+ mockAccountId();
14
+ mockApiToken();
15
+
16
+ const std = mockConsoleMethods();
17
+
18
+ afterEach(() => {
19
+ mockWebSockets.forEach((ws) => ws.close());
20
+ mockWebSockets.splice(0);
21
+ unsetAllMocks();
22
+ });
23
+
24
+ /**
25
+ * Interaction with the tailing API, including tail creation,
26
+ * deletion, and connection.
27
+ */
28
+ describe("API interaction", () => {
29
+ it("creates and then delete tails", async () => {
30
+ const api = mockWebsocketAPIs();
31
+ expect(api.requests.creation.count).toStrictEqual(0);
32
+
33
+ await runWrangler("tail test-worker");
34
+
35
+ await expect(api.ws.connected).resolves.toBeTruthy();
36
+ expect(api.requests.creation.count).toStrictEqual(1);
37
+ expect(api.requests.deletion.count).toStrictEqual(0);
38
+
39
+ api.ws.close();
40
+ expect(api.requests.deletion.count).toStrictEqual(1);
41
+ });
42
+
43
+ it("creates and then delete tails: legacy envs", async () => {
44
+ const api = mockWebsocketAPIs("some-env", true);
45
+ expect(api.requests.creation.count).toStrictEqual(0);
46
+
47
+ await runWrangler("tail test-worker --env some-env --legacy-env true");
48
+
49
+ await expect(api.ws.connected).resolves.toBeTruthy();
50
+ expect(api.requests.creation.count).toStrictEqual(1);
51
+ expect(api.requests.deletion.count).toStrictEqual(0);
52
+
53
+ api.ws.close();
54
+ expect(api.requests.deletion.count).toStrictEqual(1);
55
+ });
56
+
57
+ it("creates and then delete tails: service envs", async () => {
58
+ const api = mockWebsocketAPIs("some-env");
59
+ expect(api.requests.creation.count).toStrictEqual(0);
60
+
61
+ await runWrangler("tail test-worker --env some-env --legacy-env false");
62
+
63
+ await expect(api.ws.connected).resolves.toBeTruthy();
64
+ expect(api.requests.creation.count).toStrictEqual(1);
65
+ expect(api.requests.deletion.count).toStrictEqual(0);
66
+
67
+ api.ws.close();
68
+ expect(api.requests.deletion.count).toStrictEqual(1);
69
+ });
70
+
71
+ it("errors when the websocket closes unexpectedly", async () => {
72
+ const api = mockWebsocketAPIs();
73
+ api.ws.close();
74
+
75
+ await expect(runWrangler("tail test-worker")).rejects.toThrow();
76
+ });
77
+
78
+ it("activates debug mode when the cli arg is passed in", async () => {
79
+ const api = mockWebsocketAPIs();
80
+ await runWrangler("tail test-worker --debug");
81
+ await expect(api.nextMessageJson()).resolves.toHaveProperty(
82
+ "debug",
83
+ true
84
+ );
85
+ });
86
+ });
87
+
88
+ describe("filtering", () => {
89
+ it("sends sampling rate filters", async () => {
90
+ const api = mockWebsocketAPIs();
91
+ const tooHigh = runWrangler("tail test-worker --sampling-rate 10");
92
+ await expect(tooHigh).rejects.toThrow();
93
+
94
+ const tooLow = runWrangler("tail test-worker --sampling-rate -5");
95
+ await expect(tooLow).rejects.toThrow();
96
+
97
+ await runWrangler("tail test-worker --sampling-rate 0.25");
98
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
99
+ { sampling_rate: 0.25 },
100
+ ]);
101
+ });
102
+
103
+ it("sends single status filters", async () => {
104
+ const api = mockWebsocketAPIs();
105
+ await runWrangler("tail test-worker --status error");
106
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
107
+ { outcome: ["exception", "exceededCpu", "unknown"] },
108
+ ]);
109
+ });
110
+
111
+ it("sends multiple status filters", async () => {
112
+ const api = mockWebsocketAPIs();
113
+ await runWrangler("tail test-worker --status error --status canceled");
114
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
115
+ { outcome: ["exception", "exceededCpu", "unknown", "canceled"] },
116
+ ]);
117
+ });
118
+
119
+ it("sends single HTTP method filters", async () => {
120
+ const api = mockWebsocketAPIs();
121
+ await runWrangler("tail test-worker --method POST");
122
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
123
+ { method: ["POST"] },
124
+ ]);
125
+ });
126
+
127
+ it("sends multiple HTTP method filters", async () => {
128
+ const api = mockWebsocketAPIs();
129
+ await runWrangler("tail test-worker --method POST --method GET");
130
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
131
+ { method: ["POST", "GET"] },
132
+ ]);
133
+ });
134
+
135
+ it("sends header filters without a query", async () => {
136
+ const api = mockWebsocketAPIs();
137
+ await runWrangler("tail test-worker --header X-CUSTOM-HEADER");
138
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
139
+ { header: { key: "X-CUSTOM-HEADER" } },
140
+ ]);
141
+ });
142
+
143
+ it("sends header filters with a query", async () => {
144
+ const api = mockWebsocketAPIs();
145
+ await runWrangler("tail test-worker --header X-CUSTOM-HEADER:some-value");
146
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
147
+ { header: { key: "X-CUSTOM-HEADER", query: "some-value" } },
148
+ ]);
149
+ });
150
+
151
+ it("sends single IP filters", async () => {
152
+ const api = mockWebsocketAPIs();
153
+ const fakeIp = "192.0.2.1";
154
+
155
+ await runWrangler(`tail test-worker --ip ${fakeIp}`);
156
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
157
+ { client_ip: [fakeIp] },
158
+ ]);
159
+ });
160
+
161
+ it("sends multiple IP filters", async () => {
162
+ const api = mockWebsocketAPIs();
163
+ const fakeIp = "192.0.2.1";
164
+
165
+ await runWrangler(`tail test-worker --ip ${fakeIp} --ip self`);
166
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
167
+ { client_ip: [fakeIp, "self"] },
168
+ ]);
169
+ });
170
+
171
+ it("sends search filters", async () => {
172
+ const api = mockWebsocketAPIs();
173
+ const search = "filterMe";
174
+
175
+ await runWrangler(`tail test-worker --search ${search}`);
176
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
177
+ { query: search },
178
+ ]);
179
+ });
180
+
181
+ it("sends everything but the kitchen sink", async () => {
182
+ const api = mockWebsocketAPIs();
183
+ const sampling_rate = 0.69;
184
+ const status = ["ok", "error"];
185
+ const method = ["GET", "POST", "PUT"];
186
+ const header = "X-HELLO:world";
187
+ const client_ip = ["192.0.2.1", "self"];
188
+ const query = "onlyTheseMessagesPlease";
189
+
190
+ const cliFilters =
191
+ `--sampling-rate ${sampling_rate} ` +
192
+ status.map((s) => `--status ${s} `).join("") +
193
+ method.map((m) => `--method ${m} `).join("") +
194
+ `--header ${header} ` +
195
+ client_ip.map((c) => `--ip ${c} `).join("") +
196
+ `--search ${query} ` +
197
+ `--debug`;
198
+
199
+ const expectedWebsocketMessage = {
200
+ filters: [
201
+ { sampling_rate },
202
+ { outcome: ["ok", "exception", "exceededCpu", "unknown"] },
203
+ { method },
204
+ { header: { key: "X-HELLO", query: "world" } },
205
+ { client_ip },
206
+ { query },
207
+ ],
208
+ debug: true,
209
+ };
210
+
211
+ await runWrangler(`tail test-worker ${cliFilters}`);
212
+ await expect(api.nextMessageJson()).resolves.toEqual(
213
+ expectedWebsocketMessage
214
+ );
215
+ });
216
+ });
217
+
218
+ describe("printing", () => {
219
+ it("logs request messages in JSON format", async () => {
220
+ const api = mockWebsocketAPIs();
221
+ await runWrangler("tail test-worker --format json");
222
+
223
+ const event = generateMockRequestEvent();
224
+ const message = generateMockEventMessage({ event });
225
+ const serializedMessage = serialize(message);
226
+
227
+ api.ws.send(serializedMessage);
228
+ expect(std.out).toMatch(deserializeToJson(serializedMessage));
229
+ });
230
+
231
+ it("logs scheduled messages in JSON format", async () => {
232
+ const api = mockWebsocketAPIs();
233
+ await runWrangler("tail test-worker --format json");
234
+
235
+ const event = generateMockScheduledEvent();
236
+ const message = generateMockEventMessage({ event });
237
+ const serializedMessage = serialize(message);
238
+
239
+ api.ws.send(serializedMessage);
240
+ expect(std.out).toMatch(deserializeToJson(serializedMessage));
241
+ });
242
+
243
+ it("logs request messages in pretty format", async () => {
244
+ const api = mockWebsocketAPIs();
245
+ await runWrangler("tail test-worker --format pretty");
246
+
247
+ const event = generateMockRequestEvent();
248
+ const message = generateMockEventMessage({ event });
249
+ const serializedMessage = serialize(message);
250
+
251
+ api.ws.send(serializedMessage);
252
+ expect(
253
+ std.out
254
+ .replace(
255
+ new Date(mockEventTimestamp).toLocaleString(),
256
+ "[mock event timestamp]"
257
+ )
258
+ .replace(
259
+ mockTailExpiration.toLocaleString(),
260
+ "[mock expiration date]"
261
+ )
262
+ ).toMatchInlineSnapshot(`
263
+ "successfully created tail, expires at [mock expiration date]
264
+ Connected to test-worker, waiting for logs...
265
+ GET https://example.org/ - Ok @ [mock event timestamp]"
266
+ `);
267
+ });
268
+
269
+ it("defaults to logging in pretty format", async () => {
270
+ // the same test as the one before, but without the --format flag
271
+ const api = mockWebsocketAPIs();
272
+ await runWrangler("tail test-worker");
273
+
274
+ const event = generateMockRequestEvent();
275
+ const message = generateMockEventMessage({ event });
276
+ const serializedMessage = serialize(message);
277
+
278
+ api.ws.send(serializedMessage);
279
+ expect(
280
+ std.out
281
+ .replace(
282
+ new Date(mockEventTimestamp).toLocaleString(),
283
+ "[mock event timestamp]"
284
+ )
285
+ .replace(
286
+ mockTailExpiration.toLocaleString(),
287
+ "[mock expiration date]"
288
+ )
289
+ ).toMatchInlineSnapshot(`
290
+ "successfully created tail, expires at [mock expiration date]
291
+ Connected to test-worker, waiting for logs...
292
+ GET https://example.org/ - Ok @ [mock event timestamp]"
293
+ `);
294
+ });
295
+
296
+ it("logs console messages and exceptions", async () => {
297
+ const api = mockWebsocketAPIs();
298
+ await runWrangler("tail test-worker");
299
+
300
+ const event = generateMockRequestEvent();
301
+ const message = generateMockEventMessage({
302
+ event,
303
+ logs: [
304
+ { message: ["some string"], level: "log", timestamp: 1234561 },
305
+ {
306
+ message: [{ complex: "object" }],
307
+ level: "log",
308
+ timestamp: 1234562,
309
+ },
310
+ { message: [1234], level: "error", timestamp: 1234563 },
311
+ ],
312
+ exceptions: [
313
+ { name: "Error", message: "some error", timestamp: 1234564 },
314
+ { name: "Error", message: { complex: "error" }, timestamp: 1234564 },
315
+ ],
316
+ });
317
+ const serializedMessage = serialize(message);
318
+
319
+ api.ws.send(serializedMessage);
320
+ expect(
321
+ std.out
322
+ .replace(
323
+ new Date(mockEventTimestamp).toLocaleString(),
324
+ "[mock event timestamp]"
325
+ )
326
+ .replace(
327
+ mockTailExpiration.toLocaleString(),
328
+ "[mock expiration date]"
329
+ )
330
+ ).toMatchInlineSnapshot(`
331
+ "successfully created tail, expires at [mock expiration date]
332
+ Connected to test-worker, waiting for logs...
333
+ GET https://example.org/ - Ok @ [mock event timestamp]
334
+ (log) some string
335
+ (log) { complex: 'object' }
336
+ (error) 1234"
337
+ `);
338
+ expect(std.err).toMatchInlineSnapshot(`
339
+ " Error: some error
340
+ Error: { complex: 'error' }"
341
+ `);
342
+ expect(std.warn).toMatchInlineSnapshot(`""`);
343
+ });
344
+
345
+ it("logs scheduled messages in pretty format", async () => {
346
+ const api = mockWebsocketAPIs();
347
+ await runWrangler("tail test-worker --format pretty");
348
+
349
+ const event = generateMockScheduledEvent();
350
+ const message = generateMockEventMessage({ event });
351
+ const serializedMessage = serialize(message);
352
+
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"
368
+ `);
369
+ });
370
+ });
371
+ });
372
+
373
+ /* helpers */
374
+
375
+ /**
376
+ * The built in serialize-to-JSON feature of our mock websocket doesn't work
377
+ * for our use-case since we actually expect a raw buffer,
378
+ * not a Javascript string. Additionally, we have to do some fiddling
379
+ * with `RequestEvent`s to get them to serialize properly.
380
+ *
381
+ * @param message a message to serialize to JSON
382
+ * @returns the same type we expect when deserializing in wrangler
383
+ */
384
+ function serialize(message: TailEventMessage): WebSocket.RawData {
385
+ if (isScheduled(message.event)) {
386
+ // `ScheduledEvent`s work just fine
387
+ const stringified = JSON.stringify(message);
388
+ return Buffer.from(stringified, "utf-8");
389
+ } else {
390
+ // Since the "properties" of an `undici.Request` are actually getters,
391
+ // which don't serialize properly, we need to hydrate them manually.
392
+ // This isn't a problem outside of testing since deserialization
393
+ // works just fine and wrangler never _sends_ any event messages,
394
+ // it only receives them.
395
+ const request = (message.event as RequestEvent).request;
396
+ const stringified = JSON.stringify(message, (key, value) => {
397
+ if (key !== "request") {
398
+ return value;
399
+ }
400
+
401
+ return {
402
+ ...request,
403
+ url: request.url,
404
+ headers: request.headers,
405
+ method: request.method,
406
+ };
407
+ });
408
+
409
+ return Buffer.from(stringified, "utf-8");
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Small helper to disambiguate the event types possible in a `TailEventMessage`
415
+ *
416
+ * @param event A TailEvent
417
+ * @returns whether event is a ScheduledEvent (true) or a RequestEvent
418
+ */
419
+ function isScheduled(
420
+ event: ScheduledEvent | RequestEvent
421
+ ): event is ScheduledEvent {
422
+ return "cron" in event;
423
+ }
424
+
425
+ /**
426
+ * Similarly, we need to deserialize from a raw buffer instead
427
+ * of just JSON.parsing a raw string. This deserializer also then
428
+ * re-stringifies with some spacing, the same way wrangler tail does.
429
+ *
430
+ * @param message a buffer of data received from the websocket
431
+ * @returns a string ready to be printed to the terminal or compared against
432
+ */
433
+ function deserializeToJson(message: WebSocket.RawData): string {
434
+ return JSON.stringify(JSON.parse(message.toString()), null, 2);
435
+ }
436
+
437
+ /**
438
+ * A mock for all the different API resources wrangler accesses
439
+ * when running `wrangler tail`
440
+ */
441
+ type MockAPI = {
442
+ requests: {
443
+ creation: RequestCounter;
444
+ deletion: RequestCounter;
445
+ };
446
+ ws: MockWebSocket;
447
+ nextMessageJson(): Promise<unknown>;
448
+ };
449
+
450
+ /**
451
+ * A counter used to check how many times a mock API has been hit.
452
+ * Useful as a helper in our testing to check if wrangler is making
453
+ * the correct API calls without actually sending any web traffic
454
+ */
455
+ type RequestCounter = {
456
+ count: number;
457
+ };
458
+
459
+ /**
460
+ * Mock out the API hit during Tail creation
461
+ *
462
+ * @param websocketURL a fake URL for wrangler to connect a websocket to
463
+ * @returns a `RequestCounter` for counting how many times the API is hit
464
+ */
465
+ function mockCreateTailRequest(
466
+ websocketURL: string,
467
+ env?: string,
468
+ legacyEnv = false
469
+ ): RequestCounter {
470
+ const requests = { count: 0 };
471
+ const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
472
+ const environment = env && !legacyEnv ? "/environments/:envName" : "";
473
+ setMockResponse(
474
+ `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails`,
475
+ "POST",
476
+ ([_url, accountId, scriptName, envName]) => {
477
+ requests.count++;
478
+ expect(accountId).toEqual("some-account-id");
479
+ expect(scriptName).toEqual(
480
+ legacyEnv && env ? `test-worker-${env}` : "test-worker"
481
+ );
482
+ if (!legacyEnv) {
483
+ expect(envName).toEqual(env);
484
+ }
485
+ return {
486
+ id: "tail-id",
487
+ url: websocketURL,
488
+ expires_at: mockTailExpiration,
489
+ };
490
+ }
491
+ );
492
+
493
+ return requests;
494
+ }
495
+
496
+ /**
497
+ * Mock expiration datetime for tails created during testing
498
+ */
499
+ const mockTailExpiration = new Date(3005, 1);
500
+
501
+ /**
502
+ * Default value for event timestamps
503
+ */
504
+ const mockEventTimestamp = 1645454470467;
505
+
506
+ /**
507
+ * Mock out the API hit during Tail deletion
508
+ *
509
+ * @returns a `RequestCounter` for counting how many times the API is hit
510
+ */
511
+ function mockDeleteTailRequest(
512
+ env?: string,
513
+ legacyEnv = false
514
+ ): RequestCounter {
515
+ const requests = { count: 0 };
516
+ const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
517
+ const environment = env && !legacyEnv ? "/environments/:envName" : "";
518
+ setMockResponse(
519
+ // "/accounts/:accountId/workers/scripts/:worker/tails",
520
+ `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails/:tailId`,
521
+ "DELETE",
522
+ ([_url, accountId, scriptName, envNameOrTailId, tailId]) => {
523
+ requests.count++;
524
+ expect(accountId).toEqual("some-account-id");
525
+ expect(scriptName).toEqual(
526
+ legacyEnv && env ? `test-worker-${env}` : "test-worker"
527
+ );
528
+ if (!legacyEnv) {
529
+ if (env) {
530
+ expect(envNameOrTailId).toEqual(env);
531
+ expect(tailId).toEqual("tail-id");
532
+ } else {
533
+ expect(envNameOrTailId).toEqual("tail-id");
534
+ }
535
+ } else {
536
+ expect(envNameOrTailId).toEqual("tail-id");
537
+ }
538
+ return null;
539
+ }
540
+ );
541
+
542
+ return requests;
543
+ }
544
+
545
+ const mockWebSockets: MockWebSocket[] = [];
546
+
547
+ /**
548
+ * All-in-one convenience method to mock the appropriate API calls before
549
+ * each test, and clean up afterwards.
550
+ *
551
+ * @param websocketURL a fake websocket URL for wrangler to connect to
552
+ * @returns a mocked-out version of the API
553
+ */
554
+ function mockWebsocketAPIs(env?: string, legacyEnv = false): MockAPI {
555
+ const websocketURL = "ws://localhost:1234";
556
+ const api: MockAPI = {
557
+ requests: {
558
+ deletion: { count: 0 },
559
+ creation: { count: 0 },
560
+ },
561
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
562
+ ws: null!, // will be set in the `beforeEach()` below.
563
+
564
+ /**
565
+ * Parse the next message received by the mock websocket as JSON
566
+ * @returns JSON.parse of the next message received by the websocket
567
+ */
568
+ async nextMessageJson() {
569
+ const message = await api.ws.nextMessage;
570
+ return JSON.parse(message as string);
571
+ },
572
+ };
573
+ api.requests.creation = mockCreateTailRequest(websocketURL, env, legacyEnv);
574
+ api.requests.deletion = mockDeleteTailRequest(env, legacyEnv);
575
+ api.ws = new MockWebSocket(websocketURL);
576
+ mockWebSockets.push(api.ws);
577
+
578
+ return api;
579
+ }
580
+
581
+ /**
582
+ * Generate a mock `TailEventMessage` of the same shape sent back by the
583
+ * tail worker.
584
+ *
585
+ * @param opts Any specific parts of the message to use instead of defaults
586
+ * @returns a `TailEventMessage` that wrangler can process and display
587
+ */
588
+ function generateMockEventMessage(
589
+ opts?: Partial<TailEventMessage>
590
+ ): TailEventMessage {
591
+ return {
592
+ outcome: opts?.outcome || "ok",
593
+ exceptions: opts?.exceptions || [],
594
+ logs: opts?.logs || [],
595
+ eventTimestamp: opts?.eventTimestamp || mockEventTimestamp,
596
+ event: opts?.event || generateMockRequestEvent(),
597
+ };
598
+ }
599
+
600
+ /**
601
+ * Generate a mock `RequestEvent` that, in an alternate timeline, was used
602
+ * to trigger a worker. You can't disprove this!
603
+ *
604
+ * @param opts Any specific parts of the event to use instead of defaults
605
+ * @returns a `RequestEvent` that can be used within an `EventMessage`
606
+ */
607
+ function generateMockRequestEvent(
608
+ opts?: Partial<RequestEvent["request"]>
609
+ ): RequestEvent {
610
+ return {
611
+ request: Object.assign(
612
+ new Request(opts?.url || "https://example.org/", {
613
+ method: opts?.method || "GET",
614
+ headers:
615
+ opts?.headers || new Headers({ "X-EXAMPLE-HEADER": "some_value" }),
616
+ }),
617
+ {
618
+ cf: opts?.cf || {
619
+ tlsCipher: "AEAD-ENCRYPT-O-MATIC-SHA",
620
+ tlsVersion: "TLSv2.0",
621
+ asn: 42069,
622
+ colo: "ATL",
623
+ httpProtocol: "HTTP/4",
624
+ asOrganization: "Cloudflare",
625
+ },
626
+ }
627
+ ),
628
+ };
629
+ }
630
+
631
+ function generateMockScheduledEvent(
632
+ opts?: Partial<ScheduledEvent>
633
+ ): ScheduledEvent {
634
+ return {
635
+ cron: opts?.cron || "* * * * *",
636
+ scheduledTime: opts?.scheduledTime || mockEventTimestamp,
637
+ };
638
+ }