wrangler 0.0.0-e3ce82b → 0.0.0-e41c7e41

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 (264) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +150 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +1451 -21
  5. package/package.json +191 -153
  6. package/src/__tests__/access.test.ts +25 -0
  7. package/src/__tests__/api-dev.test.ts +209 -0
  8. package/src/__tests__/api-devregistry.test.js +56 -0
  9. package/src/__tests__/api.test.ts +80 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +30 -24
  12. package/src/__tests__/configuration.test.ts +3970 -3476
  13. package/src/__tests__/d1.test.ts +80 -0
  14. package/src/__tests__/delete.test.ts +230 -0
  15. package/src/__tests__/deployments.test.ts +91 -0
  16. package/src/__tests__/dev.test.tsx +1508 -955
  17. package/src/__tests__/dialogs.test.tsx +40 -0
  18. package/src/__tests__/generate.test.ts +235 -0
  19. package/src/__tests__/get-host-from-url.test.ts +16 -0
  20. package/src/__tests__/guess-worker-format.test.ts +68 -68
  21. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  22. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  23. package/src/__tests__/helpers/mock-bin.ts +20 -20
  24. package/src/__tests__/helpers/mock-cfetch.ts +216 -94
  25. package/src/__tests__/helpers/mock-console.ts +58 -39
  26. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  27. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  28. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  29. package/src/__tests__/helpers/mock-istty.ts +65 -18
  30. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  31. package/src/__tests__/helpers/mock-kv.ts +27 -27
  32. package/src/__tests__/helpers/mock-oauth-flow.ts +225 -228
  33. package/src/__tests__/helpers/mock-process.ts +39 -0
  34. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  35. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  36. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  37. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  38. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  39. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  40. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  41. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  42. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  43. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  44. package/src/__tests__/helpers/msw/index.ts +21 -0
  45. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  46. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  47. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  48. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  52. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  53. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  54. package/src/__tests__/https-options.test.ts +142 -109
  55. package/src/__tests__/index.test.ts +241 -234
  56. package/src/__tests__/init.test.ts +2869 -1606
  57. package/src/__tests__/jest.setup.ts +159 -34
  58. package/src/__tests__/kv.test.ts +1660 -1466
  59. package/src/__tests__/logger.test.ts +100 -74
  60. package/src/__tests__/metrics.test.ts +450 -0
  61. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  62. package/src/__tests__/middleware.test.ts +726 -0
  63. package/src/__tests__/package-manager.test.ts +303 -303
  64. package/src/__tests__/pages-deployment-tail.test.ts +820 -0
  65. package/src/__tests__/pages.test.ts +2423 -735
  66. package/src/__tests__/parse.test.ts +252 -252
  67. package/src/__tests__/paths.test.ts +39 -0
  68. package/src/__tests__/publish.test.ts +7505 -5627
  69. package/src/__tests__/pubsub.test.ts +370 -0
  70. package/src/__tests__/queues.test.ts +371 -0
  71. package/src/__tests__/r2.test.ts +388 -228
  72. package/src/__tests__/route.test.ts +18 -18
  73. package/src/__tests__/secret.test.ts +622 -459
  74. package/src/__tests__/tail.test.ts +677 -567
  75. package/src/__tests__/test-old-node-version.js +31 -0
  76. package/src/__tests__/type-generation.test.ts +226 -0
  77. package/src/__tests__/user.test.ts +140 -116
  78. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  79. package/src/__tests__/validate-dev-props.test.ts +56 -0
  80. package/src/__tests__/version.test.ts +35 -0
  81. package/src/__tests__/whoami.test.tsx +264 -125
  82. package/src/__tests__/worker-namespace.test.ts +326 -0
  83. package/src/abort.d.ts +1 -1
  84. package/src/api/dev.ts +210 -0
  85. package/src/api/index.ts +2 -0
  86. package/src/bundle-reporter.tsx +68 -0
  87. package/src/bundle.ts +785 -159
  88. package/src/cfetch/index.ts +120 -81
  89. package/src/cfetch/internal.ts +207 -86
  90. package/src/cli.ts +23 -8
  91. package/src/config/config.ts +236 -195
  92. package/src/config/diagnostics.ts +61 -61
  93. package/src/config/environment.ts +498 -357
  94. package/src/config/index.ts +302 -193
  95. package/src/config/validation-helpers.ts +379 -366
  96. package/src/config/validation.ts +1931 -1376
  97. package/src/config-cache.ts +81 -41
  98. package/src/create-worker-preview.ts +239 -142
  99. package/src/create-worker-upload-form.ts +300 -238
  100. package/src/d1/backups.tsx +218 -0
  101. package/src/d1/constants.ts +2 -0
  102. package/src/d1/create.tsx +63 -0
  103. package/src/d1/delete.tsx +56 -0
  104. package/src/d1/execute.tsx +352 -0
  105. package/src/d1/formatTimeAgo.ts +14 -0
  106. package/src/d1/index.ts +99 -0
  107. package/src/d1/list.tsx +48 -0
  108. package/src/d1/migrations.tsx +446 -0
  109. package/src/d1/options.ts +22 -0
  110. package/src/d1/types.tsx +24 -0
  111. package/src/d1/utils.ts +48 -0
  112. package/src/delete.ts +108 -0
  113. package/src/deployments.ts +77 -0
  114. package/src/deprecated/index.ts +438 -0
  115. package/src/dev/dev-vars.ts +20 -17
  116. package/src/dev/dev.tsx +522 -333
  117. package/src/dev/get-local-persistence-path.tsx +31 -0
  118. package/src/dev/local.tsx +866 -302
  119. package/src/dev/remote.tsx +591 -225
  120. package/src/dev/start-server.ts +538 -0
  121. package/src/dev/use-esbuild.ts +183 -97
  122. package/src/dev/validate-dev-props.ts +31 -0
  123. package/src/dev-registry.tsx +201 -0
  124. package/src/dev.tsx +905 -0
  125. package/src/dialogs.tsx +132 -99
  126. package/src/dispatch-namespace.ts +207 -0
  127. package/src/durable.ts +87 -87
  128. package/src/entry.ts +235 -228
  129. package/src/environment-variables.ts +38 -23
  130. package/src/errors.ts +6 -6
  131. package/src/git-client.ts +124 -0
  132. package/src/global-wrangler-config-path.ts +26 -0
  133. package/src/https-options.ts +84 -80
  134. package/src/index.tsx +625 -2789
  135. package/src/init.ts +970 -0
  136. package/src/inspect.ts +698 -593
  137. package/src/intl-polyfill.d.ts +123 -123
  138. package/src/is-ci.ts +14 -0
  139. package/src/is-interactive.ts +16 -0
  140. package/src/kv/helpers.ts +430 -0
  141. package/src/kv/index.ts +596 -0
  142. package/src/logger.ts +67 -41
  143. package/src/metrics/index.ts +5 -0
  144. package/src/metrics/metrics-config.ts +239 -0
  145. package/src/metrics/metrics-dispatcher.ts +96 -0
  146. package/src/metrics/metrics-usage-headers.ts +24 -0
  147. package/src/metrics/send-event.ts +96 -0
  148. package/src/miniflare-cli/assets.ts +215 -0
  149. package/src/miniflare-cli/index.ts +205 -33
  150. package/src/miniflare-cli/request-context.ts +18 -18
  151. package/src/module-collection.ts +221 -212
  152. package/src/open-in-browser.ts +4 -6
  153. package/src/package-manager.ts +173 -128
  154. package/src/pages/build.tsx +270 -0
  155. package/src/pages/constants.ts +18 -0
  156. package/src/pages/deployment-tails.tsx +284 -0
  157. package/src/pages/deployments.tsx +84 -0
  158. package/src/pages/dev.tsx +708 -0
  159. package/src/pages/errors.ts +66 -0
  160. package/src/pages/functions/buildPlugin.ts +107 -0
  161. package/src/pages/functions/buildWorker.ts +166 -0
  162. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  163. package/src/pages/functions/filepath-routing.ts +189 -0
  164. package/src/pages/functions/identifiers.ts +78 -0
  165. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  166. package/src/pages/functions/routes-consolidation.ts +73 -0
  167. package/src/pages/functions/routes-transformation.test.ts +282 -0
  168. package/src/pages/functions/routes-transformation.ts +115 -0
  169. package/src/pages/functions/routes-validation.test.ts +403 -0
  170. package/src/pages/functions/routes-validation.ts +202 -0
  171. package/src/pages/functions/routes.ts +151 -0
  172. package/src/pages/functions.tsx +82 -0
  173. package/src/pages/hash.tsx +13 -0
  174. package/src/pages/index.tsx +102 -0
  175. package/src/pages/projects.tsx +169 -0
  176. package/src/pages/prompt-select-project.tsx +31 -0
  177. package/src/pages/publish.tsx +451 -0
  178. package/src/pages/types.ts +41 -0
  179. package/src/pages/upload.tsx +426 -0
  180. package/src/pages/utils.ts +23 -0
  181. package/src/parse.ts +208 -125
  182. package/src/paths.ts +53 -8
  183. package/src/proxy.ts +618 -407
  184. package/src/publish/index.ts +270 -0
  185. package/src/publish/publish.ts +1035 -0
  186. package/src/pubsub/index.ts +286 -0
  187. package/src/pubsub/pubsub-commands.tsx +624 -0
  188. package/src/queues/cli/commands/consumer/add.ts +71 -0
  189. package/src/queues/cli/commands/consumer/index.ts +22 -0
  190. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  191. package/src/queues/cli/commands/create.ts +25 -0
  192. package/src/queues/cli/commands/delete.ts +26 -0
  193. package/src/queues/cli/commands/index.ts +33 -0
  194. package/src/queues/cli/commands/list.ts +25 -0
  195. package/src/queues/client.ts +135 -0
  196. package/src/r2/constants.ts +4 -0
  197. package/src/r2/helpers.ts +131 -0
  198. package/src/r2/index.ts +289 -0
  199. package/src/routes.ts +140 -0
  200. package/src/secret/index.ts +378 -0
  201. package/src/selfsigned.d.ts +23 -23
  202. package/src/sites.tsx +273 -227
  203. package/src/tail/createTail.ts +379 -0
  204. package/src/tail/filters.ts +108 -110
  205. package/src/tail/index.ts +211 -296
  206. package/src/tail/printing.ts +86 -46
  207. package/src/type-generation.ts +173 -0
  208. package/src/update-check.ts +11 -11
  209. package/src/user/access.ts +69 -0
  210. package/src/user/choose-account.tsx +69 -0
  211. package/src/user/env-vars.ts +46 -0
  212. package/src/user/generate-auth-url.ts +33 -0
  213. package/src/user/generate-random-state.ts +16 -0
  214. package/src/user/index.ts +3 -0
  215. package/src/user/user.tsx +1192 -0
  216. package/src/utils/collectKeyValues.ts +14 -0
  217. package/src/whoami.tsx +141 -43
  218. package/src/worker.ts +171 -107
  219. package/src/yargs-types.ts +24 -0
  220. package/src/zones.ts +158 -40
  221. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  222. package/templates/checked-fetch.js +17 -0
  223. package/templates/d1-beta-facade.js +205 -0
  224. package/templates/first-party-worker-module-facade.ts +18 -0
  225. package/templates/format-dev-errors.ts +32 -0
  226. package/templates/init-tests/test-jest-new-worker.js +25 -0
  227. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  228. package/templates/middleware/common.ts +62 -0
  229. package/templates/middleware/loader-modules.ts +84 -0
  230. package/templates/middleware/loader-sw.ts +227 -0
  231. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  232. package/templates/middleware/middleware-pretty-error.ts +40 -0
  233. package/templates/middleware/middleware-scheduled.ts +15 -0
  234. package/templates/new-worker-scheduled.js +3 -3
  235. package/templates/new-worker-scheduled.ts +15 -15
  236. package/templates/new-worker.js +3 -3
  237. package/templates/new-worker.ts +15 -15
  238. package/templates/no-op-worker.js +10 -0
  239. package/templates/pages-dev-pipeline.ts +28 -0
  240. package/templates/pages-dev-util.ts +52 -0
  241. package/templates/pages-shim.ts +9 -0
  242. package/templates/pages-template-plugin.ts +171 -0
  243. package/templates/pages-template-worker.ts +189 -0
  244. package/templates/serve-static-assets.ts +63 -0
  245. package/templates/service-bindings-module-facade.js +54 -0
  246. package/templates/service-bindings-sw-facade.js +42 -0
  247. package/templates/tsconfig.json +96 -95
  248. package/wrangler-dist/cli.d.ts +893 -0
  249. package/wrangler-dist/cli.js +146109 -108690
  250. package/pages/functions/buildPlugin.ts +0 -105
  251. package/pages/functions/buildWorker.ts +0 -151
  252. package/pages/functions/filepath-routing.ts +0 -189
  253. package/pages/functions/identifiers.ts +0 -78
  254. package/pages/functions/routes.ts +0 -156
  255. package/pages/functions/template-plugin.ts +0 -147
  256. package/pages/functions/template-worker.ts +0 -143
  257. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  258. package/src/kv.ts +0 -408
  259. package/src/miniflare-cli/enum-keys.ts +0 -17
  260. package/src/pages.tsx +0 -2093
  261. package/src/publish.ts +0 -721
  262. package/src/r2.ts +0 -50
  263. package/src/user.tsx +0 -1214
  264. package/templates/static-asset-facade.js +0 -43
