wrangler 0.0.0-e88a54e → 0.0.0-e89ee2a5

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 (174) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +123 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +168 -86
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +167 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +136 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-ensure-req-body-drained.ts +19 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  27. package/templates/modules-watch-stub.js +4 -0
  28. package/templates/new-worker-scheduled.js +17 -0
  29. package/templates/new-worker-scheduled.ts +32 -0
  30. package/templates/new-worker.js +3 -3
  31. package/templates/new-worker.ts +22 -4
  32. package/templates/no-op-worker.js +10 -0
  33. package/templates/pages-dev-pipeline.ts +32 -0
  34. package/templates/pages-dev-util.ts +55 -0
  35. package/templates/pages-shim.ts +9 -0
  36. package/templates/pages-template-plugin.ts +190 -0
  37. package/templates/pages-template-worker.ts +198 -0
  38. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  39. package/templates/startDevWorker/ProxyWorker.ts +326 -0
  40. package/templates/tsconfig-sanity.ts +11 -0
  41. package/templates/tsconfig.init.json +105 -0
  42. package/templates/tsconfig.json +6 -103
  43. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +237 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +23948 -0
  48. package/wrangler-dist/cli.js +164439 -134006
  49. package/wrangler-dist/wasm-sync.wasm +0 -0
  50. package/import_meta_url.js +0 -3
  51. package/miniflare-config-stubs/.env.empty +0 -0
  52. package/miniflare-config-stubs/package.empty.json +0 -1
  53. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  54. package/miniflare-dist/index.mjs +0 -79
  55. package/miniflare-dist/index.mjs.map +0 -7
  56. package/pages/functions/buildWorker.ts +0 -62
  57. package/pages/functions/filepath-routing.test.ts +0 -223
  58. package/pages/functions/filepath-routing.ts +0 -181
  59. package/pages/functions/identifiers.ts +0 -78
  60. package/pages/functions/routes.ts +0 -151
  61. package/pages/functions/template-worker.ts +0 -130
  62. package/src/__tests__/configuration.test.ts +0 -2796
  63. package/src/__tests__/dev.test.tsx +0 -496
  64. package/src/__tests__/dev2.test.tsx +0 -154
  65. package/src/__tests__/guess-worker-format.test.ts +0 -58
  66. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  67. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  68. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  69. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  70. package/src/__tests__/helpers/mock-bin.ts +0 -36
  71. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  72. package/src/__tests__/helpers/mock-console.ts +0 -70
  73. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  74. package/src/__tests__/helpers/mock-kv.ts +0 -33
  75. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  76. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  77. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  78. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  79. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  80. package/src/__tests__/https-options.test.ts +0 -127
  81. package/src/__tests__/index.test.ts +0 -991
  82. package/src/__tests__/jest.setup.ts +0 -69
  83. package/src/__tests__/kv.test.ts +0 -1382
  84. package/src/__tests__/logout.test.ts +0 -52
  85. package/src/__tests__/package-manager.test.ts +0 -206
  86. package/src/__tests__/pages.test.ts +0 -44
  87. package/src/__tests__/parse.test.ts +0 -322
  88. package/src/__tests__/publish.test.ts +0 -2704
  89. package/src/__tests__/r2.test.ts +0 -198
  90. package/src/__tests__/route.test.ts +0 -45
  91. package/src/__tests__/secret.test.ts +0 -425
  92. package/src/__tests__/sentry.test.ts +0 -146
  93. package/src/__tests__/tail.test.ts +0 -564
  94. package/src/__tests__/whoami.test.tsx +0 -100
  95. package/src/bundle.ts +0 -142
  96. package/src/cfetch/index.ts +0 -104
  97. package/src/cfetch/internal.ts +0 -139
  98. package/src/cli.ts +0 -19
  99. package/src/config/README.md +0 -107
  100. package/src/config/config.ts +0 -218
  101. package/src/config/diagnostics.ts +0 -80
  102. package/src/config/environment.ts +0 -366
  103. package/src/config/index.ts +0 -62
  104. package/src/config/validation-helpers.ts +0 -486
  105. package/src/config/validation.ts +0 -1090
  106. package/src/create-worker-preview.ts +0 -166
  107. package/src/create-worker-upload-form.ts +0 -217
  108. package/src/dev/dev.tsx +0 -364
  109. package/src/dev/local.tsx +0 -232
  110. package/src/dev/remote.tsx +0 -203
  111. package/src/dev/use-esbuild.ts +0 -100
  112. package/src/dialogs.tsx +0 -77
  113. package/src/entry.ts +0 -208
  114. package/src/environment-variables.ts +0 -33
  115. package/src/https-options.ts +0 -122
  116. package/src/index.tsx +0 -2373
  117. package/src/inspect.ts +0 -617
  118. package/src/kv.ts +0 -319
  119. package/src/miniflare-cli/README.md +0 -30
  120. package/src/miniflare-cli/enum-keys.ts +0 -17
  121. package/src/miniflare-cli/index.ts +0 -37
  122. package/src/module-collection.ts +0 -258
  123. package/src/open-in-browser.ts +0 -25
  124. package/src/package-manager.ts +0 -126
  125. package/src/pages.tsx +0 -1047
  126. package/src/parse.ts +0 -183
  127. package/src/paths.ts +0 -26
  128. package/src/proxy.ts +0 -440
  129. package/src/publish.ts +0 -347
  130. package/src/r2.ts +0 -50
  131. package/src/reporting.ts +0 -131
  132. package/src/selfsigned.d.ts +0 -29
  133. package/src/sites.tsx +0 -280
  134. package/src/tail/filters.ts +0 -279
  135. package/src/tail/index.ts +0 -299
  136. package/src/tail/printing.ts +0 -62
  137. package/src/user.tsx +0 -1118
  138. package/src/whoami.tsx +0 -69
  139. package/src/worker.ts +0 -163
  140. package/templates/static-asset-facade.js +0 -47
  141. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  142. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  143. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  144. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  145. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  146. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  147. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  148. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  149. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  150. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  151. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  152. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  153. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  154. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  155. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  156. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  157. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  158. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  159. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  160. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  161. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  162. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  163. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  164. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  165. package/vendor/wrangler-mime/LICENSE +0 -21
  166. package/vendor/wrangler-mime/Mime.js +0 -97
  167. package/vendor/wrangler-mime/README.md +0 -187
  168. package/vendor/wrangler-mime/cli.js +0 -46
  169. package/vendor/wrangler-mime/index.js +0 -4
  170. package/vendor/wrangler-mime/lite.js +0 -4
  171. package/vendor/wrangler-mime/package.json +0 -52
  172. package/vendor/wrangler-mime/types/other.js +0 -1
  173. package/vendor/wrangler-mime/types/standard.js +0 -1
  174. package/wrangler-dist/cli.js.map +0 -7
