wrangler 0.0.0-e22f9d7 → 0.0.0-e2a26a0

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 (54) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +15 -10
  3. package/pages/functions/buildWorker.ts +1 -1
  4. package/pages/functions/filepath-routing.test.ts +21 -13
  5. package/pages/functions/filepath-routing.ts +38 -28
  6. package/pages/functions/routes.ts +8 -6
  7. package/pages/functions/template-worker.ts +16 -24
  8. package/src/__tests__/dev.test.tsx +7 -3
  9. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  10. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  11. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  12. package/src/__tests__/helpers/mock-bin.ts +33 -0
  13. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +49 -13
  14. package/src/__tests__/helpers/mock-console.ts +56 -0
  15. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  16. package/src/__tests__/helpers/mock-kv.ts +40 -0
  17. package/src/__tests__/helpers/mock-user.ts +27 -0
  18. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  19. package/src/__tests__/helpers/run-wrangler.ts +14 -0
  20. package/src/__tests__/index.test.ts +312 -56
  21. package/src/__tests__/jest.setup.ts +17 -2
  22. package/src/__tests__/kv.test.ts +344 -316
  23. package/src/__tests__/logout.test.ts +50 -0
  24. package/src/__tests__/package-manager.test.ts +206 -0
  25. package/src/__tests__/publish.test.ts +1222 -0
  26. package/src/__tests__/secret.test.ts +210 -0
  27. package/src/__tests__/whoami.test.tsx +86 -0
  28. package/src/api/form_data.ts +10 -7
  29. package/src/api/preview.ts +2 -2
  30. package/src/api/worker.ts +3 -3
  31. package/src/cfetch/index.ts +14 -14
  32. package/src/cfetch/internal.ts +40 -8
  33. package/src/config.ts +162 -8
  34. package/src/dev.tsx +103 -53
  35. package/src/dialogs.tsx +2 -2
  36. package/src/index.tsx +438 -311
  37. package/src/inspect.ts +80 -23
  38. package/src/kv.tsx +9 -1
  39. package/src/module-collection.ts +5 -6
  40. package/src/package-manager.ts +120 -0
  41. package/src/pages.tsx +41 -26
  42. package/src/paths.ts +26 -0
  43. package/src/proxy.ts +78 -10
  44. package/src/publish.ts +98 -52
  45. package/src/sites.tsx +175 -53
  46. package/src/user.tsx +51 -59
  47. package/src/whoami.tsx +69 -0
  48. package/templates/new-worker.js +15 -0
  49. package/templates/new-worker.ts +15 -0
  50. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  51. package/wrangler-dist/cli.js +111479 -110187
  52. package/wrangler-dist/cli.js.map +3 -3
  53. package/src/__tests__/run-in-tmp.ts +0 -19
  54. package/src/__tests__/run-wrangler.ts +0 -32