@@ -1,6 +1,7 @@
1
1
  import { URLSearchParams } from "node:url";
2
+ import { logger } from "../logger";
2
3
  import { ParseError } from "../parse";
3
- import { fetchInternal } from "./internal";
4
+ import { fetchInternal, performApiFetch } from "./internal";
4
5
  import type { RequestInit } from "undici";
5
6
 
6
7
  // Check out https://api.cloudflare.com/ for API docs.
@@ -8,16 +9,16 @@ import type { RequestInit } from "undici";
8
9
  export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
9
10
 
10
11
  export interface FetchError {
11
- code: number;
12
- message: string;
13
- error_chain?: FetchError[];
12
+ code: number;
13
+ message: string;
14
+ error_chain?: FetchError[];
14
15
  }
15
16
  export interface FetchResult<ResponseType = unknown> {
16
- success: boolean;
17
- result: ResponseType;
18
- errors: FetchError[];
19
- messages: string[];
20
- result_info?: unknown;
17
+ success: boolean;
18
+ result: ResponseType;
19
+ errors: FetchError[];
20
+ messages: string[];
21
+ result_info?: unknown;
21
22
  }
22
23
 
23
24
  export { fetchKVGetValue } from "./internal";
@@ -26,22 +27,22 @@ export { fetchKVGetValue } from "./internal";
26
27
  * Make a fetch request, and extract the `result` from the JSON response.
