wrangler 0.0.0-e9e9872 → 0.0.0-e9f8a2fa

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 (178) hide show
  1. package/README.md +25 -13
  2. package/bin/wrangler.js +51 -61
  3. package/config-schema.json +2939 -0
  4. package/package.json +222 -160
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +19 -6
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +0 -4
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +133 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-pretty-error.ts +40 -0
  20. package/templates/middleware/middleware-scheduled.ts +15 -0
  21. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  22. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  23. package/templates/modules-watch-stub.js +4 -0
  24. package/templates/new-worker-scheduled.ts +1 -1
  25. package/templates/new-worker.js +1 -1
  26. package/templates/new-worker.ts +4 -1
  27. package/templates/pages-dev-pipeline.ts +32 -0
  28. package/templates/pages-dev-util.ts +55 -0
  29. package/templates/pages-shim.ts +9 -0
  30. package/templates/pages-template-plugin.ts +53 -18
  31. package/templates/pages-template-worker.ts +49 -12
  32. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  33. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  34. package/templates/tsconfig-sanity.ts +11 -0
  35. package/templates/tsconfig.init.json +105 -0
  36. package/templates/tsconfig.json +5 -102
  37. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  38. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  39. package/wrangler-dist/ProxyWorker.js +240 -0
  40. package/wrangler-dist/ProxyWorker.js.map +6 -0
  41. package/wrangler-dist/cli.d.ts +23879 -146
  42. package/wrangler-dist/cli.js +186358 -107113
  43. package/wrangler-dist/wasm-sync.wasm +0 -0
  44. package/import_meta_url.js +0 -3
  45. package/miniflare-config-stubs/.env.empty +0 -0
  46. package/miniflare-config-stubs/package.empty.json +0 -1
  47. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  48. package/miniflare-dist/index.mjs +0 -4894
  49. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  50. package/src/__tests__/config-cache.test.ts +0 -42
  51. package/src/__tests__/configuration.test.ts +0 -3946
  52. package/src/__tests__/dev.test.tsx +0 -1159
  53. package/src/__tests__/guess-worker-format.test.ts +0 -85
  54. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  55. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  56. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  57. package/src/__tests__/helpers/mock-bin.ts +0 -36
  58. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  59. package/src/__tests__/helpers/mock-console.ts +0 -97
  60. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  61. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  62. package/src/__tests__/helpers/mock-istty.ts +0 -74
  63. package/src/__tests__/helpers/mock-kv.ts +0 -33
  64. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  65. package/src/__tests__/helpers/mock-process.ts +0 -39
  66. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  67. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  68. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  69. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  70. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  71. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  72. package/src/__tests__/https-options.test.ts +0 -163
  73. package/src/__tests__/index.test.ts +0 -262
  74. package/src/__tests__/init.test.ts +0 -1992
  75. package/src/__tests__/jest.setup.ts +0 -120
  76. package/src/__tests__/kv.test.ts +0 -1650
  77. package/src/__tests__/logger.test.ts +0 -141
  78. package/src/__tests__/package-manager.test.ts +0 -353
  79. package/src/__tests__/pages.test.ts +0 -1254
  80. package/src/__tests__/parse.test.ts +0 -330
  81. package/src/__tests__/publish.test.ts +0 -6595
  82. package/src/__tests__/pubsub.test.ts +0 -367
  83. package/src/__tests__/r2.test.ts +0 -233
  84. package/src/__tests__/route.test.ts +0 -45
  85. package/src/__tests__/secret.test.ts +0 -492
  86. package/src/__tests__/tail.test.ts +0 -698
  87. package/src/__tests__/user.test.ts +0 -143
  88. package/src/__tests__/whoami.test.tsx +0 -230
  89. package/src/__tests__/worker-namespace.test.ts +0 -327
  90. package/src/abort.d.ts +0 -3
  91. package/src/api/dev.ts +0 -52
  92. package/src/api/index.ts +0 -1
  93. package/src/bundle-reporter.tsx +0 -29
  94. package/src/bundle.ts +0 -212
  95. package/src/cfetch/index.ts +0 -121
  96. package/src/cfetch/internal.ts +0 -149
  97. package/src/cli.ts +0 -27
  98. package/src/config/README.md +0 -107
  99. package/src/config/config.ts +0 -243
  100. package/src/config/diagnostics.ts +0 -80
  101. package/src/config/environment.ts +0 -453
  102. package/src/config/index.ts +0 -238
  103. package/src/config/validation-helpers.ts +0 -584
  104. package/src/config/validation.ts +0 -1745
  105. package/src/config-cache.ts +0 -83
  106. package/src/create-worker-preview.ts +0 -255
  107. package/src/create-worker-upload-form.ts +0 -263
  108. package/src/dev/dev-vars.ts +0 -36
  109. package/src/dev/dev.tsx +0 -417
  110. package/src/dev/local.tsx +0 -354
  111. package/src/dev/remote.tsx +0 -382
  112. package/src/dev/use-esbuild.ts +0 -150
  113. package/src/dev.tsx +0 -538
  114. package/src/dialogs.tsx +0 -135
  115. package/src/durable.ts +0 -102
  116. package/src/entry.ts +0 -328
  117. package/src/environment-variables.ts +0 -35
  118. package/src/errors.ts +0 -11
  119. package/src/faye-websocket.d.ts +0 -6
  120. package/src/generate.ts +0 -33
  121. package/src/git-client.ts +0 -42
  122. package/src/global-wrangler-config-path.ts +0 -26
  123. package/src/https-options.ts +0 -127
  124. package/src/index.tsx +0 -1896
  125. package/src/init.ts +0 -549
  126. package/src/inspect.ts +0 -662
  127. package/src/intl-polyfill.d.ts +0 -139
  128. package/src/is-interactive.ts +0 -12
  129. package/src/kv.ts +0 -430
  130. package/src/logger.ts +0 -73
  131. package/src/miniflare-cli/README.md +0 -30
  132. package/src/miniflare-cli/enum-keys.ts +0 -17
  133. package/src/miniflare-cli/index.ts +0 -53
  134. package/src/miniflare-cli/request-context.ts +0 -40
  135. package/src/module-collection.ts +0 -258
  136. package/src/open-in-browser.ts +0 -17
  137. package/src/package-manager.ts +0 -219
  138. package/src/pages/build.tsx +0 -202
  139. package/src/pages/constants.ts +0 -7
  140. package/src/pages/deployments.tsx +0 -101
  141. package/src/pages/dev.tsx +0 -964
  142. package/src/pages/functions/buildPlugin.ts +0 -105
  143. package/src/pages/functions/buildWorker.ts +0 -151
  144. package/src/pages/functions/filepath-routing.test.ts +0 -234
  145. package/src/pages/functions/filepath-routing.ts +0 -189
  146. package/src/pages/functions/identifiers.ts +0 -78
  147. package/src/pages/functions/routes.ts +0 -151
  148. package/src/pages/index.tsx +0 -84
  149. package/src/pages/projects.tsx +0 -157
  150. package/src/pages/publish.tsx +0 -335
  151. package/src/pages/types.ts +0 -40
  152. package/src/pages/upload.tsx +0 -396
  153. package/src/pages/utils.ts +0 -12
  154. package/src/parse.ts +0 -286
  155. package/src/paths.ts +0 -26
  156. package/src/preview.ts +0 -31
  157. package/src/proxy.ts +0 -476
  158. package/src/publish.ts +0 -780
  159. package/src/pubsub/index.ts +0 -286
  160. package/src/pubsub/pubsub-commands.tsx +0 -577
  161. package/src/r2.ts +0 -50
  162. package/src/selfsigned.d.ts +0 -29
  163. package/src/sites.tsx +0 -372
  164. package/src/tail/filters.ts +0 -279
  165. package/src/tail/index.ts +0 -299
  166. package/src/tail/printing.ts +0 -67
  167. package/src/update-check.ts +0 -19
  168. package/src/user/choose-account.tsx +0 -60
  169. package/src/user/env-vars.ts +0 -46
  170. package/src/user/generate-auth-url.ts +0 -33
  171. package/src/user/generate-random-state.ts +0 -16
  172. package/src/user/index.ts +0 -3
  173. package/src/user/user.tsx +0 -1170
  174. package/src/whoami.tsx +0 -90
  175. package/src/worker-namespace.ts +0 -190
  176. package/src/worker.ts +0 -191
  177. package/src/zones.ts +0 -76
  178. package/templates/static-asset-facade.js +0 -49
