wrangler 0.0.0-e2a26a0 → 0.0.0-e3cab74

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 (68) hide show
  1. package/package.json +16 -7
  2. package/pages/functions/filepath-routing.test.ts +112 -36
  3. package/pages/functions/filepath-routing.ts +66 -119
  4. package/pages/functions/routes.ts +8 -17
  5. package/pages/functions/template-worker.ts +3 -9
  6. package/src/__tests__/configuration.test.ts +2185 -0
  7. package/src/__tests__/dev.test.tsx +48 -6
  8. package/src/__tests__/guess-worker-format.test.ts +66 -0
  9. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  10. package/src/__tests__/helpers/mock-account-id.ts +6 -6
  11. package/src/__tests__/helpers/mock-bin.ts +4 -1
  12. package/src/__tests__/helpers/mock-cfetch.ts +2 -2
  13. package/src/__tests__/helpers/mock-console.ts +11 -5
  14. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  15. package/src/__tests__/helpers/run-wrangler.ts +5 -3
  16. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  17. package/src/__tests__/index.test.ts +343 -20
  18. package/src/__tests__/jest.setup.ts +21 -1
  19. package/src/__tests__/kv.test.ts +82 -80
  20. package/src/__tests__/package-manager.test.ts +2 -2
  21. package/src/__tests__/parse.test.ts +322 -0
  22. package/src/__tests__/publish.test.ts +1428 -244
  23. package/src/__tests__/r2.test.ts +198 -0
  24. package/src/__tests__/secret.test.ts +176 -60
  25. package/src/__tests__/sentry.test.ts +146 -0
  26. package/src/__tests__/tail.test.ts +564 -0
  27. package/src/api/form_data.ts +106 -23
  28. package/src/api/preview.ts +32 -13
  29. package/src/api/worker.ts +49 -18
  30. package/src/bundle.ts +133 -0
  31. package/src/cfetch/index.ts +8 -6
  32. package/src/cfetch/internal.ts +49 -17
  33. package/src/cli.ts +10 -0
  34. package/src/config/README.md +107 -0
  35. package/src/config/config.ts +265 -0
  36. package/src/config/diagnostics.ts +80 -0
  37. package/src/config/environment.ts +305 -0
  38. package/src/config/index.ts +52 -0
  39. package/src/config/validation-helpers.ts +370 -0
  40. package/src/config/validation.ts +1017 -0
  41. package/src/dev.tsx +338 -211
  42. package/src/entry.ts +57 -0
  43. package/src/environment-variables.ts +33 -0
  44. package/src/guess-worker-format.ts +68 -0
  45. package/src/index.tsx +860 -634
  46. package/src/inspect.ts +16 -3
  47. package/src/kv.tsx +20 -29
  48. package/src/module-collection.ts +141 -34
  49. package/src/open-in-browser.ts +13 -0
  50. package/src/package-manager.ts +21 -15
  51. package/src/pages.tsx +9 -10
  52. package/src/parse.ts +183 -0
  53. package/src/proxy.ts +11 -5
  54. package/src/publish.ts +272 -314
  55. package/src/r2.ts +50 -0
  56. package/src/reporting.ts +115 -0
  57. package/src/sites.tsx +16 -15
  58. package/src/tail/filters.ts +279 -0
  59. package/src/tail/index.ts +299 -0
  60. package/src/tail/printing.ts +62 -0
  61. package/src/user.tsx +74 -44
  62. package/templates/new-worker.js +1 -1
  63. package/templates/new-worker.ts +1 -1
  64. package/templates/tsconfig.json +105 -0
  65. package/wrangler-dist/cli.js +51308 -36440
  66. package/wrangler-dist/cli.js.map +3 -3
  67. package/src/config.ts +0 -641
  68. package/src/tail.tsx +0 -73