27
28
  */
28
29
  export async function fetchResult<ResponseType>(
29
- resource: string,
30
- init: RequestInit = {},
31
- queryParams?: URLSearchParams,
32
- abortSignal?: AbortSignal
30
+ resource: string,
31
+ init: RequestInit = {},
32
+ queryParams?: URLSearchParams,
33
+ abortSignal?: AbortSignal
33
34
  ): 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
- }
35
+ const json = await fetchInternal<FetchResult<ResponseType>>(
36
+ resource,
37
+ init,
38
+ queryParams,
39
+ abortSignal
40
+ );
41
+ if (json.success) {
42
+ return json.result;
43
+ } else {
44
+ throwFetchError(resource, json);
45
+ }
45
46
  }
46
47
 
47
48
  /**
@@ -50,72 +51,110 @@ export async function fetchResult<ResponseType>(
50
51
  * and repeating the request if the results are paginated.
51
52
  */
52
53
  export async function fetchListResult<ResponseType>(
53
- resource: string,
54
- init: RequestInit = {},
55
- queryParams?: URLSearchParams
54
+ resource: string,
55
+ init: RequestInit = {},
56
+ queryParams?: URLSearchParams
56
57
  ): 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;
58
+ const results: ResponseType[] = [];
59
+ let getMoreResults = true;
60
+ let cursor: string | undefined;
61
+ while (getMoreResults) {
62
+ if (cursor) {
63
+ queryParams = new URLSearchParams(queryParams);
64
+ queryParams.set("cursor", cursor);
65
+ }
66
+ const json = await fetchInternal<FetchResult<ResponseType[]>>(
67
+ resource,
68
+ init,
69
+ queryParams
70
+ );
71
+ if (json.success) {
72
+ results.push(...json.result);
73
+ if (hasCursor(json.result_info)) {
74
+ cursor = json.result_info?.cursor;
75
+ } else {
76
+ getMoreResults = false;
77
+ }
78
+ } else {
79
+ throwFetchError(resource, json);
80
+ }
81
+ }
82
+ return results;
82
83
  }