@@ -0,0 +1,210 @@
1
+ import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
2
+ import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch";
3
+ import { mockConsoleMethods } from "./helpers/mock-console";
4
+ import { mockConfirm, mockPrompt } from "./helpers/mock-dialogs";
5
+ import { runInTempDir } from "./helpers/run-in-tmp";
6
+ import { runWrangler } from "./helpers/run-wrangler";
7
+
8
+ describe("wrangler secret", () => {
9
+ const std = mockConsoleMethods();
10
+ runInTempDir();
11
+ mockAccountId();
12
+ mockApiToken();
13
+
14
+ afterEach(() => {
15
+ unsetAllMocks();
16
+ });
17
+
18
+ describe("put", () => {
19
+ function mockPutRequest(input: { name: string; text: string }) {
20
+ setMockResponse(
21
+ "/accounts/:accountId/workers/scripts/:scriptName/secrets",
22
+ "PUT",
23
+ ([_url, accountId], { body }) => {
24
+ expect(accountId).toEqual("some-account-id");
25
+ const { name, text, type } = JSON.parse(body as string);
26
+ expect(type).toEqual("secret_text");
27
+ expect(name).toEqual(input.name);
28
+ expect(text).toEqual(input.text);
29
+
30
+ return { name, type };
31
+ }
32
+ );
33
+ }
34
+
35
+ it("should create a secret", async () => {
36
+ mockPrompt({
37
+ text: "Enter a secret value:",
38
+ type: "password",
39
+ result: "the-secret",
40
+ });
41
+
42
+ mockPutRequest({ name: "the-secret-name", text: "the-secret" });
43
+ await runWrangler("secret put the-key --name script-name");
44
+
45
+ expect(std.out).toMatchInlineSnapshot(`
46
+ "🌀 Creating the secret for script script-name
47
+ ✨ Success! Uploaded secret the-key"
48
+ `);
49
+ expect(std.err).toMatchInlineSnapshot(`""`);
50
+ });
51
+
52
+ it("should error without a script name", async () => {
53
+ let error: Error | undefined;
54
+ try {
55
+ await runWrangler("secret put the-key");
56
+ } catch (e) {
57
+ error = e;
58
+ }
59
+ expect(std.out).toMatchInlineSnapshot(`""`);
60
+ expect(std.err).toMatchInlineSnapshot(`
61
+ "Missing script name
62
+
63
+ %s
64
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
65
+ `);
66
+ expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
67
+ });
68
+
69
+ it("warns about being a no-op in local mode", async () => {
70
+ mockPrompt({
71
+ text: "Enter a secret value:",
72
+ type: "password",
73
+ result: "the-secret",
74
+ });
75
+
76
+ mockPutRequest({ name: "the-secret-name", text: "the-secret" });
77
+ await runWrangler("secret put the-key --name script-name --local");
78
+ expect(std.out).toMatchInlineSnapshot(`""`);
79
+ expect(std.err).toMatchInlineSnapshot(`""`);
80
+ expect(std.warn).toMatchInlineSnapshot(
81
+ `"\`wrangler secret put\` is a no-op in --local mode"`
82
+ );
83
+ });
84
+ });
85
+
86
+ describe("delete", () => {
87
+ function mockDeleteRequest(input: {
88
+ scriptName: string;
89
+ secretName: string;
90
+ }) {
91
+ setMockResponse(
92
+ "/accounts/:accountId/workers/scripts/:scriptName/secrets/:secretName",
93
+ "DELETE",
94
+ ([_url, accountId, scriptName, secretName]) => {
95
+ expect(accountId).toEqual("some-account-id");
96
+ expect(scriptName).toEqual(input.scriptName);
97
+ expect(secretName).toEqual(input.secretName);
98
+
99
+ return null;
100
+ }
101
+ );
102
+ }
103
+ it("should delete a secret", async () => {
104
+ mockDeleteRequest({ scriptName: "script-name", secretName: "the-key" });
105
+ mockConfirm({
106
+ text: "Are you sure you want to permanently delete the variable the-key on the script script-name?",
107
+ result: true,
108
+ });
109
+ await runWrangler("secret delete the-key --name script-name");
110
+ expect(std.out).toMatchInlineSnapshot(`
111
+ "🌀 Deleting the secret the-key on script script-name.
112
+ ✨ Success! Deleted secret the-key"
113
+ `);
114
+ expect(std.err).toMatchInlineSnapshot(`""`);
115
+ });
116
+
117
+ it("should error without a script name", async () => {
118
+ let error: Error | undefined;
119
+
120
+ try {
121
+ await runWrangler("secret delete the-key");
122
+ } catch (e) {
123
+ error = e;
124
+ }
125
+ expect(std.out).toMatchInlineSnapshot(`""`);
126
+ expect(std.err).toMatchInlineSnapshot(`
127
+ "Missing script name
128
+
129
+ %s
130
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
131
+ `);
132
+ expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
133
+ });
134
+
135
+ it("warns about being a no-op in local mode", async () => {
136
+ mockConfirm({
137
+ text: "Are you sure you want to permanently delete the variable the-key on the script script-name?",
138
+ result: true,
139
+ });
140
+ await runWrangler("secret delete the-key --name script-name --local");
141
+ expect(std.out).toMatchInlineSnapshot(
142
+ `"🌀 Deleting the secret the-key on script script-name."`
143
+ );
144
+ expect(std.err).toMatchInlineSnapshot(`""`);
145
+ expect(std.warn).toMatchInlineSnapshot(
146
+ `"\`wrangler secret delete\` is a no-op in --local mode"`
147
+ );
148
+ });
149
+ });
150
+
151
+ describe("list", () => {
152
+ function mockListRequest(input: { scriptName: string }) {
153
+ setMockResponse(
154
+ "/accounts/:accountId/workers/scripts/:scriptName/secrets",
155
+ "GET",
156
+ ([_url, accountId, scriptName]) => {
157
+ expect(accountId).toEqual("some-account-id");
158
+ expect(scriptName).toEqual(input.scriptName);
159
+
160
+ return [
161
+ {
162
+ name: "the-secret-name",
163
+ type: "secret_text",
164
+ },
165
+ ];
166
+ }
167
+ );
168
+ }
169
+
170
+ it("should list secrets", async () => {
171
+ mockListRequest({ scriptName: "script-name" });
172
+ await runWrangler("secret list --name script-name");
173
+ expect(std.out).toMatchInlineSnapshot(`
174
+ "[
175
+ {
176
+ \\"name\\": \\"the-secret-name\\",
177
+ \\"type\\": \\"secret_text\\"
178
+ }
179
+ ]"
180
+ `);
181
+ expect(std.err).toMatchInlineSnapshot(`""`);
182
+ });
183
+
184
+ it("should error without a script name", async () => {
185
+ let error: Error | undefined;
186
+ try {
187
+ await runWrangler("secret list");
188
+ } catch (e) {
189
+ error = e;
190
+ }
191
+ expect(std.out).toMatchInlineSnapshot(`""`);
192
+ expect(std.err).toMatchInlineSnapshot(`
193
+ "Missing script name
194
+
195
+ %s
196
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
197
+ `);
198
+ expect(error).toMatchInlineSnapshot(`[Error: Missing script name]`);
199
+ });
200
+
201
+ it("warns about being a no-op in local mode", async () => {
202
+ await runWrangler("secret list --name script-name --local");
203
+ expect(std.out).toMatchInlineSnapshot(`""`);
204
+ expect(std.err).toMatchInlineSnapshot(`""`);
205
+ expect(std.warn).toMatchInlineSnapshot(
206
+ `"\`wrangler secret list\` is a no-op in --local mode"`
207
+ );
208
+ });
209
+ });
210
+ });
@@ -0,0 +1,86 @@
1
+ import { render } from "ink-testing-library";
2
+ import React from "react";
3
+ import { initialise } from "../user";
4
+ import { getUserInfo, WhoAmI } from "../whoami";
5
+ import { setMockResponse } from "./helpers/mock-cfetch";
6
+ import { writeUserConfig } from "./helpers/mock-user";
7
+ import { runInTempDir } from "./helpers/run-in-tmp";
8
+ import type { UserInfo } from "../whoami";
9
+
10
+ describe("getUserInfo()", () => {
11
+ runInTempDir({ homedir: "./home" });
12
+
13
+ it("should return undefined if there is no config file", async () => {
14
+ await initialise();
15
+ const userInfo = await getUserInfo();
16
+ expect(userInfo).toBeUndefined();
17
+ });
18
+
19
+ it("should return undefined if there is an empty config file", async () => {
20
+ writeUserConfig();
21
+ await initialise();
22
+ const userInfo = await getUserInfo();
23
+ expect(userInfo).toBeUndefined();
24
+ });
25
+
26
+ it("should return the user's email and accounts if authenticated via config token", async () => {
27
+ writeUserConfig("some-oauth-token");
28
+ setMockResponse("/user", () => {
29
+ return { email: "user@example.com" };
30
+ });
31
+ setMockResponse("/accounts", () => {
32
+ return [
33
+ { name: "Account One", id: "account-1" },
34
+ { name: "Account Two", id: "account-2" },
35
+ { name: "Account Three", id: "account-3" },
36
+ ];
37
+ });
38
+
39
+ await initialise();
40
+ const userInfo = await getUserInfo();
41
+
42
+ expect(userInfo).toEqual({
43
+ authType: "OAuth",
44
+ apiToken: "some-oauth-token",
45
+ email: "user@example.com",
46
+ accounts: [
47
+ { name: "Account One", id: "account-1" },
48
+ { name: "Account Two", id: "account-2" },
49
+ { name: "Account Three", id: "account-3" },
50
+ ],
51
+ });
52
+ });
53
+ });
54
+
55
+ describe("WhoAmI component", () => {
56
+ it("should return undefined if there is no user", async () => {
57
+ const { lastFrame } = render(<WhoAmI user={undefined}></WhoAmI>);
58
+
59
+ expect(lastFrame()).toMatchInlineSnapshot(
60
+ `"You are not authenticated. Please run \`wrangler login\`."`
61
+ );
62
+ });
63
+
64
+ it("should display the user's email and accounts", async () => {
65
+ const user: UserInfo = {
66
+ authType: "OAuth",
67
+ apiToken: "some-oauth-token",
68
+ email: "user@example.com",
69
+ accounts: [
70
+ { name: "Account One", id: "account-1" },
71
+ { name: "Account Two", id: "account-2" },
72
+ { name: "Account Three", id: "account-3" },
73
+ ],
74
+ };
75
+
76
+ const { lastFrame } = render(<WhoAmI user={user}></WhoAmI>);
77
+
78
+ expect(lastFrame()).toContain(
79
+ "You are logged in with an OAuth Token, associated with the email 'user@example.com'!"
80
+ );
81
+ expect(lastFrame()).toMatch(/Account Name .+ Account ID/);
82
+ expect(lastFrame()).toMatch(/Account One .+ account-1/);
83
+ expect(lastFrame()).toMatch(/Account Two .+ account-2/);
84
+ expect(lastFrame()).toMatch(/Account Three .+ account-3/);
85
+ });
86
+ });
@@ -1,10 +1,10 @@
1
+ import { FormData, File } from "undici";
1
2
  import type {
2
3
  CfWorkerInit,
3
4
  CfModuleType,
4
5
  CfModule,
5
6
  CfDurableObjectMigrations,
6
7
  } from "./worker.js";
