wrangler 0.0.0-eab9542 → 0.0.0-eaf71b86c

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 (180) hide show
  1. package/README.md +29 -13
  2. package/bin/wrangler.js +50 -88
  3. package/config-schema.json +3074 -0
  4. package/package.json +196 -157
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +19 -6
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +2 -3
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +134 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  21. package/templates/middleware/middleware-pretty-error.ts +40 -0
  22. package/templates/middleware/middleware-scheduled.ts +29 -0
  23. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  24. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.js +1 -1
  28. package/templates/new-worker.ts +4 -1
  29. package/templates/pages-dev-pipeline.ts +32 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +9 -0
  32. package/templates/pages-template-plugin.ts +53 -18
  33. package/templates/pages-template-worker.ts +49 -12
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +22 -0
  38. package/templates/tsconfig.json +5 -102
  39. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  40. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  41. package/wrangler-dist/ProxyWorker.js +241 -0
  42. package/wrangler-dist/ProxyWorker.js.map +6 -0
  43. package/wrangler-dist/cli.d.ts +26465 -0
  44. package/wrangler-dist/cli.js +198587 -108581
  45. package/wrangler-dist/wasm-sync.wasm +0 -0
  46. package/Cloudflare_CA.pem +0 -18
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -4894
  52. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  53. package/src/__tests__/config-cache.test.ts +0 -42
  54. package/src/__tests__/configuration.test.ts +0 -3946
  55. package/src/__tests__/dev.test.tsx +0 -1159
  56. package/src/__tests__/guess-worker-format.test.ts +0 -85
  57. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  58. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  59. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  60. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  61. package/src/__tests__/helpers/mock-bin.ts +0 -36
  62. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  63. package/src/__tests__/helpers/mock-console.ts +0 -97
  64. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  65. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  66. package/src/__tests__/helpers/mock-istty.ts +0 -74
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  69. package/src/__tests__/helpers/mock-process.ts +0 -39
  70. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  71. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  72. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  73. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  74. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  75. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  76. package/src/__tests__/https-options.test.ts +0 -130
  77. package/src/__tests__/index.test.ts +0 -262
  78. package/src/__tests__/init.test.ts +0 -1992
  79. package/src/__tests__/jest.setup.ts +0 -107
  80. package/src/__tests__/kv.test.ts +0 -1619
  81. package/src/__tests__/logger.test.ts +0 -141
  82. package/src/__tests__/package-manager.test.ts +0 -353
  83. package/src/__tests__/pages.test.ts +0 -1254
  84. package/src/__tests__/parse.test.ts +0 -330
  85. package/src/__tests__/publish.test.ts +0 -6569
  86. package/src/__tests__/pubsub.test.ts +0 -367
  87. package/src/__tests__/r2.test.ts +0 -233
  88. package/src/__tests__/route.test.ts +0 -45
  89. package/src/__tests__/secret.test.ts +0 -486
  90. package/src/__tests__/tail.test.ts +0 -690
  91. package/src/__tests__/user.test.ts +0 -143
  92. package/src/__tests__/whoami.test.tsx +0 -220
  93. package/src/__tests__/worker-namespace.test.ts +0 -327
  94. package/src/abort.d.ts +0 -3
  95. package/src/api/dev.ts +0 -52
  96. package/src/api/index.ts +0 -1
  97. package/src/bundle-reporter.tsx +0 -29
  98. package/src/bundle.ts +0 -212
  99. package/src/cfetch/index.ts +0 -121
  100. package/src/cfetch/internal.ts +0 -149
  101. package/src/cli.ts +0 -27
  102. package/src/config/README.md +0 -107
  103. package/src/config/config.ts +0 -243
  104. package/src/config/diagnostics.ts +0 -80
  105. package/src/config/environment.ts +0 -453
  106. package/src/config/index.ts +0 -238
  107. package/src/config/validation-helpers.ts +0 -584
  108. package/src/config/validation.ts +0 -1745
  109. package/src/config-cache.ts +0 -83
  110. package/src/create-worker-preview.ts +0 -255
  111. package/src/create-worker-upload-form.ts +0 -263
  112. package/src/dev/dev-vars.ts +0 -36
  113. package/src/dev/dev.tsx +0 -417
  114. package/src/dev/local.tsx +0 -352
  115. package/src/dev/remote.tsx +0 -382
  116. package/src/dev/use-esbuild.ts +0 -150
  117. package/src/dev.tsx +0 -538
  118. package/src/dialogs.tsx +0 -135
  119. package/src/durable.ts +0 -102
  120. package/src/entry.ts +0 -328
  121. package/src/environment-variables.ts +0 -35
  122. package/src/errors.ts +0 -11
  123. package/src/generate.ts +0 -33
  124. package/src/git-client.ts +0 -42
  125. package/src/https-options.ts +0 -123
  126. package/src/index.tsx +0 -1871
  127. package/src/init.ts +0 -549
  128. package/src/inspect.ts +0 -662
  129. package/src/intl-polyfill.d.ts +0 -139
  130. package/src/is-interactive.ts +0 -12
  131. package/src/kv.ts +0 -408
  132. package/src/logger.ts +0 -73
  133. package/src/miniflare-cli/README.md +0 -30
  134. package/src/miniflare-cli/enum-keys.ts +0 -17
  135. package/src/miniflare-cli/index.ts +0 -53
  136. package/src/miniflare-cli/request-context.ts +0 -40
  137. package/src/module-collection.ts +0 -258
  138. package/src/open-in-browser.ts +0 -17
  139. package/src/package-manager.ts +0 -174
  140. package/src/pages/build.tsx +0 -202
  141. package/src/pages/constants.ts +0 -7
  142. package/src/pages/deployments.tsx +0 -101
  143. package/src/pages/dev.tsx +0 -964
  144. package/src/pages/functions/buildPlugin.ts +0 -105
  145. package/src/pages/functions/buildWorker.ts +0 -151
  146. package/src/pages/functions/filepath-routing.test.ts +0 -234
  147. package/src/pages/functions/filepath-routing.ts +0 -189
  148. package/src/pages/functions/identifiers.ts +0 -78
  149. package/src/pages/functions/routes.ts +0 -151
  150. package/src/pages/index.tsx +0 -84
  151. package/src/pages/projects.tsx +0 -157
  152. package/src/pages/publish.tsx +0 -335
  153. package/src/pages/types.ts +0 -40
  154. package/src/pages/upload.tsx +0 -384
  155. package/src/pages/utils.ts +0 -12
  156. package/src/parse.ts +0 -286
  157. package/src/paths.ts +0 -26
  158. package/src/preview.ts +0 -31
  159. package/src/proxy.ts +0 -476
  160. package/src/publish.ts +0 -767
  161. package/src/pubsub/index.ts +0 -286
  162. package/src/pubsub/pubsub-commands.tsx +0 -577
  163. package/src/r2.ts +0 -50
  164. package/src/selfsigned.d.ts +0 -29
  165. package/src/sites.tsx +0 -372
  166. package/src/tail/filters.ts +0 -279
  167. package/src/tail/index.ts +0 -299
  168. package/src/tail/printing.ts +0 -67
  169. package/src/update-check.ts +0 -19
  170. package/src/user/choose-account.tsx +0 -60
  171. package/src/user/env-vars.ts +0 -46
  172. package/src/user/generate-auth-url.ts +0 -33
  173. package/src/user/generate-random-state.ts +0 -16
  174. package/src/user/index.ts +0 -3
  175. package/src/user/user.tsx +0 -1161
  176. package/src/whoami.tsx +0 -90
  177. package/src/worker-namespace.ts +0 -190
  178. package/src/worker.ts +0 -191
  179. package/src/zones.ts +0 -76
  180. package/templates/static-asset-facade.js +0 -43
