wrangler 0.0.0-e14e589 → 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 (61) hide show
  1. package/README.md +51 -0
  2. package/bin/wrangler.js +2 -2
  3. package/package.json +49 -30
  4. package/pages/functions/buildWorker.ts +62 -0
  5. package/pages/functions/filepath-routing.test.ts +47 -0
  6. package/pages/functions/filepath-routing.ts +231 -0
  7. package/pages/functions/identifiers.ts +78 -0
  8. package/pages/functions/routes.ts +160 -0
  9. package/pages/functions/template-worker.ts +136 -0
  10. package/src/__tests__/dev.test.tsx +71 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  14. package/src/__tests__/helpers/mock-bin.ts +33 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  16. package/src/__tests__/helpers/mock-console.ts +56 -0
  17. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  18. package/src/__tests__/helpers/mock-kv.ts +40 -0
  19. package/src/__tests__/helpers/mock-user.ts +27 -0
  20. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  21. package/src/__tests__/helpers/run-wrangler.ts +14 -0
  22. package/src/__tests__/index.test.ts +509 -119
  23. package/src/__tests__/jest.setup.ts +37 -0
  24. package/src/__tests__/kv.test.ts +1139 -0
  25. package/src/__tests__/logout.test.ts +50 -0
  26. package/src/__tests__/package-manager.test.ts +206 -0
  27. package/src/__tests__/publish.test.ts +1222 -0
  28. package/src/__tests__/secret.test.ts +210 -0
  29. package/src/__tests__/whoami.test.tsx +86 -0
  30. package/src/api/form_data.ts +85 -76
  31. package/src/api/preview.ts +29 -24
  32. package/src/api/worker.ts +50 -35
  33. package/src/cfetch/index.ts +102 -0
  34. package/src/cfetch/internal.ts +101 -0
  35. package/src/cli.ts +6 -7
  36. package/src/config.ts +630 -85
  37. package/src/dev.tsx +446 -282
  38. package/src/dialogs.tsx +6 -14
  39. package/src/index.tsx +773 -426
  40. package/src/inspect.ts +596 -0
  41. package/src/kv.tsx +118 -45
  42. package/src/module-collection.ts +63 -0
  43. package/src/package-manager.ts +120 -0
  44. package/src/pages.tsx +917 -211
  45. package/src/paths.ts +26 -0
  46. package/src/proxy.ts +370 -0
  47. package/src/publish.ts +220 -88
  48. package/src/sites.tsx +180 -55
  49. package/src/tail.tsx +6 -4
  50. package/src/user.tsx +77 -87
  51. package/src/whoami.tsx +69 -0
  52. package/templates/new-worker.js +15 -0
  53. package/templates/new-worker.ts +15 -0
  54. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  55. package/wrangler-dist/cli.js +125330 -557
  56. package/wrangler-dist/cli.js.map +3 -3
  57. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  58. package/src/__tests__/mock-cfetch.js +0 -46
  59. package/src/api/inspect.ts +0 -441
  60. package/src/cfetch.ts +0 -72
  61. package/src/util/fetch.ts +0 -74
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
  *
@@ -62,49 +62,57 @@ export interface CfModule {
62
62
  type?: CfModuleType;
63
63
  }
64
64
 
65
+ /**
66
+ * A map of variable names to values.
67
+ */
68
+ interface CfVars {
69
+ [key: string]: string;
70
+ }
71
+
65
72
  /**
66
73
  * A KV namespace.
67
74
  */
