wrangler 0.0.0-e464fcdb → 0.0.0-e4a8591e7

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