wrangler 0.0.0-ddde8d4 → 0.0.0-e043479

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 (46) hide show
  1. package/package.json +7 -5
  2. package/src/__tests__/configuration.test.ts +2186 -0
  3. package/src/__tests__/dev.test.tsx +218 -75
  4. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  5. package/src/__tests__/helpers/mock-account-id.ts +18 -4
  6. package/src/__tests__/helpers/mock-console.ts +17 -9
  7. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  8. package/src/__tests__/helpers/write-wrangler-toml.ts +2 -5
  9. package/src/__tests__/index.test.ts +125 -49
  10. package/src/__tests__/jest.setup.ts +16 -4
  11. package/src/__tests__/kv.test.ts +399 -132
  12. package/src/__tests__/parse.test.ts +322 -0
  13. package/src/__tests__/publish.test.ts +791 -382
  14. package/src/__tests__/r2.test.ts +16 -24
  15. package/src/__tests__/secret.test.ts +299 -84
  16. package/src/__tests__/tail.test.ts +309 -176
  17. package/src/api/form_data.ts +43 -7
  18. package/src/api/preview.ts +36 -17
  19. package/src/api/worker.ts +18 -6
  20. package/src/bundle.ts +21 -15
  21. package/src/cfetch/index.ts +7 -5
  22. package/src/cfetch/internal.ts +24 -7
  23. package/src/config/README.md +107 -0
  24. package/src/config/config.ts +270 -0
  25. package/src/config/diagnostics.ts +80 -0
  26. package/src/config/environment.ts +305 -0
  27. package/src/config/index.ts +52 -0
  28. package/src/config/validation-helpers.ts +370 -0
  29. package/src/config/validation.ts +1019 -0
  30. package/src/dev.tsx +123 -49
  31. package/src/entry.ts +57 -0
  32. package/src/guess-worker-format.ts +1 -1
  33. package/src/index.tsx +631 -869
  34. package/src/kv.tsx +101 -44
  35. package/src/module-collection.ts +133 -47
  36. package/src/package-manager.ts +21 -15
  37. package/src/parse.ts +183 -0
  38. package/src/proxy.ts +18 -10
  39. package/src/publish.ts +70 -65
  40. package/src/sites.tsx +5 -11
  41. package/src/tail/index.ts +17 -7
  42. package/src/user.tsx +19 -5
  43. package/templates/tsconfig.json +105 -0
  44. package/wrangler-dist/cli.js +6177 -2424
  45. package/wrangler-dist/cli.js.map +3 -3
  46. package/src/config.ts +0 -671
@@ -1,31 +1,23 @@
1
- import { render } from "ink-testing-library";
1
+ import * as fs from "node:fs";
2
2
  import patchConsole from "patch-console";
3
- import React from "react";
4
3
  import Dev from "../dev";
4
+ import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
5
+ import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch";
5
6
  import { mockConsoleMethods } from "./helpers/mock-console";
7
+ import { runInTempDir } from "./helpers/run-in-tmp";
6
8
  import { runWrangler } from "./helpers/run-wrangler";
7
9
  import writeWranglerToml from "./helpers/write-wrangler-toml";
8
- import type { DevProps } from "../dev";
9
10
 
