wrangler 0.0.0-e88a54e → 0.0.0-e8a2a1d9

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 (173) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +123 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +155 -86
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +172 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +137 -0
  17. package/templates/middleware/loader-sw.ts +228 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  20. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  21. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  22. package/templates/middleware/middleware-pretty-error.ts +40 -0
  23. package/templates/middleware/middleware-scheduled.ts +15 -0
  24. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  25. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +22 -4
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +31 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +652 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +252 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +105 -0
  41. package/templates/tsconfig.json +6 -103
  42. package/wrangler-dist/InspectorProxyWorker.js +460 -0
  43. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  44. package/wrangler-dist/ProxyWorker.js +186 -0
  45. package/wrangler-dist/ProxyWorker.js.map +6 -0
  46. package/wrangler-dist/cli.d.ts +23507 -0
  47. package/wrangler-dist/cli.js +152534 -132977
  48. package/wrangler-dist/wasm-sync.wasm +0 -0
  49. package/import_meta_url.js +0 -3
  50. package/miniflare-config-stubs/.env.empty +0 -0
  51. package/miniflare-config-stubs/package.empty.json +0 -1
  52. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  53. package/miniflare-dist/index.mjs +0 -79
  54. package/miniflare-dist/index.mjs.map +0 -7
  55. package/pages/functions/buildWorker.ts +0 -62
  56. package/pages/functions/filepath-routing.test.ts +0 -223
  57. package/pages/functions/filepath-routing.ts +0 -181
  58. package/pages/functions/identifiers.ts +0 -78
  59. package/pages/functions/routes.ts +0 -151
  60. package/pages/functions/template-worker.ts +0 -130
  61. package/src/__tests__/configuration.test.ts +0 -2796
  62. package/src/__tests__/dev.test.tsx +0 -496
  63. package/src/__tests__/dev2.test.tsx +0 -154
  64. package/src/__tests__/guess-worker-format.test.ts +0 -58
  65. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  66. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  67. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  68. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  69. package/src/__tests__/helpers/mock-bin.ts +0 -36
  70. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  71. package/src/__tests__/helpers/mock-console.ts +0 -70
  72. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  73. package/src/__tests__/helpers/mock-kv.ts +0 -33
  74. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  75. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  76. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  77. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  78. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  79. package/src/__tests__/https-options.test.ts +0 -127
  80. package/src/__tests__/index.test.ts +0 -991
  81. package/src/__tests__/jest.setup.ts +0 -69
  82. package/src/__tests__/kv.test.ts +0 -1382
  83. package/src/__tests__/logout.test.ts +0 -52
  84. package/src/__tests__/package-manager.test.ts +0 -206
  85. package/src/__tests__/pages.test.ts +0 -44
  86. package/src/__tests__/parse.test.ts +0 -322
  87. package/src/__tests__/publish.test.ts +0 -2704
  88. package/src/__tests__/r2.test.ts +0 -198
  89. package/src/__tests__/route.test.ts +0 -45
  90. package/src/__tests__/secret.test.ts +0 -425
  91. package/src/__tests__/sentry.test.ts +0 -146
  92. package/src/__tests__/tail.test.ts +0 -564
  93. package/src/__tests__/whoami.test.tsx +0 -100
  94. package/src/bundle.ts +0 -142
  95. package/src/cfetch/index.ts +0 -104
  96. package/src/cfetch/internal.ts +0 -139
  97. package/src/cli.ts +0 -19
  98. package/src/config/README.md +0 -107
  99. package/src/config/config.ts +0 -218
  100. package/src/config/diagnostics.ts +0 -80
  101. package/src/config/environment.ts +0 -366
  102. package/src/config/index.ts +0 -62
  103. package/src/config/validation-helpers.ts +0 -486
  104. package/src/config/validation.ts +0 -1090
  105. package/src/create-worker-preview.ts +0 -166
  106. package/src/create-worker-upload-form.ts +0 -217
  107. package/src/dev/dev.tsx +0 -364
  108. package/src/dev/local.tsx +0 -232
  109. package/src/dev/remote.tsx +0 -203
  110. package/src/dev/use-esbuild.ts +0 -100
  111. package/src/dialogs.tsx +0 -77
  112. package/src/entry.ts +0 -208
  113. package/src/environment-variables.ts +0 -33
  114. package/src/https-options.ts +0 -122
  115. package/src/index.tsx +0 -2373
  116. package/src/inspect.ts +0 -617
  117. package/src/kv.ts +0 -319
  118. package/src/miniflare-cli/README.md +0 -30
  119. package/src/miniflare-cli/enum-keys.ts +0 -17
  120. package/src/miniflare-cli/index.ts +0 -37
  121. package/src/module-collection.ts +0 -258
  122. package/src/open-in-browser.ts +0 -25
  123. package/src/package-manager.ts +0 -126
  124. package/src/pages.tsx +0 -1047
  125. package/src/parse.ts +0 -183
  126. package/src/paths.ts +0 -26
  127. package/src/proxy.ts +0 -440
  128. package/src/publish.ts +0 -347
  129. package/src/r2.ts +0 -50
  130. package/src/reporting.ts +0 -131
  131. package/src/selfsigned.d.ts +0 -29
  132. package/src/sites.tsx +0 -280
  133. package/src/tail/filters.ts +0 -279
  134. package/src/tail/index.ts +0 -299
  135. package/src/tail/printing.ts +0 -62
  136. package/src/user.tsx +0 -1118
  137. package/src/whoami.tsx +0 -69
  138. package/src/worker.ts +0 -163
  139. package/templates/static-asset-facade.js +0 -47
  140. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  141. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  142. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  143. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  144. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  145. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  146. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  147. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  148. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  149. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  150. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  151. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  152. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  153. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  154. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  155. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  156. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  157. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  158. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  159. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  160. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  161. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  162. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  163. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  164. package/vendor/wrangler-mime/LICENSE +0 -21
  165. package/vendor/wrangler-mime/Mime.js +0 -97
  166. package/vendor/wrangler-mime/README.md +0 -187
  167. package/vendor/wrangler-mime/cli.js +0 -46
  168. package/vendor/wrangler-mime/index.js +0 -4
  169. package/vendor/wrangler-mime/lite.js +0 -4
  170. package/vendor/wrangler-mime/package.json +0 -52
  171. package/vendor/wrangler-mime/types/other.js +0 -1
  172. package/vendor/wrangler-mime/types/standard.js +0 -1
  173. package/wrangler-dist/cli.js.map +0 -7
