wrangler 0.0.0-ece06ea → 0.0.0-ed08df4

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 (121) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +34 -2
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +71 -36
  6. package/pages/functions/buildPlugin.ts +92 -0
  7. package/pages/functions/buildWorker.ts +138 -0
  8. package/pages/functions/filepath-routing.test.ts +234 -0
  9. package/pages/functions/filepath-routing.ts +189 -0
  10. package/pages/functions/identifiers.ts +78 -0
  11. package/pages/functions/routes.ts +156 -0
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +143 -0
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3125 -0
  16. package/src/__tests__/dev.test.tsx +829 -0
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +90 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/helpers/mock-kv.ts +33 -0
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  31. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  32. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  33. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  34. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  35. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  36. package/src/__tests__/https-options.test.ts +130 -0
  37. package/src/__tests__/index.test.ts +221 -132
  38. package/src/__tests__/init.test.ts +1516 -0
  39. package/src/__tests__/jest.setup.ts +77 -0
  40. package/src/__tests__/kv.test.ts +1481 -0
  41. package/src/__tests__/logger.test.ts +115 -0
  42. package/src/__tests__/package-manager.test.ts +206 -0
  43. package/src/__tests__/pages.test.ts +327 -0
  44. package/src/__tests__/parse.test.ts +326 -0
  45. package/src/__tests__/publish.test.ts +4996 -0
  46. package/src/__tests__/r2.test.ts +210 -0
  47. package/src/__tests__/route.test.ts +45 -0
  48. package/src/__tests__/secret.test.ts +446 -0
  49. package/src/__tests__/tail.test.ts +690 -0
  50. package/src/__tests__/user.test.ts +131 -0
  51. package/src/__tests__/whoami.test.tsx +105 -0
  52. package/src/bundle.ts +169 -0
  53. package/src/cfetch/index.ts +104 -0
  54. package/src/cfetch/internal.ts +140 -0
  55. package/src/cli.ts +10 -7
  56. package/src/config/README.md +107 -0
  57. package/src/config/config.ts +234 -0
  58. package/src/config/diagnostics.ts +80 -0
  59. package/src/config/environment.ts +394 -0
  60. package/src/config/index.ts +63 -0
  61. package/src/config/validation-helpers.ts +575 -0
  62. package/src/config/validation.ts +1424 -0
  63. package/src/config-cache.ts +45 -0
  64. package/src/create-worker-preview.ts +175 -0
  65. package/src/create-worker-upload-form.ts +240 -0
  66. package/src/dev/dev-vars.ts +36 -0
  67. package/src/dev/dev.tsx +421 -0
  68. package/src/dev/local.tsx +312 -0
  69. package/src/dev/remote.tsx +213 -0
  70. package/src/dev/use-esbuild.ts +118 -0
  71. package/src/dialogs.tsx +22 -20
  72. package/src/entry.ts +322 -0
  73. package/src/environment-variables.ts +35 -0
  74. package/src/errors.ts +11 -0
  75. package/src/https-options.ts +123 -0
  76. package/src/index.tsx +1869 -1020
  77. package/src/inspect.ts +623 -0
  78. package/src/intl-polyfill.d.ts +139 -0
  79. package/src/kv.ts +344 -0
  80. package/src/logger.ts +66 -0
  81. package/src/miniflare-cli/README.md +30 -0
  82. package/src/miniflare-cli/enum-keys.ts +17 -0
  83. package/src/miniflare-cli/index.ts +41 -0
  84. package/src/miniflare-cli/request-context.ts +40 -0
  85. package/src/module-collection.ts +258 -0
  86. package/src/open-in-browser.ts +26 -0
  87. package/src/package-manager.ts +127 -0
  88. package/src/pages.tsx +1756 -218
  89. package/src/parse.ts +185 -0
  90. package/src/paths.ts +26 -0
  91. package/src/proxy.ts +449 -0
  92. package/src/publish.ts +377 -262
  93. package/src/r2.ts +50 -0
  94. package/src/selfsigned.d.ts +29 -0
  95. package/src/sites.tsx +237 -59
  96. package/src/tail/filters.ts +279 -0
  97. package/src/tail/index.ts +299 -0
  98. package/src/tail/printing.ts +67 -0
  99. package/src/update-check.ts +19 -0
  100. package/src/user.tsx +395 -221
  101. package/src/whoami.tsx +70 -0
  102. package/src/worker.ts +172 -0
  103. package/templates/gitignore +171 -0
  104. package/templates/new-worker.js +15 -0
  105. package/templates/new-worker.ts +15 -0
  106. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  107. package/templates/tsconfig.json +105 -0
  108. package/wrangler-dist/cli.js +108921 -132528
  109. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  110. package/src/__tests__/mock-cfetch.js +0 -46
  111. package/src/api/form_data.ts +0 -158
  112. package/src/api/inspect.ts +0 -441
  113. package/src/api/preview.ts +0 -123
  114. package/src/api/worker.ts +0 -161
  115. package/src/cfetch.ts +0 -72
  116. package/src/config.ts +0 -124
  117. package/src/dev.tsx +0 -736
  118. package/src/kv.tsx +0 -211
  119. package/src/tail.tsx +0 -71
  120. package/src/util/fetch.ts +0 -74
  121. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,131 @@
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
+ requireAuth,
8
+ USER_AUTH_CONFIG_FILE,
9
+ writeAuthConfigFile,
10
+ } from "../user";
11
+ import { mockConsoleMethods } from "./helpers/mock-console";
12
+ import { useMockIsTTY } from "./helpers/mock-istty";
13
+ import { mockOAuthFlow } from "./helpers/mock-oauth-flow";
14
+ import { runInTempDir } from "./helpers/run-in-tmp";
15
+ import { runWrangler } from "./helpers/run-wrangler";
16
+ import type { Config } from "../config";
17
+ import type { UserAuthConfig } from "../user";
18
+
19
+ describe("User", () => {
20
+ runInTempDir({ homedir: "./home" });
21
+ const std = mockConsoleMethods();
22
+ const {
23
+ mockOAuthServerCallback,
24
+ mockGrantAccessToken,
25
+ mockGrantAuthorization,
26
+ mockRevokeAuthorization,
27
+ mockExchangeRefreshTokenForAccessToken,
28
+ } = mockOAuthFlow();
29
+
30
+ const { setIsTTY } = useMockIsTTY();
31
+
32
+ describe("login", () => {
33
+ it("should login a user when `wrangler login` is run", async () => {
34
+ mockOAuthServerCallback();
35
+ const accessTokenRequest = mockGrantAccessToken({ respondWith: "ok" });
36
+ mockGrantAuthorization({ respondWith: "success" });
37
+
38
+ await runWrangler("login");
39
+
40
+ expect(accessTokenRequest.actual.url).toEqual(
41
+ accessTokenRequest.expected.url
42
+ );
43
+ expect(accessTokenRequest.actual.method).toEqual(
44
+ accessTokenRequest.expected.method
45
+ );
46
+
47
+ expect(std.out).toMatchInlineSnapshot(`
48
+ "Attempting to login via OAuth...
49
+ Successfully logged in."
50
+ `);
51
+
52
+ expect(readAuthConfigFile()).toEqual<UserAuthConfig>({
53
+ api_token: undefined,
54
+ oauth_token: "test-access-token",
55
+ refresh_token: "test-refresh-token",
56
+ expiration_time: expect.any(String),
57
+ });
58
+ });
59
+ });
60
+
61
+ describe("logout", () => {
62
+ it("should exit with a message stating the user is not logged in", async () => {
63
+ await runWrangler("logout");
64
+ expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
65
+ });
66
+
67
+ it("should logout user that has been properly logged in", async () => {
68
+ writeAuthConfigFile({
69
+ oauth_token: "some-oauth-tok",
70
+ refresh_token: "some-refresh-tok",
71
+ });
72
+ const outcome = mockRevokeAuthorization();
73
+
74
+ await runWrangler("logout");
75
+
76
+ expect(outcome.actual.url).toEqual(
77
+ "https://dash.cloudflare.com/oauth2/revoke"
78
+ );
79
+ expect(outcome.actual.method).toEqual("POST");
80
+
81
+ expect(std.out).toMatchInlineSnapshot(`"Successfully logged out."`);
82
+
83
+ // Make sure that we made the request to logout.
84
+ expect(fetchMock).toHaveBeenCalledTimes(1);
85
+
86
+ // Make sure that logout removed the config file containing the auth tokens.
87
+ const config = path.join(os.homedir(), USER_AUTH_CONFIG_FILE);
88
+ expect(fs.existsSync(config)).toBeFalsy();
89
+ });
90
+ });
91
+
92
+ // TODO: Improve OAuth mocking to handle `/token` endpoints from different calls
93
+ it("should handle errors for failed token refresh", async () => {
94
+ setIsTTY(false);
95
+ mockOAuthServerCallback();
96
+ writeAuthConfigFile({
97
+ oauth_token: "hunter2",
98
+ refresh_token: "Order 66",
99
+ });
100
+ mockGrantAuthorization({ respondWith: "success" });
101
+
102
+ mockExchangeRefreshTokenForAccessToken({
103
+ respondWith: "badResponse",
104
+ });
105
+
106
+ // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
107
+ await expect(
108
+ requireAuth({} as Config)
109
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
110
+ `"Did not login, quitting..."`
111
+ );
112
+ });
113
+
114
+ it("should confirm no error message when refresh is successful", async () => {
115
+ setIsTTY(false);
116
+ mockOAuthServerCallback();
117
+ writeAuthConfigFile({
118
+ oauth_token: "hunter2",
119
+ refresh_token: "Order 66",
120
+ });
121
+ mockGrantAuthorization({ respondWith: "success" });
122
+
123
+ mockExchangeRefreshTokenForAccessToken({
124
+ respondWith: "refreshSuccess",
125
+ });
126
+
127
+ // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
128
+ await expect(requireAuth({} as Config)).rejects.toThrowError();
129
+ expect(std.err).toContain("");
130
+ });
131
+ });
@@ -0,0 +1,105 @@
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 { useMockIsTTY } from "./helpers/mock-istty";
8
+ import { runInTempDir } from "./helpers/run-in-tmp";
9
+ import type { UserInfo } from "../whoami";
10
+
11
+ describe("getUserInfo()", () => {
12
+ runInTempDir({ homedir: "./home" });
13
+ const std = mockConsoleMethods();
14
+ const { setIsTTY } = useMockIsTTY();
15
+
16
+ beforeEach(() => {
17
+ setIsTTY(true);
18
+ });
19
+
20
+ it("should return undefined if there is no config file", async () => {
21
+ const userInfo = await getUserInfo();
22
+ expect(userInfo).toBeUndefined();
23
+ });
24
+
25
+ it("should return undefined if there is an empty config file", async () => {
26
+ writeAuthConfigFile({});
27
+ const userInfo = await getUserInfo();
28
+ expect(userInfo).toBeUndefined();
29
+ });
30
+
31
+ it("should return the user's email and accounts if authenticated via config token", async () => {
32
+ writeAuthConfigFile({ oauth_token: "some-oauth-token" });
33
+
34
+ setMockResponse("/user", () => {
35
+ return { email: "user@example.com" };
36
+ });
37
+ setMockResponse("/accounts", () => {
38
+ return [
39
+ { name: "Account One", id: "account-1" },
40
+ { name: "Account Two", id: "account-2" },
41
+ { name: "Account Three", id: "account-3" },
42
+ ];
43
+ });
44
+
45
+ const userInfo = await getUserInfo();
46
+
47
+ expect(userInfo).toEqual({
48
+ authType: "OAuth",
49
+ apiToken: "some-oauth-token",
50
+ email: "user@example.com",
51
+ accounts: [
52
+ { name: "Account One", id: "account-1" },
53
+ { name: "Account Two", id: "account-2" },
54
+ { name: "Account Three", id: "account-3" },
55
+ ],
56
+ });
57
+ });
58
+
59
+ it("should display a warning message if the config file contains a legacy api_token field", async () => {
60
+ writeAuthConfigFile({ api_token: "API_TOKEN" });
61
+ await getUserInfo();
62
+ expect(std.warn).toMatchInlineSnapshot(`
63
+ "▲ [WARNING] It looks like you have used Wrangler 1's \`config\` command to login with an API token.
64
+
65
+ This is no longer supported in the current version of Wrangler.
66
+ If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\`
67
+ environment variable.
68
+
69
+ "
70
+ `);
71
+ });
72
+ });
73
+
74
+ describe("WhoAmI component", () => {
75
+ it("should return undefined if there is no user", async () => {
76
+ const { lastFrame } = render(<WhoAmI user={undefined}></WhoAmI>);
77
+
78
+ expect(lastFrame()).toMatchInlineSnapshot(
79
+ `"You are not authenticated. Please run \`wrangler login\`."`
80
+ );
81
+ });
82
+
83
+ it("should display the user's email and accounts", async () => {
84
+ const user: UserInfo = {
85
+ authType: "OAuth",
86
+ apiToken: "some-oauth-token",
87
+ email: "user@example.com",
88
+ accounts: [
89
+ { name: "Account One", id: "account-1" },
90
+ { name: "Account Two", id: "account-2" },
91
+ { name: "Account Three", id: "account-3" },
92
+ ],
93
+ };
94
+
95
+ const { lastFrame } = render(<WhoAmI user={user}></WhoAmI>);
96
+
97
+ expect(lastFrame()).toContain(
98
+ "You are logged in with an OAuth Token, associated with the email 'user@example.com'!"
99
+ );
100
+ expect(lastFrame()).toMatch(/Account Name .+ Account ID/);
101
+ expect(lastFrame()).toMatch(/Account One .+ account-1/);
102
+ expect(lastFrame()).toMatch(/Account Two .+ account-2/);
103
+ expect(lastFrame()).toMatch(/Account Three .+ account-3/);
104
+ });
105
+ });
package/src/bundle.ts ADDED
@@ -0,0 +1,169 @@
1
+ import assert from "node:assert";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import NodeGlobalsPolyfills from "@esbuild-plugins/node-globals-polyfill";
5
+ import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
6
+ import * as esbuild from "esbuild";
7
+ import createModuleCollector from "./module-collection";
8
+ import type { Config } from "./config";
9
+ import type { Entry } from "./entry";
10
+ import type { CfModule } from "./worker";
11
+
12
+ type BundleResult = {
13
+ modules: CfModule[];
14
+ resolvedEntryPointPath: string;
15
+ bundleType: "esm" | "commonjs";
16
+ stop: (() => void) | undefined;
17
+ };
18
+
19
+ /**
20
+ * Generate a bundle for the worker identified by the arguments passed in.
21
+ */
22
+ export async function bundleWorker(
23
+ entry: Entry,
24
+ destination: string,
25
+ options: {
26
+ serveAssetsFromWorker: boolean;
27
+ jsxFactory: string | undefined;
28
+ jsxFragment: string | undefined;
29
+ rules: Config["rules"];
30
+ watch?: esbuild.WatchMode;
31
+ tsconfig: string | undefined;
32
+ minify: boolean | undefined;
33
+ nodeCompat: boolean | undefined;
34
+ }
35
+ ): Promise<BundleResult> {
36
+ const {
37
+ serveAssetsFromWorker,
38
+ jsxFactory,
39
+ jsxFragment,
40
+ rules,
41
+ watch,
42
+ tsconfig,
43
+ minify,
44
+ nodeCompat,
45
+ } = options;
46
+ const entryDirectory = path.dirname(entry.file);
47
+ const moduleCollector = createModuleCollector({
48
+ wrangler1xlegacyModuleReferences: {
49
+ rootDirectory: entryDirectory,
50
+ fileNames: new Set(
51
+ fs
52
+ .readdirSync(entryDirectory, { withFileTypes: true })
53
+ .filter(
54
+ (dirEntry) =>
55
+ dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
56
+ )
57
+ .map((dirEnt) => dirEnt.name)
58
+ ),
59
+ },
60
+ format: entry.format,
61
+ rules,
62
+ });
63
+ const result = await esbuild.build({
64
+ ...getEntryPoint(entry.file, serveAssetsFromWorker),
65
+ bundle: true,
66
+ absWorkingDir: entry.directory,
67
+ outdir: destination,
68
+ external: ["__STATIC_CONTENT_MANIFEST"],
69
+ format: entry.format === "modules" ? "esm" : "iife",
70
+ target: "es2020",
71
+ sourcemap: true,
72
+ minify,
73
+ metafile: true,
74
+ conditions: ["worker", "browser"],
75
+ ...(process.env.NODE_ENV && {
76
+ define: {
77
+ "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
78
+ ...(nodeCompat ? { global: "globalThis" } : {}),
79
+ },
80
+ }),
81
+ loader: {
82
+ ".js": "jsx",
83
+ ".mjs": "jsx",
84
+ ".cjs": "jsx",
85
+ },
86
+ plugins: [
87
+ moduleCollector.plugin,
88
+ ...(nodeCompat
89
+ ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
90
+ : []),
91
+ ],
92
+ ...(jsxFactory && { jsxFactory }),
93
+ ...(jsxFragment && { jsxFragment }),
94
+ ...(tsconfig && { tsconfig }),
95
+ watch,
96
+ });
97
+
98
+ const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
99
+ ([_path, output]) => output.entryPoint !== undefined
100
+ );
101
+ assert(
102
+ entryPointOutputs.length > 0,
103
+ `Cannot find entry-point "${entry.file}" in generated bundle.` +
104
+ listEntryPoints(entryPointOutputs)
105
+ );
106
+ assert(
107
+ entryPointOutputs.length < 2,
108
+ "More than one entry-point found for generated bundle." +
109
+ listEntryPoints(entryPointOutputs)
110
+ );
111
+
112
+ const entryPointExports = entryPointOutputs[0][1].exports;
113
+ const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
114
+
115
+ return {
116
+ modules: moduleCollector.modules,
117
+ resolvedEntryPointPath: path.resolve(
118
+ entry.directory,
119
+ entryPointOutputs[0][0]
120
+ ),
121
+ bundleType,
122
+ stop: result.stop,
123
+ };
124
+ }
125
+
126
+ type EntryPoint =
127
+ | { stdin: esbuild.StdinOptions; nodePaths: string[] }
128
+ | { entryPoints: string[] };
129
+
130
+ /**
131
+ * Create an object that describes the entry point for esbuild.
132
+ *
133
+ * If we are using the experimental asset handling, then the entry point is
134
+ * actually a shim worker that will either return an asset from a KV store,
135
+ * or delegate to the actual worker.
136
+ */
137
+ function getEntryPoint(
138
+ entryFile: string,
139
+ serveAssetsFromWorker: boolean
140
+ ): EntryPoint {
141
+ if (serveAssetsFromWorker) {
142
+ return {
143
+ stdin: {
144
+ contents: fs
145
+ .readFileSync(
146
+ path.join(__dirname, "../templates/static-asset-facade.js"),
147
+ "utf8"
148
+ )
149
+ .replace("__ENTRY_POINT__", entryFile),
150
+ sourcefile: "static-asset-facade.js",
151
+ resolveDir: path.dirname(entryFile),
152
+ },
153
+ nodePaths: [path.join(__dirname, "../vendor")],
154
+ };
155
+ } else {
156
+ return { entryPoints: [entryFile] };
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Generate a string that describes the entry-points that were identified by esbuild.
162
+ */
163
+ function listEntryPoints(
164
+ outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
165
+ ): string {
166
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
167
+ }
168
+
169
+ 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,140 @@
1
+ import { fetch, Headers } from "undici";
2
+ import { getEnvironmentVariableFactory } from "../environment-variables";
3
+ import { ParseError, parseJSON } from "../parse";
4
+ import { getAPIToken, loginOrRefreshIfRequired } from "../user";
5
+ import type { URLSearchParams } from "node:url";
6
+ import type { RequestInit, HeadersInit } from "undici";
7
+
8
+ /**
9
+ * Get the URL to use to access the Cloudflare API.
10
+ */
11
+ export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
12
+ variableName: "CLOUDFLARE_API_BASE_URL",
13
+ deprecatedName: "CF_API_BASE_URL",
14
+ defaultValue: "https://api.cloudflare.com/client/v4",
15
+ });
16
+
17
+ /**
18
+ * Make a fetch request to the Cloudflare API.
19
+ *
20
+ * This function handles acquiring the API token and logging the caller in, as necessary.
21
+ *
22
+ * Check out https://api.cloudflare.com/ for API docs.
23
+ *
24
+ * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
25
+ */
26
+ export async function fetchInternal<ResponseType>(
27
+ resource: string,
28
+ init: RequestInit = {},
29
+ queryParams?: URLSearchParams
30
+ ): Promise<ResponseType> {
31
+ await requireLoggedIn();
32
+ const apiToken = requireApiToken();
33
+ const headers = cloneHeaders(init.headers);
34
+ addAuthorizationHeader(headers, apiToken);
35
+
36
+ const queryString = queryParams ? `?${queryParams.toString()}` : "";
37
+ const method = init.method ?? "GET";
38
+ const response = await fetch(
39
+ `${getCloudflareAPIBaseURL()}${resource}${queryString}`,
40
+ {
41
+ method,
42
+ ...init,
43
+ headers,
44
+ }
45
+ );
46
+ const jsonText = await response.text();
47
+ try {
48
+ return parseJSON(jsonText) as ResponseType;
49
+ } catch (err) {
50
+ throw new ParseError({
51
+ text: "Received a malformed response from the API",
52
+ notes: [
53
+ {
54
+ text: truncate(jsonText, 100),
55
+ },
56
+ {
57
+ text: `${method} ${resource} -> ${response.status} ${response.statusText}`,
58
+ },
59
+ ],
60
+ });
61
+ }
62
+ }
63
+
64
+ function truncate(text: string, maxLength: number): string {
65
+ const { length } = text;
66
+ if (length <= maxLength) {
67
+ return text;
68
+ }
69
+ return `${text.substring(0, maxLength)}... (length = ${length})`;
70
+ }
71
+
72
+ function cloneHeaders(
73
+ headers: HeadersInit | undefined
74
+ ): Record<string, string> {
75
+ return headers instanceof Headers
76
+ ? Object.fromEntries(headers.entries())
77
+ : Array.isArray(headers)
78
+ ? Object.fromEntries(headers)
79
+ : { ...headers };
80
+ }
81
+
82
+ async function requireLoggedIn(): Promise<void> {
83
+ const loggedIn = await loginOrRefreshIfRequired();
84
+ if (!loggedIn) {
85
+ throw new Error("Not logged in.");
86
+ }
87
+ }
88
+
89
+ function requireApiToken(): string {
90
+ const authToken = getAPIToken();
91
+ if (!authToken) {
92
+ throw new Error("No API token found.");
93
+ }
94
+ return authToken;
95
+ }
96
+
97
+ function addAuthorizationHeader(
98
+ headers: Record<string, string>,
99
+ apiToken: string
100
+ ): void {
101
+ if ("Authorization" in headers) {
102
+ throw new Error(
103
+ "The request already specifies an authorisation header - cannot add a new one."
104
+ );
105
+ }
106
+ headers["Authorization"] = `Bearer ${apiToken}`;
107
+ }
108
+
109
+ /**
110
+ * The implementation for fetching a kv value from the cloudflare API.
111
+ * We special-case this one call, because it's the only API call that
112
+ * doesn't return json. We inline the implementation and try not to share
113
+ * any code with the other calls. We should push back on any new APIs that
114
+ * try to introduce non-"standard" response structures.
115
+ *
116
+ * Note: any calls to fetchKVGetValue must call encodeURIComponent on key
117
+ * before passing it
118
+ */
119
+
120
+ export async function fetchKVGetValue(
121
+ accountId: string,
122
+ namespaceId: string,
123
+ key: string
124
+ ): Promise<string> {
125
+ await requireLoggedIn();
126
+ const apiToken = requireApiToken();
127
+ const headers = { Authorization: `Bearer ${apiToken}` };
128
+ const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
129
+ const response = await fetch(resource, {
130
+ method: "GET",
131
+ headers,
132
+ });
133
+ if (response.ok) {
134
+ return await response.text();
135
+ } else {
136
+ throw new Error(
137
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
138
+ );
139
+ }
140
+ }
package/src/cli.ts CHANGED
@@ -1,10 +1,13 @@
1
+ import "dotenv/config"; // Grab locally specified env params from a `.env` file.
2
+ import process from "process";
3
+ import { hideBin } from "yargs/helpers";
4
+ import { FatalError } from "./errors";
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
+ main(hideBin(process.argv)).catch((e) => {
8
+ // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
9
+ // Here we just want to ensure that the process exits with a non-zero code.
10
+ // We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
11
+ const exitCode = (e instanceof FatalError && e.code) || 1;
12
+ process.exit(exitCode);
10
13
  });