83
84
 
84
85
  function throwFetchError(
85
- resource: string,
86
- response: FetchResult<unknown>
86
+ resource: string,
87
+ response: FetchResult<unknown>
87
88
  ): 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;
89
+ const error = new ParseError({
90
+ text: `A request to the Cloudflare API (${resource}) failed.`,
91
+ notes: response.errors.map((err) => ({
92
+ text: renderError(err),
93
+ })),
94
+ });
95
+ // add the first error code directly to this error
96
+ // so consumers can use it for specific behaviour
97
+ const code = response.errors[0]?.code;
98
+ if (code) {
99
+ //@ts-expect-error non-standard property on Error
100
+ error.code = code;
101
+ }
102
+ throw error;
102
103
  }
103
104
 
104
105
  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 !== "";
106
+ const cursor = (result_info as { cursor: string } | undefined)?.cursor;
107
+ return cursor !== undefined && cursor !== null && cursor !== "";
107
108
  }
108
109
 
109
110
  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
- );
111
+ const chainedMessages =
112
+ err.error_chain
113
+ ?.map(
114
+ (chainedError) =>
115
+ `\n${" ".repeat(level)}- ${renderError(chainedError, level + 1)}`
116
+ )
117
+ .join("\n") ?? "";
118
+ return (
119
+ (err.code ? `${err.message} [code: ${err.code}]` : err.message) +
120
+ chainedMessages
121
+ );
122
+ }
123
+
124
+ /**
125
+ * Fetch the raw script content of a Worker
126
+ * Note, this will concatenate the files of multi-module workers
127
+ */
128
+ export async function fetchScriptContent(
129
+ resource: string,
130
+ init: RequestInit = {},
131
+ queryParams?: URLSearchParams,
132
+ abortSignal?: AbortSignal
133
+ ): Promise<string> {
134
+ const response = await performApiFetch(
135
+ resource,
136
+ init,
137
+ queryParams,
138
+ abortSignal
139
+ );
140
+
141
+ logger.debug(
142
+ "-- START CF API RESPONSE:",
143
+ response.statusText,
144
+ response.status
145
+ );
146
+
147
+ logger.debug("HEADERS:", { ...response.headers });
148
+ // logger.debug("RESPONSE:", text);
149
+ logger.debug("-- END CF API RESPONSE");
150
+ const contentType = response.headers.get("content-type");
151
+
152
+ const usesModules = contentType?.startsWith("multipart");
153
+ if (usesModules && contentType) {
154
+ const form = await response.formData();
155
+ const entries = Array.from(form.entries());
156
+ return entries.map((e) => e[1]).join("\n");
157
+ } else {
158
+ return await response.text();
159
+ }
121
160
  }
