wrangler 0.0.0-e8e684c7 → 0.0.0-e9106dfa5

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 (207) hide show
  1. package/README.md +35 -49
  2. package/bin/wrangler.js +25 -100
  3. package/config-schema.json +2277 -0
  4. package/package.json +182 -174
  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-patch-console-prefix.d.ts +3 -0
  22. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +29 -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 +33 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +1 -1
  32. package/templates/pages-template-plugin.ts +37 -14
  33. package/templates/pages-template-worker.ts +33 -7
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +679 -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 +12 -102
  39. package/templates/tsconfig.tsbuildinfo +1 -0
  40. package/wrangler-dist/InspectorProxyWorker.js +471 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +238 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +26527 -172
  45. package/wrangler-dist/cli.js +148646 -148093
  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 -5542
  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 -4026
  55. package/src/__tests__/dev.test.tsx +0 -1318
  56. package/src/__tests__/generate.test.ts +0 -91
  57. package/src/__tests__/guess-worker-format.test.ts +0 -85
  58. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  59. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  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 -296
  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-get-zone-from-host.ts +0 -8
  66. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  67. package/src/__tests__/helpers/mock-istty.ts +0 -74
  68. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  69. package/src/__tests__/helpers/mock-kv.ts +0 -33
  70. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  71. package/src/__tests__/helpers/mock-process.ts +0 -39
  72. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  73. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  74. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  75. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  76. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  77. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  78. package/src/__tests__/https-options.test.ts +0 -163
  79. package/src/__tests__/index.test.ts +0 -245
  80. package/src/__tests__/init.test.ts +0 -2170
  81. package/src/__tests__/jest.setup.ts +0 -157
  82. package/src/__tests__/kv.test.ts +0 -1671
  83. package/src/__tests__/logger.test.ts +0 -141
  84. package/src/__tests__/metrics.test.ts +0 -450
  85. package/src/__tests__/package-manager.test.ts +0 -353
  86. package/src/__tests__/pages.test.ts +0 -1275
  87. package/src/__tests__/parse.test.ts +0 -330
  88. package/src/__tests__/publish.test.ts +0 -6955
  89. package/src/__tests__/pubsub.test.ts +0 -367
  90. package/src/__tests__/r2.test.ts +0 -336
  91. package/src/__tests__/route.test.ts +0 -45
  92. package/src/__tests__/secret.test.ts +0 -492
  93. package/src/__tests__/tail.test.ts +0 -802
  94. package/src/__tests__/test-old-node-version.js +0 -31
  95. package/src/__tests__/user.test.ts +0 -155
  96. package/src/__tests__/validate-dev-props.test.ts +0 -56
  97. package/src/__tests__/version.test.ts +0 -35
  98. package/src/__tests__/whoami.test.tsx +0 -289
  99. package/src/__tests__/worker-namespace.test.ts +0 -329
  100. package/src/abort.d.ts +0 -3
  101. package/src/api/dev.ts +0 -93
  102. package/src/api/index.ts +0 -1
  103. package/src/bundle-reporter.tsx +0 -29
  104. package/src/bundle.ts +0 -473
  105. package/src/cfetch/index.ts +0 -121
  106. package/src/cfetch/internal.ts +0 -298
  107. package/src/cli.ts +0 -27
  108. package/src/config/README.md +0 -107
  109. package/src/config/config.ts +0 -263
  110. package/src/config/diagnostics.ts +0 -80
  111. package/src/config/environment.ts +0 -485
  112. package/src/config/index.ts +0 -251
  113. package/src/config/validation-helpers.ts +0 -597
  114. package/src/config/validation.ts +0 -1862
  115. package/src/config-cache.ts +0 -85
  116. package/src/create-worker-preview.ts +0 -257
  117. package/src/create-worker-upload-form.ts +0 -291
  118. package/src/dev/dev-vars.ts +0 -36
  119. package/src/dev/dev.tsx +0 -545
  120. package/src/dev/local.tsx +0 -449
  121. package/src/dev/remote.tsx +0 -422
  122. package/src/dev/use-esbuild.ts +0 -178
  123. package/src/dev/validate-dev-props.ts +0 -31
  124. package/src/dev-registry.tsx +0 -160
  125. package/src/dev.tsx +0 -696
  126. package/src/dialogs.tsx +0 -135
  127. package/src/dispatch-namespace.ts +0 -206
  128. package/src/durable.ts +0 -102
  129. package/src/entry.ts +0 -328
  130. package/src/environment-variables.ts +0 -35
  131. package/src/errors.ts +0 -11
  132. package/src/faye-websocket.d.ts +0 -6
  133. package/src/generate.ts +0 -131
  134. package/src/git-client.ts +0 -42
  135. package/src/global-wrangler-config-path.ts +0 -26
  136. package/src/https-options.ts +0 -127
  137. package/src/index.tsx +0 -2260
  138. package/src/init.ts +0 -622
  139. package/src/inspect.ts +0 -747
  140. package/src/intl-polyfill.d.ts +0 -139
  141. package/src/is-ci.ts +0 -14
  142. package/src/is-interactive.ts +0 -12
  143. package/src/kv.ts +0 -430
  144. package/src/logger.ts +0 -73
  145. package/src/metrics/index.ts +0 -5
  146. package/src/metrics/metrics-config.ts +0 -239
  147. package/src/metrics/metrics-dispatcher.ts +0 -96
  148. package/src/metrics/metrics-usage-headers.ts +0 -24
  149. package/src/metrics/send-event.ts +0 -92
  150. package/src/miniflare-cli/README.md +0 -30
  151. package/src/miniflare-cli/assets.ts +0 -554
  152. package/src/miniflare-cli/enum-keys.ts +0 -17
  153. package/src/miniflare-cli/index.ts +0 -207
  154. package/src/miniflare-cli/request-context.ts +0 -40
  155. package/src/module-collection.ts +0 -258
  156. package/src/open-in-browser.ts +0 -17
  157. package/src/package-manager.ts +0 -219
  158. package/src/pages/build.tsx +0 -238
  159. package/src/pages/constants.ts +0 -12
  160. package/src/pages/deployments.tsx +0 -106
  161. package/src/pages/dev.tsx +0 -528
  162. package/src/pages/errors.ts +0 -22
  163. package/src/pages/functions/buildPlugin.ts +0 -109
  164. package/src/pages/functions/buildWorker.ts +0 -155
  165. package/src/pages/functions/filepath-routing.test.ts +0 -234
  166. package/src/pages/functions/filepath-routing.ts +0 -189
  167. package/src/pages/functions/identifiers.ts +0 -78
  168. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  169. package/src/pages/functions/routes-consolidation.ts +0 -73
  170. package/src/pages/functions/routes-transformation.test.ts +0 -271
  171. package/src/pages/functions/routes-transformation.ts +0 -122
  172. package/src/pages/functions/routes.ts +0 -151
  173. package/src/pages/functions.tsx +0 -96
  174. package/src/pages/index.tsx +0 -94
  175. package/src/pages/projects.tsx +0 -169
  176. package/src/pages/publish.tsx +0 -391
  177. package/src/pages/types.ts +0 -49
  178. package/src/pages/upload.tsx +0 -413
  179. package/src/pages/utils.ts +0 -12
  180. package/src/parse.ts +0 -286
  181. package/src/paths.ts +0 -26
  182. package/src/preview.ts +0 -31
  183. package/src/proxy.ts +0 -486
  184. package/src/publish.ts +0 -822
  185. package/src/pubsub/index.ts +0 -286
  186. package/src/pubsub/pubsub-commands.tsx +0 -623
  187. package/src/r2.ts +0 -131
  188. package/src/selfsigned.d.ts +0 -29
  189. package/src/sites.tsx +0 -372
  190. package/src/tail/filters.ts +0 -281
  191. package/src/tail/index.ts +0 -312
  192. package/src/tail/printing.ts +0 -107
  193. package/src/update-check.ts +0 -19
  194. package/src/user/choose-account.tsx +0 -69
  195. package/src/user/env-vars.ts +0 -46
  196. package/src/user/generate-auth-url.ts +0 -33
  197. package/src/user/generate-random-state.ts +0 -16
  198. package/src/user/index.ts +0 -3
  199. package/src/user/user.tsx +0 -1191
  200. package/src/whoami.tsx +0 -169
  201. package/src/worker.ts +0 -204
  202. package/src/zones.ts +0 -167
  203. package/templates/first-party-worker-module-facade.ts +0 -18
  204. package/templates/format-dev-errors.ts +0 -32
  205. package/templates/serve-static-assets.ts +0 -63
  206. package/templates/service-bindings-module-facade.js +0 -54
  207. package/templates/service-bindings-sw-facade.js +0 -42