@@ -1,100 +0,0 @@
1
- import { render } from "ink-testing-library";
2
- import React from "react";
3
- import { reinitialiseAuthTokens, 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
- // Now that we have changed the auth tokens in the wrangler.toml we must reinitialize the user auth state.
22
- reinitialiseAuthTokens();
23
- const userInfo = await getUserInfo();
24
- expect(userInfo).toBeUndefined();
25
- });
26
-
27
- it("should return the user's email and accounts if authenticated via config token", async () => {
28
- writeAuthConfigFile({ oauth_token: "some-oauth-token" });
29
- // Now that we have changed the auth tokens in the wrangler.toml we must reinitialize the user auth state.
30
- reinitialiseAuthTokens();
31
-
32
- setMockResponse("/user", () => {
33
- return { email: "user@example.com" };
34
- });
35
- setMockResponse("/accounts", () => {
36
- return [
37
- { name: "Account One", id: "account-1" },
38
- { name: "Account Two", id: "account-2" },
39
- { name: "Account Three", id: "account-3" },
40
- ];
41
- });
42
-
43
- const userInfo = await getUserInfo();
44
-
45
- expect(userInfo).toEqual({
46
- authType: "OAuth",
47
- apiToken: "some-oauth-token",
48
- email: "user@example.com",
49
- accounts: [
50
- { name: "Account One", id: "account-1" },
51
- { name: "Account Two", id: "account-2" },
52
- { name: "Account Three", id: "account-3" },
53
- ],
54
- });
55
- });
56
-
57
- it("should display a warning message if the config file contains a legacy api_token field", async () => {
58
- writeAuthConfigFile({ api_token: "API_TOKEN" });
59
- await reinitialiseAuthTokens();
60
- await getUserInfo();
61
- expect(std.warn).toMatchInlineSnapshot(`
62
- "It looks like you have used Wrangler 1's \`config\` command to login with an API token.
63
- This is no longer supported in the current version of Wrangler.
64
- If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\` environment variable."
65
- `);
66
- });
67
- });
68
-
69
- describe("WhoAmI component", () => {
70
- it("should return undefined if there is no user", async () => {
71
- const { lastFrame } = render(<WhoAmI user={undefined}></WhoAmI>);
72
-
73
- expect(lastFrame()).toMatchInlineSnapshot(
74
- `"You are not authenticated. Please run \`wrangler login\`."`
75
- );
76
- });
77
-
78
- it("should display the user's email and accounts", async () => {
79
- const user: UserInfo = {
80
- authType: "OAuth",
81
- apiToken: "some-oauth-token",
82
- email: "user@example.com",
83
- accounts: [
84
- { name: "Account One", id: "account-1" },
85
- { name: "Account Two", id: "account-2" },
86
- { name: "Account Three", id: "account-3" },
87
- ],
88
- };
89
-
90
- const { lastFrame } = render(<WhoAmI user={user}></WhoAmI>);
91
-
92
- expect(lastFrame()).toContain(
93
- "You are logged in with an OAuth Token, associated with the email 'user@example.com'!"
94
- );
95
- expect(lastFrame()).toMatch(/Account Name .+ Account ID/);
96
- expect(lastFrame()).toMatch(/Account One .+ account-1/);
97
- expect(lastFrame()).toMatch(/Account Two .+ account-2/);
98
- expect(lastFrame()).toMatch(/Account Three .+ account-3/);
99
- });
100
- });
package/src/bundle.ts DELETED
@@ -1,142 +0,0 @@
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
- }
30
- ): Promise<BundleResult> {
31
- const { serveAssetsFromWorker, jsxFactory, jsxFragment, rules, watch } =
32
- options;
33
- const entryDirectory = path.dirname(entry.file);
34
- const moduleCollector = createModuleCollector({
35
- wrangler1xlegacyModuleReferences: {
36
- rootDirectory: entryDirectory,
37
- fileNames: new Set(
38
- fs
39
- .readdirSync(entryDirectory, { withFileTypes: true })
40
- .filter(
41
- (dirEntry) =>
42
- dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
43
- )
44
- .map((dirEnt) => dirEnt.name)
45
- ),
46
- },
47
- format: entry.format,
48
- rules,
49
- });
50
- const result = await esbuild.build({
51
- ...getEntryPoint(entry.file, serveAssetsFromWorker),
52
- bundle: true,
53
- absWorkingDir: entry.directory,
54
- outdir: destination,
55
- external: ["__STATIC_CONTENT_MANIFEST"],
56
- format: "esm",
57
- sourcemap: true,
58
- metafile: true,
59
- conditions: ["worker", "browser"],
60
- loader: {
61
- ".js": "jsx",
62
- ".mjs": "jsx",
63
- ".cjs": "jsx",
64
- },
65
- plugins: [moduleCollector.plugin],
66
- ...(jsxFactory && { jsxFactory }),
67
- ...(jsxFragment && { jsxFragment }),
68
- watch,
69
- });
70
-
71
- const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
72
- ([_path, output]) => output.entryPoint !== undefined
73
- );
74
- assert(
75
- entryPointOutputs.length > 0,
76
- `Cannot find entry-point "${entry.file}" in generated bundle.` +
77
- listEntryPoints(entryPointOutputs)
78
- );
79
- assert(
80
- entryPointOutputs.length < 2,
81
- "More than one entry-point found for generated bundle." +
82
- listEntryPoints(entryPointOutputs)
83
- );
84
-
85
- const entryPointExports = entryPointOutputs[0][1].exports;
86
- const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
87
-
88
- return {
89
- modules: moduleCollector.modules,
90
- resolvedEntryPointPath: path.resolve(
91
- entry.directory,
92
- entryPointOutputs[0][0]
93
- ),
94
- bundleType,
95
- stop: result.stop,
96
- };
97
- }
98
-
99
- type EntryPoint =
100
- | { stdin: esbuild.StdinOptions; nodePaths: string[] }
101
- | { entryPoints: string[] };
102
-
103
- /**
104
- * Create an object that describes the entry point for esbuild.
105
- *
106
- * If we are using the experimental asset handling, then the entry point is
107
- * actually a shim worker that will either return an asset from a KV store,
108
- * or delegate to the actual worker.
109
- */
110
- function getEntryPoint(
111
- entryFile: string,
112
- serveAssetsFromWorker: boolean
113
- ): EntryPoint {
114
- if (serveAssetsFromWorker) {
115
- return {
116
- stdin: {
117
- contents: fs
118
- .readFileSync(
119
- path.join(__dirname, "../templates/static-asset-facade.js"),
120
- "utf8"
121
- )
122
- .replace("__ENTRY_POINT__", entryFile),
123
- sourcefile: "static-asset-facade.js",
124
- resolveDir: path.dirname(entryFile),
125
- },
126
- nodePaths: [path.join(__dirname, "../vendor")],
127
- };
128
- } else {
129
- return { entryPoints: [entryFile] };
130
- }
131
- }
132
-
133
- /**
134
- * Generate a string that describes the entry-points that were identified by esbuild.
135
- */
136
- function listEntryPoints(
137
- outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
138
- ): string {
139
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
140
- }
141
-
142
- type ValueOf<T> = T[keyof T];
@@ -1,104 +0,0 @@
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
- }
@@ -1,139 +0,0 @@
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 DELETED
@@ -1,19 +0,0 @@
1
- import process from "process";
2
- import { hideBin } from "yargs/helpers";
3
- import { reportError, initReporting } from "./reporting";
4
- import { main } from ".";
5
-
6
- try {
7
- initReporting();
8
- } catch (error) {}
9
-
10
- process.on("uncaughtExceptionMonitor", async (err, origin) => {
11
- await reportError(err, origin);
12
- });
13
-
14
- main(hideBin(process.argv)).catch(() => {
15
- // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
16
- // Here we just want to ensure that the process exits with a non-zero code.
17
- // We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
18
- process.exit(1);
19
- });
@@ -1,107 +0,0 @@
1
- # Configuration validation
2
-
3
- The files in this directory define and validate the configuration that is read from a `wrangler.toml` file.
4
-
5
- The configuration for a Worker is complicated since we can define different "environments", and each environment can have its own configuration.
6
- There is a default ("top-level") environment and then named environments that provide environment specific configuration.
7
-
8
- This is further complicated by the fact that there are three kinds of environment configuration:
9
-
10
- - **non-overridable**: these values are defined once in the top-level configuration, apply to all environments and cannot be overridden by an environment.
11
- - **inheritable**: these values can be defined at the top-level but can also be overridden by environment specific values.
12
- Named environments do not need to provide their own values, in which case they inherit the value from the top-level.
13
- - **non-inheritable**: these values must be explicitly defined in each environment if they are defined at the top-level.
14
- Named environments do not inherit such configuration and must provide their own values.
15
-
16
- All configuration values in `wrangler.toml` are optional and will receive a default value if not defined.
17
-
18
- ## Types
19
-
20
- ### Environment
21
-
22
- The fields that can be defined within the `env` containers are defined in the [`Environment`](./environment.ts) type.
23
- This includes the `EnvironmentInheritable` and `EnvironmentNonInheritable` fields.
24
-
25
- ### Config
26
-
27
- The "non-overridable" types are defined in the [`ConfigFields`](./config.ts) type.
28
- The `Config` type is the overall configuration, which consists of the `ConfigFields` and also an `Environment`.
29
- In this case the `Environment`, here, corresponds to the "currently active" environment. This is specified by the `--env` command line argument.
30
- If there is no argument passed then the currently active environment is the "top-level" environment.
31
- The fields in `Config` and `Environment` are not generally optional and so you can expect they have been filled with suitable inherited or default values.
32
- These types should be used when you are working with fields that should be passed to commands.
33
-
34
- ### RawConfig
35
-
36
- The `RawConfig` type is a version of `Config`, where all the fields are optional.
37
- The `RawConfig` type includes `DeprecatedConfigFields` and `EnvironmentMap`.
38
- It also extends the `RawEnvironment` type, which is a version of `Environment` where all the fields are optional.
39
- These optional fields map to the actual fields found in the `wrangler.toml`.
40
- These types should be used when you are working with raw configuration that is read or will be written to a `wrangler.toml`.
41
-
42
- ## Validation
43
-
44
- Validation is triggered by passing a `RawConfig` object, and the active environment name, to the `normalizeAndValidateConfig()` function.
45
- This function will return:
46
-
47
- - a `Config` object, where all the fields have suitable valid values
48
- - a `Diagnostics` object, which contains any errors or warnings from the validation process
49
-
50
- The field values may have been parsed directly from the `RawConfig`, inherited into a named environment from the top-level environment, or given a default value.
51
- Generally, if there are any warnings they should be presented to the user via `console.warn()` messages,
52
- and if there are any errors then an `Error` should be thrown describing these errors.
53
-
54
- The `Diagnostics` object is hierarchical: each `Diagnostics` instance can contain a collection of child `Diagnostics` instance.
55
- When checking for or rendering warnings and errors, the `Diagnostics` class will automatically traverse down to all its children.
56
-
57
- ## Usage
58
-
59
- The [high level API](./index.ts) for configuration processing consists of the `findWranglerToml()` and `readConfig()` functions.
60
-
61
- ### readConfig()
62
-
63
- The `readConfig()` function will find the nearest `wrangler.toml` file, load and parse it, then validate and normalize the values into a `Config` object.
64
- Note that you should pass the current active environment name in as a parameter. The resulting `Config` object will contain only the fields appropriate to that environment.
65
- If there are validation errors then it will throw a suitable error.
66
-
67
- ## Changing configuration
68
-
69
- ### Add a new configuration field
70
-
71
- When a new field needs to be added to the `wrangler.toml` configuration you will need to add to the types and validation code in this directory.
72
-
73
- Here are some steps that you should consider when doing this:
74
-
75
- - add the new field to one of the interface:
76
- - if the field is not overridable in an environment then add it to the `ConfigFields` interface.
77
- - if the field can be inherited and overridden in a named environment then add it to the `EnvironmentInheritable` interface.
78
- - if the field cannot be inherited and must be specified in each named environment then add it to the `EnvironmentNonInheritable` interface.
79
- - if the field is experimental then add a call to the `experimental()` function:
80
- - if the field is now in the `ConfigDeprecated` interface then add the call to the `normalizeAndValidateConfig()` function.
81
- - if the field is now in the `EnvironmentDeprecated` interface then add the call to the `normalizeAndValidateEnvironment()` function.
82
- - add validation and normalization to the interface
83
- - if the field is in `ConfigFields` then add validation calls to `normalizeAndValidateConfig()` and assign the normalized value to the appropriate property in the `config` object.
84
- - if the field is in `EnvironmentInheritable` then call `inheritable()` in `normalizeAndValidateEnvironment()` and assign the normalized value to the appropriate property in the `environment` object.
85
- - if the field is in `EnvironmentNonInheritable` then call `notInheritable()` in `normalizeAndValidateEnvironment()` and assign the normalized value to the appropriate property in the `environment` object.
86
- - update the tests in `configuration.test.ts`
87
- - add to the `"should use defaults for empty configuration"` test to prove the correct default value is assigned
88
- - if the field is in `ConfigFields` add tests to the `"top-level non-environment configuration"` block to check the validation and normalization of values
89
- - if the field is in `EnvironmentInheritable` or `EnvironmentNonInheritable`
90
- - add tests to the `"top-level environment configuration"` block to check the validation and normalization of values
91
- - add tests to the `"named environment configuration"` block to check the inheritance of values
92
-
93
- ### Remove a configuration field
94
-
95
- We should not just remove a field from use, since users would not know that this field is no longer needed, nor how to migrate to any new usage.
96
- Instead we should first deprecate it, and then then remove it in a future major release.
97
-
98
- - move the field to a deprecation interface:
99
- - if the field was originally in `ConfigFields` then move it to the `ConfigDeprecated` interface.
100
- - if the field was originally in either `EnvironmentInheritable` or `EnvironmentNonInheritable` then move it to the `EnvironmentDeprecatedInterface`.
101
- - remove the validation for the field
102
- - the TypeScript compiler should indicate where there is now an unknown field, so that you can remove its validation and normalization from the code base.
103
- - add a deprecation warning by calling `deprecated()`
104
- - if the field is now in the `ConfigDeprecated` interface then add the call to the `normalizeAndValidateConfig()` function.
105
- - if the field is now in the `EnvironmentDeprecated` interface then add the call to the `normalizeAndValidateEnvironment()` function.
106
- - update the tests in `configuration.test.ts`
107
- - Find tests where the field is mentioned and either remove them (e.g. validation) or update to show the deprecation message.