68
- export interface CfKvNamespace {
69
- /**
70
- * The namespace ID.
71
- */
72
- namespaceId: string;
75
+ interface CfKvNamespace {
76
+ binding: string;
77
+ id: string;
73
78
  }
74
79
 
75
80
  /**
76
- * A `WebCrypto` key.
77
- *
78
- * @link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey
81
+ * A Durable Object.
79
82
  */
80
- export interface CfCryptoKey {
81
- /**
82
- * The format.
83
- */
84
- format: string;
85
- /**
86
- * The algorithm.
87
- */
88
- algorithm: string;
89
- /**
90
- * The usages.
91
- */
92
- usages: string[];
93
- /**
94
- * The data.
95
- */
96
- data: BufferSource | JsonWebKey;
83
+ interface CfDurableObject {
84
+ name: string;
85
+ class_name: string;
86
+ script_name?: string;
97
87
  }
98
88
 
99
89
  /**
100
- * A variable (aka. environment variable).
90
+ * A Service.
101
91
  */
102
- export type CfVariable = string | CfKvNamespace | CfCryptoKey;
92
+ interface CfService {
93
+ name: string;
94
+ service: string;
95
+ environment: string;
96
+ }
97
+
98
+ export interface CfDurableObjectMigrations {
99
+ old_tag?: string;
100
+ new_tag: string;
101
+ steps: {
102
+ new_classes?: string[];
103
+ renamed_classes?: string[];
104
+ deleted_classes?: string[];
105
+ }[];
106
+ }
103
107
 
104
108
  /**
105
109
  * Options for creating a `CfWorker`.
106
110
  */
107
111
  export interface CfWorkerInit {
112
+ /**
113
+ * The name of the worker.
114
+ */
115
+ name: string | undefined;
108
116
  /**
109
117
  * The entrypoint module.
110
118
  */
@@ -112,13 +120,20 @@ export interface CfWorkerInit {
112
120
  /**
113
121
  * The list of additional modules.
114
122
  */
115
- modules: void | CfModule[];
123
+ modules: undefined | CfModule[];
116
124
  /**
117
- * The map of names to variables. (aka. environment variables)
125
+ * All the bindings
118
126
  */
119
- variables?: { [name: string]: CfVariable };
120
- compatibility_date?: string;
121
- usage_model?: void | "bundled" | "unbound";
127
+ bindings: {
128
+ kv_namespaces?: CfKvNamespace[];
129
+ durable_objects?: { bindings: CfDurableObject[] };
130
+ vars?: CfVars;
131
+ services?: CfService[];
132
+ };
133
+ migrations: undefined | CfDurableObjectMigrations;
134
+ compatibility_date: string | undefined;
135
+ compatibility_flags: undefined | string[];
136
+ usage_model: undefined | "bundled" | "unbound";
122
137
  }
123
138
 
124
139
  /**
@@ -0,0 +1,102 @@
1
+ import { URLSearchParams } from "node:url";
2
+ import { fetchInternal } from "./internal";
3
+ import type { RequestInit } from "undici";
4
+
5
+ // Check out https://api.cloudflare.com/ for API docs.
6
+
7
+ export { CF_API_BASE_URL } from "./internal";
8
+
9
+ export interface FetchError {
10
+ code: number;
11
+ message: string;
12
+ }
13
+ export interface FetchResult<ResponseType = unknown> {
14
+ success: boolean;
15
+ result: ResponseType;
16
+ errors: FetchError[];
17
+ messages: string[];
18
+ result_info?: unknown;
19
+ }
20
+
21
+ export { fetchKVGetValue } from "./internal";
22
+
23
+ /**
24
+ * Make a fetch request, and extract the `result` from the JSON response.
25
+ */
26
+ export async function fetchResult<ResponseType>(
27
+ resource: string,
28
+ init: RequestInit = {},
29
+ queryParams?: URLSearchParams
30
+ ): Promise<ResponseType> {
31
+ const json = await fetchInternal<FetchResult<ResponseType>>(
32
+ resource,
33
+ init,
34
+ queryParams
35
+ );
36
+ if (json.success) {
37
+ return json.result;
38
+ } else {
39
+ throwFetchError(resource, json);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Make a fetch request for a list of values,
45
+ * extracting the `result` from the JSON response,
46
+ * and repeating the request if the results are paginated.
47
+ */
48
+ export async function fetchListResult<ResponseType>(
49
+ resource: string,
50
+ init: RequestInit = {},
51
+ queryParams?: URLSearchParams
52
+ ): Promise<ResponseType[]> {
53
+ const results: ResponseType[] = [];
54
+ let getMoreResults = true;
55
+ let cursor: string | undefined;
56
+ while (getMoreResults) {
57
+ if (cursor) {
58
+ queryParams = new URLSearchParams(queryParams);
59
+ queryParams.set("cursor", cursor);
60
+ }
61
+ const json = await fetchInternal<FetchResult<ResponseType[]>>(
62
+ resource,
63
+ init,
64
+ queryParams
65
+ );
66
+ if (json.success) {
67
+ results.push(...json.result);
68
+ if (hasCursor(json.result_info)) {
69
+ cursor = json.result_info?.cursor;
70
+ } else {
71
+ getMoreResults = false;
72
+ }
73
+ } else {
74
+ throwFetchError(resource, json);
75
+ }
76
+ }
77
+ return results;
78
+ }
79
+
80
+ function throwFetchError(
81
+ resource: string,
82
+ response: FetchResult<unknown>
83
+ ): never {
84
+ response.messages.forEach((message) => console.warn(message));
85
+ const errors = response.errors
86
+ .map((error) => `${error.code}: ${error.message}`)
87
+ .join("\n");
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;
97
+ }
98
+
99
+ function hasCursor(result_info: unknown): result_info is { cursor: string } {
100
+ const cursor = (result_info as { cursor: string } | undefined)?.cursor;
101
+ return cursor !== undefined && cursor !== null && cursor !== "";
102
+ }
@@ -0,0 +1,101 @@
1
+ import { fetch } from "undici";
2
+ import { getAPIToken, loginOrRefreshIfRequired } from "../user";
3
+ import type { URLSearchParams } from "node:url";
4
+ import type { RequestInit, HeadersInit } from "undici";
5
+
6
+ export const CF_API_BASE_URL =
7
+ process.env.CF_API_BASE_URL || "https://api.cloudflare.com/client/v4";
8
+
9
+ /**
10
+ * Make a fetch request to the Cloudflare API.
11
+ *
12
+ * This function handles acquiring the API token and logging the caller in, as necessary.
13
+ *
14
+ * Check out https://api.cloudflare.com/ for API docs.
15
+ *
16
+ * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
17
+ */
18
+ export async function fetchInternal<ResponseType>(
19
+ resource: string,
20
+ init: RequestInit = {},
21
+ queryParams?: URLSearchParams
22
+ ): Promise<ResponseType> {
23
+ await requireLoggedIn();
24
+ const apiToken = requireApiToken();
25
+ const headers = cloneHeaders(init.headers);
26
+ addAuthorizationHeader(headers, apiToken);
27
+
28
+ const queryString = queryParams ? `?${queryParams.toString()}` : "";
29
+ const response = await fetch(`${CF_API_BASE_URL}${resource}${queryString}`, {
30
+ method: "GET",
31
+ ...init,
32
+ headers,
33
+ });
34
+ const jsonText = await response.text();
35
+ try {
36
+ const json = JSON.parse(jsonText);
37
+ return json as ResponseType;
38
+ } catch (e) {
39
+ throw new Error(
40
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText}\nInvalid JSON response:\n${jsonText}`
41
+ );
42
+ }
43
+ }
44
+
45
+ function cloneHeaders(headers: HeadersInit | undefined): HeadersInit {
46
+ return { ...headers };
47
+ }
48
+
49
+ async function requireLoggedIn(): Promise<void> {
50
+ const loggedIn = await loginOrRefreshIfRequired();
51
+ if (!loggedIn) {
52
+ throw new Error("Not logged in.");
53
+ }
54
+ }
55
+
56
+ function requireApiToken(): string {
57
+ const apiToken = getAPIToken();
58
+ if (!apiToken) {
59
+ throw new Error("No API token found.");
60
+ }
61
+ return apiToken;
62
+ }
63
+
64
+ function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void {
65
+ if (headers["Authorization"]) {
66
+ throw new Error(
67
+ "The request already specifies an authorisation header - cannot add a new one."
68
+ );
69
+ }
70
+ headers["Authorization"] = `Bearer ${apiToken}`;
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
+ }
package/src/cli.ts CHANGED
@@ -1,10 +1,9 @@
1
+ import { hideBin } from "yargs/helpers";
1
2
  import { main } from ".";
2
3
 
3
- main(process.argv.slice(2)).catch((cause) => {
4
- const { name, message } = cause;
5
- if (name === "CloudflareError") {
6
- console.error("\x1b[31m", message);
7
- return;
8
- }
9
- throw cause;
4
+ main(hideBin(process.argv)).catch(() => {
5
+ // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
6
+ // Here we just want to ensure that the process exits with a non-zero code.
7
+ // We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
8
+ process.exit(1);
10
9
  });