wrangler 0.0.0-e1b8ac4 → 0.0.0-e1c2f5b9

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