10
11
  describe("Dev component", () => {
11
- let restoreConsole: ReturnType<typeof patchConsole>;
12
- beforeEach(() => (restoreConsole = patchConsole(() => {})));
13
- afterEach(() => restoreConsole());
12
+ beforeEach(() => {});
13
+ mockAccountId();
14
+ mockApiToken();
15
+ runInTempDir();
14
16
  const std = mockConsoleMethods();
15
-
16
- // This test needs to be rewritten because the error now throws asynchronously
17
- // and the Ink framework does not yet have async testing support.
18
- it.skip("should throw if format is service-worker and there is a public directory", () => {
19
- const { lastFrame } = renderDev({
20
- format: "service-worker",
21
- accountId: "some-account-id",
22
- public: "some/public/path",
23
- });
24
- expect(lastFrame()?.split("\n").slice(0, 2).join("\n"))
25
- .toMatchInlineSnapshot(`
26
- "Something went wrong:
27
- Error: You cannot use the service worker format with a \`public\` directory."
28
- `);
17
+ afterEach(() => {
18
+ (Dev as jest.Mock).mockClear();
19
+ patchConsole(() => {});
20
+ unsetAllMocks();
29
21
  });
30
22
 
31
23
  describe("entry-points", () => {
@@ -35,70 +27,221 @@ describe("Dev component", () => {
35
27
  await expect(
36
28
  runWrangler("dev")
37
29
  ).rejects.toThrowErrorMatchingInlineSnapshot(
38
- `"Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`build.upload.main\` config field."`
30
+ `"Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`main\` config field."`
39
31
  );
40
32
 
41
33
  expect(std.out).toMatchInlineSnapshot(`""`);
42
34
  expect(std.err).toMatchInlineSnapshot(`
43
- "Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`build.upload.main\` config field.
35
+ "Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`main\` config field.
44
36
 
45
- %s
46
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
37
+ %s If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
47
38
  `);
48
39
  });
49
40
  });
41
+
42
+ describe("host", () => {
43
+ it("should resolve a host to its zone", async () => {
44
+ writeWranglerToml({
45
+ main: "index.js",
46
+ });
47
+ fs.writeFileSync("index.js", `export default {};`);
48
+ mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
49
+ await runWrangler("dev --host some-host.com");
50
+ expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({
51
+ host: "some-host.com",
52
+ id: "some-zone-id",
53
+ });
54
+ });
55
+
56
+ it("should read wrangler.toml's dev.host", async () => {
57
+ writeWranglerToml({
58
+ main: "index.js",
59
+ dev: {
60
+ host: "some-host.com",
61
+ },
62
+ });
63
+ fs.writeFileSync("index.js", `export default {};`);
64
+ mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
65
+ await runWrangler("dev");
66
+ expect((Dev as jest.Mock).mock.calls[0][0].zone.host).toEqual(
67
+ "some-host.com"
68
+ );
69
+ });
70
+
71
+ it("should read --route", async () => {
72
+ writeWranglerToml({
73
+ main: "index.js",
74
+ });
75
+ fs.writeFileSync("index.js", `export default {};`);
76
+ mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
77
+ await runWrangler("dev --route http://some-host.com/some/path/*");
78
+ expect((Dev as jest.Mock).mock.calls[0][0].zone.host).toEqual(
79
+ "some-host.com"
80
+ );
81
+ });
82
+
83
+ it("should read wrangler.toml's routes", async () => {
84
+ writeWranglerToml({
85
+ main: "index.js",
86
+ routes: [
87
+ "http://some-host.com/some/path/*",
88
+ "http://some-other-host.com/path/*",
89
+ ],
90
+ });
91
+ fs.writeFileSync("index.js", `export default {};`);
92
+ mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
93
+ await runWrangler("dev");
94
+ expect((Dev as jest.Mock).mock.calls[0][0].zone.host).toEqual(
95
+ "some-host.com"
96
+ );
97
+ });
98
+
99
+ it("should read wrangler.toml's environment specific routes", async () => {
100
+ writeWranglerToml({
101
+ main: "index.js",
102
+ routes: [
103
+ "http://a-host.com/some/path/*",
104
+ "http://another-host.com/path/*",
105
+ ],
106
+ env: {
107
+ staging: {
108
+ routes: [
109
+ "http://some-host.com/some/path/*",
110
+ "http://some-other-host.com/path/*",
111
+ ],
112
+ },
113
+ },
114
+ });
115
+ fs.writeFileSync("index.js", `export default {};`);
116
+ mockGetZones("some-host.com", [{ id: "some-zone-id" }]);
117
+ await runWrangler("dev --env staging");
118
+ expect((Dev as jest.Mock).mock.calls[0][0].zone.host).toEqual(
119
+ "some-host.com"
120
+ );
121
+ });
122
+
123
+ it("given a long host, it should use the longest subdomain that resolves to a zone", async () => {
124
+ writeWranglerToml({
125
+ main: "index.js",
126
+ });
127
+ fs.writeFileSync("index.js", `export default {};`);
128
+ mockGetZones("111.222.333.some-host.com", []);
129
+ mockGetZones("222.333.some-host.com", []);
130
+ mockGetZones("333.some-host.com", [{ id: "some-zone-id" }]);
131
+ await runWrangler("dev --host 111.222.333.some-host.com");
132
+ expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({
133
+ host: "111.222.333.some-host.com",
134
+ id: "some-zone-id",
135
+ });
136
+ });
137
+
138
+ it("should, in order, use args.host/config.dev.host/args.routes/config.route/config.routes", async () => {
139
+ // This test might seem like it's testing implmentation details, but let's be specific and consider it a spec
140
+
141
+ fs.writeFileSync("index.js", `export default {};`);
142
+
143
+ // config.routes
144
+ mockGetZones("5.some-host.com", [{ id: "some-zone-id-5" }]);
145
+ writeWranglerToml({
146
+ main: "index.js",
147
+ routes: ["http://5.some-host.com/some/path/*"],
148
+ });
149
+ await runWrangler("dev");
150
+ expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({
151
+ host: "5.some-host.com",
152
+ id: "some-zone-id-5",
153
+ });
154
+ (Dev as jest.Mock).mockClear();
155
+
156
+ // config.route
157
+ mockGetZones("4.some-host.com", [{ id: "some-zone-id-4" }]);
158
+ writeWranglerToml({
159
+ main: "index.js",
160
+ route: "https://4.some-host.com/some/path/*",
161
+ routes: ["http://5.some-host.com/some/path/*"],
162
+ });
163
+ await runWrangler("dev");
164
+ expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({
165
+ host: "4.some-host.com",
166
+ id: "some-zone-id-4",
167
+ });
168
+ (Dev as jest.Mock).mockClear();
169
+
170
+ // --routes
171
+ mockGetZones("3.some-host.com", [{ id: "some-zone-id-3" }]);
172
+ writeWranglerToml({
173
+ main: "index.js",
174
+ route: "https://4.some-host.com/some/path/*",
175
+ routes: ["http://5.some-host.com/some/path/*"],
176
+ });
177
+ await runWrangler("dev --routes http://3.some-host.com/some/path/*");
178
+ expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({
179
+ host: "3.some-host.com",
180
+ id: "some-zone-id-3",
181
+ });
182
+ (Dev as jest.Mock).mockClear();
183
+
184
+ // config.dev.host
185
+ mockGetZones("2.some-host.com", [{ id: "some-zone-id-2" }]);
186
+ writeWranglerToml({
187
+ main: "index.js",
188
+ dev: {
189
+ host: `2.some-host.com`,
190
+ },
191
+ route: "4.some-host.com/some/path/*",
192
+ routes: ["5.some-host.com/some/path/*"],
193
+ });
194
+ await runWrangler("dev --routes http://3.some-host.com/some/path/*");
195
+ expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({
196
+ host: "2.some-host.com",
197
+ id: "some-zone-id-2",
198
+ });
199
+ (Dev as jest.Mock).mockClear();
200
+
201
+ // --host
202
+ mockGetZones("1.some-host.com", [{ id: "some-zone-id-1" }]);
203
+ writeWranglerToml({
204
+ main: "index.js",
205
+ dev: {
206
+ host: `2.some-host.com`,
207
+ },
208
+ route: "4.some-host.com/some/path/*",
209
+ routes: ["5.some-host.com/some/path/*"],
210
+ });
211
+ await runWrangler(
212
+ "dev --routes http://3.some-host.com/some/path/* --host 1.some-host.com"
213
+ );
214
+ expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({
215
+ host: "1.some-host.com",
216
+ id: "some-zone-id-1",
217
+ });
218
+ (Dev as jest.Mock).mockClear();
219
+ });
220
+
221
+ it("should error if a host can't resolve to a zone", async () => {
222
+ writeWranglerToml({
223
+ main: "index.js",
224
+ });
225
+ fs.writeFileSync("index.js", `export default {};`);
226
+ mockGetZones("some-host.com", []);
227
+ await expect(
228
+ runWrangler("dev --host some-host.com")
229
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
230
+ `"Could not find zone for some-host.com"`
231
+ );
232
+ });
233
+ });
50
234
  });
51
235
 
52
- /**
53
- * Helper function to make it easier to setup and render the `Dev` component.
54
- *
55
- * All the `Dev` props are optional here, with sensible defaults for testing.
56
- */
57
- function renderDev({
58
- name,
59
- entry = { file: "some/entry.ts", directory: process.cwd() },
60
- port,
61
- format,
62
- accountId,
63
- initialMode = "local",
64
- jsxFactory,
65
- jsxFragment,
66
- bindings = {
67
- kv_namespaces: [],
68
- vars: {},
69
- durable_objects: { bindings: [] },
70
- r2_buckets: [],
71
- wasm_modules: {},
72
- unsafe: [],
73
- },
74
- public: publicDir,
75
- assetPaths,
76
- compatibilityDate,
77
- compatibilityFlags,
78
- usageModel,
79
- buildCommand = {},
80
- enableLocalPersistence = false,
81
- env = undefined,
82
- }: Partial<DevProps>) {
83
- return render(
84
- <Dev
85
- name={name}
86
- entry={entry}
87
- env={env}
88
- port={port}
89
- buildCommand={buildCommand}
90
- format={format}
91
- initialMode={initialMode}
92
- jsxFactory={jsxFactory}
93
- jsxFragment={jsxFragment}
94
- accountId={accountId}
95
- assetPaths={assetPaths}
96
- public={publicDir}
97
- compatibilityDate={compatibilityDate}
98
- compatibilityFlags={compatibilityFlags}
99
- usageModel={usageModel}
100
- bindings={bindings}
101
- enableLocalPersistence={enableLocalPersistence}
102
- />
236
+ function mockGetZones(domain: string, zones: { id: string }[] = []) {
237
+ const removeMock = setMockResponse(
238
+ "/zones",
239
+ "GET",
240
+ (_urlPieces, _init, queryParams) => {
241
+ expect([...queryParams.entries()]).toEqual([["name", domain]]);
242
+ // Because the API URL `/zones` is the same for each request, we can get into a situation where earlier mocks get triggered for later requests. So, we simply clear the mock on every trigger.
243
+ removeMock();
244
+ return zones;
245
+ }
103
246
  );
104
247
  }
@@ -0,0 +1,6 @@
1
+ module "faye-websocket" {
2
+ /**
3
+ * Standards-compliant WebSocket client and server.
4
+ */
5
+ export default WebSocket;
6
+ }
@@ -3,12 +3,19 @@ const ORIGINAL_CLOUDFLARE_ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID;
3
3
 
4
4
  /**
5
5
  * Mock the API token so that we don't need to read it from user configuration files.
6
+ *
7
+ * Note that you can remove any API token from the environment by setting the value to `null`.
8
+ * This is useful if a higher `describe()` block has already called `mockApiToken()`.
6
9
  */
7
10
  export function mockApiToken({
8
11
  apiToken = "some-api-token",
9
- }: { apiToken?: string } = {}) {
12
+ }: { apiToken?: string | null } = {}) {
10
13
  beforeEach(() => {
11
- process.env.CLOUDFLARE_API_TOKEN = apiToken;
14
+ if (apiToken === null) {
15
+ delete process.env.CLOUDFLARE_API_TOKEN;
16
+ } else {
17
+ process.env.CLOUDFLARE_API_TOKEN = apiToken;
18
+ }
12
19
  });
13
20
  afterEach(() => {
14
21
  process.env.CLOUDFLARE_API_TOKEN = ORIGINAL_CLOUDFLARE_API_TOKEN;
@@ -17,12 +24,19 @@ export function mockApiToken({
17
24
 
18
25
  /**
19
26
  * Mock the current account ID so that we don't need to read it from configuration files.
27
+ *
28
+ * Note that you can remove any account ID from the environment by setting the value to `null`.
29
+ * This is useful if a higher `describe()` block has already called `mockAccountId()`.
20
30
  */
21
31
  export function mockAccountId({
22
32
  accountId = "some-account-id",
23
- }: { accountId?: string } = {}) {
33
+ }: { accountId?: string | null } = {}) {
24
34
  beforeEach(() => {
25
- process.env.CLOUDFLARE_ACCOUNT_ID = accountId;
35
+ if (accountId === null) {
36
+ delete process.env.CLOUDFLARE_ACCOUNT_ID;
37
+ } else {
38
+ process.env.CLOUDFLARE_ACCOUNT_ID = accountId;
39
+ }
26
40
  });
27
41
  afterEach(() => {
28
42
  process.env.CLOUDFLARE_ACCOUNT_ID = ORIGINAL_CLOUDFLARE_ACCOUNT_ID;
@@ -1,3 +1,5 @@
1
+ import * as util from "node:util";
2
+
1
3
  /**
2
4
  * We use this module to mock console methods, and optionally
3
5
  * assert on the values they're called with in our tests.
@@ -9,22 +11,28 @@ let logSpy: jest.SpyInstance,
9
11
 
10
12
  const std = {
11
13
  get out() {
12
- return stripTrailingWhitespace(
13
- normalizeSlashes(stripTimings(logSpy.mock.calls.flat(2).join("\n")))
14
- );
14
+ return normalizeOutput(logSpy);
15
15
  },
16
16
  get err() {
17
- return stripTrailingWhitespace(
18
- normalizeSlashes(stripTimings(errorSpy.mock.calls.flat(2).join("\n")))
19
- );
17
+ return normalizeOutput(errorSpy);
20
18
  },
21
19
  get warn() {
22
- return stripTrailingWhitespace(
23
- normalizeSlashes(stripTimings(warnSpy.mock.calls.flat(2).join("\n")))
24
- );
20
+ return normalizeOutput(warnSpy);
25
21
  },
26
22
  };
27
23
 
24
+ function normalizeOutput(spy: jest.SpyInstance): string {
25
+ return stripTrailingWhitespace(
26
+ normalizeSlashes(stripTimings(captureCalls(spy)))
27
+ );
28
+ }
29
+
30
+ function captureCalls(spy: jest.SpyInstance): string {
31
+ return spy.mock.calls
32
+ .map((args: unknown[]) => util.format("%s", ...args))
33
+ .join("\n");
34
+ }
35
+
28
36
  export function mockConsoleMethods() {
29
37
  beforeEach(() => {
30
38
  logSpy = jest.spyOn(console, "log").mockImplementation();
@@ -0,0 +1,103 @@
1
+ const ORIGINAL_STDIN = process.stdin;
2
+
3
+ /**
4
+ * Mock process.stdin so that we can pipe in text for non-interactive mode tests.
5
+ */
6
+ export function useMockStdin({ isTTY }: { isTTY: boolean }) {
7
+ const mockStdin = new MockStdIn(isTTY);
8
+
9
+ beforeEach(() => {
10
+ mockStdin.reset();
11
+ Object.defineProperty(process, "stdin", {
12
+ value: mockStdin,
13
+ configurable: true,
14
+ writable: false,
15
+ });
16
+ });
17
+
18
+ afterEach(() => {
19
+ Object.defineProperty(process, "stdin", {
20
+ value: ORIGINAL_STDIN,
21
+ configurable: true,
22
+ writable: false,
23
+ });
24
+ });
25
+
26
+ return mockStdin;
27
+ }
28
+
29
+ const failCallback: (value: unknown) => void = () => {
30
+ throw new Error(
31
+ "TEST FAILURE: stdin callback called before being initialized."
32
+ );
33
+ };
34
+
35
+ /**
36
+ * A mock version of `process.std`, which can be used to simulate piping data
37
+ * into the wrangler process in non-interactive mode.
38
+ */
39
+ class MockStdIn {
40
+ private endCallback = failCallback;
41
+ private errorCallback = failCallback;
42
+ private chunks: string[] = [];
43
+ private error: Error | undefined;
44
+
45
+ /**
46
+ * Set this to true if you want the stdin stream to error.
47
+ */
48
+ throwError(error: Error) {
49
+ this.error = error;
50
+ }
51
+
52
+ /**
53
+ * Call this to clean out the chunks that are queued for sending.
54
+ */
55
+ reset() {
56
+ this.chunks.length = 0;
57
+ this.error = undefined;
58
+ }
59
+
60
+ /**
61
+ * Queue up some chunks to be sent.
62
+ */
63
+ send(...chunks: string[]) {
64
+ this.chunks.push(...chunks);
65
+ }
66
+
67
+ constructor(
68
+ /**
69
+ * Used by wrangler to check whether stdin is interactive.
70
+ */
71
+ readonly isTTY: boolean
72
+ ) {}
73
+
74
+ /**
75
+ * Used by wrangler to add event listeners.
76
+ */
77
+ on(eventName: string, callback: () => void) {
78
+ switch (eventName) {
79
+ case "readable":
80
+ setImmediate(callback);
81
+ break;
82
+ case "end":
83
+ this.endCallback = callback;
84
+ break;
85
+ case "error":
86
+ this.errorCallback = callback;
87
+ break;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Used by wrangler to get the next chunk of data in the stream.
93
+ */
94
+ read() {
95
+ if (this.error) {
96
+ setImmediate(() => this.errorCallback(this.error));
97
+ }
98
+ if (this.chunks.length === 0) {
99
+ setImmediate(this.endCallback);
100
+ }
101
+ return this.chunks.shift() ?? null;
102
+ }
103
+ }
@@ -1,12 +1,9 @@
1
1
  import * as fs from "fs";
2
2
  import TOML from "@iarna/toml";
3
- import type { Config } from "../../config";
3
+ import type { RawConfig } from "../../config";
4
4
 
5
5
  /** Write a mock wrangler.toml file to disk. */
6
- export default function writeWranglerToml(config: Omit<Config, "env"> = {}) {
7
- // We Omit `env` from config because TOML.stringify() appears to
8
- // have a weird type signature that appears to fail. We'll revisit this
9
- // when we write tests for publishing environments
6
+ export default function writeWranglerToml(config: RawConfig = {}) {
10
7
  fs.writeFileSync(
11
8
  "./wrangler.toml",
12
9
  TOML.stringify({