@@ -1,802 +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 { mockGetZoneFromHostRequest } from "./helpers/mock-get-zone-from-host";
7
- import { useMockIsTTY } from "./helpers/mock-istty";
8
- import { mockCollectKnownRoutesRequest } from "./helpers/mock-known-routes";
9
- import { runInTempDir } from "./helpers/run-in-tmp";
10
- import { runWrangler } from "./helpers/run-wrangler";
11
- import type {
12
- TailEventMessage,
13
- RequestEvent,
14
- ScheduledEvent,
15
- AlarmEvent,
16
- } from "../tail";
17
- import type WebSocket from "ws";
18
-
19
- describe("tail", () => {
20
- runInTempDir();
21
- mockAccountId();
22
- mockApiToken();
23
-
24
- const std = mockConsoleMethods();
25
-
26
- afterEach(() => {
27
- mockWebSockets.forEach((ws) => ws.close());
28
- mockWebSockets.splice(0);
29
- unsetAllMocks();
30
- });
31
-
32
- /**
33
- * Interaction with the tailing API, including tail creation,
34
- * deletion, and connection.
35
- */
36
- describe("API interaction", () => {
37
- it("should throw an error if name isn't provided", async () => {
38
- await expect(
39
- runWrangler("tail")
40
- ).rejects.toThrowErrorMatchingInlineSnapshot(
41
- `"Required Worker name missing. Please specify the Worker name in wrangler.toml, or pass it as an argument with \`wrangler tail <worker-name>\`"`
42
- );
43
- });
44
-
45
- it("creates and then delete tails", async () => {
46
- const api = mockWebsocketAPIs();
47
- expect(api.requests.creation.count).toStrictEqual(0);
48
-
49
- await runWrangler("tail test-worker");
50
-
51
- await expect(api.ws.connected).resolves.toBeTruthy();
52
- expect(api.requests.creation.count).toStrictEqual(1);
53
- expect(api.requests.deletion.count).toStrictEqual(0);
54
-
55
- api.ws.close();
56
- expect(api.requests.deletion.count).toStrictEqual(1);
57
- });
58
- it("should connect to the worker assigned to a given route", async () => {
59
- const api = mockWebsocketAPIs();
60
- expect(api.requests.creation.count).toStrictEqual(0);
61
-
62
- mockGetZoneFromHostRequest("example.com", "test-zone");
63
- mockCollectKnownRoutesRequest([
64
- {
65
- pattern: "example.com/*",
66
- script: "test-worker",
67
- },
68
- ]);
69
- await runWrangler("tail example.com/*");
70
-
71
- await expect(api.ws.connected).resolves.toBeTruthy();
72
- expect(api.requests.creation.count).toStrictEqual(1);
73
- expect(api.requests.deletion.count).toStrictEqual(0);
74
-
75
- api.ws.close();
76
- expect(api.requests.deletion.count).toStrictEqual(1);
77
- });
78
-
79
- it("should error if a given route is not assigned to the user's zone", async () => {
80
- mockGetZoneFromHostRequest("example.com", "test-zone");
81
- mockCollectKnownRoutesRequest([]);
82
-
83
- await expect(runWrangler("tail example.com/*")).rejects.toThrow();
84
- });
85
- it("should error if a given route is not within the user's zone", async () => {
86
- mockGetZoneFromHostRequest("example.com");
87
-
88
- await expect(runWrangler("tail example.com/*")).rejects.toThrow();
89
- });
90
-
91
- it("creates and then delete tails: legacy envs", async () => {
92
- const api = mockWebsocketAPIs("some-env", true);
93
- expect(api.requests.creation.count).toStrictEqual(0);
94
-
95
- await runWrangler("tail test-worker --env some-env --legacy-env true");
96
-
97
- await expect(api.ws.connected).resolves.toBeTruthy();
98
- expect(api.requests.creation.count).toStrictEqual(1);
99
- expect(api.requests.deletion.count).toStrictEqual(0);
100
-
101
- api.ws.close();
102
- expect(api.requests.deletion.count).toStrictEqual(1);
103
- });
104
-
105
- it("creates and then delete tails: service envs", async () => {
106
- const api = mockWebsocketAPIs("some-env");
107
- expect(api.requests.creation.count).toStrictEqual(0);
108
-
109
- await runWrangler("tail test-worker --env some-env --legacy-env false");
110
-
111
- await expect(api.ws.connected).resolves.toBeTruthy();
112
- expect(api.requests.creation.count).toStrictEqual(1);
113
- expect(api.requests.deletion.count).toStrictEqual(0);
114
-
115
- api.ws.close();
116
- expect(api.requests.deletion.count).toStrictEqual(1);
117
- });
118
-
119
- it("errors when the websocket closes unexpectedly", async () => {
120
- const api = mockWebsocketAPIs();
121
- api.ws.close();
122
-
123
- await expect(runWrangler("tail test-worker")).rejects.toThrow();
124
- });
125
-
126
- it("activates debug mode when the cli arg is passed in", async () => {
127
- const api = mockWebsocketAPIs();
128
- await runWrangler("tail test-worker --debug");
129
- await expect(api.nextMessageJson()).resolves.toHaveProperty(
130
- "debug",
131
- true
132
- );
133
- });
134
- });
135
-
136
- describe("filtering", () => {
137
- it("sends sampling rate filters", async () => {
138
- const api = mockWebsocketAPIs();
139
- const tooHigh = runWrangler("tail test-worker --sampling-rate 10");
140
- await expect(tooHigh).rejects.toThrow();
141
-
142
- const tooLow = runWrangler("tail test-worker --sampling-rate -5");
143
- await expect(tooLow).rejects.toThrow();
144
-
145
- await runWrangler("tail test-worker --sampling-rate 0.25");
146
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
147
- { sampling_rate: 0.25 },
148
- ]);
149
- });
150
-
151
- it("sends single status filters", async () => {
152
- const api = mockWebsocketAPIs();
153
- await runWrangler("tail test-worker --status error");
154
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
155
- { outcome: ["exception", "exceededCpu", "exceededMemory", "unknown"] },
156
- ]);
157
- });
158
-
159
- it("sends multiple status filters", async () => {
160
- const api = mockWebsocketAPIs();
161
- await runWrangler("tail test-worker --status error --status canceled");
162
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
163
- {
164
- outcome: [
165
- "exception",
166
- "exceededCpu",
167
- "exceededMemory",
168
- "unknown",
169
- "canceled",
170
- ],
171
- },
172
- ]);
173
- });
174
-
175
- it("sends single HTTP method filters", async () => {
176
- const api = mockWebsocketAPIs();
177
- await runWrangler("tail test-worker --method POST");
178
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
179
- { method: ["POST"] },
180
- ]);
181
- });
182
-
183
- it("sends multiple HTTP method filters", async () => {
184
- const api = mockWebsocketAPIs();
185
- await runWrangler("tail test-worker --method POST --method GET");
186
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
187
- { method: ["POST", "GET"] },
188
- ]);
189
- });
190
-
191
- it("sends header filters without a query", async () => {
192
- const api = mockWebsocketAPIs();
193
- await runWrangler("tail test-worker --header X-CUSTOM-HEADER");
194
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
195
- { header: { key: "X-CUSTOM-HEADER" } },
196
- ]);
197
- });
198
-
199
- it("sends header filters with a query", async () => {
200
- const api = mockWebsocketAPIs();
201
- await runWrangler("tail test-worker --header X-CUSTOM-HEADER:some-value");
202
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
203
- { header: { key: "X-CUSTOM-HEADER", query: "some-value" } },
204
- ]);
205
- });
206
-
207
- it("sends single IP filters", async () => {
208
- const api = mockWebsocketAPIs();
209
- const fakeIp = "192.0.2.1";
210
-
211
- await runWrangler(`tail test-worker --ip ${fakeIp}`);
212
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
213
- { client_ip: [fakeIp] },
214
- ]);
215
- });
216
-
217
- it("sends multiple IP filters", async () => {
218
- const api = mockWebsocketAPIs();
219
- const fakeIp = "192.0.2.1";
220
-
221
- await runWrangler(`tail test-worker --ip ${fakeIp} --ip self`);
222
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
223
- { client_ip: [fakeIp, "self"] },
224
- ]);
225
- });
226
-
227
- it("sends search filters", async () => {
228
- const api = mockWebsocketAPIs();
229
- const search = "filterMe";
230
-
231
- await runWrangler(`tail test-worker --search ${search}`);
232
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
233
- { query: search },
234
- ]);
235
- });
236
-
237
- it("sends everything but the kitchen sink", async () => {
238
- const api = mockWebsocketAPIs();
239
- const sampling_rate = 0.69;
240
- const status = ["ok", "error"];
241
- const method = ["GET", "POST", "PUT"];
242
- const header = "X-HELLO:world";
243
- const client_ip = ["192.0.2.1", "self"];
244
- const query = "onlyTheseMessagesPlease";
245
-
246
- const cliFilters =
247
- `--sampling-rate ${sampling_rate} ` +
248
- status.map((s) => `--status ${s} `).join("") +
249
- method.map((m) => `--method ${m} `).join("") +
250
- `--header ${header} ` +
251
- client_ip.map((c) => `--ip ${c} `).join("") +
252
- `--search ${query} ` +
253
- `--debug`;
254
-
255
- const expectedWebsocketMessage = {
256
- filters: [
257
- { sampling_rate },
258
- {
259
- outcome: [
260
- "ok",
261
- "exception",
262
- "exceededCpu",
263
- "exceededMemory",
264
- "unknown",
265
- ],
266
- },
267
- { method },
268
- { header: { key: "X-HELLO", query: "world" } },
269
- { client_ip },
270
- { query },
271
- ],
272
- debug: true,
273
- };
274
-
275
- await runWrangler(`tail test-worker ${cliFilters}`);
276
- await expect(api.nextMessageJson()).resolves.toEqual(
277
- expectedWebsocketMessage
278
- );
279
- });
280
- });
281
-
282
- describe("printing", () => {
283
- const { setIsTTY } = useMockIsTTY();
284
-
285
- it("logs request messages in JSON format", async () => {
286
- const api = mockWebsocketAPIs();
287
- await runWrangler("tail test-worker --format json");
288
-
289
- const event = generateMockRequestEvent();
290
- const message = generateMockEventMessage({ event });
291
- const serializedMessage = serialize(message);
292
-
293
- api.ws.send(serializedMessage);
294
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
295
- });
296
-
297
- it("logs scheduled messages in JSON format", async () => {
298
- const api = mockWebsocketAPIs();
299
- await runWrangler("tail test-worker --format json");
300
-
301
- const event = generateMockScheduledEvent();
302
- const message = generateMockEventMessage({ event });
303
- const serializedMessage = serialize(message);
304
-
305
- api.ws.send(serializedMessage);
306
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
307
- });
308
-
309
- it("logs alarm messages in json format", async () => {
310
- const api = mockWebsocketAPIs();
311
- await runWrangler("tail test-worker --format json");
312
-
313
- const event = generateMockAlarmEvent();
314
- const message = generateMockEventMessage({ event });
315
- const serializedMessage = serialize(message);
316
-
317
- api.ws.send(serializedMessage);
318
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
319
- });
320
-
321
- it("logs request messages in pretty format", async () => {
322
- const api = mockWebsocketAPIs();
323
- await runWrangler("tail test-worker --format pretty");
324
-
325
- const event = generateMockRequestEvent();
326
- const message = generateMockEventMessage({ event });
327
- const serializedMessage = serialize(message);
328
-
329
- api.ws.send(serializedMessage);
330
- expect(
331
- std.out
332
- .replace(
333
- new Date(mockEventTimestamp).toLocaleString(),
334
- "[mock event timestamp]"
335
- )
336
- .replace(
337
- mockTailExpiration.toLocaleString(),
338
- "[mock expiration date]"
339
- )
340
- ).toMatchInlineSnapshot(`
341
- "Successfully created tail, expires at [mock expiration date]
342
- Connected to test-worker, waiting for logs...
343
- GET https://example.org/ - Ok @ [mock event timestamp]"
344
- `);
345
- });
346
-
347
- it("logs scheduled messages in pretty format", async () => {
348
- const api = mockWebsocketAPIs();
349
- await runWrangler("tail test-worker --format pretty");
350
-
351
- const event = generateMockScheduledEvent();
352
- const message = generateMockEventMessage({ event });
353
- const serializedMessage = serialize(message);
354
-
355
- api.ws.send(serializedMessage);
356
- expect(
357
- std.out
358
- .replace(
359
- new Date(mockEventTimestamp).toLocaleString(),
360
- "[mock timestamp string]"
361
- )
362
- .replace(
363
- mockTailExpiration.toLocaleString(),
364
- "[mock expiration date]"
365
- )
366
- ).toMatchInlineSnapshot(`
367
- "Successfully created tail, expires at [mock expiration date]
368
- Connected to test-worker, waiting for logs...
369
- \\"* * * * *\\" @ [mock timestamp string] - Ok"
370
- `);
371
- });
372
-
373
- it("logs alarm messages in pretty format", async () => {
374
- const api = mockWebsocketAPIs();
375
- await runWrangler("tail test-worker --format pretty");
376
-
377
- const event = generateMockAlarmEvent();
378
- const message = generateMockEventMessage({ event });
379
- const serializedMessage = serialize(message);
380
-
381
- api.ws.send(serializedMessage);
382
- expect(
383
- std.out
384
- .replace(
385
- new Date(mockEventScheduledTime).toLocaleString(),
386
- "[mock scheduled time]"
387
- )
388
- .replace(
389
- mockTailExpiration.toLocaleString(),
390
- "[mock expiration date]"
391
- )
392
- ).toMatchInlineSnapshot(`
393
- "Successfully created tail, expires at [mock expiration date]
394
- Connected to test-worker, waiting for logs...
395
- Alarm @ [mock scheduled time] - Ok"
396
- `);
397
- });
398
-
399
- it("should not crash when the tail message has a void event", async () => {
400
- const api = mockWebsocketAPIs();
401
- await runWrangler("tail test-worker --format pretty");
402
-
403
- const message = generateMockEventMessage({ event: null });
404
- const serializedMessage = serialize(message);
405
-
406
- api.ws.send(serializedMessage);
407
- expect(
408
- std.out
409
- .replace(
410
- mockTailExpiration.toLocaleString(),
411
- "[mock expiration date]"
412
- )
413
- .replace(
414
- new Date(mockEventTimestamp).toLocaleString(),
415
- "[mock timestamp string]"
416
- )
417
- ).toMatchInlineSnapshot(`
418
- "Successfully created tail, expires at [mock expiration date]
419
- Connected to test-worker, waiting for logs...
420
- Unknown Event - Ok @ [mock timestamp string]"
421
- `);
422
- });
423
-
424
- it("defaults to logging in pretty format when the output is a TTY", async () => {
425
- setIsTTY(true);
426
- const api = mockWebsocketAPIs();
427
- await runWrangler("tail test-worker");
428
-
429
- const event = generateMockRequestEvent();
430
- const message = generateMockEventMessage({ event });
431
- const serializedMessage = serialize(message);
432
-
433
- api.ws.send(serializedMessage);
434
- expect(
435
- std.out
436
- .replace(
437
- new Date(mockEventTimestamp).toLocaleString(),
438
- "[mock event timestamp]"
439
- )
440
- .replace(
441
- mockTailExpiration.toLocaleString(),
442
- "[mock expiration date]"
443
- )
444
- ).toMatchInlineSnapshot(`
445
- "Successfully created tail, expires at [mock expiration date]
446
- Connected to test-worker, waiting for logs...
447
- GET https://example.org/ - Ok @ [mock event timestamp]"
448
- `);
449
- });
450
-
451
- it("defaults to logging in json format when the output is not a TTY", async () => {
452
- setIsTTY(false);
453
-
454
- const api = mockWebsocketAPIs();
455
- await runWrangler("tail test-worker");
456
-
457
- const event = generateMockRequestEvent();
458
- const message = generateMockEventMessage({ event });
459
- const serializedMessage = serialize(message);
460
-
461
- api.ws.send(serializedMessage);
462
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
463
- });
464
-
465
- it("logs console messages and exceptions", async () => {
466
- setIsTTY(true);
467
- const api = mockWebsocketAPIs();
468
- await runWrangler("tail test-worker");
469
-
470
- const event = generateMockRequestEvent();
471
- const message = generateMockEventMessage({
472
- event,
473
- logs: [
474
- { message: ["some string"], level: "log", timestamp: 1234561 },
475
- {
476
- message: [{ complex: "object" }],
477
- level: "log",
478
- timestamp: 1234562,
479
- },
480
- { message: [1234], level: "error", timestamp: 1234563 },
481
- ],
482
- exceptions: [
483
- { name: "Error", message: "some error", timestamp: 1234564 },
484
- { name: "Error", message: { complex: "error" }, timestamp: 1234564 },
485
- ],
486
- });
487
- const serializedMessage = serialize(message);
488
-
489
- api.ws.send(serializedMessage);
490
- expect(
491
- std.out
492
- .replace(
493
- new Date(mockEventTimestamp).toLocaleString(),
494
- "[mock event timestamp]"
495
- )
496
- .replace(
497
- mockTailExpiration.toLocaleString(),
498
- "[mock expiration date]"
499
- )
500
- ).toMatchInlineSnapshot(`
501
- "Successfully created tail, expires at [mock expiration date]
502
- Connected to test-worker, waiting for logs...
503
- GET https://example.org/ - Ok @ [mock event timestamp]
504
- (log) some string
505
- (log) { complex: 'object' }
506
- (error) 1234"
507
- `);
508
- expect(std.err).toMatchInlineSnapshot(`
509
- "X [ERROR]  Error: some error
510
-
511
-
512
- X [ERROR]  Error: { complex: 'error' }
513
-
514
- "
515
- `);
516
- expect(std.warn).toMatchInlineSnapshot(`""`);
517
- });
518
- });
519
- });
520
-
521
- /* helpers */
522
-
523
- /**
524
- * The built in serialize-to-JSON feature of our mock websocket doesn't work
525
- * for our use-case since we actually expect a raw buffer,
526
- * not a Javascript string. Additionally, we have to do some fiddling
527
- * with `RequestEvent`s to get them to serialize properly.
528
- *
529
- * @param message a message to serialize to JSON
530
- * @returns the same type we expect when deserializing in wrangler
531
- */
532
- function serialize(message: TailEventMessage): WebSocket.RawData {
533
- if (!isRequest(message.event)) {
534
- // `ScheduledEvent`s and `TailEvent`s work just fine
535
- const stringified = JSON.stringify(message);
536
- return Buffer.from(stringified, "utf-8");
537
- } else {
538
- // Since the "properties" of an `undici.Request` are actually getters,
539
- // which don't serialize properly, we need to hydrate them manually.
540
- // This isn't a problem outside of testing since deserialization
541
- // works just fine and wrangler never _sends_ any event messages,
542
- // it only receives them.
543
- const request = ((message.event as RequestEvent | undefined | null) || {})
544
- .request;
545
- const stringified = JSON.stringify(message, (key, value) => {
546
- if (key !== "request") {
547
- return value;
548
- }
549
-
550
- return {
551
- ...request,
552
- url: request?.url,
553
- headers: request?.headers,
554
- method: request?.method,
555
- };
556
- });
557
-
558
- return Buffer.from(stringified, "utf-8");
559
- }
560
- }
561
-
562
- /**
563
- * Small helper to disambiguate the event types possible in a `TailEventMessage`
564
- *
565
- * @param event A TailEvent
566
- * @returns true if `event` is a RequestEvent
567
- */
568
- function isRequest(
569
- event: ScheduledEvent | RequestEvent | AlarmEvent | undefined | null
570
- ): event is RequestEvent {
571
- return Boolean(event && "request" in event);
572
- }
573
-
574
- /**
575
- * Similarly, we need to deserialize from a raw buffer instead
576
- * of just JSON.parsing a raw string. This deserializer also then
577
- * re-stringifies with some spacing, the same way wrangler tail does.
578
- *
579
- * @param message a buffer of data received from the websocket
580
- * @returns a string ready to be printed to the terminal or compared against
581
- */
582
- function deserializeToJson(message: WebSocket.RawData): string {
583
- return JSON.stringify(JSON.parse(message.toString()), null, 2);
584
- }
585
-
586
- /**
587
- * A mock for all the different API resources wrangler accesses
588
- * when running `wrangler tail`
589
- */
590
- type MockAPI = {
591
- requests: {
592
- creation: RequestCounter;
593
- deletion: RequestCounter;
594
- };
595
- ws: MockWebSocket;
596
- nextMessageJson(): Promise<unknown>;
597
- };
598
-
599
- /**
600
- * A counter used to check how many times a mock API has been hit.
601
- * Useful as a helper in our testing to check if wrangler is making
602
- * the correct API calls without actually sending any web traffic
603
- */
604
- type RequestCounter = {
605
- count: number;
606
- };
607
-
608
- /**
609
- * Mock out the API hit during Tail creation
610
- *
611
- * @param websocketURL a fake URL for wrangler to connect a websocket to
612
- * @returns a `RequestCounter` for counting how many times the API is hit
613
- */
614
- function mockCreateTailRequest(
615
- websocketURL: string,
616
- env?: string,
617
- legacyEnv = false
618
- ): RequestCounter {
619
- const requests = { count: 0 };
620
- const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
621
- const environment = env && !legacyEnv ? "/environments/:envName" : "";
622
- setMockResponse(
623
- `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails`,
624
- "POST",
625
- ([_url, accountId, scriptName, envName]) => {
626
- requests.count++;
627
- expect(accountId).toEqual("some-account-id");
628
- expect(scriptName).toEqual(
629
- legacyEnv && env ? `test-worker-${env}` : "test-worker"
630
- );
631
- if (!legacyEnv) {
632
- expect(envName).toEqual(env);
633
- }
634
- return {
635
- id: "tail-id",
636
- url: websocketURL,
637
- expires_at: mockTailExpiration,
638
- };
639
- }
640
- );
641
-
642
- return requests;
643
- }
644
-
645
- /**
646
- * Mock expiration datetime for tails created during testing
647
- */
648
- const mockTailExpiration = new Date(3005, 1);
649
-
650
- /**
651
- * Default value for event timestamps
652
- */
653
- const mockEventTimestamp = 1645454470467;
654
-
655
- /**
656
- * Default value for event time ISO strings
657
- */
658
- const mockEventScheduledTime = new Date(mockEventTimestamp).toISOString();
659
-
660
- /**
661
- * Mock out the API hit during Tail deletion
662
- *
663
- * @returns a `RequestCounter` for counting how many times the API is hit
664
- */
665
- function mockDeleteTailRequest(
666
- env?: string,
667
- legacyEnv = false
668
- ): RequestCounter {
669
- const requests = { count: 0 };
670
- const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
671
- const environment = env && !legacyEnv ? "/environments/:envName" : "";
672
- setMockResponse(
673
- // "/accounts/:accountId/workers/scripts/:worker/tails",
674
- `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails/:tailId`,
675
- "DELETE",
676
- ([_url, accountId, scriptName, envNameOrTailId, tailId]) => {
677
- requests.count++;
678
- expect(accountId).toEqual("some-account-id");
679
- expect(scriptName).toEqual(
680
- legacyEnv && env ? `test-worker-${env}` : "test-worker"
681
- );
682
- if (!legacyEnv) {
683
- if (env) {
684
- expect(envNameOrTailId).toEqual(env);
685
- expect(tailId).toEqual("tail-id");
686
- } else {
687
- expect(envNameOrTailId).toEqual("tail-id");
688
- }
689
- } else {
690
- expect(envNameOrTailId).toEqual("tail-id");
691
- }
692
- return null;
693
- }
694
- );
695
-
696
- return requests;
697
- }
698
-
699
- const mockWebSockets: MockWebSocket[] = [];
700
-
701
- /**
702
- * All-in-one convenience method to mock the appropriate API calls before
703
- * each test, and clean up afterwards.
704
- *
705
- * @param websocketURL a fake websocket URL for wrangler to connect to
706
- * @returns a mocked-out version of the API
707
- */
708
- function mockWebsocketAPIs(env?: string, legacyEnv = false): MockAPI {
709
- const websocketURL = "ws://localhost:1234";
710
- const api: MockAPI = {
711
- requests: {
712
- deletion: { count: 0 },
713
- creation: { count: 0 },
714
- },
715
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
716
- ws: null!, // will be set in the `beforeEach()` below.
717
-
718
- /**
719
- * Parse the next message received by the mock websocket as JSON
720
- * @returns JSON.parse of the next message received by the websocket
721
- */
722
- async nextMessageJson() {
723
- const message = await api.ws.nextMessage;
724
- return JSON.parse(message as string);
725
- },
726
- };
727
- api.requests.creation = mockCreateTailRequest(websocketURL, env, legacyEnv);
728
- api.requests.deletion = mockDeleteTailRequest(env, legacyEnv);
729
- api.ws = new MockWebSocket(websocketURL);
730
- mockWebSockets.push(api.ws);
731
-
732
- return api;
733
- }
734
-
735
- /**
736
- * Generate a mock `TailEventMessage` of the same shape sent back by the
737
- * tail worker.
738
- *
739
- * @param opts Any specific parts of the message to use instead of defaults
740
- * @returns a `TailEventMessage` that wrangler can process and display
741
- */
742
- function generateMockEventMessage({
743
- outcome = "ok",
744
- exceptions = [],
745
- logs = [],
746
- eventTimestamp = mockEventTimestamp,
747
- event = generateMockRequestEvent(),
748
- }: Partial<TailEventMessage>): TailEventMessage {
749
- return {
750
- outcome,
751
- exceptions,
752
- logs,
753
- eventTimestamp,
754
- event,
755
- };
756
- }
757
-
758
- /**
759
- * Generate a mock `RequestEvent` that, in an alternate timeline, was used
760
- * to trigger a worker. You can't disprove this!
761
- *
762
- * @param opts Any specific parts of the event to use instead of defaults
763
- * @returns a `RequestEvent` that can be used within an `EventMessage`
764
- */
765
- function generateMockRequestEvent(
766
- opts?: Partial<RequestEvent["request"]>
767
- ): RequestEvent {
768
- return {
769
- request: Object.assign(
770
- new Request(opts?.url || "https://example.org/", {
771
- method: opts?.method || "GET",
772
- headers:
773
- opts?.headers || new Headers({ "X-EXAMPLE-HEADER": "some_value" }),
774
- }),
775
- {
776
- cf: opts?.cf || {
777
- tlsCipher: "AEAD-ENCRYPT-O-MATIC-SHA",
778
- tlsVersion: "TLSv2.0",
779
- asn: 42069,
780
- colo: "ATL",
781
- httpProtocol: "HTTP/4",
782
- asOrganization: "Cloudflare",
783
- },
784
- }
785
- ),
786
- };
787
- }
788
-
789
- function generateMockScheduledEvent(
790
- opts?: Partial<ScheduledEvent>
791
- ): ScheduledEvent {
792
- return {
793
- cron: opts?.cron || "* * * * *",
794
- scheduledTime: opts?.scheduledTime || mockEventTimestamp,
795
- };
796
- }
797
-
798
- function generateMockAlarmEvent(opts?: Partial<AlarmEvent>): AlarmEvent {
799
- return {
800
- scheduledTime: opts?.scheduledTime || mockEventScheduledTime,
801
- };
802
- }