@@ -1,21 +1,60 @@
1
1
  import assert from "node:assert";
2
- import { fetch, Headers } from "undici";
2
+ import { fetch, File, Headers } from "undici";
3
3
  import { version as wranglerVersion } from "../../package.json";
4
4
  import { getEnvironmentVariableFactory } from "../environment-variables";
5
+ import { logger } from "../logger";
5
6
  import { ParseError, parseJSON } from "../parse";
6
7
  import { loginOrRefreshIfRequired, requireApiToken } from "../user";
8
+ import type { ApiCredentials } from "../user";
7
9
  import type { URLSearchParams } from "node:url";
8
- import type { RequestInit, HeadersInit } from "undici";
10
+ import type { RequestInit, HeadersInit, Response } from "undici";
9
11
 
10
12
  /**
11
13
  * Get the URL to use to access the Cloudflare API.
12
14
  */
13
15
  export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
14
- variableName: "CLOUDFLARE_API_BASE_URL",
15
- deprecatedName: "CF_API_BASE_URL",
16
- defaultValue: "https://api.cloudflare.com/client/v4",
16
+ variableName: "CLOUDFLARE_API_BASE_URL",
17
+ deprecatedName: "CF_API_BASE_URL",
18
+ defaultValue: "https://api.cloudflare.com/client/v4",
17
19
  });