package/src/api/dev.ts DELETED
@@ -1,52 +0,0 @@
1
- import { startDev } from "../dev";
2
- import { logger } from "../logger";
3
-
4
- import type { RequestInit, Response } from "undici";
5
-
6
- interface DevOptions {
7
- env?: string;
8
- ip?: string;
9
- port?: number;
10
- localProtocol?: "http" | "https";
11
- assets?: string;
12
- site?: string;
13
- siteInclude?: string[];
14
- siteExclude?: string[];
15
- nodeCompat?: boolean;
16
- experimentalEnableLocalPersistence?: boolean;
17
- _: (string | number)[]; //yargs wants this
18
- $0: string; //yargs wants this
19
- }
20
- /**
21
- * unstable_dev starts a wrangler dev server, and returns a promise that resolves with utility functions to interact with it.
22
- * @param {string} script
23
- * @param {DevOptions} options
24
- */
25
- export async function unstable_dev(script: string, options: DevOptions) {
26
- logger.warn(
27
- `unstable_dev() is experimental\nunstable_dev()'s behaviour will likely change in future releases`
28
- );
29
-
30
- return new Promise<{
31
- stop: () => void;
32
- fetch: (init?: RequestInit) => Promise<Response | undefined>;
33
- }>((resolve) => {
34
- //lmao
35
- return new Promise<Awaited<ReturnType<typeof startDev>>>((ready) => {
36
- const devServer = startDev({
37
- script: script,
38
- ...options,
39
- local: true,
40
- onReady: () => ready(devServer),
41
- inspect: false,
42
- logLevel: "none",
43
- showInteractiveDevSession: false,
44
- });
45
- }).then((devServer) => {
46
- resolve({
47
- stop: devServer.stop,
48
- fetch: devServer.fetch,
49
- });
50
- });
51
- });
52
- }
package/src/api/index.ts DELETED
@@ -1 +0,0 @@
1
- export { unstable_dev } from "./dev";
@@ -1,29 +0,0 @@
1
- import { Blob } from "node:buffer";
2
- import { gzipSync } from "node:zlib";
3
- import { logger } from "./logger";
4
- import type { CfModule } from "./worker";
5
-
6
- async function getSize(modules: CfModule[]) {
7
- const gzipSize = gzipSync(
8
- await new Blob(modules.map((file) => file.content)).arrayBuffer()
9
- ).byteLength;
10
- const aggregateSize = new Blob(modules.map((file) => file.content)).size;
11
-
12
- return { size: aggregateSize, gzipSize };
13
- }
14
-
15
- export async function printBundleSize(
16
- main: {
17
- name: string;
18
- content: string;
19
- },
20
- modules: CfModule[]
21
- ) {
22
- const { size, gzipSize } = await getSize([...modules, main]);
23
-
24
- const bundleReport = `${(size / 1024).toFixed(2)} KiB / gzip: ${(
25
- gzipSize / 1024
26
- ).toFixed(2)} KiB`;
27
-
28
- logger.log(`Total Upload: ${bundleReport}`);
29
- }
package/src/bundle.ts DELETED
@@ -1,212 +0,0 @@
1
- import assert from "node:assert";
2
- import * as fs from "node:fs";
3
- import { builtinModules } from "node:module";
4
- import * as path from "node:path";
5
- import NodeGlobalsPolyfills from "@esbuild-plugins/node-globals-polyfill";
6
- import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
7
- import * as esbuild from "esbuild";
8
- import createModuleCollector from "./module-collection";
9
- import type { Config } from "./config";
10
- import type { Entry } from "./entry";
11
- import type { CfModule } from "./worker";
12
-
13
- type BundleResult = {
14
- modules: CfModule[];
15
- resolvedEntryPointPath: string;
16
- bundleType: "esm" | "commonjs";
17
- stop: (() => void) | undefined;
18
- };
19
-
20
- /**
21
- * Searches for any uses of node's builtin modules, and throws an error if it
22
- * finds anything. This plugin is only used when nodeCompat is not enabled.
23
- * Supports both regular node builtins, and the new "node:<MODULE>" format.
24
- */
25
- const checkForNodeBuiltinsPlugin = {
26
- name: "checkForNodeBuiltins",
27
- setup(build: esbuild.PluginBuild) {
28
- build.onResolve(
29
- {
30
- filter: new RegExp(
31
- "^(" +
32
- builtinModules.join("|") +
33
- "|" +
34
- builtinModules.map((module) => "node:" + module).join("|") +
35
- ")$"
36
- ),
37
- },
38
- () => {
39
- throw new Error(
40
- `Detected a Node builtin module import while Node compatibility is disabled.\nAdd node_compat = true to your wrangler.toml file to enable Node compatibility.`
41
- );
42
- }
43
- );
44
- },
45
- };
46
-
47
- /**
48
- * Generate a bundle for the worker identified by the arguments passed in.
49
- */
50
- export async function bundleWorker(
51
- entry: Entry,
52
- destination: string,
53
- options: {
54
- serveAssetsFromWorker: boolean;
55
- jsxFactory: string | undefined;
56
- jsxFragment: string | undefined;
57
- rules: Config["rules"];
58
- watch?: esbuild.WatchMode;
59
- tsconfig: string | undefined;
60
- minify: boolean | undefined;
61
- nodeCompat: boolean | undefined;
62
- define: Config["define"];
63
- checkFetch: boolean;
64
- }
65
- ): Promise<BundleResult> {
66
- const {
67
- serveAssetsFromWorker,
68
- jsxFactory,
69
- jsxFragment,
70
- rules,
71
- watch,
72
- tsconfig,
73
- minify,
74
- nodeCompat,
75
- checkFetch,
76
- } = options;
77
- const entryDirectory = path.dirname(entry.file);
78
- const moduleCollector = createModuleCollector({
79
- wrangler1xlegacyModuleReferences: {
80
- rootDirectory: entryDirectory,
81
- fileNames: new Set(
82
- fs
83
- .readdirSync(entryDirectory, { withFileTypes: true })
84
- .filter(
85
- (dirEntry) =>
86
- dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
87
- )
88
- .map((dirEnt) => dirEnt.name)
89
- ),
90
- },
91
- format: entry.format,
92
- rules,
93
- });
94
-
95
- const result = await esbuild.build({
96
- ...getEntryPoint(entry.file, serveAssetsFromWorker),
97
- bundle: true,
98
- absWorkingDir: entry.directory,
99
- outdir: destination,
100
- inject: checkFetch
101
- ? [path.resolve(__dirname, "../templates/checked-fetch.js")]
102
- : [],
103
- external: ["__STATIC_CONTENT_MANIFEST"],
104
- format: entry.format === "modules" ? "esm" : "iife",
105
- target: "es2020",
106
- sourcemap: true,
107
- minify,
108
- metafile: true,
109
- conditions: ["worker", "browser"],
110
- ...(process.env.NODE_ENV && {
111
- define: {
112
- "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
113
- ...(nodeCompat ? { global: "globalThis" } : {}),
114
- ...(checkFetch ? { fetch: "checkedFetch" } : {}),
115
- ...options.define,
116
- },
117
- }),
118
- loader: {
119
- ".js": "jsx",
120
- ".mjs": "jsx",
121
- ".cjs": "jsx",
122
- },
123
- plugins: [
124
- moduleCollector.plugin,
125
- ...(nodeCompat
126
- ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
127
- : // we use checkForNodeBuiltinsPlugin to throw a nicer error
128
- // if we find node builtins when nodeCompat isn't turned on
129
- [checkForNodeBuiltinsPlugin]),
130
- ],
131
- ...(jsxFactory && { jsxFactory }),
132
- ...(jsxFragment && { jsxFragment }),
133
- ...(tsconfig && { tsconfig }),
134
- watch,
135
- });
136
-
137
- const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
138
- ([_path, output]) => output.entryPoint !== undefined
139
- );
140
- assert(
141
- entryPointOutputs.length > 0,
142
- `Cannot find entry-point "${entry.file}" in generated bundle.` +
143
- listEntryPoints(entryPointOutputs)
144
- );
145
- assert(
146
- entryPointOutputs.length < 2,
147
- "More than one entry-point found for generated bundle." +
148
- listEntryPoints(entryPointOutputs)
149
- );
150
-
151
- const entryPointExports = entryPointOutputs[0][1].exports;
152
- const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
153
-
154
- return {
155
- modules: moduleCollector.modules,
156
- resolvedEntryPointPath: path.resolve(
157
- entry.directory,
158
- entryPointOutputs[0][0]
159
- ),
160
- bundleType,
161
- stop: result.stop,
162
- };
163
- }
164
-
165
- type EntryPoint = { stdin: esbuild.StdinOptions } | { entryPoints: string[] };
166
-
167
- /**
168
- * Create an object that describes the entry point for esbuild.
169
- *
170
- * If we are using the experimental asset handling, then the entry point is
171
- * actually a shim worker that will either return an asset from a KV store,
172
- * or delegate to the actual worker.
173
- */
174
- function getEntryPoint(
175
- entryFile: string,
176
- serveAssetsFromWorker: boolean
177
- ): EntryPoint {
178
- if (serveAssetsFromWorker) {
179
- return {
180
- stdin: {
181
- contents: fs
182
- .readFileSync(
183
- path.join(__dirname, "../templates/static-asset-facade.js"),
184
- "utf8"
185
- )
186
- // on windows, escape backslashes in the path (`\`)
187
- .replace("__ENTRY_POINT__", entryFile.replaceAll("\\", "\\\\"))
188
- .replace(
189
- "__KV_ASSET_HANDLER__",
190
- path
191
- .join(__dirname, "../kv-asset-handler.js")
192
- .replaceAll("\\", "\\\\")
193
- ),
194
- sourcefile: "static-asset-facade.js",
195
- resolveDir: path.dirname(entryFile),
196
- },
197
- };
198
- } else {
199
- return { entryPoints: [entryFile] };
200
- }
201
- }
202
-
203
- /**
204
- * Generate a string that describes the entry-points that were identified by esbuild.
205
- */
206
- function listEntryPoints(
207
- outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
208
- ): string {
209
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
210
- }
211
-
212
- type ValueOf<T> = T[keyof T];
@@ -1,121 +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
- error_chain?: FetchError[];
14
- }
15
- export interface FetchResult<ResponseType = unknown> {
16
- success: boolean;
17
- result: ResponseType;
18
- errors: FetchError[];
19
- messages: string[];
20
- result_info?: unknown;
21
- }
22
-
23
- export { fetchKVGetValue } from "./internal";
24
-
25
- /**
26
- * Make a fetch request, and extract the `result` from the JSON response.
27
- */
28
- export async function fetchResult<ResponseType>(
29
- resource: string,
30
- init: RequestInit = {},
31
- queryParams?: URLSearchParams,
32
- abortSignal?: AbortSignal
33
- ): Promise<ResponseType> {
34
- const json = await fetchInternal<FetchResult<ResponseType>>(
35
- resource,
36
- init,
37
- queryParams,
38
- abortSignal
39
- );
40
- if (json.success) {
41
- return json.result;
42
- } else {
43
- throwFetchError(resource, json);
44
- }
45
- }
46
-
47
- /**
48
- * Make a fetch request for a list of values,
49
- * extracting the `result` from the JSON response,
50
- * and repeating the request if the results are paginated.
51
- */
52
- export async function fetchListResult<ResponseType>(
53
- resource: string,
54
- init: RequestInit = {},
55
- queryParams?: URLSearchParams
56
- ): Promise<ResponseType[]> {
57
- const results: ResponseType[] = [];
58
- let getMoreResults = true;
59
- let cursor: string | undefined;
60
- while (getMoreResults) {
61
- if (cursor) {
62
- queryParams = new URLSearchParams(queryParams);
63
- queryParams.set("cursor", cursor);
64
- }
65
- const json = await fetchInternal<FetchResult<ResponseType[]>>(
66
- resource,
67
- init,
68
- queryParams
69
- );
70
- if (json.success) {
71
- results.push(...json.result);
72
- if (hasCursor(json.result_info)) {
73
- cursor = json.result_info?.cursor;
74
- } else {
75
- getMoreResults = false;
76
- }
77
- } else {
78
- throwFetchError(resource, json);
79
- }
80
- }
81
- return results;
82
- }
83
-
84
- function throwFetchError(
85
- resource: string,
86
- response: FetchResult<unknown>
87
- ): never {
88
- const error = new ParseError({
89
- text: `A request to the Cloudflare API (${resource}) failed.`,
90
- notes: response.errors.map((err) => ({
91
- text: renderError(err),
92
- })),
93
- });
94
- // add the first error code directly to this error
95
- // so consumers can use it for specific behaviour
96
- const code = response.errors[0]?.code;
97
- if (code) {
98
- //@ts-expect-error non-standard property on Error
99
- error.code = code;
100
- }
101
- throw error;
102
- }
103
-
104
- function hasCursor(result_info: unknown): result_info is { cursor: string } {
105
- const cursor = (result_info as { cursor: string } | undefined)?.cursor;
106
- return cursor !== undefined && cursor !== null && cursor !== "";
107
- }
108
-
109
- function renderError(err: FetchError, level = 0): string {
110
- const chainedMessages =
111
- err.error_chain
112
- ?.map(
113
- (chainedError) =>
114
- `\n${" ".repeat(level)}- ${renderError(chainedError, level + 1)}`
115
- )
116
- .join("\n") ?? "";
117
- return (
118
- (err.code ? `${err.message} [code: ${err.code}]` : err.message) +
119
- chainedMessages
120
- );
121
- }
@@ -1,149 +0,0 @@
1
- import assert from "node:assert";
2
- import { fetch, Headers } from "undici";
3
- import { version as wranglerVersion } from "../../package.json";
4
- import { getEnvironmentVariableFactory } from "../environment-variables";
5
- import { ParseError, parseJSON } from "../parse";
6
- import { loginOrRefreshIfRequired, requireApiToken } from "../user";
7
- import type { ApiCredentials } from "../user";
8
- import type { URLSearchParams } from "node:url";
9
- import type { RequestInit, HeadersInit } from "undici";
10
-
11
- /**
12
- * Get the URL to use to access the Cloudflare API.
13
- */
14
- export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
15
- variableName: "CLOUDFLARE_API_BASE_URL",
16
- deprecatedName: "CF_API_BASE_URL",
17
- defaultValue: "https://api.cloudflare.com/client/v4",
18
- });
19
-
20
- /**
21
- * Make a fetch request to the Cloudflare API.
22
- *
23
- * This function handles acquiring the API token and logging the caller in, as necessary.
24
- *
25
- * Check out https://api.cloudflare.com/ for API docs.
26
- *
27
- * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
28
- */
29
- export async function fetchInternal<ResponseType>(
30
- resource: string,
31
- init: RequestInit = {},
32
- queryParams?: URLSearchParams,
33
- abortSignal?: AbortSignal
34
- ): Promise<ResponseType> {
35
- assert(
36
- resource.startsWith("/"),
37
- `CF API fetch - resource path must start with a "/" but got "${resource}"`
38
- );
39
- await requireLoggedIn();
40
- const apiToken = requireApiToken();
41
- const headers = cloneHeaders(init.headers);
42
- addAuthorizationHeaderIfUnspecified(headers, apiToken);
43
- addUserAgent(headers);
44
-
45
- const queryString = queryParams ? `?${queryParams.toString()}` : "";
46
- const method = init.method ?? "GET";
47
- const response = await fetch(
48
- `${getCloudflareAPIBaseURL()}${resource}${queryString}`,
49
- {
50
- method,
51
- ...init,
52
- headers,
53
- signal: abortSignal,
54
- }
55
- );
56
- const jsonText = await response.text();
57
- try {
58
- return parseJSON<ResponseType>(jsonText);
59
- } catch (err) {
60
- throw new ParseError({
61
- text: "Received a malformed response from the API",
62
- notes: [
63
- {
64
- text: truncate(jsonText, 100),
65
- },
66
- {
67
- text: `${method} ${resource} -> ${response.status} ${response.statusText}`,
68
- },
69
- ],
70
- });
71
- }
72
- }
73
-
74
- function truncate(text: string, maxLength: number): string {
75
- const { length } = text;
76
- if (length <= maxLength) {
77
- return text;
78
- }
79
- return `${text.substring(0, maxLength)}... (length = ${length})`;
80
- }
81
-
82
- function cloneHeaders(
83
- headers: HeadersInit | undefined
84
- ): Record<string, string> {
85
- return headers instanceof Headers
86
- ? Object.fromEntries(headers.entries())
87
- : Array.isArray(headers)
88
- ? Object.fromEntries(headers)
89
- : { ...headers };
90
- }
91
-
92
- async function requireLoggedIn(): Promise<void> {
93
- const loggedIn = await loginOrRefreshIfRequired();
94
- if (!loggedIn) {
95
- throw new Error("Not logged in.");
96
- }
97
- }
98
-
99
- function addAuthorizationHeaderIfUnspecified(
100
- headers: Record<string, string>,
101
- auth: ApiCredentials
102
- ): void {
103
- if (!("Authorization" in headers)) {
104
- if ("apiToken" in auth) {
105
- headers["Authorization"] = `Bearer ${auth.apiToken}`;
106
- } else {
107
- headers["X-Auth-Key"] = auth.authKey;
108
- headers["X-Auth-Email"] = auth.authEmail;
109
- }
110
- }
111
- }
112
-
113
- function addUserAgent(headers: Record<string, string>): void {
114
- headers["User-Agent"] = `wrangler/${wranglerVersion}`;
115
- }
116
-
117
- /**
118
- * The implementation for fetching a kv value from the cloudflare API.
119
- * We special-case this one call, because it's the only API call that
120
- * doesn't return json. We inline the implementation and try not to share
121
- * any code with the other calls. We should push back on any new APIs that
122
- * try to introduce non-"standard" response structures.
123
- *
124
- * Note: any calls to fetchKVGetValue must call encodeURIComponent on key
125
- * before passing it
126
- */
127
-
128
- export async function fetchKVGetValue(
129
- accountId: string,
130
- namespaceId: string,
131
- key: string
132
- ): Promise<ArrayBuffer> {
133
- await requireLoggedIn();
134
- const auth = requireApiToken();
135
- const headers: Record<string, string> = {};
136
- addAuthorizationHeaderIfUnspecified(headers, auth);
137
- const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
138
- const response = await fetch(resource, {
139
- method: "GET",
140
- headers,
141
- });
142
- if (response.ok) {
143
- return await response.arrayBuffer();
144
- } else {
145
- throw new Error(
146
- `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
147
- );
148
- }
149
- }
package/src/cli.ts DELETED
@@ -1,27 +0,0 @@
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 { unstable_dev } from "./api";
5
- import { FatalError } from "./errors";
6
- import { main } from ".";
7
-
8
- /**
9
- * The main entrypoint for the CLI.
10
- * main only gets called when the script is run directly, not when it's imported as a module.
11
- */
12
- if (typeof jest === "undefined" && require.main) {
13
- main(hideBin(process.argv)).catch((e) => {
14
- // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
15
- // Here we just want to ensure that the process exits with a non-zero code.
16
- // We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
17
- const exitCode = (e instanceof FatalError && e.code) || 1;
18
- process.exit(exitCode);
19
- });
20
- }
21
-
22
- /**
23
- * This is how we're exporting the API.
24
- * It makes it possible to import wrangler from 'wrangler',
25
- * and call wrangler.unstable_dev().
26
- */
27
- export default { unstable_dev };