wrangler 0.0.0-ece06ea → 0.0.0-ef13735

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 (63) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +35 -21
  3. package/pages/functions/buildWorker.ts +62 -0
  4. package/pages/functions/filepath-routing.test.ts +66 -0
  5. package/pages/functions/filepath-routing.ts +219 -0
  6. package/pages/functions/identifiers.ts +78 -0
  7. package/pages/functions/routes.ts +151 -0
  8. package/pages/functions/template-worker.ts +130 -0
  9. package/src/__tests__/dev.test.tsx +73 -0
  10. package/src/__tests__/guess-worker-format.test.ts +51 -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 +715 -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 +1381 -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 +93 -100
  31. package/src/api/preview.ts +29 -24
  32. package/src/api/worker.ts +55 -47
  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 +641 -112
  37. package/src/dev.tsx +476 -355
  38. package/src/dialogs.tsx +6 -14
  39. package/src/guess-worker-format.ts +66 -0
  40. package/src/index.tsx +828 -496
  41. package/src/inspect.ts +596 -0
  42. package/src/kv.tsx +118 -45
  43. package/src/module-collection.ts +63 -0
  44. package/src/open-in-browser.ts +13 -0
  45. package/src/package-manager.ts +120 -0
  46. package/src/pages.tsx +915 -215
  47. package/src/paths.ts +26 -0
  48. package/src/proxy.ts +370 -0
  49. package/src/publish.ts +349 -290
  50. package/src/sites.tsx +184 -55
  51. package/src/tail.tsx +5 -3
  52. package/src/user.tsx +81 -91
  53. package/src/whoami.tsx +69 -0
  54. package/templates/new-worker.js +15 -0
  55. package/templates/new-worker.ts +15 -0
  56. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  57. package/wrangler-dist/cli.js +119231 -130682
  58. package/wrangler-dist/cli.js.map +3 -3
  59. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  60. package/src/__tests__/mock-cfetch.js +0 -46
  61. package/src/api/inspect.ts +0 -441
  62. package/src/cfetch.ts +0 -72
  63. 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.
@@ -22,6 +22,11 @@ export interface CfAccount {
22
22
  zoneId?: string;
23
23
  }
24
24
 
25
+ /**
26
+ * The type of Worker
27
+ */
28
+ export type CfScriptFormat = "modules" | "service-worker";
29
+
25
30
  /**
26
31
  * A module type.
27
32
  */
@@ -53,7 +58,7 @@ export interface CfModule {
53
58
  * }
54
59
  * }
55
60
  */
56
- content: string | BufferSource;
61
+ content: string | Buffer;
57
62
  /**
58
63
  * The module type.
59
64
  *
@@ -62,22 +67,48 @@ export interface CfModule {
62
67
  type?: CfModuleType;
63
68
  }
64
69
 
70
+ /**
71
+ * A map of variable names to values.
72
+ */
73
+ interface CfVars {
74
+ [key: string]: string;
75
+ }
76
+
65
77
  /**
66
78
  * A KV namespace.
67
79
  */
68
- export interface CfKvNamespace {
69
- /**
70
- * The namespace ID.
71
- */
72
- namespaceId: string;
80
+ interface CfKvNamespace {
81
+ binding: string;
82
+ id: string;
73
83
  }
74
84
 
75
- export interface CfDurableObject {
85
+ /**
86
+ * A binding to a wasm module (in service worker format)
87
+ */
88
+
89
+ interface CfWasmModuleBindings {
90
+ [key: string]: string;
91
+ }
92
+
93
+ /**
94
+ * A Durable Object.
95
+ */
96
+ interface CfDurableObject {
97
+ name: string;
76
98
  class_name: string;
77
99
  script_name?: string;
78
100
  }
79
101
 
80
- interface CfDOMigrations {
102
+ /**
103
+ * A Service.
104
+ */
105
+ interface CfService {
106
+ name: string;
107
+ service: string;
108
+ environment: string;
109
+ }
110
+
111
+ export interface CfDurableObjectMigrations {
81
112
  old_tag?: string;
82
113
  new_tag: string;
83
114
  steps: {
@@ -87,35 +118,6 @@ interface CfDOMigrations {
87
118
  }[];
88
119
  }
89
120
 
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
121
  /**
120
122
  * Options for creating a `CfWorker`.
121
123
  */
@@ -123,7 +125,7 @@ export interface CfWorkerInit {
123
125
  /**
124
126
  * The name of the worker.
125
127
  */
126
- name: string;
128
+ name: string | undefined;
127
129
  /**
128
130
  * The entrypoint module.
129
131
  */
@@ -131,15 +133,21 @@ export interface CfWorkerInit {
131
133
  /**
132
134
  * The list of additional modules.
133
135
  */
134
- modules: void | CfModule[];
136
+ modules: undefined | CfModule[];
135
137
  /**
136
- * The map of names to variables. (aka. environment variables)
138
+ * All the bindings
137
139
  */
138
- variables?: { [name: string]: CfVariable };
139
- migrations: void | CfDOMigrations;
140
- compatibility_date: string | void;
141
- compatibility_flags: void | string[];
142
- usage_model: void | "bundled" | "unbound";
140
+ bindings: {
141
+ vars?: CfVars;
142
+ kv_namespaces?: CfKvNamespace[];
143
+ wasm_modules?: CfWasmModuleBindings;
144
+ durable_objects?: { bindings: CfDurableObject[] };
145
+ services?: CfService[];
146
+ };
147
+ migrations: undefined | CfDurableObjectMigrations;
148
+ compatibility_date: string | undefined;
149
+ compatibility_flags: undefined | string[];
150
+ usage_model: undefined | "bundled" | "unbound";
143
151
  }
144
152
 
145
153
  /**
@@ -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
  });