@@ -1,146 +0,0 @@
1
- import * as fs from "node:fs";
2
- import * as fsp from "node:fs/promises";
3
- import os from "node:os";
4
- import path from "node:path";
5
- import * as TOML from "@iarna/toml";
6
- import * as Sentry from "@sentry/node";
7
- import prompts from "prompts";
8
-
9
- import { mockConsoleMethods } from "./helpers/mock-console";
10
- import { runInTempDir } from "./helpers/run-in-tmp";
11
- import { runWrangler } from "./helpers/run-wrangler";
12
- const { reportError } = jest.requireActual("../reporting");
13
-
14
- describe("Error Reporting", () => {
15
- runInTempDir({ homedir: "./home" });
16
- mockConsoleMethods();
17
- const reportingTOMLPath = ".wrangler/config/reporting.toml";
18
-
19
- const originalTTY = process.stdout.isTTY;
20
- beforeEach(() => {
21
- jest.mock("@sentry/node");
22
- jest.spyOn(Sentry, "captureException");
23
- process.stdout.isTTY = true;
24
- });
25
-
26
- afterEach(() => {
27
- jest.unmock("@sentry/node");
28
- jest.clearAllMocks();
29
- process.stdout.isTTY = originalTTY;
30
- });
31
-
32
- it("should confirm user will allow error reporting usage", async () => {
33
- jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: true });
34
-
35
- await reportError(new Error("test error"), "testFalse");
36
-
37
- const { error_tracking_opt, error_tracking_opt_date } = TOML.parse(
38
- await fsp.readFile(path.join(os.homedir(), reportingTOMLPath), "utf-8")
39
- );
40
-
41
- expect(error_tracking_opt).toBe(true);
42
- expect(error_tracking_opt_date).toBeTruthy();
43
-
44
- expect(Sentry.captureException).toHaveBeenCalledWith(
45
- new Error("test error")
46
- );
47
- });
48
-
49
- it("should confirm user will disallow error reporting usage", async () => {
50
- jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: false });
51
- await reportError(new Error("test error"), "testFalse");
52
-
53
- const { error_tracking_opt, error_tracking_opt_date } = TOML.parse(
54
- await fsp.readFile(path.join(os.homedir(), reportingTOMLPath), "utf-8")
55
- );
56
-
57
- expect(error_tracking_opt).toBe(false);
58
- expect(error_tracking_opt_date).toBeTruthy();
59
-
60
- expect(Sentry.captureException).not.toHaveBeenCalledWith(
61
- new Error("test error"),
62
- "testFalse"
63
- );
64
- });
65
-
66
- it("should confirm user will allow 'once' error reporting usage", async () => {
67
- jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: "once" });
68
- await runWrangler();
69
- await reportError(new Error("test error"), "testFalse");
70
-
71
- expect(fs.existsSync(path.join(os.homedir(), reportingTOMLPath))).toBe(
72
- false
73
- );
74
-
75
- expect(Sentry.captureException).not.toHaveBeenCalledWith(
76
- new Error("test error"),
77
- "testFalse"
78
- );
79
- });
80
-
81
- it("should not prompt w/ subsequent Errors after user disallows error reporting", async () => {
82
- jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: false });
83
- await reportError(new Error("test error"), "testFalse");
84
-
85
- expect(Sentry.captureException).not.toHaveBeenCalledWith(
86
- new Error("test error"),
87
- "testFalse"
88
- );
89
-
90
- await reportError(new Error("second test error"), "testFalse");
91
- expect(Sentry.captureException).not.toHaveBeenCalledWith(
92
- new Error("second test error"),
93
- "testFalse"
94
- );
95
- });
96
-
97
- it("should not prompt w/ subsequent Errors after user Always allows error reporting", async () => {
98
- jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: true });
99
- await reportError(new Error("test error"), "testFalse");
100
-
101
- expect(Sentry.captureException).toHaveBeenCalledWith(
102
- new Error("test error")
103
- );
104
-
105
- await reportError(new Error("second test error"), "testFalse");
106
- expect(Sentry.captureException).toHaveBeenCalledWith(
107
- new Error("second test error")
108
- );
109
- });
110
-
111
- it("should prompt w/ subsequent Errors after user allows error reporting once", async () => {
112
- const promptSpy = jest
113
- .spyOn(prompts, "prompt")
114
- .mockResolvedValue({ sentryDecision: "once" });
115
- await reportError(new Error("test error"), "testFalse");
116
-
117
- expect(Sentry.captureException).toHaveBeenCalledWith(
118
- new Error("test error")
119
- );
120
-
121
- await reportError(new Error("second test error"), "testFalse");
122
- expect(Sentry.captureException).toHaveBeenCalledWith(
123
- new Error("second test error")
124
- );
125
-
126
- expect(promptSpy).toBeCalledTimes(2);
127
- });
128
-
129
- it("should not prompt in non-TTY environment", async () => {
130
- process.stdout.isTTY = false;
131
-
132
- await reportError(new Error("test error"), "testFalse");
133
-
134
- const { error_tracking_opt, error_tracking_opt_date } = TOML.parse(
135
- await fsp.readFile(path.join(os.homedir(), reportingTOMLPath), "utf-8")
136
- );
137
-
138
- expect(error_tracking_opt).toBe(false);
139
- expect(error_tracking_opt_date).toBeTruthy();
140
-
141
- expect(Sentry.captureException).not.toHaveBeenCalledWith(
142
- new Error("test error")
143
- );
144
- process.stdout.isTTY = originalTTY;
145
- });
146
- });
@@ -1,564 +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 { runInTempDir } from "./helpers/run-in-tmp";
7
- import { runWrangler } from "./helpers/run-wrangler";
8
- import type { TailEventMessage, RequestEvent, ScheduledEvent } from "../tail";
9
- import type WebSocket from "ws";
10
-
11
- describe("tail", () => {
12
- runInTempDir();
13
- mockAccountId();
14
- mockApiToken();
15
-
16
- const std = mockConsoleMethods();
17
-
18
- afterEach(() => {
19
- mockWebSockets.forEach((ws) => ws.close());
20
- mockWebSockets.splice(0);
21
- unsetAllMocks();
22
- });
23
-
24
- /**
25
- * Interaction with the tailing API, including tail creation,
26
- * deletion, and connection.
27
- */
28
- describe("API interaction", () => {
29
- it("creates and then delete tails", async () => {
30
- const api = mockWebsocketAPIs();
31
- expect(api.requests.creation.count).toStrictEqual(0);
32
-
33
- await runWrangler("tail test-worker");
34
-
35
- await expect(api.ws.connected).resolves.toBeTruthy();
36
- expect(api.requests.creation.count).toStrictEqual(1);
37
- expect(api.requests.deletion.count).toStrictEqual(0);
38
-
39
- api.ws.close();
40
- expect(api.requests.deletion.count).toStrictEqual(1);
41
- });
42
-
43
- it("creates and then delete tails: legacy envs", async () => {
44
- const api = mockWebsocketAPIs("some-env", true);
45
- expect(api.requests.creation.count).toStrictEqual(0);
46
-
47
- await runWrangler("tail test-worker --env some-env --legacy-env true");
48
-
49
- await expect(api.ws.connected).resolves.toBeTruthy();
50
- expect(api.requests.creation.count).toStrictEqual(1);
51
- expect(api.requests.deletion.count).toStrictEqual(0);
52
-
53
- api.ws.close();
54
- expect(api.requests.deletion.count).toStrictEqual(1);
55
- });
56
-
57
- it("creates and then delete tails: service envs", async () => {
58
- const api = mockWebsocketAPIs("some-env");
59
- expect(api.requests.creation.count).toStrictEqual(0);
60
-
61
- await runWrangler("tail test-worker --env some-env --legacy-env false");
62
-
63
- await expect(api.ws.connected).resolves.toBeTruthy();
64
- expect(api.requests.creation.count).toStrictEqual(1);
65
- expect(api.requests.deletion.count).toStrictEqual(0);
66
-
67
- api.ws.close();
68
- expect(api.requests.deletion.count).toStrictEqual(1);
69
- });
70
-
71
- it("errors when the websocket closes unexpectedly", async () => {
72
- const api = mockWebsocketAPIs();
73
- api.ws.close();
74
-
75
- await expect(runWrangler("tail test-worker")).rejects.toThrow();
76
- });
77
-
78
- it("activates debug mode when the cli arg is passed in", async () => {
79
- const api = mockWebsocketAPIs();
80
- await runWrangler("tail test-worker --debug");
81
- await expect(api.nextMessageJson()).resolves.toHaveProperty(
82
- "debug",
83
- true
84
- );
85
- });
86
- });
87
-
88
- describe("filtering", () => {
89
- it("sends sampling rate filters", async () => {
90
- const api = mockWebsocketAPIs();
91
- const tooHigh = runWrangler("tail test-worker --sampling-rate 10");
92
- await expect(tooHigh).rejects.toThrow();
93
-
94
- const tooLow = runWrangler("tail test-worker --sampling-rate -5");
95
- await expect(tooLow).rejects.toThrow();
96
-
97
- await runWrangler("tail test-worker --sampling-rate 0.25");
98
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
99
- { sampling_rate: 0.25 },
100
- ]);
101
- });
102
-
103
- it("sends single status filters", async () => {
104
- const api = mockWebsocketAPIs();
105
- await runWrangler("tail test-worker --status error");
106
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
107
- { outcome: ["exception", "exceededCpu", "unknown"] },
108
- ]);
109
- });
110
-
111
- it("sends multiple status filters", async () => {
112
- const api = mockWebsocketAPIs();
113
- await runWrangler("tail test-worker --status error --status canceled");
114
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
115
- { outcome: ["exception", "exceededCpu", "unknown", "canceled"] },
116
- ]);
117
- });
118
-
119
- it("sends single HTTP method filters", async () => {
120
- const api = mockWebsocketAPIs();
121
- await runWrangler("tail test-worker --method POST");
122
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
123
- { method: ["POST"] },
124
- ]);
125
- });
126
-
127
- it("sends multiple HTTP method filters", async () => {
128
- const api = mockWebsocketAPIs();
129
- await runWrangler("tail test-worker --method POST --method GET");
130
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
131
- { method: ["POST", "GET"] },
132
- ]);
133
- });
134
-
135
- it("sends header filters without a query", async () => {
136
- const api = mockWebsocketAPIs();
137
- await runWrangler("tail test-worker --header X-CUSTOM-HEADER ");
138
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
139
- { header: { key: "X-CUSTOM-HEADER" } },
140
- ]);
141
- });
142
-
143
- it("sends header filters with a query", async () => {
144
- const api = mockWebsocketAPIs();
145
- await runWrangler(
146
- "tail test-worker --header X-CUSTOM-HEADER:some-value "
147
- );
148
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
149
- { header: { key: "X-CUSTOM-HEADER", query: "some-value" } },
150
- ]);
151
- });
152
-
153
- it("sends single IP filters", async () => {
154
- const api = mockWebsocketAPIs();
155
- const fakeIp = "192.0.2.1";
156
-
157
- await runWrangler(`tail test-worker --ip ${fakeIp}`);
158
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
159
- { client_ip: [fakeIp] },
160
- ]);
161
- });
162
-
163
- it("sends multiple IP filters", async () => {
164
- const api = mockWebsocketAPIs();
165
- const fakeIp = "192.0.2.1";
166
-
167
- await runWrangler(`tail test-worker --ip ${fakeIp} --ip self`);
168
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
169
- { client_ip: [fakeIp, "self"] },
170
- ]);
171
- });
172
-
173
- it("sends search filters", async () => {
174
- const api = mockWebsocketAPIs();
175
- const search = "filterMe";
176
-
177
- await runWrangler(`tail test-worker --search ${search}`);
178
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
179
- { query: search },
180
- ]);
181
- });
182
-
183
- it("sends everything but the kitchen sink", async () => {
184
- const api = mockWebsocketAPIs();
185
- const sampling_rate = 0.69;
186
- const status = ["ok", "error"];
187
- const method = ["GET", "POST", "PUT"];
188
- const header = "X-HELLO:world";
189
- const client_ip = ["192.0.2.1", "self"];
190
- const query = "onlyTheseMessagesPlease";
191
-
192
- const cliFilters =
193
- `--sampling-rate ${sampling_rate} ` +
194
- status.map((s) => `--status ${s} `).join("") +
195
- method.map((m) => `--method ${m} `).join("") +
196
- `--header ${header} ` +
197
- client_ip.map((c) => `--ip ${c} `).join("") +
198
- `--search ${query} ` +
199
- `--debug`;
200
-
201
- const expectedWebsocketMessage = {
202
- filters: [
203
- { sampling_rate },
204
- { outcome: ["ok", "exception", "exceededCpu", "unknown"] },
205
- { method },
206
- { header: { key: "X-HELLO", query: "world" } },
207
- { client_ip },
208
- { query },
209
- ],
210
- debug: true,
211
- };
212
-
213
- await runWrangler(`tail test-worker ${cliFilters}`);
214
- await expect(api.nextMessageJson()).resolves.toEqual(
215
- expectedWebsocketMessage
216
- );
217
- });
218
- });
219
-
220
- describe("printing", () => {
221
- it("logs request messages in JSON format", async () => {
222
- const api = mockWebsocketAPIs();
223
- await runWrangler("tail test-worker --format json");
224
-
225
- const event = generateMockRequestEvent();
226
- const message = generateMockEventMessage({ event });
227
- const serializedMessage = serialize(message);
228
-
229
- api.ws.send(serializedMessage);
230
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
231
- });
232
-
233
- it("logs scheduled messages in JSON format", async () => {
234
- const api = mockWebsocketAPIs();
235
- await runWrangler("tail test-worker --format json");
236
-
237
- const event = generateMockScheduledEvent();
238
- const message = generateMockEventMessage({ event });
239
- const serializedMessage = serialize(message);
240
-
241
- api.ws.send(serializedMessage);
242
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
243
- });
244
-
245
- it("logs request messages in pretty format", async () => {
246
- const api = mockWebsocketAPIs();
247
- await runWrangler("tail test-worker --format pretty");
248
-
249
- const event = generateMockRequestEvent();
250
- const message = generateMockEventMessage({ event });
251
- const serializedMessage = serialize(message);
252
-
253
- api.ws.send(serializedMessage);
254
- expect(
255
- std.out
256
- .replace(
257
- new Date(mockEventTimestamp).toLocaleString(),
258
- "[mock event timestamp]"
259
- )
260
- .replace(
261
- mockTailExpiration.toLocaleString(),
262
- "[mock expiration date]"
263
- )
264
- ).toMatchInlineSnapshot(`
265
- "successfully created tail, expires at [mock expiration date]
266
- Connected to test-worker, waiting for logs...
267
- GET https://example.org/ - Ok @ [mock event timestamp]"
268
- `);
269
- });
270
-
271
- it("logs scheduled messages in pretty format", async () => {
272
- const api = mockWebsocketAPIs();
273
- await runWrangler("tail test-worker --format pretty");
274
-
275
- const event = generateMockScheduledEvent();
276
- const message = generateMockEventMessage({ event });
277
- const serializedMessage = serialize(message);
278
-
279
- api.ws.send(serializedMessage);
280
- expect(
281
- std.out
282
- .replace(
283
- new Date(mockEventTimestamp).toLocaleString(),
284
- "[mock timestamp string]"
285
- )
286
- .replace(
287
- mockTailExpiration.toLocaleString(),
288
- "[mock expiration date]"
289
- )
290
- ).toMatchInlineSnapshot(`
291
- "successfully created tail, expires at [mock expiration date]
292
- Connected to test-worker, waiting for logs...
293
- \\"* * * * *\\" @ [mock timestamp string] - Ok"
294
- `);
295
- });
296
- });
297
- });
298
-
299
- /* helpers */
300
-
301
- /**
302
- * The built in serialize-to-JSON feature of our mock websocket doesn't work
303
- * for our use-case since we actually expect a raw buffer,
304
- * not a Javascript string. Additionally, we have to do some fiddling
305
- * with `RequestEvent`s to get them to serialize properly.
306
- *
307
- * @param message a message to serialize to JSON
308
- * @returns the same type we expect when deserializing in wrangler
309
- */
310
- function serialize(message: TailEventMessage): WebSocket.RawData {
311
- if (isScheduled(message.event)) {
312
- // `ScheduledEvent`s work just fine
313
- const stringified = JSON.stringify(message);
314
- return Buffer.from(stringified, "utf-8");
315
- } else {
316
- // Since the "properties" of an `undici.Request` are actually getters,
317
- // which don't serialize properly, we need to hydrate them manually.
318
- // This isn't a problem outside of testing since deserialization
319
- // works just fine and wrangler never _sends_ any event messages,
320
- // it only receives them.
321
- const request = (message.event as RequestEvent).request;
322
- const stringified = JSON.stringify(message, (key, value) => {
323
- if (key !== "request") {
324
- return value;
325
- }
326
-
327
- return {
328
- ...request,
329
- url: request.url,
330
- headers: request.headers,
331
- method: request.method,
332
- };
333
- });
334
-
335
- return Buffer.from(stringified, "utf-8");
336
- }
337
- }
338
-
339
- /**
340
- * Small helper to disambiguate the event types possible in a `TailEventMessage`
341
- *
342
- * @param event A TailEvent
343
- * @returns whether event is a ScheduledEvent (true) or a RequestEvent
344
- */
345
- function isScheduled(
346
- event: ScheduledEvent | RequestEvent
347
- ): event is ScheduledEvent {
348
- return "cron" in event;
349
- }
350
-
351
- /**
352
- * Similarly, we need to deserialize from a raw buffer instead
353
- * of just JSON.parsing a raw string. This deserializer also then
354
- * re-stringifies with some spacing, the same way wrangler tail does.
355
- *
356
- * @param message a buffer of data received from the websocket
357
- * @returns a string ready to be printed to the terminal or compared against
358
- */
359
- function deserializeToJson(message: WebSocket.RawData): string {
360
- return JSON.stringify(JSON.parse(message.toString()), null, 2);
361
- }
362
-
363
- /**
364
- * A mock for all the different API resources wrangler accesses
365
- * when running `wrangler tail`
366
- */
367
- type MockAPI = {
368
- requests: {
369
- creation: RequestCounter;
370
- deletion: RequestCounter;
371
- };
372
- ws: MockWebSocket;
373
- nextMessageJson(): Promise<unknown>;
374
- };
375
-
376
- /**
377
- * A counter used to check how many times a mock API has been hit.
378
- * Useful as a helper in our testing to check if wrangler is making
379
- * the correct API calls without actually sending any web traffic
380
- */
381
- type RequestCounter = {
382
- count: number;
383
- };
384
-
385
- /**
386
- * Mock out the API hit during Tail creation
387
- *
388
- * @param websocketURL a fake URL for wrangler to connect a websocket to
389
- * @returns a `RequestCounter` for counting how many times the API is hit
390
- */
391
- function mockCreateTailRequest(
392
- websocketURL: string,
393
- env?: string,
394
- legacyEnv = false
395
- ): RequestCounter {
396
- const requests = { count: 0 };
397
- const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
398
- const environment = env && !legacyEnv ? "/environments/:envName" : "";
399
- setMockResponse(
400
- `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails`,
401
- "POST",
402
- ([_url, accountId, scriptName, envName]) => {
403
- requests.count++;
404
- expect(accountId).toEqual("some-account-id");
405
- expect(scriptName).toEqual(
406
- legacyEnv && env ? `test-worker-${env}` : "test-worker"
407
- );
408
- if (!legacyEnv) {
409
- expect(envName).toEqual(env);
410
- }
411
- return {
412
- id: "tail-id",
413
- url: websocketURL,
414
- expires_at: mockTailExpiration,
415
- };
416
- }
417
- );
418
-
419
- return requests;
420
- }
421
-
422
- /**
423
- * Mock expiration datetime for tails created during testing
424
- */
425
- const mockTailExpiration = new Date(3005, 1);
426
-
427
- /**
428
- * Default value for event timestamps
429
- */
430
- const mockEventTimestamp = 1645454470467;
431
-
432
- /**
433
- * Mock out the API hit during Tail deletion
434
- *
435
- * @returns a `RequestCounter` for counting how many times the API is hit
436
- */
437
- function mockDeleteTailRequest(
438
- env?: string,
439
- legacyEnv = false
440
- ): RequestCounter {
441
- const requests = { count: 0 };
442
- const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
443
- const environment = env && !legacyEnv ? "/environments/:envName" : "";
444
- setMockResponse(
445
- // "/accounts/:accountId/workers/scripts/:worker/tails",
446
- `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails/:tailId`,
447
- "DELETE",
448
- ([_url, accountId, scriptName, envNameOrTailId, tailId]) => {
449
- requests.count++;
450
- expect(accountId).toEqual("some-account-id");
451
- expect(scriptName).toEqual(
452
- legacyEnv && env ? `test-worker-${env}` : "test-worker"
453
- );
454
- if (!legacyEnv) {
455
- if (env) {
456
- expect(envNameOrTailId).toEqual(env);
457
- expect(tailId).toEqual("tail-id");
458
- } else {
459
- expect(envNameOrTailId).toEqual("tail-id");
460
- }
461
- } else {
462
- expect(envNameOrTailId).toEqual("tail-id");
463
- }
464
- return null;
465
- }
466
- );
467
-
468
- return requests;
469
- }
470
-
471
- const mockWebSockets: MockWebSocket[] = [];
472
-
473
- /**
474
- * All-in-one convenience method to mock the appropriate API calls before
475
- * each test, and clean up afterwards.
476
- *
477
- * @param websocketURL a fake websocket URL for wrangler to connect to
478
- * @returns a mocked-out version of the API
479
- */
480
- function mockWebsocketAPIs(env?: string, legacyEnv = false): MockAPI {
481
- const websocketURL = "ws://localhost:1234";
482
- const api: MockAPI = {
483
- requests: {
484
- deletion: { count: 0 },
485
- creation: { count: 0 },
486
- },
487
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
488
- ws: null!, // will be set in the `beforeEach()` below.
489
-
490
- /**
491
- * Parse the next message received by the mock websocket as JSON
492
- * @returns JSON.parse of the next message received by the websocket
493
- */
494
- async nextMessageJson() {
495
- const message = await api.ws.nextMessage;
496
- return JSON.parse(message as string);
497
- },
498
- };
499
- api.requests.creation = mockCreateTailRequest(websocketURL, env, legacyEnv);
500
- api.requests.deletion = mockDeleteTailRequest(env, legacyEnv);
501
- api.ws = new MockWebSocket(websocketURL);
502
- mockWebSockets.push(api.ws);
503
-
504
- return api;
505
- }
506
-
507
- /**
508
- * Generate a mock `TailEventMessage` of the same shape sent back by the
509
- * tail worker.
510
- *
511
- * @param opts Any specific parts of the message to use instead of defaults
512
- * @returns a `TailEventMessage` that wrangler can process and display
513
- */
514
- function generateMockEventMessage(
515
- opts?: Partial<TailEventMessage>
516
- ): TailEventMessage {
517
- return {
518
- outcome: opts?.outcome || "ok",
519
- exceptions: opts?.exceptions || [],
520
- logs: opts?.logs || [],
521
- eventTimestamp: opts?.eventTimestamp || mockEventTimestamp,
522
- event: opts?.event || generateMockRequestEvent(),
523
- };
524
- }
525
-
526
- /**
527
- * Generate a mock `RequestEvent` that, in an alternate timeline, was used
528
- * to trigger a worker. You can't disprove this!
529
- *
530
- * @param opts Any specific parts of the event to use instead of defaults
531
- * @returns a `RequestEvent` that can be used within an `EventMessage`
532
- */
533
- function generateMockRequestEvent(
534
- opts?: Partial<RequestEvent["request"]>
535
- ): RequestEvent {
536
- return {
537
- request: Object.assign(
538
- new Request(opts?.url || "https://example.org/", {
539
- method: opts?.method || "GET",
540
- headers:
541
- opts?.headers || new Headers({ "X-EXAMPLE-HEADER": "some_value" }),
542
- }),
543
- {
544
- cf: opts?.cf || {
545
- tlsCipher: "AEAD-ENCRYPT-O-MATIC-SHA",
546
- tlsVersion: "TLSv2.0",
547
- asn: 42069,
548
- colo: "ATL",
549
- httpProtocol: "HTTP/4",
550
- asOrganization: "Cloudflare",
551
- },
552
- }
553
- ),
554
- };
555
- }
556
-
557
- function generateMockScheduledEvent(
558
- opts?: Partial<ScheduledEvent>
559
- ): ScheduledEvent {
560
- return {
561
- cron: opts?.cron || "* * * * *",
562
- scheduledTime: opts?.scheduledTime || mockEventTimestamp,
563
- };
564
- }