18
20
 
21
+ /*
22
+ * performApiFetch does everything required to make a CF API request,
23
+ * but doesn't parse the response as JSON. For normal V4 API responses,
24
+ * use `fetchInternal`
25
+ * */
26
+ export async function performApiFetch(
27
+ resource: string,
28
+ init: RequestInit = {},
29
+ queryParams?: URLSearchParams,
30
+ abortSignal?: AbortSignal
31
+ ) {
32
+ const method = init.method ?? "GET";
33
+ assert(
34
+ resource.startsWith("/"),
35
+ `CF API fetch - resource path must start with a "/" but got "${resource}"`
36
+ );
37
+ await requireLoggedIn();
38
+ const apiToken = requireApiToken();
39
+ const headers = cloneHeaders(init.headers);
40
+ addAuthorizationHeaderIfUnspecified(headers, apiToken);
41
+ addUserAgent(headers);
42
+
43
+ const queryString = queryParams ? `?${queryParams.toString()}` : "";
44
+ logger.debug(
45
+ `-- START CF API REQUEST: ${method} ${getCloudflareAPIBaseURL()}${resource}${queryString}`
46
+ );
47
+ logger.debug("HEADERS:", JSON.stringify(headers, null, 2));
48
+ logger.debug("INIT:", JSON.stringify(init, null, 2));
49
+ logger.debug("-- END CF API REQUEST");
50
+ return await fetch(`${getCloudflareAPIBaseURL()}${resource}${queryString}`, {
51
+ method,
52
+ ...init,
53
+ headers,
54
+ signal: abortSignal,
55
+ });
56
+ }
57
+
19
58
  /**
20
59
  * Make a fetch request to the Cloudflare API.
21
60
  *
@@ -26,86 +65,86 @@ export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
26
65
  * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
27
66
  */
28
67
  export async function fetchInternal<ResponseType>(
29
- resource: string,
30
- init: RequestInit = {},
31
- queryParams?: URLSearchParams,
32
- abortSignal?: AbortSignal
68
+ resource: string,
69
+ init: RequestInit = {},
70
+ queryParams?: URLSearchParams,
71
+ abortSignal?: AbortSignal
33
72
  ): Promise<ResponseType> {
34
- assert(
35
- resource.startsWith("/"),
36
- `CF API fetch - resource path must start with a "/" but got "${resource}"`
37
- );
38
- await requireLoggedIn();
39
- const apiToken = requireApiToken();
40
- const headers = cloneHeaders(init.headers);
41
- addAuthorizationHeaderIfUnspecified(headers, apiToken);
42
- addUserAgent(headers);
43
-
44
- const queryString = queryParams ? `?${queryParams.toString()}` : "";
45
- const method = init.method ?? "GET";
46
- const response = await fetch(
47
- `${getCloudflareAPIBaseURL()}${resource}${queryString}`,
48
- {
49
- method,
50
- ...init,
51
- headers,
52
- signal: abortSignal,
53
- }
54
- );
55
- const jsonText = await response.text();
56
- try {
57
- return parseJSON<ResponseType>(jsonText);
58
- } catch (err) {
59
- throw new ParseError({
60
- text: "Received a malformed response from the API",
61
- notes: [
62
- {
63
- text: truncate(jsonText, 100),
64
- },
65
- {
66
- text: `${method} ${resource} -> ${response.status} ${response.statusText}`,
67
- },
68
- ],
69
- });
70
- }
73
+ const method = init.method ?? "GET";
74
+ const response = await performApiFetch(
75
+ resource,
76
+ init,
77
+ queryParams,
78
+ abortSignal
79
+ );
80
+ const jsonText = await response.text();
81
+ logger.debug(
82
+ "-- START CF API RESPONSE:",
83
+ response.statusText,
84
+ response.status
85
+ );
86
+ logger.debug("HEADERS:", JSON.stringify(response.headers, null, 2));
87
+ logger.debug("RESPONSE:", jsonText);
88
+ logger.debug("-- END CF API RESPONSE");
89
+
90
+ try {
91
+ return parseJSON<ResponseType>(jsonText);
92
+ } catch (err) {
93
+ throw new ParseError({
94
+ text: "Received a malformed response from the API",
95
+ notes: [
96
+ {
97
+ text: truncate(jsonText, 100),
98
+ },
99
+ {
100
+ text: `${method} ${resource} -> ${response.status} ${response.statusText}`,
101
+ },
102
+ ],
103
+ });
104
+ }
71
105
  }
