wrangler 0.0.0-ece06ea → 0.0.0-eebdb6c

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 (39) hide show
  1. package/package.json +22 -15
  2. package/pages/functions/buildWorker.ts +57 -0
  3. package/pages/functions/filepath-routing.test.ts +32 -0
  4. package/pages/functions/filepath-routing.ts +225 -0
  5. package/pages/functions/identifiers.ts +78 -0
  6. package/pages/functions/routes.ts +158 -0
  7. package/pages/functions/template-worker.ts +135 -0
  8. package/src/__tests__/index.test.ts +254 -120
  9. package/src/__tests__/jest.setup.ts +22 -0
  10. package/src/__tests__/kv.test.ts +1098 -0
  11. package/src/__tests__/mock-cfetch.ts +171 -0
  12. package/src/__tests__/mock-dialogs.ts +65 -0
  13. package/src/__tests__/run-in-tmp.ts +19 -0
  14. package/src/__tests__/run-wrangler.ts +32 -0
  15. package/src/api/form_data.ts +70 -97
  16. package/src/api/inspect.ts +0 -11
  17. package/src/api/preview.ts +29 -24
  18. package/src/api/worker.ts +34 -40
  19. package/src/cfetch/index.ts +103 -0
  20. package/src/cfetch/internal.ts +69 -0
  21. package/src/cli.ts +6 -7
  22. package/src/config.ts +14 -7
  23. package/src/dev.tsx +274 -131
  24. package/src/dialogs.tsx +4 -12
  25. package/src/index.tsx +304 -245
  26. package/src/kv.tsx +101 -45
  27. package/src/module-collection.ts +64 -0
  28. package/src/pages.tsx +681 -104
  29. package/src/proxy.ts +103 -0
  30. package/src/publish.ts +54 -58
  31. package/src/sites.tsx +5 -6
  32. package/src/tail.tsx +5 -3
  33. package/src/user.tsx +9 -16
  34. package/wrangler-dist/cli.js +36633 -49770
  35. package/wrangler-dist/cli.js.map +3 -3
  36. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  37. package/src/__tests__/mock-cfetch.js +0 -46
  38. package/src/cfetch.ts +0 -72
  39. package/src/util/fetch.ts +0 -74
