wrangler 0.0.0-ecc8b172 → 0.0.0-ecded1af1

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