72
106
 
73
107
  function truncate(text: string, maxLength: number): string {
74
- const { length } = text;
75
- if (length <= maxLength) {
76
- return text;
77
- }
78
- return `${text.substring(0, maxLength)}... (length = ${length})`;
108
+ const { length } = text;
109
+ if (length <= maxLength) {
110
+ return text;
111
+ }
112
+ return `${text.substring(0, maxLength)}... (length = ${length})`;
79
113
  }
80
114
 
81
115
  function cloneHeaders(
82
- headers: HeadersInit | undefined
116
+ headers: HeadersInit | undefined
83
117
  ): Record<string, string> {
84
- return headers instanceof Headers
85
- ? Object.fromEntries(headers.entries())
86
- : Array.isArray(headers)
87
- ? Object.fromEntries(headers)
88
- : { ...headers };
118
+ return headers instanceof Headers
119
+ ? Object.fromEntries(headers.entries())
120
+ : Array.isArray(headers)
121
+ ? Object.fromEntries(headers)
122
+ : { ...headers };
89
123
  }
90
124
 
91
125
  async function requireLoggedIn(): Promise<void> {
92
- const loggedIn = await loginOrRefreshIfRequired();
93
- if (!loggedIn) {
94
- throw new Error("Not logged in.");
95
- }
126
+ const loggedIn = await loginOrRefreshIfRequired();
127
+ if (!loggedIn) {
128
+ throw new Error("Not logged in.");
129
+ }
96
130
  }
97
131
 
98
132
  function addAuthorizationHeaderIfUnspecified(
99
- headers: Record<string, string>,
100
- apiToken: string
133
+ headers: Record<string, string>,
134
+ auth: ApiCredentials
101
135
  ): void {
102
- if (!("Authorization" in headers)) {
103
- headers["Authorization"] = `Bearer ${apiToken}`;
104
- }
136
+ if (!("Authorization" in headers)) {
137
+ if ("apiToken" in auth) {
138
+ headers["Authorization"] = `Bearer ${auth.apiToken}`;
139
+ } else {
140
+ headers["X-Auth-Key"] = auth.authKey;
141
+ headers["X-Auth-Email"] = auth.authEmail;
142
+ }
143
+ }
105
144
  }
106
145
 
107
146
  function addUserAgent(headers: Record<string, string>): void {
108
- headers["User-Agent"] = `wrangler/${wranglerVersion}`;
147
+ headers["User-Agent"] = `wrangler/${wranglerVersion}`;
109
148
  }
110
149
 
111
150
  /**
@@ -118,25 +157,107 @@ function addUserAgent(headers: Record<string, string>): void {
118
157
  * Note: any calls to fetchKVGetValue must call encodeURIComponent on key
119
158
  * before passing it
120
159
  */