@@ -1,690 +0,0 @@
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 { useMockIsTTY } from "./helpers/mock-istty";
7
- import { runInTempDir } from "./helpers/run-in-tmp";
8
- import { runWrangler } from "./helpers/run-wrangler";
9
- import type { TailEventMessage, RequestEvent, ScheduledEvent } from "../tail";
10
- import type WebSocket from "ws";
11
-
12
- describe("tail", () => {
13
- runInTempDir();
14
- mockAccountId();
15
- mockApiToken();
16
-
17
- const std = mockConsoleMethods();
18
-
19
- afterEach(() => {
20
- mockWebSockets.forEach((ws) => ws.close());
21
- mockWebSockets.splice(0);
22
- unsetAllMocks();
23
- });
24
-
25
- /**
26
- * Interaction with the tailing API, including tail creation,
27
- * deletion, and connection.
28
- */
29
- describe("API interaction", () => {
30
- it("creates and then delete tails", async () => {
31
- const api = mockWebsocketAPIs();
32
- expect(api.requests.creation.count).toStrictEqual(0);
33
-
34
- await runWrangler("tail test-worker");
35
-
36
- await expect(api.ws.connected).resolves.toBeTruthy();
37
- expect(api.requests.creation.count).toStrictEqual(1);
38
- expect(api.requests.deletion.count).toStrictEqual(0);
39
-
40
- api.ws.close();
41
- expect(api.requests.deletion.count).toStrictEqual(1);
42
- });
43
-
44
- it("creates and then delete tails: legacy envs", async () => {
45
- const api = mockWebsocketAPIs("some-env", true);
46
- expect(api.requests.creation.count).toStrictEqual(0);
47
-
48
- await runWrangler("tail test-worker --env some-env --legacy-env true");
49
-
50
- await expect(api.ws.connected).resolves.toBeTruthy();
51
- expect(api.requests.creation.count).toStrictEqual(1);
52
- expect(api.requests.deletion.count).toStrictEqual(0);
53
-
54
- api.ws.close();
55
- expect(api.requests.deletion.count).toStrictEqual(1);
56
- });
57
-
58
- it("creates and then delete tails: service envs", async () => {
59
- const api = mockWebsocketAPIs("some-env");
60
- expect(api.requests.creation.count).toStrictEqual(0);
61
-
62
- await runWrangler("tail test-worker --env some-env --legacy-env false");
63
-
64
- await expect(api.ws.connected).resolves.toBeTruthy();
65
- expect(api.requests.creation.count).toStrictEqual(1);
66
- expect(api.requests.deletion.count).toStrictEqual(0);
67
-
68
- api.ws.close();
69
- expect(api.requests.deletion.count).toStrictEqual(1);
70
- });
71
-
72
- it("errors when the websocket closes unexpectedly", async () => {
73
- const api = mockWebsocketAPIs();
74
- api.ws.close();
75
-
76
- await expect(runWrangler("tail test-worker")).rejects.toThrow();
77
- });
78
-
79
- it("activates debug mode when the cli arg is passed in", async () => {
80
- const api = mockWebsocketAPIs();
81
- await runWrangler("tail test-worker --debug");
82
- await expect(api.nextMessageJson()).resolves.toHaveProperty(
83
- "debug",
84
- true
85
- );
86
- });
87
- });
88
-
89
- describe("filtering", () => {
90
- it("sends sampling rate filters", async () => {
91
- const api = mockWebsocketAPIs();
92
- const tooHigh = runWrangler("tail test-worker --sampling-rate 10");
93
- await expect(tooHigh).rejects.toThrow();
94
-
95
- const tooLow = runWrangler("tail test-worker --sampling-rate -5");
96
- await expect(tooLow).rejects.toThrow();
97
-
98
- await runWrangler("tail test-worker --sampling-rate 0.25");
99
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
100
- { sampling_rate: 0.25 },
101
- ]);
102
- });
103
-
104
- it("sends single status filters", async () => {
105
- const api = mockWebsocketAPIs();
106
- await runWrangler("tail test-worker --status error");
107
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
108
- { outcome: ["exception", "exceededCpu", "unknown"] },
109
- ]);
110
- });
111
-
112
- it("sends multiple status filters", async () => {
113
- const api = mockWebsocketAPIs();
114
- await runWrangler("tail test-worker --status error --status canceled");
115
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
116
- { outcome: ["exception", "exceededCpu", "unknown", "canceled"] },
117
- ]);
118
- });
119
-
120
- it("sends single HTTP method filters", async () => {
121
- const api = mockWebsocketAPIs();
122
- await runWrangler("tail test-worker --method POST");
123
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
124
- { method: ["POST"] },
125
- ]);
126
- });
127
-
128
- it("sends multiple HTTP method filters", async () => {
129
- const api = mockWebsocketAPIs();
130
- await runWrangler("tail test-worker --method POST --method GET");
131
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
132
- { method: ["POST", "GET"] },
133
- ]);
134
- });
135
-
136
- it("sends header filters without a query", async () => {
137
- const api = mockWebsocketAPIs();
138
- await runWrangler("tail test-worker --header X-CUSTOM-HEADER");
139
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
140
- { header: { key: "X-CUSTOM-HEADER" } },
141
- ]);
142
- });
143
-
144
- it("sends header filters with a query", async () => {
145
- const api = mockWebsocketAPIs();
146
- await runWrangler("tail test-worker --header X-CUSTOM-HEADER:some-value");
147
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
148
- { header: { key: "X-CUSTOM-HEADER", query: "some-value" } },
149
- ]);
150
- });
151
-
152
- it("sends single IP filters", async () => {
153
- const api = mockWebsocketAPIs();
154
- const fakeIp = "192.0.2.1";
155
-
156
- await runWrangler(`tail test-worker --ip ${fakeIp}`);
157
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
158
- { client_ip: [fakeIp] },
159
- ]);
160
- });
161
-
162
- it("sends multiple IP filters", async () => {
163
- const api = mockWebsocketAPIs();
164
- const fakeIp = "192.0.2.1";
165
-
166
- await runWrangler(`tail test-worker --ip ${fakeIp} --ip self`);
167
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
168
- { client_ip: [fakeIp, "self"] },
169
- ]);
170
- });
171
-
172
- it("sends search filters", async () => {
173
- const api = mockWebsocketAPIs();
174
- const search = "filterMe";
175
-
176
- await runWrangler(`tail test-worker --search ${search}`);
177
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
178
- { query: search },
179
- ]);
180
- });
181
-
182
- it("sends everything but the kitchen sink", async () => {
183
- const api = mockWebsocketAPIs();
184
- const sampling_rate = 0.69;
185
- const status = ["ok", "error"];
186
- const method = ["GET", "POST", "PUT"];
187
- const header = "X-HELLO:world";
188
- const client_ip = ["192.0.2.1", "self"];
189
- const query = "onlyTheseMessagesPlease";
190
-
191
- const cliFilters =
192
- `--sampling-rate ${sampling_rate} ` +
193
- status.map((s) => `--status ${s} `).join("") +
194
- method.map((m) => `--method ${m} `).join("") +
195
- `--header ${header} ` +
196
- client_ip.map((c) => `--ip ${c} `).join("") +
197
- `--search ${query} ` +
198
- `--debug`;
199
-
200
- const expectedWebsocketMessage = {
201
- filters: [
202
- { sampling_rate },
203
- { outcome: ["ok", "exception", "exceededCpu", "unknown"] },
204
- { method },
205
- { header: { key: "X-HELLO", query: "world" } },
206
- { client_ip },
207
- { query },
208
- ],
209
- debug: true,
210
- };
211
-
212
- await runWrangler(`tail test-worker ${cliFilters}`);
213
- await expect(api.nextMessageJson()).resolves.toEqual(
214
- expectedWebsocketMessage
215
- );
216
- });
217
- });
218
-
219
- describe("printing", () => {
220
- const { setIsTTY } = useMockIsTTY();
221
-
222
- it("logs request messages in JSON format", async () => {
223
- const api = mockWebsocketAPIs();
224
- await runWrangler("tail test-worker --format json");
225
-
226
- const event = generateMockRequestEvent();
227
- const message = generateMockEventMessage({ event });
228
- const serializedMessage = serialize(message);
229
-
230
- api.ws.send(serializedMessage);
231
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
232
- });
233
-
234
- it("logs scheduled messages in JSON format", async () => {
235
- const api = mockWebsocketAPIs();
236
- await runWrangler("tail test-worker --format json");
237
-
238
- const event = generateMockScheduledEvent();
239
- const message = generateMockEventMessage({ event });
240
- const serializedMessage = serialize(message);
241
-
242
- api.ws.send(serializedMessage);
243
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
244
- });
245
-
246
- it("logs request messages in pretty format", async () => {
247
- const api = mockWebsocketAPIs();
248
- await runWrangler("tail test-worker --format pretty");
249
-
250
- const event = generateMockRequestEvent();
251
- const message = generateMockEventMessage({ event });
252
- const serializedMessage = serialize(message);
253
-
254
- api.ws.send(serializedMessage);
255
- expect(
256
- std.out
257
- .replace(
258
- new Date(mockEventTimestamp).toLocaleString(),
259
- "[mock event timestamp]"
260
- )
261
- .replace(
262
- mockTailExpiration.toLocaleString(),
263
- "[mock expiration date]"
264
- )
265
- ).toMatchInlineSnapshot(`
266
- "Successfully created tail, expires at [mock expiration date]
267
- Connected to test-worker, waiting for logs...
268
- GET https://example.org/ - Ok @ [mock event timestamp]"
269
- `);
270
- });
271
-
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);
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
- });
417
- });
418
- });
419
-
420
- /* helpers */
421
-
422
- /**
423
- * The built in serialize-to-JSON feature of our mock websocket doesn't work
424
- * for our use-case since we actually expect a raw buffer,
425
- * not a Javascript string. Additionally, we have to do some fiddling
426
- * with `RequestEvent`s to get them to serialize properly.
427
- *
428
- * @param message a message to serialize to JSON
429
- * @returns the same type we expect when deserializing in wrangler
430
- */
431
- function serialize(message: TailEventMessage): WebSocket.RawData {
432
- if (isScheduled(message.event)) {
433
- // `ScheduledEvent`s work just fine
434
- const stringified = JSON.stringify(message);
435
- return Buffer.from(stringified, "utf-8");
436
- } else {
437
- // Since the "properties" of an `undici.Request` are actually getters,
438
- // which don't serialize properly, we need to hydrate them manually.
439
- // This isn't a problem outside of testing since deserialization
440
- // works just fine and wrangler never _sends_ any event messages,
441
- // it only receives them.
442
- const request = ((message.event as RequestEvent | undefined | null) || {})
443
- .request;
444
- const stringified = JSON.stringify(message, (key, value) => {
445
- if (key !== "request") {
446
- return value;
447
- }
448
-
449
- return {
450
- ...request,
451
- url: request?.url,
452
- headers: request?.headers,
453
- method: request?.method,
454
- };
455
- });
456
-
457
- return Buffer.from(stringified, "utf-8");
458
- }
459
- }
460
-
461
- /**
462
- * Small helper to disambiguate the event types possible in a `TailEventMessage`
463
- *
464
- * @param event A TailEvent
465
- * @returns whether event is a ScheduledEvent (true) or a RequestEvent
466
- */
467
- function isScheduled(
468
- event: ScheduledEvent | RequestEvent | undefined | null
469
- ): event is ScheduledEvent {
470
- return Boolean(event && "cron" in event);
471
- }
472
-
473
- /**
474
- * Similarly, we need to deserialize from a raw buffer instead
475
- * of just JSON.parsing a raw string. This deserializer also then
476
- * re-stringifies with some spacing, the same way wrangler tail does.
477
- *
478
- * @param message a buffer of data received from the websocket
479
- * @returns a string ready to be printed to the terminal or compared against
480
- */
481
- function deserializeToJson(message: WebSocket.RawData): string {
482
- return JSON.stringify(JSON.parse(message.toString()), null, 2);
483
- }
484
-
485
- /**
486
- * A mock for all the different API resources wrangler accesses
487
- * when running `wrangler tail`
488
- */
489
- type MockAPI = {
490
- requests: {
491
- creation: RequestCounter;
492
- deletion: RequestCounter;
493
- };
494
- ws: MockWebSocket;
495
- nextMessageJson(): Promise<unknown>;
496
- };
497
-
498
- /**
499
- * A counter used to check how many times a mock API has been hit.
500
- * Useful as a helper in our testing to check if wrangler is making
501
- * the correct API calls without actually sending any web traffic
502
- */
503
- type RequestCounter = {
504
- count: number;
505
- };
506
-
507
- /**
508
- * Mock out the API hit during Tail creation
509
- *
510
- * @param websocketURL a fake URL for wrangler to connect a websocket to
511
- * @returns a `RequestCounter` for counting how many times the API is hit
512
- */
513
- function mockCreateTailRequest(
514
- websocketURL: string,
515
- env?: string,
516
- legacyEnv = false
517
- ): RequestCounter {
518
- const requests = { count: 0 };
519
- const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
520
- const environment = env && !legacyEnv ? "/environments/:envName" : "";
521
- setMockResponse(
522
- `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails`,
523
- "POST",
524
- ([_url, accountId, scriptName, envName]) => {
525
- requests.count++;
526
- expect(accountId).toEqual("some-account-id");
527
- expect(scriptName).toEqual(
528
- legacyEnv && env ? `test-worker-${env}` : "test-worker"
529
- );
530
- if (!legacyEnv) {
531
- expect(envName).toEqual(env);
532
- }
533
- return {
534
- id: "tail-id",
535
- url: websocketURL,
536
- expires_at: mockTailExpiration,
537
- };
538
- }
539
- );
540
-
541
- return requests;
542
- }
543
-
544
- /**
545
- * Mock expiration datetime for tails created during testing
546
- */
547
- const mockTailExpiration = new Date(3005, 1);
548
-
549
- /**
550
- * Default value for event timestamps
551
- */
552
- const mockEventTimestamp = 1645454470467;
553
-
554
- /**
555
- * Mock out the API hit during Tail deletion
556
- *
557
- * @returns a `RequestCounter` for counting how many times the API is hit
558
- */
559
- function mockDeleteTailRequest(
560
- env?: string,
561
- legacyEnv = false
562
- ): RequestCounter {
563
- const requests = { count: 0 };
564
- const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
565
- const environment = env && !legacyEnv ? "/environments/:envName" : "";
566
- setMockResponse(
567
- // "/accounts/:accountId/workers/scripts/:worker/tails",
568
- `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails/:tailId`,
569
- "DELETE",
570
- ([_url, accountId, scriptName, envNameOrTailId, tailId]) => {
571
- requests.count++;
572
- expect(accountId).toEqual("some-account-id");
573
- expect(scriptName).toEqual(
574
- legacyEnv && env ? `test-worker-${env}` : "test-worker"
575
- );
576
- if (!legacyEnv) {
577
- if (env) {
578
- expect(envNameOrTailId).toEqual(env);
579
- expect(tailId).toEqual("tail-id");
580
- } else {
581
- expect(envNameOrTailId).toEqual("tail-id");
582
- }
583
- } else {
584
- expect(envNameOrTailId).toEqual("tail-id");
585
- }
586
- return null;
587
- }
588
- );
589
-
590
- return requests;
591
- }
592
-
593
- const mockWebSockets: MockWebSocket[] = [];
594
-
595
- /**
596
- * All-in-one convenience method to mock the appropriate API calls before
597
- * each test, and clean up afterwards.
598
- *
599
- * @param websocketURL a fake websocket URL for wrangler to connect to
600
- * @returns a mocked-out version of the API
601
- */
602
- function mockWebsocketAPIs(env?: string, legacyEnv = false): MockAPI {
603
- const websocketURL = "ws://localhost:1234";
604
- const api: MockAPI = {
605
- requests: {
606
- deletion: { count: 0 },
607
- creation: { count: 0 },
608
- },
609
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
610
- ws: null!, // will be set in the `beforeEach()` below.
611
-
612
- /**
613
- * Parse the next message received by the mock websocket as JSON
614
- * @returns JSON.parse of the next message received by the websocket
615
- */
616
- async nextMessageJson() {
617
- const message = await api.ws.nextMessage;
618
- return JSON.parse(message as string);
619
- },
620
- };
621
- api.requests.creation = mockCreateTailRequest(websocketURL, env, legacyEnv);
622
- api.requests.deletion = mockDeleteTailRequest(env, legacyEnv);
623
- api.ws = new MockWebSocket(websocketURL);
624
- mockWebSockets.push(api.ws);
625
-
626
- return api;
627
- }
628
-
629
- /**
630
- * Generate a mock `TailEventMessage` of the same shape sent back by the
631
- * tail worker.
632
- *
633
- * @param opts Any specific parts of the message to use instead of defaults
634
- * @returns a `TailEventMessage` that wrangler can process and display
635
- */
636
- function generateMockEventMessage({
637
- outcome = "ok",
638
- exceptions = [],
639
- logs = [],
640
- eventTimestamp = mockEventTimestamp,
641
- event = generateMockRequestEvent(),
642
- }: Partial<TailEventMessage>): TailEventMessage {
643
- return {
644
- outcome,
645
- exceptions,
646
- logs,
647
- eventTimestamp,
648
- event,
649
- };
650
- }
651
-
652
- /**
653
- * Generate a mock `RequestEvent` that, in an alternate timeline, was used
654
- * to trigger a worker. You can't disprove this!
655
- *
656
- * @param opts Any specific parts of the event to use instead of defaults
657
- * @returns a `RequestEvent` that can be used within an `EventMessage`
658
- */
659
- function generateMockRequestEvent(
660
- opts?: Partial<RequestEvent["request"]>
661
- ): RequestEvent {
662
- return {
663
- request: Object.assign(
664
- new Request(opts?.url || "https://example.org/", {
665
- method: opts?.method || "GET",
666
- headers:
667
- opts?.headers || new Headers({ "X-EXAMPLE-HEADER": "some_value" }),
668
- }),
669
- {
670
- cf: opts?.cf || {
671
- tlsCipher: "AEAD-ENCRYPT-O-MATIC-SHA",
672
- tlsVersion: "TLSv2.0",
673
- asn: 42069,
674
- colo: "ATL",
675
- httpProtocol: "HTTP/4",
676
- asOrganization: "Cloudflare",
677
- },
678
- }
679
- ),
680
- };
681
- }
682
-
683
- function generateMockScheduledEvent(
684
- opts?: Partial<ScheduledEvent>
685
- ): ScheduledEvent {
686
- return {
687
- cron: opts?.cron || "* * * * *",
688
- scheduledTime: opts?.scheduledTime || mockEventTimestamp,
689
- };
690
- }