7
- import { FormData, Blob } from "formdata-node";
8
8
 
9
9
  export function toMimeType(type: CfModuleType): string {
10
10
  switch (type) {
@@ -23,14 +23,17 @@ export function toMimeType(type: CfModuleType): string {
23
23
  }
24
24
  }
25
25
 
26
- function toModule(module: CfModule, entryType: CfModuleType): Blob {
26
+ function toModule(module: CfModule, entryType: CfModuleType): File {
27
27
  const { type: moduleType, content } = module;
28
28
  const type = toMimeType(moduleType ?? entryType);
29
-
30
- return new Blob([content], { type });
29
+ return new File([content], module.name, { type });
31
30
  }
32
31
 
33
- interface WorkerMetadata {
32
+ export interface WorkerMetadata {
33
+ /** The name of the entry point module. Only exists when the worker is in the ES module format */
34
+ main_module?: string;
35
+ /** The name of the entry point module. Only exists when the worker is in the Service Worker format */
36
+ body_part?: string;
34
37
  compatibility_date?: string;
35
38
  compatibility_flags?: string[];
36
39
  usage_model?: "bundled" | "unbound";
@@ -123,8 +126,8 @@ export function toFormData(worker: CfWorkerInit): FormData {
123
126
 
124
127
  for (const module of [main].concat(modules || [])) {
125
128
  const { name } = module;
126
- const blob = toModule(module, main.type ?? "esm");
127
- formData.set(name, blob, name);
129
+ const file = toModule(module, main.type ?? "esm");
130
+ formData.set(name, file);
128
131
  }
129
132
 
130
133
  return formData;
@@ -1,4 +1,5 @@
1
- import fetch from "node-fetch";
1
+ import { URL } from "node:url";
2
+ import { fetch } from "undici";
2
3
  import { fetchResult } from "../cfetch";
3
4
  import { toFormData } from "./form_data";
4
5
  import type { CfAccount, CfWorkerInit } from "./worker";
@@ -108,7 +109,6 @@ export async function previewToken(
108
109
 
109
110
  const { preview_token } = await fetchResult<{ preview_token: string }>(url, {
110
111
  method: "POST",
111
- // @ts-expect-error TODO: fix this
112
112
  body: formData,
113
113
  headers: {
114
114
  "cf-preview-upload-config-token": value,
package/src/api/worker.ts CHANGED
@@ -1,6 +1,6 @@
1
- import type { CfPreviewToken } from "./preview";
1
+ import { fetch } from "undici";
2
2
  import { previewToken } from "./preview";
3
- import fetch from "node-fetch";
3
+ import type { CfPreviewToken } from "./preview";
4
4
 
5
5
  /**
6
6
  * A Cloudflare account.
@@ -53,7 +53,7 @@ export interface CfModule {
53
53
  * }
54
54
  * }
55
55
  */
56
- content: string | BufferSource;
56
+ content: string | Buffer;
57
57
  /**
58
58
  * The module type.
59
59
  *
@@ -1,6 +1,6 @@
1
- import type { RequestInit } from "node-fetch";
2
- import { URLSearchParams } from "url";
1
+ import { URLSearchParams } from "node:url";
3
2
  import { fetchInternal } from "./internal";
3
+ import type { RequestInit } from "undici";
4
4
 
5
5
  // Check out https://api.cloudflare.com/ for API docs.
6
6
 
@@ -18,16 +18,7 @@ export interface FetchResult<ResponseType = unknown> {
18
18
  result_info?: unknown;
19
19
  }
20
20
 
21
- /**
22
- * Make a fetch request for a raw JSON value.
23
- */
24
- export async function fetchRaw<ResponseType>(
25
- resource: string,
26
- init: RequestInit = {},
27
- queryParams?: URLSearchParams
28
- ): Promise<ResponseType> {
29
- return fetchInternal<ResponseType>(resource, init, queryParams);
30
- }
21
+ export { fetchKVGetValue } from "./internal";
31
22
 
32
23
  /**
33
24
  * Make a fetch request, and extract the `result` from the JSON response.
@@ -94,9 +85,18 @@ function throwFetchError(
94
85
  const errors = response.errors
95
86
  .map((error) => `${error.code}: ${error.message}`)
96
87
  .join("\n");
97
- throw new Error(`Failed to fetch ${resource} - ${errors}`);
88
+ const error = new Error(`Failed to fetch ${resource} - \n${errors}`);
89
+ // add the first error code directly to this error
90
+ // so consumers can use it for specific behaviour
91
+ const code = response.errors[0]?.code;
92
+ if (code) {
93
+ //@ts-expect-error non-standard property on Error
94
+ error.code = code;
95
+ }
96
+ throw error;
98
97
  }
99
98
 
100
99
  function hasCursor(result_info: unknown): result_info is { cursor: string } {
101
- return (result_info as { cursor } | undefined)?.cursor !== undefined;
100
+ const cursor = (result_info as { cursor: string } | undefined)?.cursor;
101
+ return cursor !== undefined && cursor !== null && cursor !== "";
102
102
  }
@@ -1,6 +1,7 @@
1
- import fetch from "node-fetch";
2
- import type { RequestInit, HeadersInit } from "node-fetch";
1
+ import { fetch } from "undici";
3
2
  import { getAPIToken, loginOrRefreshIfRequired } from "../user";
3
+ import type { URLSearchParams } from "node:url";
4
+ import type { RequestInit, HeadersInit } from "undici";
4
5
 
5
6
  export const CF_API_BASE_URL =
6
7
  process.env.CF_API_BASE_URL || "https://api.cloudflare.com/client/v4";
@@ -30,17 +31,18 @@ export async function fetchInternal<ResponseType>(
30
31
  ...init,
31
32
  headers,
32
33
  });
33
-
34
- if (response.ok) {
35
- return (await response.json()) as ResponseType;
36
- } else {
34
+ const jsonText = await response.text();
35
+ try {
36
+ const json = JSON.parse(jsonText);
37
+ return json as ResponseType;
38
+ } catch (e) {
37
39
  throw new Error(
38
- `Failed to fetch ${resource} - ${response.status}: ${response.statusText}`
40
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText}\nInvalid JSON response:\n${jsonText}`
39
41
  );
40
42
  }
41
43
  }
42
44
 
43
- function cloneHeaders(headers: HeadersInit): HeadersInit {
45
+ function cloneHeaders(headers: HeadersInit | undefined): HeadersInit {
44
46
  return { ...headers };
45
47
  }
46
48
 
@@ -67,3 +69,33 @@ function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void {
67
69
  }
68
70
  headers["Authorization"] = `Bearer ${apiToken}`;
69
71
  }
72
+
73
+ /**
74
+ * The implementation for fetching a kv value from the cloudflare API.
75
+ * We special-case this one call, because it's the only API call that
76
+ * doesn't return json. We inline the implementation and try not to share
77
+ * any code with the other calls. We should push back on any new APIs that
78
+ * try to introduce non-"standard" response structures.
79
+ */
80
+
81
+ export async function fetchKVGetValue(
82
+ accountId: string,
83
+ namespaceId: string,
84
+ key: string
85
+ ): Promise<string> {
86
+ await requireLoggedIn();
87
+ const apiToken = requireApiToken();
88
+ const headers = { Authorization: `Bearer ${apiToken}` };
89
+ const resource = `${CF_API_BASE_URL}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
90
+ const response = await fetch(resource, {
91
+ method: "GET",
92
+ headers,
93
+ });
94
+ if (response.ok) {
95
+ return await response.text();
96
+ } else {
97
+ throw new Error(
98
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
99
+ );
100
+ }
101
+ }