wrangler 0.0.0-eab9542 → 0.0.0-eaf71b86c

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 (180) hide show
  1. package/README.md +29 -13
  2. package/bin/wrangler.js +50 -88
  3. package/config-schema.json +3074 -0
  4. package/package.json +196 -157
  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 +2 -3
  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 +134 -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-mock-analytics-engine.d.ts +3 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  21. package/templates/middleware/middleware-pretty-error.ts +40 -0
  22. package/templates/middleware/middleware-scheduled.ts +29 -0
  23. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  24. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.js +1 -1
  28. package/templates/new-worker.ts +4 -1
  29. package/templates/pages-dev-pipeline.ts +32 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +9 -0
  32. package/templates/pages-template-plugin.ts +53 -18
  33. package/templates/pages-template-worker.ts +49 -12
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +22 -0
  38. package/templates/tsconfig.json +5 -102
  39. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  40. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  41. package/wrangler-dist/ProxyWorker.js +241 -0
  42. package/wrangler-dist/ProxyWorker.js.map +6 -0
  43. package/wrangler-dist/cli.d.ts +26465 -0
  44. package/wrangler-dist/cli.js +198587 -108581
  45. package/wrangler-dist/wasm-sync.wasm +0 -0
  46. package/Cloudflare_CA.pem +0 -18
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -4894
  52. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  53. package/src/__tests__/config-cache.test.ts +0 -42
  54. package/src/__tests__/configuration.test.ts +0 -3946
  55. package/src/__tests__/dev.test.tsx +0 -1159
  56. package/src/__tests__/guess-worker-format.test.ts +0 -85
  57. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  58. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  59. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  60. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  61. package/src/__tests__/helpers/mock-bin.ts +0 -36
  62. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  63. package/src/__tests__/helpers/mock-console.ts +0 -97
  64. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  65. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  66. package/src/__tests__/helpers/mock-istty.ts +0 -74
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  69. package/src/__tests__/helpers/mock-process.ts +0 -39
  70. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  71. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  72. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  73. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  74. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  75. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  76. package/src/__tests__/https-options.test.ts +0 -130
  77. package/src/__tests__/index.test.ts +0 -262
  78. package/src/__tests__/init.test.ts +0 -1992
  79. package/src/__tests__/jest.setup.ts +0 -107
  80. package/src/__tests__/kv.test.ts +0 -1619
  81. package/src/__tests__/logger.test.ts +0 -141
  82. package/src/__tests__/package-manager.test.ts +0 -353
  83. package/src/__tests__/pages.test.ts +0 -1254
  84. package/src/__tests__/parse.test.ts +0 -330
  85. package/src/__tests__/publish.test.ts +0 -6569
  86. package/src/__tests__/pubsub.test.ts +0 -367
  87. package/src/__tests__/r2.test.ts +0 -233
  88. package/src/__tests__/route.test.ts +0 -45
  89. package/src/__tests__/secret.test.ts +0 -486
  90. package/src/__tests__/tail.test.ts +0 -690
  91. package/src/__tests__/user.test.ts +0 -143
  92. package/src/__tests__/whoami.test.tsx +0 -220
  93. package/src/__tests__/worker-namespace.test.ts +0 -327
  94. package/src/abort.d.ts +0 -3
  95. package/src/api/dev.ts +0 -52
  96. package/src/api/index.ts +0 -1
  97. package/src/bundle-reporter.tsx +0 -29
  98. package/src/bundle.ts +0 -212
  99. package/src/cfetch/index.ts +0 -121
  100. package/src/cfetch/internal.ts +0 -149
  101. package/src/cli.ts +0 -27
  102. package/src/config/README.md +0 -107
  103. package/src/config/config.ts +0 -243
  104. package/src/config/diagnostics.ts +0 -80
  105. package/src/config/environment.ts +0 -453
  106. package/src/config/index.ts +0 -238
  107. package/src/config/validation-helpers.ts +0 -584
  108. package/src/config/validation.ts +0 -1745
  109. package/src/config-cache.ts +0 -83
  110. package/src/create-worker-preview.ts +0 -255
  111. package/src/create-worker-upload-form.ts +0 -263
  112. package/src/dev/dev-vars.ts +0 -36
  113. package/src/dev/dev.tsx +0 -417
  114. package/src/dev/local.tsx +0 -352
  115. package/src/dev/remote.tsx +0 -382
  116. package/src/dev/use-esbuild.ts +0 -150
  117. package/src/dev.tsx +0 -538
  118. package/src/dialogs.tsx +0 -135
  119. package/src/durable.ts +0 -102
  120. package/src/entry.ts +0 -328
  121. package/src/environment-variables.ts +0 -35
  122. package/src/errors.ts +0 -11
  123. package/src/generate.ts +0 -33
  124. package/src/git-client.ts +0 -42
  125. package/src/https-options.ts +0 -123
  126. package/src/index.tsx +0 -1871
  127. package/src/init.ts +0 -549
  128. package/src/inspect.ts +0 -662
  129. package/src/intl-polyfill.d.ts +0 -139
  130. package/src/is-interactive.ts +0 -12
  131. package/src/kv.ts +0 -408
  132. package/src/logger.ts +0 -73
  133. package/src/miniflare-cli/README.md +0 -30
  134. package/src/miniflare-cli/enum-keys.ts +0 -17
  135. package/src/miniflare-cli/index.ts +0 -53
  136. package/src/miniflare-cli/request-context.ts +0 -40
  137. package/src/module-collection.ts +0 -258
  138. package/src/open-in-browser.ts +0 -17
  139. package/src/package-manager.ts +0 -174
  140. package/src/pages/build.tsx +0 -202
  141. package/src/pages/constants.ts +0 -7
  142. package/src/pages/deployments.tsx +0 -101
  143. package/src/pages/dev.tsx +0 -964
  144. package/src/pages/functions/buildPlugin.ts +0 -105
  145. package/src/pages/functions/buildWorker.ts +0 -151
  146. package/src/pages/functions/filepath-routing.test.ts +0 -234
  147. package/src/pages/functions/filepath-routing.ts +0 -189
  148. package/src/pages/functions/identifiers.ts +0 -78
  149. package/src/pages/functions/routes.ts +0 -151
  150. package/src/pages/index.tsx +0 -84
  151. package/src/pages/projects.tsx +0 -157
  152. package/src/pages/publish.tsx +0 -335
  153. package/src/pages/types.ts +0 -40
  154. package/src/pages/upload.tsx +0 -384
  155. package/src/pages/utils.ts +0 -12
  156. package/src/parse.ts +0 -286
  157. package/src/paths.ts +0 -26
  158. package/src/preview.ts +0 -31
  159. package/src/proxy.ts +0 -476
  160. package/src/publish.ts +0 -767
  161. package/src/pubsub/index.ts +0 -286
  162. package/src/pubsub/pubsub-commands.tsx +0 -577
  163. package/src/r2.ts +0 -50
  164. package/src/selfsigned.d.ts +0 -29
  165. package/src/sites.tsx +0 -372
  166. package/src/tail/filters.ts +0 -279
  167. package/src/tail/index.ts +0 -299
  168. package/src/tail/printing.ts +0 -67
  169. package/src/update-check.ts +0 -19
  170. package/src/user/choose-account.tsx +0 -60
  171. package/src/user/env-vars.ts +0 -46
  172. package/src/user/generate-auth-url.ts +0 -33
  173. package/src/user/generate-random-state.ts +0 -16
  174. package/src/user/index.ts +0 -3
  175. package/src/user/user.tsx +0 -1161
  176. package/src/whoami.tsx +0 -90
  177. package/src/worker-namespace.ts +0 -190
  178. package/src/worker.ts +0 -191
  179. package/src/zones.ts +0 -76
  180. package/templates/static-asset-facade.js +0 -43
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
- module.exports = { unstable_dev };