121
-
122
160
  export async function fetchKVGetValue(
123
- accountId: string,
124
- namespaceId: string,
125
- key: string
161
+ accountId: string,
162
+ namespaceId: string,
163
+ key: string
164
+ ): Promise<ArrayBuffer> {
165
+ await requireLoggedIn();
166
+ const auth = requireApiToken();
167
+ const headers: Record<string, string> = {};
168
+ addAuthorizationHeaderIfUnspecified(headers, auth);
169
+ const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
170
+ const response = await fetch(resource, {
171
+ method: "GET",
172
+ headers,
173
+ });
174
+ if (response.ok) {
175
+ return await response.arrayBuffer();
176
+ } else {
177
+ throw new Error(
178
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
179
+ );
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The implementation for fetching a R2 object from Cloudflare API.
185
+ * We have a special implementation to handle the non-standard API response
186
+ * that doesn't return JSON, likely due to the streaming nature.
187
+ *
188
+ * note: The implementation should be called from light wrappers for
189
+ * different methods (GET, PUT)
190
+ */
191
+ type ResponseWithBody = Response & { body: NonNullable<Response["body"]> };
192
+ export async function fetchR2Objects(
193
+ resource: string,
194
+ bodyInit: RequestInit = {}
195
+ ): Promise<ResponseWithBody> {
196
+ await requireLoggedIn();
197
+ const auth = requireApiToken();
198
+ const headers = cloneHeaders(bodyInit.headers);
199
+ addAuthorizationHeaderIfUnspecified(headers, auth);
200
+ addUserAgent(headers);
201
+
202
+ const response = await fetch(`${getCloudflareAPIBaseURL()}${resource}`, {
203
+ ...bodyInit,
204
+ headers,
205
+ });
206
+
207
+ if (response.ok && response.body) {
208
+ return response as ResponseWithBody;
209
+ } else {
210
+ throw new Error(
211
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
212
+ );
213
+ }
214
+ }
215
+
216
+ /**
217
+ * This is a wrapper STOPGAP for getting the script which returns a raw text response.
218
+ */
219
+ export async function fetchDashboardScript(
220
+ resource: string,
221
+ bodyInit: RequestInit = {}
126
222
  ): Promise<string> {
127
- await requireLoggedIn();
128
- const apiToken = requireApiToken();
129
- const headers = { Authorization: `Bearer ${apiToken}` };
130
- const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
131
- const response = await fetch(resource, {
132
- method: "GET",
133
- headers,
134
- });
135
- if (response.ok) {
136
- return await response.text();
137
- } else {
138
- throw new Error(
139
- `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
140
- );
141
- }
223
+ await requireLoggedIn();
224
+ const auth = requireApiToken();
225
+ const headers = cloneHeaders(bodyInit.headers);
226
+ addAuthorizationHeaderIfUnspecified(headers, auth);
227
+ addUserAgent(headers);
228
+
229
+ const response = await fetch(`${getCloudflareAPIBaseURL()}${resource}`, {
230
+ ...bodyInit,
231
+ headers,
232
+ });
233
+
234
+ if (!response.ok || !response.body) {
235
+ throw new Error(
236
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
237
+ );
238
+ }
239
+
240
+ const usesModules = response.headers
241
+ .get("content-type")
242
+ ?.startsWith("multipart");
243
+
244
+ if (usesModules) {
245
+ // Response from edge contains generic "name = worker.js" for dashboard created scripts
246
+ const form = await response.formData();
247
+ const entries = Array.from(form.entries());
248
+ if (entries.length > 1)
249
+ throw new RangeError("Expected only one entry in multipart response");
250
+ const [_, file] = entries[0];
251
+
252
+ if (file instanceof File) {
253
+ return await file.text();
254
+ }
255
+
256
+ return file ?? "";
257
+
258
+ // Follow up on issue in Undici about multipart/form-data support & replace the workaround: https://github.com/nodejs/undici/issues/974
259
+ // This should be using a builtin formData() parser pattern.
260
+ } else {
261
+ return response.text();
262
+ }
142
263
  }
package/src/cli.ts CHANGED
@@ -1,13 +1,28 @@
1
- import "dotenv/config"; // Grab locally specified env params from a `.env` file.
2
1
  import process from "process";
3
2
  import { hideBin } from "yargs/helpers";
3
+ import { unstable_dev } from "./api";
4
4
  import { FatalError } from "./errors";
5
5
  import { main } from ".";
6
6
 
7
- main(hideBin(process.argv)).catch((e) => {
8
- // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
9
- // Here we just want to ensure that the process exits with a non-zero code.
10
- // We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
11
- const exitCode = (e instanceof FatalError && e.code) || 1;
12
- process.exit(exitCode);
13
- });
7
+ import type { UnstableDevWorker } from "./api";
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 === module) {
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 { unstable_dev };
28
+ export type { UnstableDevWorker };