wrangler 0.0.0-ece06ea → 0.0.0-ed4f2ef

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 (109) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +12 -3
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +49 -22
  6. package/pages/functions/buildWorker.ts +62 -0
  7. package/pages/functions/filepath-routing.test.ts +223 -0
  8. package/pages/functions/filepath-routing.ts +181 -0
  9. package/pages/functions/identifiers.ts +78 -0
  10. package/pages/functions/routes.ts +151 -0
  11. package/pages/functions/template-worker.ts +130 -0
  12. package/src/__tests__/configuration.test.ts +2874 -0
  13. package/src/__tests__/dev.test.tsx +588 -0
  14. package/src/__tests__/guess-worker-format.test.ts +83 -0
  15. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  16. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  17. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  18. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  19. package/src/__tests__/helpers/mock-bin.ts +36 -0
  20. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  21. package/src/__tests__/helpers/mock-console.ts +70 -0
  22. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  23. package/src/__tests__/helpers/mock-kv.ts +33 -0
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +178 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +127 -0
  31. package/src/__tests__/index.test.ts +953 -119
  32. package/src/__tests__/jest.setup.ts +74 -0
  33. package/src/__tests__/kv.test.ts +1380 -0
  34. package/src/__tests__/package-manager.test.ts +206 -0
  35. package/src/__tests__/pages.test.ts +180 -0
  36. package/src/__tests__/parse.test.ts +322 -0
  37. package/src/__tests__/publish.test.ts +3946 -0
  38. package/src/__tests__/r2.test.ts +198 -0
  39. package/src/__tests__/route.test.ts +45 -0
  40. package/src/__tests__/secret.test.ts +425 -0
  41. package/src/__tests__/sentry.test.ts +146 -0
  42. package/src/__tests__/tail.test.ts +638 -0
  43. package/src/__tests__/user.test.ts +83 -0
  44. package/src/__tests__/whoami.test.tsx +95 -0
  45. package/src/bundle.ts +155 -0
  46. package/src/cfetch/index.ts +104 -0
  47. package/src/cfetch/internal.ts +139 -0
  48. package/src/cli.ts +18 -7
  49. package/src/config/README.md +107 -0
  50. package/src/config/config.ts +229 -0
  51. package/src/config/diagnostics.ts +80 -0
  52. package/src/config/environment.ts +371 -0
  53. package/src/config/index.ts +62 -0
  54. package/src/config/validation-helpers.ts +557 -0
  55. package/src/config/validation.ts +1240 -0
  56. package/src/create-worker-preview.ts +173 -0
  57. package/src/create-worker-upload-form.ts +240 -0
  58. package/src/dev/dev.tsx +413 -0
  59. package/src/dev/local.tsx +287 -0
  60. package/src/dev/remote.tsx +209 -0
  61. package/src/dev/use-esbuild.ts +109 -0
  62. package/src/dialogs.tsx +6 -14
  63. package/src/entry.ts +256 -0
  64. package/src/environment-variables.ts +33 -0
  65. package/src/errors.ts +11 -0
  66. package/src/https-options.ts +122 -0
  67. package/src/index.tsx +1503 -959
  68. package/src/inspect.ts +624 -0
  69. package/src/intl-polyfill.d.ts +139 -0
  70. package/src/kv.ts +319 -0
  71. package/src/miniflare-cli/README.md +30 -0
  72. package/src/miniflare-cli/enum-keys.ts +17 -0
  73. package/src/miniflare-cli/index.ts +38 -0
  74. package/src/module-collection.ts +257 -0
  75. package/src/open-in-browser.ts +25 -0
  76. package/src/package-manager.ts +126 -0
  77. package/src/pages.tsx +1074 -212
  78. package/src/parse.ts +183 -0
  79. package/src/paths.ts +26 -0
  80. package/src/proxy.ts +455 -0
  81. package/src/publish.ts +326 -295
  82. package/src/r2.ts +50 -0
  83. package/src/reporting.ts +131 -0
  84. package/src/selfsigned.d.ts +29 -0
  85. package/src/sites.tsx +224 -59
  86. package/src/tail/filters.ts +279 -0
  87. package/src/tail/index.ts +299 -0
  88. package/src/tail/printing.ts +62 -0
  89. package/src/user.tsx +340 -203
  90. package/src/whoami.tsx +69 -0
  91. package/src/worker.ts +172 -0
  92. package/templates/new-worker.js +15 -0
  93. package/templates/new-worker.ts +15 -0
  94. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  95. package/templates/tsconfig.json +105 -0
  96. package/wrangler-dist/cli.js +136988 -131174
  97. package/wrangler-dist/cli.js.map +3 -3
  98. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  99. package/src/__tests__/mock-cfetch.js +0 -46
  100. package/src/api/form_data.ts +0 -158
  101. package/src/api/inspect.ts +0 -441
  102. package/src/api/preview.ts +0 -123
  103. package/src/api/worker.ts +0 -161
  104. package/src/cfetch.ts +0 -72
  105. package/src/config.ts +0 -124
  106. package/src/dev.tsx +0 -736
  107. package/src/kv.tsx +0 -211
  108. package/src/tail.tsx +0 -71
  109. package/src/util/fetch.ts +0 -74