@@ -1,8 +1,8 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import { FormData, File } from "undici";
2
3
  import type {
3
4
  CfWorkerInit,
4
5
  CfModuleType,
5
- CfModule,
6
6
  CfDurableObjectMigrations,
7
7
  } from "./worker.js";
8
8
 
@@ -23,12 +23,6 @@ export function toMimeType(type: CfModuleType): string {
23
23
  }
24
24
  }
25
25
 
26
- function toModule(module: CfModule, entryType: CfModuleType): File {
27
- const { type: moduleType, content } = module;
28
- const type = toMimeType(moduleType ?? entryType);
29
- return new File([content], module.name, { type });
30
- }
31
-
32
26
  export interface WorkerMetadata {
33
27
  /** The name of the entry point module. Only exists when the worker is in the ES module format */
34
28
  main_module?: string;
@@ -41,18 +35,16 @@ export interface WorkerMetadata {
41
35
  bindings: (
42
36
  | { type: "kv_namespace"; name: string; namespace_id: string }
43
37
  | { type: "plain_text"; name: string; text: string }
38
+ | { type: "json"; name: string; json: unknown }
39
+ | { type: "wasm_module"; name: string; part: string }
40
+ | { type: "text_blob"; name: string; part: string }
44
41
  | {
45
42
  type: "durable_object_namespace";
46
43
  name: string;
47
44
  class_name: string;
48
45
  script_name?: string;
49
46
  }
50
- | {
51
- type: "service";
52
- name: string;
53
- service: string;
54
- environment: string;
55
- }
47
+ | { type: "r2_bucket"; name: string; bucket_name: string }
56
48
  )[];
57
49
  }
58
50
 
@@ -63,7 +55,6 @@ export function toFormData(worker: CfWorkerInit): FormData {
63
55
  const formData = new FormData();
64
56
  const {
65
57
  main,
66
- modules,
67
58
  bindings,
68
59
  migrations,
69
60
  usage_model,
@@ -71,6 +62,8 @@ export function toFormData(worker: CfWorkerInit): FormData {
71
62
  compatibility_flags,
72
63
  } = worker;
73
64
 
65
+ let { modules } = worker;
66
+
74
67
  const metadataBindings: WorkerMetadata["bindings"] = [];
75
68
 
76
69
  bindings.kv_namespaces?.forEach(({ id, binding }) => {
@@ -92,18 +85,105 @@ export function toFormData(worker: CfWorkerInit): FormData {
92
85
  }
93
86
  );
94
87
 
88
+ bindings.r2_buckets?.forEach(({ binding, bucket_name }) => {
89
+ metadataBindings.push({
90
+ name: binding,
91
+ type: "r2_bucket",
92
+ bucket_name,
93
+ });
94
+ });
95
+
95
96
  Object.entries(bindings.vars || {})?.forEach(([key, value]) => {
96
- metadataBindings.push({ name: key, type: "plain_text", text: value });
97
+ if (typeof value === "string") {
98
+ metadataBindings.push({ name: key, type: "plain_text", text: value });
99
+ } else {
100
+ metadataBindings.push({ name: key, type: "json", json: value });
101
+ }
97
102
  });
98
103
 
99
- bindings.services?.forEach(({ name, service, environment }) => {
104
+ for (const [name, filePath] of Object.entries(bindings.wasm_modules || {})) {
100
105
  metadataBindings.push({
101
106
  name,
102
- type: "service",
103
- service,
104
- environment,
107
+ type: "wasm_module",
108
+ part: name,
105
109
  });
106
- });
110
+
111
+ formData.set(
112
+ name,
113
+ new File([readFileSync(filePath)], filePath, {
114
+ type: "application/wasm",
115
+ })
116
+ );
117
+ }
118
+
119
+ for (const [name, filePath] of Object.entries(bindings.text_blobs || {})) {
120
+ metadataBindings.push({
121
+ name,
122
+ type: "text_blob",
123
+ part: name,
124
+ });
125
+
126
+ if (name !== "__STATIC_CONTENT_MANIFEST") {
127
+ formData.set(
128
+ name,
129
+ new File([readFileSync(filePath)], filePath, {
130
+ type: "text/plain",
131
+ })
132
+ );
133
+ }
134
+ }
135
+
136
+ if (main.type === "commonjs") {
137
+ // This is a service-worker format worker.
138
+ for (const module of Object.values([...(modules || [])])) {
139
+ if (module.name === "__STATIC_CONTENT_MANIFEST") {
140
+ // Add the manifest to the form data.
141
+ formData.set(
142
+ module.name,
143
+ new File([module.content], module.name, {
144
+ type: "text/plain",
145
+ })
146
+ );
147
+ // And then remove it from the modules collection
148
+ modules = modules?.filter((m) => m !== module);
149
+ } else if (module.type === "compiled-wasm" || module.type === "text") {
150
+ // Convert all wasm/text modules into `wasm_module`/`text_blob` bindings.
151
+ // The "name" of the module is a file path. We use it
152
+ // to instead be a "part" of the body, and a reference
153
+ // that we can use inside our source. This identifier has to be a valid
154
+ // JS identifier, so we replace all non alphanumeric characters
155
+ // with an underscore.
156
+ const name = module.name.replace(/[^a-zA-Z0-9_$]/g, "_");
157
+ metadataBindings.push({
158
+ name,
159
+ type: module.type === "compiled-wasm" ? "wasm_module" : "text_blob",
160
+ part: name,
161
+ });
162
+
163
+ // Add the module to the form data.
164
+ formData.set(
165
+ name,
166
+ new File([module.content], module.name, {
167
+ type:
168
+ module.type === "compiled-wasm"
169
+ ? "application/wasm"
170
+ : "text/plain",
171
+ })
172
+ );
173
+ // And then remove it from the modules collection
174
+ modules = modules?.filter((m) => m !== module);
175
+ } else if (module.type === "buffer") {
176
+ throw new Error(
177
+ 'The "buffer" module type is not yet supported in service worker format workers'
178
+ );
179
+ }
180
+ }
181
+ }
182
+
183
+ if (bindings.unsafe) {
184
+ // @ts-expect-error unsafe bindings don't need to match a specific type here
185
+ metadataBindings.push(...bindings.unsafe);
186
+ }
107
187
 
108
188
  const metadata: WorkerMetadata = {
109
189
  ...(main.type !== "commonjs"
@@ -125,9 +205,12 @@ export function toFormData(worker: CfWorkerInit): FormData {
125
205
  }
126
206
 
127
207
  for (const module of [main].concat(modules || [])) {
128
- const { name } = module;
129
- const file = toModule(module, main.type ?? "esm");
130
- formData.set(name, file);
208
+ formData.set(
209
+ module.name,
210
+ new File([module.content], module.name, {
211
+ type: toMimeType(module.type ?? main.type ?? "esm"),
212
+ })
213
+ );
131
214
  }
132
215
 
133
216
  return formData;
@@ -2,7 +2,7 @@ import { URL } from "node:url";
2
2
  import { fetch } from "undici";
3
3
  import { fetchResult } from "../cfetch";
4
4
  import { toFormData } from "./form_data";
5
- import type { CfAccount, CfWorkerInit } from "./worker";
5
+ import type { CfAccount, CfWorkerContext, CfWorkerInit } from "./worker";
6
6
 
7
7
  /**
8
8
  * A preview mode.
@@ -55,10 +55,13 @@ export interface CfPreviewToken {
55
55
  /**
56
56
  * Generates a preview session token.
57
57
  */
58
- async function sessionToken(account: CfAccount): Promise<CfPreviewToken> {
59
- const { accountId, zoneId } = account;
60
- const initUrl = zoneId
61
- ? `/zones/${zoneId}/workers/edge-preview`
58
+ async function sessionToken(
59
+ account: CfAccount,
60
+ ctx: CfWorkerContext
61
+ ): Promise<CfPreviewToken> {
62
+ const { accountId } = account;
63
+ const initUrl = ctx.zone
64
+ ? `/zones/${ctx.zone}/workers/edge-preview`
62
65
  : `/accounts/${accountId}/workers/subdomain/edge-preview`;
63
66
 
64
67
  const { exchange_url } = await fetchResult<{ exchange_url: string }>(initUrl);
@@ -92,15 +95,22 @@ function randomId(): string {
92
95
  */
93
96
  export async function previewToken(
94
97
  account: CfAccount,
95
- worker: CfWorkerInit
98
+ worker: CfWorkerInit,
99
+ ctx: CfWorkerContext
96
100
  ): Promise<CfPreviewToken> {
97
- const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(account);
101
+ const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(
102
+ account,
103
+ ctx
104
+ );
98
105
 
99
- const { accountId, zoneId } = account;
100
- const scriptId = zoneId ? randomId() : worker.name || host.split(".")[0];
101
- const url = `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
106
+ const { accountId } = account;
107
+ const scriptId = ctx.zone ? randomId() : worker.name || host.split(".")[0];
108
+ const url =
109
+ ctx.env && !ctx.legacyEnv
110
+ ? `/accounts/${accountId}/workers/services/${scriptId}/environments/${ctx.env}/edge-preview`
111
+ : `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
102
112
 
103
- const mode: CfPreviewMode = zoneId
113
+ const mode: CfPreviewMode = ctx.zone
104
114
  ? { routes: ["*/*"] }
105
115
  : { workers_dev: true };
106
116
 
@@ -119,8 +129,17 @@ export async function previewToken(
119
129
  value: preview_token,
120
130
  // TODO: verify this works with zoned workers
121
131
  host:
122
- worker.name && !zoneId
123
- ? `${worker.name}.${host.split(".").slice(1).join(".")}`
132
+ worker.name && !ctx.zone
133
+ ? // hrmm this might need change as well
134
+ `${
135
+ worker.name
136
+ // TODO: this should also probably have the env prefix
137
+ // but it doesn't appear to work yet, instead giving us the
138
+ // "There is nothing here yet" screen
139
+ // ctx.env && !ctx.legacyEnv
140
+ // ? `${ctx.env}.${worker.name}`
141
+ // : worker.name
142
+ }.${host.split(".").slice(1).join(".")}`
124
143
  : host,
125
144
  inspectorUrl,
126
145
  prewarmUrl,
package/src/api/worker.ts CHANGED
@@ -16,12 +16,13 @@ export interface CfAccount {
16
16
  * An account ID.
17
17
  */
18
18
  accountId: string;
19
- /**
20
- * A zone ID, only required if not using `workers.dev`.
21
- */
22
- zoneId?: string;
23
19
  }
24
20
 
21
+ /**
22
+ * The type of Worker
23
+ */
24
+ export type CfScriptFormat = "modules" | "service-worker";
25
+
25
26
  /**
26
27
  * A module type.
27
28
  */
@@ -66,7 +67,7 @@ export interface CfModule {
66
67
  * A map of variable names to values.
67
68
  */
68
69
  interface CfVars {
69
- [key: string]: string;
70
+ [key: string]: unknown;
70
71
  }
71
72
 
72
73
  /**
@@ -77,6 +78,22 @@ interface CfKvNamespace {
77
78
  id: string;
78
79
  }
79
80
 
81
+ /**
82
+ * A binding to a wasm module (in service worker format)
83
+ */
84
+
85
+ interface CfWasmModuleBindings {
86
+ [key: string]: string;
87
+ }
88
+
89
+ /**
90
+ * A binding to a text blob (in service worker format)
91
+ */
92
+
93
+ interface CfTextBlobBindings {
94
+ [key: string]: string;
95
+ }
96
+
80
97
  /**
81
98
  * A Durable Object.
82
99
  */
@@ -86,13 +103,14 @@ interface CfDurableObject {
86
103
  script_name?: string;
87
104
  }
88
105
 
89
- /**
90
- * A Service.
91
- */
92
- interface CfService {
106
+ interface CfR2Bucket {
107
+ binding: string;
108
+ bucket_name: string;
109
+ }
110
+
111
+ interface CfUnsafeBinding {
93
112
  name: string;
94
- service: string;
95
- environment: string;
113
+ type: string;
96
114
  }
97
115
 
98
116
  export interface CfDurableObjectMigrations {
@@ -100,7 +118,10 @@ export interface CfDurableObjectMigrations {
100
118
  new_tag: string;
101
119
  steps: {
102
120
  new_classes?: string[];
103
- renamed_classes?: string[];
121
+ renamed_classes?: {
122
+ from: string;
123
+ to: string;
124
+ }[];
104
125
  deleted_classes?: string[];
105
126
  }[];
106
127
  }
@@ -125,10 +146,13 @@ export interface CfWorkerInit {
125
146
  * All the bindings
126
147
  */
127
148
  bindings: {
128
- kv_namespaces?: CfKvNamespace[];
129
- durable_objects?: { bindings: CfDurableObject[] };
130
- vars?: CfVars;
131
- services?: CfService[];
149
+ vars: CfVars | undefined;
150
+ kv_namespaces: CfKvNamespace[] | undefined;
151
+ wasm_modules: CfWasmModuleBindings | undefined;
152
+ text_blobs: CfTextBlobBindings | undefined;
153
+ durable_objects: { bindings: CfDurableObject[] } | undefined;
154
+ r2_buckets: CfR2Bucket[] | undefined;
155
+ unsafe: CfUnsafeBinding[] | undefined;
132
156
  };
133
157
  migrations: undefined | CfDurableObjectMigrations;
134
158
  compatibility_date: string | undefined;
@@ -136,6 +160,12 @@ export interface CfWorkerInit {
136
160
  usage_model: undefined | "bundled" | "unbound";
137
161
  }
138
162
 
163
+ export interface CfWorkerContext {
164
+ env: string | undefined;
165
+ legacyEnv: boolean | undefined;
166
+ zone: string | undefined;
167
+ }
168
+
139
169
  /**
140
170
  * A stub to create a Cloudflare Worker preview.
141
171
  *
@@ -144,9 +174,10 @@ export interface CfWorkerInit {
144
174
  */
145
175
  export async function createWorker(
146
176
  init: CfWorkerInit,
147
- account: CfAccount
177
+ account: CfAccount,
178
+ ctx: CfWorkerContext
148
179
  ): Promise<CfPreviewToken> {
149
- const token = await previewToken(account, init);
180
+ const token = await previewToken(account, init, ctx);
150
181
  const response = await fetch(token.prewarmUrl.href, { method: "POST" });
151
182
  if (!response.ok) {
152
183
  // console.error("worker failed to prewarm: ", response.statusText);
package/src/bundle.ts ADDED
@@ -0,0 +1,133 @@
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 makeModuleCollector from "./module-collection";
6
+ import type { CfModule, CfScriptFormat } from "./api/worker";
7
+ import type { Config } from "./config";
8
+ import type { Entry } from "./entry";
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
+ format: CfScriptFormat;
28
+ rules: Config["rules"];
29
+ watch?: esbuild.WatchMode;
30
+ }
31
+ ): Promise<BundleResult> {
32
+ const {
33
+ serveAssetsFromWorker,
34
+ jsxFactory,
35
+ jsxFragment,
36
+ format,
37
+ rules,
38
+ watch,
39
+ } = options;
40
+ const moduleCollector = makeModuleCollector({ format, rules });
41
+ const result = await esbuild.build({
42
+ ...getEntryPoint(entry.file, serveAssetsFromWorker),
43
+ bundle: true,
44
+ absWorkingDir: entry.directory,
45
+ outdir: destination,
46
+ external: ["__STATIC_CONTENT_MANIFEST"],
47
+ format: "esm",
48
+ sourcemap: true,
49
+ metafile: true,
50
+ conditions: ["worker", "browser"],
51
+ loader: {
52
+ ".js": "jsx",
53
+ ".mjs": "jsx",
54
+ ".cjs": "jsx",
55
+ },
56
+ plugins: [moduleCollector.plugin],
57
+ ...(jsxFactory && { jsxFactory }),
58
+ ...(jsxFragment && { jsxFragment }),
59
+ watch,
60
+ });
61
+
62
+ const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
63
+ ([_path, output]) => output.entryPoint !== undefined
64
+ );
65
+ assert(
66
+ entryPointOutputs.length > 0,
67
+ `Cannot find entry-point "${entry.file}" in generated bundle.` +
68
+ listEntryPoints(entryPointOutputs)
69
+ );
70
+ assert(
71
+ entryPointOutputs.length < 2,
72
+ "More than one entry-point found for generated bundle." +
73
+ listEntryPoints(entryPointOutputs)
74
+ );
75
+
76
+ const entryPointExports = entryPointOutputs[0][1].exports;
77
+ const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
78
+
79
+ return {
80
+ modules: moduleCollector.modules,
81
+ resolvedEntryPointPath: path.resolve(
82
+ entry.directory,
83
+ entryPointOutputs[0][0]
84
+ ),
85
+ bundleType,
86
+ stop: result.stop,
87
+ };
88
+ }
89
+
90
+ type EntryPoint =
91
+ | { stdin: esbuild.StdinOptions; nodePaths: string[] }
92
+ | { entryPoints: string[] };
93
+
94
+ /**
95
+ * Create an object that describes the entry point for esbuild.
96
+ *
97
+ * If we are using the experimental asset handling, then the entry point is
98
+ * actually a shim worker that will either return an asset from a KV store,
99
+ * or delegate to the actual worker.
100
+ */
101
+ function getEntryPoint(
102
+ entryFile: string,
103
+ serveAssetsFromWorker: boolean
104
+ ): EntryPoint {
105
+ if (serveAssetsFromWorker) {
106
+ return {
107
+ stdin: {
108
+ contents: fs
109
+ .readFileSync(
110
+ path.join(__dirname, "../templates/static-asset-facade.js"),
111
+ "utf8"
112
+ )
113
+ .replace("__ENTRY_POINT__", entryFile),
114
+ sourcefile: "static-asset-facade.js",
115
+ resolveDir: path.dirname(entryFile),
116
+ },
117
+ nodePaths: [path.join(__dirname, "../vendor")],
118
+ };
119
+ } else {
120
+ return { entryPoints: [entryFile] };
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Generate a string that describes the entry-points that were identified by esbuild.
126
+ */
127
+ function listEntryPoints(
128
+ outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
129
+ ): string {
130
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
131
+ }
132
+
133
+ type ValueOf<T> = T[keyof T];
@@ -1,10 +1,11 @@
1
1
  import { URLSearchParams } from "node:url";
2
+ import { ParseError } from "../parse";
2
3
  import { fetchInternal } from "./internal";
3
4
  import type { RequestInit } from "undici";
4
5
 
5
6
  // Check out https://api.cloudflare.com/ for API docs.
6
7
 
7
- export { CF_API_BASE_URL } from "./internal";
8
+ export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
8
9
 
9
10
  export interface FetchError {
10
11
  code: number;
@@ -81,11 +82,12 @@ function throwFetchError(
81
82
  resource: string,
82
83
  response: FetchResult<unknown>
83
84
  ): never {
84
- response.messages.forEach((message) => console.warn(message));
85
- const errors = response.errors
86
- .map((error) => `${error.code}: ${error.message}`)
87
- .join("\n");
88
- const error = new Error(`Failed to fetch ${resource} - \n${errors}`);
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
+ });
89
91
  // add the first error code directly to this error
90
92
  // so consumers can use it for specific behaviour
91
93
  const code = response.errors[0]?.code;
@@ -1,10 +1,18 @@
1
1
  import { fetch } from "undici";
2
+ import { getEnvironmentVariableFactory } from "../environment-variables";
3
+ import { ParseError, parseJSON } from "../parse";
2
4
  import { getAPIToken, loginOrRefreshIfRequired } from "../user";
3
5
  import type { URLSearchParams } from "node:url";
4
6
  import type { RequestInit, HeadersInit } from "undici";
5
7
 
6
- export const CF_API_BASE_URL =
7
- process.env.CF_API_BASE_URL || "https://api.cloudflare.com/client/v4";
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
+ });
8
16
 
9
17
  /**
10
18
  * Make a fetch request to the Cloudflare API.
@@ -26,23 +34,44 @@ export async function fetchInternal<ResponseType>(
26
34
  addAuthorizationHeader(headers, apiToken);
27
35
 
28
36
  const queryString = queryParams ? `?${queryParams.toString()}` : "";
29
- const response = await fetch(`${CF_API_BASE_URL}${resource}${queryString}`, {
30
- method: "GET",
31
- ...init,
32
- headers,
33
- });
37
+ const method = init.method ?? "GET";
38
+ const response = await fetch(
39
+ `${getCloudflareAPIBaseURL()}${resource}${queryString}`,
40
+ {
41
+ method,
42
+ ...init,
43
+ headers,
44
+ }
45
+ );
34
46
  const jsonText = await response.text();
35
47
  try {
36
- const json = JSON.parse(jsonText);
37
- return json as ResponseType;
38
- } catch (e) {
39
- throw new Error(
40
- `Failed to fetch ${resource} - ${response.status}: ${response.statusText}\nInvalid JSON response:\n${jsonText}`
41
- );
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;
42
68
  }
69
+ return `${text.substring(0, maxLength)}... (length = ${length})`;
43
70
  }
44
71
 
45
- function cloneHeaders(headers: HeadersInit | undefined): HeadersInit {
72
+ function cloneHeaders(
73
+ headers: HeadersInit | undefined
74
+ ): Record<string, string> {
46
75
  return { ...headers };
47
76
  }
48
77
 
@@ -61,8 +90,11 @@ function requireApiToken(): string {
61
90
  return apiToken;
62
91
  }
63
92
 
64
- function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void {
65
- if (headers["Authorization"]) {
93
+ function addAuthorizationHeader(
94
+ headers: Record<string, string>,
95
+ apiToken: string
96
+ ): void {
97
+ if ("Authorization" in headers) {
66
98
  throw new Error(
67
99
  "The request already specifies an authorisation header - cannot add a new one."
68
100
  );
@@ -86,7 +118,7 @@ export async function fetchKVGetValue(
86
118
  await requireLoggedIn();
87
119
  const apiToken = requireApiToken();
88
120
  const headers = { Authorization: `Bearer ${apiToken}` };
89
- const resource = `${CF_API_BASE_URL}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
121
+ const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
90
122
  const response = await fetch(resource, {
91
123
  method: "GET",
92
124
  headers,
package/src/cli.ts CHANGED
@@ -1,6 +1,16 @@
1
+ import process from "process";
1
2
  import { hideBin } from "yargs/helpers";
3
+ import { reportError, initReporting } from "./reporting";
2
4
  import { main } from ".";
3
5
 
6
+ try {
7
+ initReporting();
8
+ } catch (error) {}
9
+
10
+ process.on("uncaughtExceptionMonitor", async (err, origin) => {
11
+ await reportError(err, origin);
12
+ });
13
+
4
14
  main(hideBin(process.argv)).catch(() => {
5
15
  // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
6
16
  // Here we just want to ensure that the process exits with a non-zero code.