package/src/api/worker.ts CHANGED
@@ -62,22 +62,40 @@ 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
- export interface CfDurableObject {
80
+ /**
81
+ * A Durable Object.
82
+ */
83
+ interface CfDurableObject {
84
+ name: string;
76
85
  class_name: string;
77
86
  script_name?: string;
78
87
  }
79
88
 
80
- interface CfDOMigrations {
89
+ /**
90
+ * A Service.
91
+ */
92
+ interface CfService {
93
+ name: string;
94
+ service: string;
95
+ environment: string;
96
+ }
97
+
98
+ export interface CfDurableObjectMigrations {
81
99
  old_tag?: string;
82
100
  new_tag: string;
83
101
  steps: {
@@ -87,35 +105,6 @@ interface CfDOMigrations {
87
105
  }[];
88
106
  }
89
107
 
90
- /**
91
- * A `WebCrypto` key.
92
- *
93
- * @link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey
94
- */
95
- export interface CfCryptoKey {
96
- /**
97
- * The format.
98
- */
99
- format: string;
100
- /**
101
- * The algorithm.
102
- */
103
- algorithm: string;
104
- /**
105
- * The usages.
106
- */
107
- usages: string[];
108
- /**
109
- * The data.
110
- */
111
- data: BufferSource | JsonWebKey;
112
- }
113
-
114
- /**
115
- * A variable (aka. environment variable).
116
- */
117
- export type CfVariable = string | CfKvNamespace | CfCryptoKey | CfDurableObject;
118
-
119
108
  /**
120
109
  * Options for creating a `CfWorker`.
121
110
  */
@@ -123,7 +112,7 @@ export interface CfWorkerInit {
123
112
  /**
124
113
  * The name of the worker.
125
114
  */
126
- name: string;
115
+ name: string | void;
127
116
  /**
128
117
  * The entrypoint module.
129
118
  */
@@ -133,10 +122,15 @@ export interface CfWorkerInit {
133
122
  */
134
123
  modules: void | CfModule[];
135
124
  /**
136
- * The map of names to variables. (aka. environment variables)
125
+ * All the bindings
137
126
  */
138
- variables?: { [name: string]: CfVariable };
139
- migrations: void | CfDOMigrations;
127
+ bindings: {
128
+ kv_namespaces?: CfKvNamespace[];
129
+ durable_objects?: { bindings: CfDurableObject[] };
130
+ vars?: CfVars;
131
+ services?: CfService[];
132
+ };
133
+ migrations: void | CfDurableObjectMigrations;
140
134
  compatibility_date: string | void;
141
135
  compatibility_flags: void | string[];
142
136
  usage_model: void | "bundled" | "unbound";
@@ -0,0 +1,103 @@
1
+ import type { RequestInit } from "node-fetch";
2
+ import { URLSearchParams } from "url";
3
+ import { fetchInternal } from "./internal";
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
+ /**
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
+ }
31
+
32
+ /**
33
+ * Make a fetch request, and extract the `result` from the JSON response.
34
+ */
35
+ export async function fetchResult<ResponseType>(
36
+ resource: string,
37
+ init: RequestInit = {},
38
+ queryParams?: URLSearchParams
39
+ ): Promise<ResponseType> {
40
+ const json = await fetchInternal<FetchResult<ResponseType>>(
41
+ resource,
42
+ init,
43
+ queryParams
44
+ );
45
+ if (json.success) {
46
+ return json.result;
47
+ } else {
48
+ throwFetchError(resource, json);
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Make a fetch request for a list of values,
54
+ * extracting the `result` from the JSON response,
55
+ * and repeating the request if the results are paginated.
56
+ */
57
+ export async function fetchListResult<ResponseType>(
58
+ resource: string,
59
+ init: RequestInit = {},
60
+ queryParams?: URLSearchParams
61
+ ): Promise<ResponseType[]> {
62
+ const results: ResponseType[] = [];
63
+ let getMoreResults = true;
64
+ let cursor: string | undefined;
65
+ while (getMoreResults) {
66
+ if (cursor) {
67
+ queryParams = new URLSearchParams(queryParams);
68
+ queryParams.set("cursor", cursor);
69
+ }
70
+ const json = await fetchInternal<FetchResult<ResponseType[]>>(
71
+ resource,
72
+ init,
73
+ queryParams
74
+ );
75
+ if (json.success) {
76
+ results.push(...json.result);
77
+ if (hasCursor(json.result_info)) {
78
+ cursor = json.result_info?.cursor;
79
+ } else {
80
+ getMoreResults = false;
81
+ }
82
+ } else {
83
+ throwFetchError(resource, json);
84
+ }
85
+ }
86
+ return results;
87
+ }
88
+
89
+ function throwFetchError(
90
+ resource: string,
91
+ response: FetchResult<unknown>
92
+ ): never {
93
+ response.messages.forEach((message) => console.warn(message));
94
+ const errors = response.errors
95
+ .map((error) => `${error.code}: ${error.message}`)
96
+ .join("\n");
97
+ throw new Error(`Failed to fetch ${resource} - ${errors}`);
98
+ }
99
+
100
+ function hasCursor(result_info: unknown): result_info is { cursor: string } {
101
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
102
+ return (result_info as any)?.cursor !== undefined;
103
+ }
@@ -0,0 +1,69 @@
1
+ import fetch from "node-fetch";
2
+ import type { RequestInit, HeadersInit } from "node-fetch";
3
+ import { getAPIToken, loginOrRefreshIfRequired } from "../user";
4
+
5
+ export const CF_API_BASE_URL =
6
+ process.env.CF_API_BASE_URL || "https://api.cloudflare.com/client/v4";
7
+
8
+ /**
9
+ * Make a fetch request to the Cloudflare API.
10
+ *
11
+ * This function handles acquiring the API token and logging the caller in, as necessary.
12
+ *
13
+ * Check out https://api.cloudflare.com/ for API docs.
14
+ *
15
+ * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
16
+ */
17
+ export async function fetchInternal<ResponseType>(
18
+ resource: string,
19
+ init: RequestInit = {},
20
+ queryParams?: URLSearchParams
21
+ ): Promise<ResponseType> {
22
+ await requireLoggedIn();
23
+ const apiToken = requireApiToken();
24
+ const headers = cloneHeaders(init.headers);
25
+ addAuthorizationHeader(headers, apiToken);
26
+
27
+ const queryString = queryParams ? `?${queryParams.toString()}` : "";
28
+ const response = await fetch(`${CF_API_BASE_URL}${resource}${queryString}`, {
29
+ method: "GET",
30
+ ...init,
31
+ headers,
32
+ });
33
+
34
+ if (response.ok) {
35
+ return (await response.json()) as ResponseType;
36
+ } else {
37
+ throw new Error(
38
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText}`
39
+ );
40
+ }
41
+ }
42
+
43
+ async function requireLoggedIn(): Promise<void> {
44
+ const loggedIn = await loginOrRefreshIfRequired();
45
+ if (!loggedIn) {
46
+ throw new Error("Not logged in.");
47
+ }
48
+ }
49
+
50
+ function requireApiToken(): string {
51
+ const apiToken = getAPIToken();
52
+ if (!apiToken) {
53
+ throw new Error("No API token found.");
54
+ }
55
+ return apiToken;
56
+ }
57
+
58
+ function cloneHeaders(headers: HeadersInit): HeadersInit {
59
+ return { ...headers };
60
+ }
61
+
62
+ function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void {
63
+ if (headers["Authorization"]) {
64
+ throw new Error(
65
+ "The request already specifies an authorisation header - cannot add a new one."
66
+ );
67
+ }
68
+ headers["Authorization"] = `Bearer ${apiToken}`;
69
+ }
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
  });
package/src/config.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // we're going to manually write both the type definition AND
2
2
  // the validator for the config, so that we can give better error messages
3
3
 
4
- type DOMigration = {
4
+ type DurableObjectMigration = {
5
5
  tag: string;
6
6
  new_classes?: string[];
7
7
  renamed_classes?: string[];
@@ -25,13 +25,13 @@ type Dev = {
25
25
  upstream_protocol?: string;
26
26
  };
27
27
 
28
- type Vars = { [key: string]: string };
28
+ export type Vars = { [key: string]: string };
29
29
 
30
30
  type Cron = string; // TODO: we should be able to parse a cron pattern with ts
31
31
 
32
32
  type KVNamespace = {
33
- binding?: string;
34
- preview_id: string;
33
+ binding: string;
34
+ preview_id?: string;
35
35
  id: string;
36
36
  };
37
37
 
@@ -41,6 +41,12 @@ type DurableObject = {
41
41
  script_name?: string;
42
42
  };
43
43
 
44
+ type Service = {
45
+ name: string;
46
+ service: string;
47
+ environment: string;
48
+ };
49
+
44
50
  type Build = {
45
51
  command?: string;
46
52
  cwd?: string;
@@ -81,12 +87,13 @@ type Env = {
81
87
  site?: Site;
82
88
  jsx_factory?: string; // inherited
83
89
  jsx_fragment?: string; // inherited
84
- polyfill_node?: boolean; //inherited
85
90
  // we should use typescript to parse cron patterns
86
91
  triggers?: { crons: Cron[] }; // inherited
87
92
  vars?: Vars;
88
93
  durable_objects?: { bindings: DurableObject[] };
89
94
  kv_namespaces?: KVNamespace[];
95
+ experimental_services?: Service[];
96
+ migrations?: DurableObjectMigration[];
90
97
  usage_model?: UsageModel; // inherited
91
98
  };
92
99
 
@@ -108,11 +115,11 @@ export type Config = {
108
115
  webpack_config?: string; // inherited
109
116
  jsx_factory?: string; // inherited
110
117
  jsx_fragment?: string; // inherited
111
- polyfill_node?: boolean; //inherited
112
118
  vars?: Vars;
113
- migrations?: DOMigration[];
114
119
  durable_objects?: { bindings: DurableObject[] };
115
120
  kv_namespaces?: KVNamespace[];
121
+ experimental_services?: Service[];
122
+ migrations?: DurableObjectMigration[];
116
123
  site?: Site; // inherited
117
124
  // we should use typescript to parse cron patterns
118
125
  triggers?: { crons: Cron[] }; // inherited