@@ -0,0 +1,83 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import fetchMock from "jest-fetch-mock";
5
+ import {
6
+ readAuthConfigFile,
7
+ USER_AUTH_CONFIG_FILE,
8
+ writeAuthConfigFile,
9
+ } from "../user";
10
+ import { mockConsoleMethods } from "./helpers/mock-console";
11
+ import { mockOAuthFlow } from "./helpers/mock-oauth-flow";
12
+ import { runInTempDir } from "./helpers/run-in-tmp";
13
+ import { runWrangler } from "./helpers/run-wrangler";
14
+ import type { UserAuthConfig } from "../user";
15
+
16
+ describe("wrangler", () => {
17
+ runInTempDir({ homedir: "./home" });
18
+ const std = mockConsoleMethods();
19
+ const {
20
+ mockGrantAccessToken,
21
+ mockGrantAuthorization,
22
+ mockRevokeAuthorization,
23
+ } = mockOAuthFlow();
24
+
25
+ describe("login", () => {
26
+ it("should should log in a user when `wrangler login` is run", async () => {
27
+ const accessTokenRequest = mockGrantAccessToken({ respondWith: "ok" });
28
+ mockGrantAuthorization({ respondWith: "success" });
29
+
30
+ await runWrangler("login");
31
+
32
+ expect(accessTokenRequest.actual.url).toEqual(
33
+ accessTokenRequest.expected.url
34
+ );
35
+ expect(accessTokenRequest.actual.method).toEqual(
36
+ accessTokenRequest.expected.method
37
+ );
38
+
39
+ expect(std.out).toMatchInlineSnapshot(`
40
+ "Attempting to login via OAuth...
41
+ Successfully logged in."
42
+ `);
43
+
44
+ expect(readAuthConfigFile()).toEqual<UserAuthConfig>({
45
+ api_token: undefined,
46
+ oauth_token: "test-access-token",
47
+ refresh_token: "test-refresh-token",
48
+ expiration_time: expect.any(String),
49
+ });
50
+ });
51
+ });
52
+
53
+ describe("logout", () => {
54
+ it("should exit with a message stating the user is not logged in", async () => {
55
+ await runWrangler("logout");
56
+ expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
57
+ });
58
+
59
+ it("should logout user that has been properly logged in", async () => {
60
+ writeAuthConfigFile({
61
+ oauth_token: "some-oauth-tok",
62
+ refresh_token: "some-refresh-tok",
63
+ });
64
+ const outcome = mockRevokeAuthorization();
65
+
66
+ await runWrangler("logout");
67
+
68
+ expect(outcome.actual.url).toEqual(
69
+ "https://dash.cloudflare.com/oauth2/revoke"
70
+ );
71
+ expect(outcome.actual.method).toEqual("POST");
72
+
73
+ expect(std.out).toMatchInlineSnapshot(`"Successfully logged out."`);
74
+
75
+ // Make sure that we made the request to logout.
76
+ expect(fetchMock).toHaveBeenCalledTimes(1);
77
+
78
+ // Make sure that logout removed the config file containing the auth tokens.
79
+ const config = path.join(os.homedir(), USER_AUTH_CONFIG_FILE);
80
+ expect(fs.existsSync(config)).toBeFalsy();
81
+ });
82
+ });
83
+ });
@@ -0,0 +1,95 @@
1
+ import { render } from "ink-testing-library";
2
+ import React from "react";
3
+ import { writeAuthConfigFile } from "../user";
4
+ import { getUserInfo, WhoAmI } from "../whoami";
5
+ import { setMockResponse } from "./helpers/mock-cfetch";
6
+ import { mockConsoleMethods } from "./helpers/mock-console";
7
+ import { runInTempDir } from "./helpers/run-in-tmp";
8
+ import type { UserInfo } from "../whoami";
9
+
10
+ describe("getUserInfo()", () => {
11
+ runInTempDir({ homedir: "./home" });
12
+ const std = mockConsoleMethods();
13
+
14
+ it("should return undefined if there is no config file", async () => {
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
+ writeAuthConfigFile({});
21
+ const userInfo = await getUserInfo();
22
+ expect(userInfo).toBeUndefined();
23
+ });
24
+
25
+ it("should return the user's email and accounts if authenticated via config token", async () => {
26
+ writeAuthConfigFile({ oauth_token: "some-oauth-token" });
27
+
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
+ const userInfo = await getUserInfo();
40
+
41
+ expect(userInfo).toEqual({
42
+ authType: "OAuth",
43
+ apiToken: "some-oauth-token",
44
+ email: "user@example.com",
45
+ accounts: [
46
+ { name: "Account One", id: "account-1" },
47
+ { name: "Account Two", id: "account-2" },
48
+ { name: "Account Three", id: "account-3" },
49
+ ],
50
+ });
51
+ });
52
+
53
+ it("should display a warning message if the config file contains a legacy api_token field", async () => {
54
+ writeAuthConfigFile({ api_token: "API_TOKEN" });
55
+ await getUserInfo();
56
+ expect(std.warn).toMatchInlineSnapshot(`
57
+ "It looks like you have used Wrangler 1's \`config\` command to login with an API token.
58
+ This is no longer supported in the current version of Wrangler.
59
+ If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\` environment variable."
60
+ `);
61
+ });
62
+ });
63
+
64
+ describe("WhoAmI component", () => {
65
+ it("should return undefined if there is no user", async () => {
66
+ const { lastFrame } = render(<WhoAmI user={undefined}></WhoAmI>);
67
+
68
+ expect(lastFrame()).toMatchInlineSnapshot(
69
+ `"You are not authenticated. Please run \`wrangler login\`."`
70
+ );
71
+ });
72
+
73
+ it("should display the user's email and accounts", async () => {
74
+ const user: UserInfo = {
75
+ authType: "OAuth",
76
+ apiToken: "some-oauth-token",
77
+ email: "user@example.com",
78
+ accounts: [
79
+ { name: "Account One", id: "account-1" },
80
+ { name: "Account Two", id: "account-2" },
81
+ { name: "Account Three", id: "account-3" },
82
+ ],
83
+ };
84
+
85
+ const { lastFrame } = render(<WhoAmI user={user}></WhoAmI>);
86
+
87
+ expect(lastFrame()).toContain(
88
+ "You are logged in with an OAuth Token, associated with the email 'user@example.com'!"
89
+ );
90
+ expect(lastFrame()).toMatch(/Account Name .+ Account ID/);
91
+ expect(lastFrame()).toMatch(/Account One .+ account-1/);
92
+ expect(lastFrame()).toMatch(/Account Two .+ account-2/);
93
+ expect(lastFrame()).toMatch(/Account Three .+ account-3/);
94
+ });
95
+ });
package/src/bundle.ts ADDED
@@ -0,0 +1,155 @@
1
+ import assert from "node:assert";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import * as esbuild from "esbuild";
5
+ import createModuleCollector from "./module-collection";
6
+ import type { Config } from "./config";
7
+ import type { Entry } from "./entry";
8
+ import type { CfModule } from "./worker";
9
+
10
+ type BundleResult = {
11
+ modules: CfModule[];
12
+ resolvedEntryPointPath: string;
13
+ bundleType: "esm" | "commonjs";
14
+ stop: (() => void) | undefined;
15
+ };
16
+
17
+ /**
18
+ * Generate a bundle for the worker identified by the arguments passed in.
19
+ */
20
+ export async function bundleWorker(
21
+ entry: Entry,
22
+ destination: string,
23
+ options: {
24
+ serveAssetsFromWorker: boolean;
25
+ jsxFactory: string | undefined;
26
+ jsxFragment: string | undefined;
27
+ rules: Config["rules"];
28
+ watch?: esbuild.WatchMode;
29
+ tsconfig: string | undefined;
30
+ }
31
+ ): Promise<BundleResult> {
32
+ const {
33
+ serveAssetsFromWorker,
34
+ jsxFactory,
35
+ jsxFragment,
36
+ rules,
37
+ watch,
38
+ tsconfig,
39
+ } = options;
40
+ const entryDirectory = path.dirname(entry.file);
41
+ const moduleCollector = createModuleCollector({
42
+ wrangler1xlegacyModuleReferences: {
43
+ rootDirectory: entryDirectory,
44
+ fileNames: new Set(
45
+ fs
46
+ .readdirSync(entryDirectory, { withFileTypes: true })
47
+ .filter(
48
+ (dirEntry) =>
49
+ dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
50
+ )
51
+ .map((dirEnt) => dirEnt.name)
52
+ ),
53
+ },
54
+ format: entry.format,
55
+ rules,
56
+ });
57
+ const result = await esbuild.build({
58
+ ...getEntryPoint(entry.file, serveAssetsFromWorker),
59
+ bundle: true,
60
+ absWorkingDir: entry.directory,
61
+ outdir: destination,
62
+ external: ["__STATIC_CONTENT_MANIFEST"],
63
+ format: "esm",
64
+ sourcemap: true,
65
+ metafile: true,
66
+ conditions: ["worker", "browser"],
67
+ ...(process.env.NODE_ENV && {
68
+ define: {
69
+ "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
70
+ },
71
+ }),
72
+ loader: {
73
+ ".js": "jsx",
74
+ ".mjs": "jsx",
75
+ ".cjs": "jsx",
76
+ },
77
+ plugins: [moduleCollector.plugin],
78
+ ...(jsxFactory && { jsxFactory }),
79
+ ...(jsxFragment && { jsxFragment }),
80
+ ...(tsconfig && { tsconfig }),
81
+ watch,
82
+ });
83
+
84
+ const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
85
+ ([_path, output]) => output.entryPoint !== undefined
86
+ );
87
+ assert(
88
+ entryPointOutputs.length > 0,
89
+ `Cannot find entry-point "${entry.file}" in generated bundle.` +
90
+ listEntryPoints(entryPointOutputs)
91
+ );
92
+ assert(
93
+ entryPointOutputs.length < 2,
94
+ "More than one entry-point found for generated bundle." +
95
+ listEntryPoints(entryPointOutputs)
96
+ );
97
+
98
+ const entryPointExports = entryPointOutputs[0][1].exports;
99
+ const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
100
+
101
+ return {
102
+ modules: moduleCollector.modules,
103
+ resolvedEntryPointPath: path.resolve(
104
+ entry.directory,
105
+ entryPointOutputs[0][0]
106
+ ),
107
+ bundleType,
108
+ stop: result.stop,
109
+ };
110
+ }
111
+
112
+ type EntryPoint =
113
+ | { stdin: esbuild.StdinOptions; nodePaths: string[] }
114
+ | { entryPoints: string[] };
115
+
116
+ /**
117
+ * Create an object that describes the entry point for esbuild.
118
+ *
119
+ * If we are using the experimental asset handling, then the entry point is
120
+ * actually a shim worker that will either return an asset from a KV store,
121
+ * or delegate to the actual worker.
122
+ */
123
+ function getEntryPoint(
124
+ entryFile: string,
125
+ serveAssetsFromWorker: boolean
126
+ ): EntryPoint {
127
+ if (serveAssetsFromWorker) {
128
+ return {
129
+ stdin: {
130
+ contents: fs
131
+ .readFileSync(
132
+ path.join(__dirname, "../templates/static-asset-facade.js"),
133
+ "utf8"
134
+ )
135
+ .replace("__ENTRY_POINT__", entryFile),
136
+ sourcefile: "static-asset-facade.js",
137
+ resolveDir: path.dirname(entryFile),
138
+ },
139
+ nodePaths: [path.join(__dirname, "../vendor")],
140
+ };
141
+ } else {
142
+ return { entryPoints: [entryFile] };
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Generate a string that describes the entry-points that were identified by esbuild.
148
+ */
149
+ function listEntryPoints(
150
+ outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
151
+ ): string {
152
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
153
+ }
154
+
155
+ type ValueOf<T> = T[keyof T];
@@ -0,0 +1,104 @@
1
+ import { URLSearchParams } from "node:url";
2
+ import { ParseError } from "../parse";
3
+ import { fetchInternal } from "./internal";
4
+ import type { RequestInit } from "undici";
5
+
6
+ // Check out https://api.cloudflare.com/ for API docs.
7
+
8
+ export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
9
+
10
+ export interface FetchError {
11
+ code: number;
12
+ message: string;
13
+ }
14
+ export interface FetchResult<ResponseType = unknown> {
15
+ success: boolean;
16
+ result: ResponseType;
17
+ errors: FetchError[];
18
+ messages: string[];
19
+ result_info?: unknown;
20
+ }
21
+
22
+ export { fetchKVGetValue } from "./internal";
23
+
24
+ /**
25
+ * Make a fetch request, and extract the `result` from the JSON response.
26
+ */
27
+ export async function fetchResult<ResponseType>(
28
+ resource: string,
29
+ init: RequestInit = {},
30
+ queryParams?: URLSearchParams
31
+ ): Promise<ResponseType> {
32
+ const json = await fetchInternal<FetchResult<ResponseType>>(
33
+ resource,
34
+ init,
35
+ queryParams
36
+ );
37
+ if (json.success) {
38
+ return json.result;
39
+ } else {
40
+ throwFetchError(resource, json);
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Make a fetch request for a list of values,
46
+ * extracting the `result` from the JSON response,
47
+ * and repeating the request if the results are paginated.
48
+ */
49
+ export async function fetchListResult<ResponseType>(
50
+ resource: string,
51
+ init: RequestInit = {},
52
+ queryParams?: URLSearchParams
53
+ ): Promise<ResponseType[]> {
54
+ const results: ResponseType[] = [];
55
+ let getMoreResults = true;
56
+ let cursor: string | undefined;
57
+ while (getMoreResults) {
58
+ if (cursor) {
59
+ queryParams = new URLSearchParams(queryParams);
60
+ queryParams.set("cursor", cursor);
61
+ }
62
+ const json = await fetchInternal<FetchResult<ResponseType[]>>(
63
+ resource,
64
+ init,
65
+ queryParams
66
+ );
67
+ if (json.success) {
68
+ results.push(...json.result);
69
+ if (hasCursor(json.result_info)) {
70
+ cursor = json.result_info?.cursor;
71
+ } else {
72
+ getMoreResults = false;
73
+ }
74
+ } else {
75
+ throwFetchError(resource, json);
76
+ }
77
+ }
78
+ return results;
79
+ }
80
+
81
+ function throwFetchError(
82
+ resource: string,
83
+ response: FetchResult<unknown>
84
+ ): never {
85
+ const error = new ParseError({
86
+ text: "Received a bad response from the API",
87
+ notes: response.errors.map((err) => ({
88
+ text: err.code ? `${err.message} [code: ${err.code}]` : err.message,
89
+ })),
90
+ });
91
+ // add the first error code directly to this error
92
+ // so consumers can use it for specific behaviour
93
+ const code = response.errors[0]?.code;
94
+ if (code) {
95
+ //@ts-expect-error non-standard property on Error
96
+ error.code = code;
97
+ }
98
+ throw error;
99
+ }
100
+
101
+ function hasCursor(result_info: unknown): result_info is { cursor: string } {
102
+ const cursor = (result_info as { cursor: string } | undefined)?.cursor;
103
+ return cursor !== undefined && cursor !== null && cursor !== "";
104
+ }
@@ -0,0 +1,139 @@
1
+ import { fetch, Headers } from "undici";
2
+ import { getEnvironmentVariableFactory } from "../environment-variables";
3
+ import { ParseError, parseJSON } from "../parse";
4
+ import { reportError } from "../reporting";
5
+ import { getAPIToken, loginOrRefreshIfRequired } from "../user";
6
+ import type { URLSearchParams } from "node:url";
7
+ import type { RequestInit, HeadersInit } from "undici";
8
+
9
+ /**
10
+ * Get the URL to use to access the Cloudflare API.
11
+ */
12
+ export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
13
+ variableName: "CLOUDFLARE_API_BASE_URL",
14
+ deprecatedName: "CF_API_BASE_URL",
15
+ defaultValue: "https://api.cloudflare.com/client/v4",
16
+ });
17
+
18
+ /**
19
+ * Make a fetch request to the Cloudflare API.
20
+ *
21
+ * This function handles acquiring the API token and logging the caller in, as necessary.
22
+ *
23
+ * Check out https://api.cloudflare.com/ for API docs.
24
+ *
25
+ * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
26
+ */
27
+ export async function fetchInternal<ResponseType>(
28
+ resource: string,
29
+ init: RequestInit = {},
30
+ queryParams?: URLSearchParams
31
+ ): Promise<ResponseType> {
32
+ await requireLoggedIn();
33
+ const apiToken = requireApiToken();
34
+ const headers = cloneHeaders(init.headers);
35
+ addAuthorizationHeader(headers, apiToken);
36
+
37
+ const queryString = queryParams ? `?${queryParams.toString()}` : "";
38
+ const method = init.method ?? "GET";
39
+ const response = await fetch(
40
+ `${getCloudflareAPIBaseURL()}${resource}${queryString}`,
41
+ {
42
+ method,
43
+ ...init,
44
+ headers,
45
+ }
46
+ );
47
+ const jsonText = await response.text();
48
+ try {
49
+ return parseJSON(jsonText) as ResponseType;
50
+ } catch (err) {
51
+ await reportError(err as Error);
52
+ throw new ParseError({
53
+ text: "Received a malformed response from the API",
54
+ notes: [
55
+ {
56
+ text: truncate(jsonText, 100),
57
+ },
58
+ {
59
+ text: `${method} ${resource} -> ${response.status} ${response.statusText}`,
60
+ },
61
+ ],
62
+ });
63
+ }
64
+ }
65
+
66
+ function truncate(text: string, maxLength: number): string {
67
+ const { length } = text;
68
+ if (length <= maxLength) {
69
+ return text;
70
+ }
71
+ return `${text.substring(0, maxLength)}... (length = ${length})`;
72
+ }
73
+
74
+ function cloneHeaders(
75
+ headers: HeadersInit | undefined
76
+ ): Record<string, string> {
77
+ return headers instanceof Headers
78
+ ? Object.fromEntries(headers.entries())
79
+ : Array.isArray(headers)
80
+ ? Object.fromEntries(headers)
81
+ : { ...headers };
82
+ }
83
+
84
+ async function requireLoggedIn(): Promise<void> {
85
+ const loggedIn = await loginOrRefreshIfRequired();
86
+ if (!loggedIn) {
87
+ throw new Error("Not logged in.");
88
+ }
89
+ }
90
+
91
+ function requireApiToken(): string {
92
+ const authToken = getAPIToken();
93
+ if (!authToken) {
94
+ throw new Error("No API token found.");
95
+ }
96
+ return authToken;
97
+ }
98
+
99
+ function addAuthorizationHeader(
100
+ headers: Record<string, string>,
101
+ apiToken: string
102
+ ): void {
103
+ if ("Authorization" in headers) {
104
+ throw new Error(
105
+ "The request already specifies an authorisation header - cannot add a new one."
106
+ );
107
+ }
108
+ headers["Authorization"] = `Bearer ${apiToken}`;
109
+ }
110
+
111
+ /**
112
+ * The implementation for fetching a kv value from the cloudflare API.
113
+ * We special-case this one call, because it's the only API call that
114
+ * doesn't return json. We inline the implementation and try not to share
115
+ * any code with the other calls. We should push back on any new APIs that
116
+ * try to introduce non-"standard" response structures.
117
+ */
118
+
119
+ export async function fetchKVGetValue(
120
+ accountId: string,
121
+ namespaceId: string,
122
+ key: string
123
+ ): Promise<string> {
124
+ await requireLoggedIn();
125
+ const apiToken = requireApiToken();
126
+ const headers = { Authorization: `Bearer ${apiToken}` };
127
+ const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
128
+ const response = await fetch(resource, {
129
+ method: "GET",
130
+ headers,
131
+ });
132
+ if (response.ok) {
133
+ return await response.text();
134
+ } else {
135
+ throw new Error(
136
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
137
+ );
138
+ }
139
+ }
package/src/cli.ts CHANGED
@@ -1,10 +1,21 @@
1
+ import process from "process";
2
+ import { hideBin } from "yargs/helpers";
3
+ import { FatalError } from "./errors";
4
+ import { reportError, initReporting } from "./reporting";
1
5
  import { main } from ".";
2
6
 
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;
7
+ try {
8
+ initReporting();
9
+ } catch (error) {}
10
+
11
+ process.on("uncaughtExceptionMonitor", async (err, origin) => {
12
+ await reportError(err, origin);
13
+ });
14
+
15
+ main(hideBin(process.argv)).catch((e) => {
16
+ // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
17
+ // Here we just want to ensure that the process exits with a non-zero code.
18
+ // We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
19
+ const exitCode = (e instanceof FatalError && e.code) || 1;
20
+ process.exit(exitCode);
10
21
  });