wrangler 0.0.0-e6733a3 → 0.0.0-e7a0cd5b

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 (302) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -14
  3. package/bin/wrangler.js +160 -28
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +6316 -0
  6. package/package.json +190 -124
  7. package/src/__tests__/access.test.ts +25 -0
  8. package/src/__tests__/api-dev.test.ts +209 -0
  9. package/src/__tests__/api-devregistry.test.js +57 -0
  10. package/src/__tests__/api.test.ts +80 -0
  11. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  12. package/src/__tests__/config-cache.test.ts +42 -0
  13. package/src/__tests__/configuration.test.ts +4028 -0
  14. package/src/__tests__/d1.test.ts +72 -0
  15. package/src/__tests__/delete.test.ts +230 -0
  16. package/src/__tests__/deployments.test.ts +95 -0
  17. package/src/__tests__/dev.test.tsx +1505 -62
  18. package/src/__tests__/dialogs.test.tsx +40 -0
  19. package/src/__tests__/generate.test.ts +235 -0
  20. package/src/__tests__/get-host-from-url.test.ts +16 -0
  21. package/src/__tests__/guess-worker-format.test.ts +85 -0
  22. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  23. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  24. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  25. package/src/__tests__/helpers/mock-bin.ts +36 -0
  26. package/src/__tests__/helpers/mock-cfetch.ts +333 -0
  27. package/src/__tests__/helpers/mock-console.ts +106 -0
  28. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  29. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  30. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  31. package/src/__tests__/helpers/mock-istty.ts +74 -0
  32. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  33. package/src/__tests__/helpers/mock-kv.ts +33 -0
  34. package/src/__tests__/helpers/mock-oauth-flow.ts +252 -0
  35. package/src/__tests__/helpers/mock-process.ts +39 -0
  36. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  37. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  38. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  39. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  40. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  41. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  42. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  43. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  44. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  45. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  46. package/src/__tests__/helpers/msw/index.ts +21 -0
  47. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  48. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  49. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  51. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  52. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  53. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  54. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  55. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  56. package/src/__tests__/https-options.test.ts +163 -0
  57. package/src/__tests__/index.test.ts +259 -284
  58. package/src/__tests__/init.test.ts +2900 -0
  59. package/src/__tests__/jest.setup.ts +190 -10
  60. package/src/__tests__/kv.test.ts +1668 -1091
  61. package/src/__tests__/logger.test.ts +141 -0
  62. package/src/__tests__/metrics.test.ts +450 -0
  63. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  64. package/src/__tests__/middleware.test.ts +726 -0
  65. package/src/__tests__/package-manager.test.ts +353 -0
  66. package/src/__tests__/pages.test.ts +2223 -0
  67. package/src/__tests__/parse.test.ts +330 -0
  68. package/src/__tests__/paths.test.ts +39 -0
  69. package/src/__tests__/publish.test.ts +7660 -0
  70. package/src/__tests__/pubsub.test.ts +370 -0
  71. package/src/__tests__/queues.test.ts +371 -0
  72. package/src/__tests__/r2.test.ts +376 -0
  73. package/src/__tests__/route.test.ts +45 -0
  74. package/src/__tests__/secret.test.ts +644 -0
  75. package/src/__tests__/tail.test.ts +800 -0
  76. package/src/__tests__/test-old-node-version.js +31 -0
  77. package/src/__tests__/type-generation.test.ts +217 -0
  78. package/src/__tests__/user.test.ts +155 -0
  79. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  80. package/src/__tests__/validate-dev-props.test.ts +56 -0
  81. package/src/__tests__/version.test.ts +35 -0
  82. package/src/__tests__/whoami.test.tsx +278 -0
  83. package/src/__tests__/worker-namespace.test.ts +326 -0
  84. package/src/abort.d.ts +3 -0
  85. package/src/api/dev.ts +208 -0
  86. package/src/api/index.ts +2 -0
  87. package/src/bundle-reporter.tsx +68 -0
  88. package/src/bundle.ts +785 -0
  89. package/src/cfetch/index.ts +128 -70
  90. package/src/cfetch/internal.ts +240 -46
  91. package/src/cli.ts +25 -6
  92. package/src/config/README.md +107 -0
  93. package/src/config/config.ts +275 -0
  94. package/src/config/diagnostics.ts +80 -0
  95. package/src/config/environment.ts +563 -0
  96. package/src/config/index.ts +342 -0
  97. package/src/config/validation-helpers.ts +597 -0
  98. package/src/config/validation.ts +2113 -0
  99. package/src/config-cache.ts +85 -0
  100. package/src/create-worker-preview.ts +282 -0
  101. package/src/create-worker-upload-form.ts +321 -0
  102. package/src/d1/backups.tsx +218 -0
  103. package/src/d1/create.tsx +54 -0
  104. package/src/d1/delete.tsx +56 -0
  105. package/src/d1/execute.tsx +299 -0
  106. package/src/d1/formatTimeAgo.ts +14 -0
  107. package/src/d1/index.ts +76 -0
  108. package/src/d1/list.tsx +48 -0
  109. package/src/d1/options.ts +12 -0
  110. package/src/d1/types.tsx +14 -0
  111. package/src/d1/utils.ts +39 -0
  112. package/src/delete.ts +108 -0
  113. package/src/deployments.ts +74 -0
  114. package/src/deprecated/index.ts +438 -0
  115. package/src/dev/dev-vars.ts +39 -0
  116. package/src/dev/dev.tsx +587 -0
  117. package/src/dev/get-local-persistence-path.tsx +31 -0
  118. package/src/dev/local.tsx +717 -0
  119. package/src/dev/remote.tsx +603 -0
  120. package/src/dev/start-server.ts +513 -0
  121. package/src/dev/use-esbuild.ts +204 -0
  122. package/src/dev/validate-dev-props.ts +31 -0
  123. package/src/dev-registry.tsx +201 -0
  124. package/src/dev.tsx +848 -750
  125. package/src/dialogs.tsx +146 -60
  126. package/src/dispatch-namespace.ts +207 -0
  127. package/src/durable.ts +102 -0
  128. package/src/entry.ts +329 -0
  129. package/src/environment-variables.ts +50 -0
  130. package/src/errors.ts +11 -0
  131. package/src/git-client.ts +124 -0
  132. package/src/global-wrangler-config-path.ts +26 -0
  133. package/src/https-options.ts +127 -0
  134. package/src/index.tsx +669 -1959
  135. package/src/init.ts +970 -0
  136. package/src/inspect.ts +720 -477
  137. package/src/intl-polyfill.d.ts +139 -0
  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 +92 -0
  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 +94 -0
  148. package/src/miniflare-cli/README.md +30 -0
  149. package/src/miniflare-cli/assets.ts +215 -0
  150. package/src/miniflare-cli/index.ts +213 -0
  151. package/src/miniflare-cli/request-context.ts +40 -0
  152. package/src/module-collection.ts +256 -53
  153. package/src/open-in-browser.ts +17 -0
  154. package/src/package-manager.ts +219 -0
  155. package/src/pages/build.tsx +238 -0
  156. package/src/pages/constants.ts +18 -0
  157. package/src/pages/deployments.tsx +106 -0
  158. package/src/pages/dev.tsx +693 -0
  159. package/src/pages/errors.ts +66 -0
  160. package/src/pages/functions/buildPlugin.ts +110 -0
  161. package/src/pages/functions/buildWorker.ts +156 -0
  162. package/src/pages/functions/filepath-routing.test.ts +234 -0
  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 +94 -0
  175. package/src/pages/projects.tsx +169 -0
  176. package/src/pages/publish.tsx +436 -0
  177. package/src/pages/types.ts +49 -0
  178. package/src/pages/upload.tsx +425 -0
  179. package/src/pages/utils.ts +12 -0
  180. package/src/parse.ts +286 -0
  181. package/src/paths.ts +71 -0
  182. package/src/proxy.ts +647 -252
  183. package/src/publish/index.ts +270 -0
  184. package/src/publish/publish.ts +1035 -0
  185. package/src/pubsub/index.ts +286 -0
  186. package/src/pubsub/pubsub-commands.tsx +624 -0
  187. package/src/queues/cli/commands/consumer/add.ts +71 -0
  188. package/src/queues/cli/commands/consumer/index.ts +22 -0
  189. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  190. package/src/queues/cli/commands/create.ts +25 -0
  191. package/src/queues/cli/commands/delete.ts +26 -0
  192. package/src/queues/cli/commands/index.ts +33 -0
  193. package/src/queues/cli/commands/list.ts +25 -0
  194. package/src/queues/client.ts +135 -0
  195. package/src/r2/helpers.ts +131 -0
  196. package/src/r2/index.ts +277 -0
  197. package/src/routes.ts +140 -0
  198. package/src/secret/index.ts +379 -0
  199. package/src/selfsigned.d.ts +29 -0
  200. package/src/sites.tsx +357 -99
  201. package/src/tail/createTail.ts +315 -0
  202. package/src/tail/filters.ts +277 -0
  203. package/src/tail/index.ts +214 -0
  204. package/src/tail/printing.ts +107 -0
  205. package/src/type-generation.ts +159 -0
  206. package/src/update-check.ts +19 -0
  207. package/src/user/access.ts +69 -0
  208. package/src/user/choose-account.tsx +69 -0
  209. package/src/user/env-vars.ts +46 -0
  210. package/src/user/generate-auth-url.ts +33 -0
  211. package/src/user/generate-random-state.ts +16 -0
  212. package/src/user/index.ts +3 -0
  213. package/src/user/user.tsx +1192 -0
  214. package/src/utils/collectKeyValues.ts +14 -0
  215. package/src/whoami.tsx +169 -0
  216. package/src/worker.ts +242 -0
  217. package/src/yargs-types.ts +20 -0
  218. package/src/zones.ts +191 -0
  219. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  220. package/templates/checked-fetch.js +17 -0
  221. package/templates/d1-beta-facade.js +174 -0
  222. package/templates/experimental-local-cache-stubs.js +27 -0
  223. package/templates/first-party-worker-module-facade.ts +18 -0
  224. package/templates/format-dev-errors.ts +32 -0
  225. package/templates/gitignore +171 -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 +213 -0
  231. package/templates/middleware/middleware-pretty-error.ts +40 -0
  232. package/templates/middleware/middleware-scheduled.ts +15 -0
  233. package/templates/new-worker-scheduled.js +17 -0
  234. package/templates/new-worker-scheduled.ts +32 -0
  235. package/templates/new-worker.js +15 -0
  236. package/templates/new-worker.ts +30 -0
  237. package/templates/no-op-worker.js +10 -0
  238. package/templates/pages-dev-pipeline.ts +28 -0
  239. package/templates/pages-dev-util.ts +52 -0
  240. package/templates/pages-shim.ts +9 -0
  241. package/templates/pages-template-plugin.ts +171 -0
  242. package/templates/pages-template-worker.ts +189 -0
  243. package/templates/serve-static-assets.ts +63 -0
  244. package/templates/service-bindings-module-facade.js +54 -0
  245. package/templates/service-bindings-sw-facade.js +42 -0
  246. package/templates/tsconfig.json +106 -0
  247. package/wrangler-dist/cli.d.ts +892 -0
  248. package/wrangler-dist/cli.js +142402 -103276
  249. package/pages/functions/buildWorker.ts +0 -62
  250. package/pages/functions/filepath-routing.test.ts +0 -39
  251. package/pages/functions/filepath-routing.ts +0 -221
  252. package/pages/functions/identifiers.ts +0 -78
  253. package/pages/functions/routes.ts +0 -158
  254. package/pages/functions/template-worker.ts +0 -144
  255. package/src/__tests__/mock-cfetch.ts +0 -171
  256. package/src/__tests__/mock-dialogs.ts +0 -65
  257. package/src/__tests__/run-in-tmp.ts +0 -19
  258. package/src/__tests__/run-wrangler.ts +0 -32
  259. package/src/api/form_data.ts +0 -131
  260. package/src/api/preview.ts +0 -128
  261. package/src/api/worker.ts +0 -155
  262. package/src/config.ts +0 -487
  263. package/src/kv.tsx +0 -267
  264. package/src/pages.tsx +0 -1031
  265. package/src/publish.ts +0 -358
  266. package/src/tail.tsx +0 -73
  267. package/src/user.tsx +0 -1025
  268. package/static-asset-facade.js +0 -47
  269. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  270. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  271. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  272. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  273. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  274. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  275. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  276. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  277. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  278. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  279. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  280. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  281. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  282. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  283. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  284. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  285. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  286. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  287. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  288. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  289. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  290. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  291. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  292. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  293. package/vendor/wrangler-mime/LICENSE +0 -21
  294. package/vendor/wrangler-mime/Mime.js +0 -97
  295. package/vendor/wrangler-mime/README.md +0 -187
  296. package/vendor/wrangler-mime/cli.js +0 -46
  297. package/vendor/wrangler-mime/index.js +0 -4
  298. package/vendor/wrangler-mime/lite.js +0 -4
  299. package/vendor/wrangler-mime/package.json +0 -52
  300. package/vendor/wrangler-mime/types/other.js +0 -1
  301. package/vendor/wrangler-mime/types/standard.js +0 -1
  302. package/wrangler-dist/cli.js.map +0 -7
package/src/dev.tsx CHANGED
@@ -1,771 +1,869 @@
1
- import esbuild from "esbuild";
2
- import { readFile } from "fs/promises";
3
- import { existsSync } from "fs";
4
- import type { DirectoryResult } from "tmp-promise";
5
- import tmp from "tmp-promise";
6
- import type { CfPreviewToken } from "./api/preview";
7
- import { Box, Text, useApp, useInput } from "ink";
8
- import React, { useState, useEffect, useRef } from "react";
9
- import path from "path";
10
- import open from "open";
11
- import useInspector from "./inspect";
12
- import type { CfModule } from "./api/worker";
13
- import { createWorker } from "./api/worker";
14
- import type { CfWorkerInit } from "./api/worker";
15
- import { spawn } from "child_process";
16
- import onExit from "signal-exit";
17
- import { syncAssets } from "./sites";
18
- import clipboardy from "clipboardy";
19
- import commandExists from "command-exists";
20
- import assert from "assert";
21
- import { getAPIToken } from "./user";
22
- import fetch from "node-fetch";
23
- import makeModuleCollector from "./module-collection";
24
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
25
- import { usePreviewServer } from "./proxy";
26
- import { execa } from "execa";
1
+ import path from "node:path";
27
2
  import { watch } from "chokidar";
28
-
29
- type CfScriptFormat = undefined | "modules" | "service-worker";
30
-
31
- export type DevProps = {
32
- name?: string;
33
- entry: string;
34
- port?: number;
35
- format: CfScriptFormat;
36
- accountId: undefined | string;
37
- initialMode: "local" | "remote";
38
- jsxFactory: undefined | string;
39
- jsxFragment: undefined | string;
40
- bindings: CfWorkerInit["bindings"];
41
- public: undefined | string;
42
- site: undefined | string;
43
- compatibilityDate: undefined | string;
44
- compatibilityFlags: undefined | string[];
45
- usageModel: undefined | "bundled" | "unbound";
46
- buildCommand: {
47
- command?: undefined | string;
48
- cwd?: undefined | string;
49
- watch_dir?: undefined | string;
50
- };
51
- };
52
-
53
- function Dev(props: DevProps): JSX.Element {
54
- if (props.public && props.format === "service-worker") {
55
- throw new Error(
56
- "You cannot use the service worker format with a `public` directory."
57
- );
58
- }
59
- const port = props.port || 8787;
60
- const apiToken = getAPIToken();
61
- const directory = useTmpDir();
62
-
63
- // if there isn't a build command, we just return the entry immediately
64
- // ideally there would be a conditional here, but the rules of hooks
65
- // kinda forbid that, so we thread the entry through useCustomBuild
66
- const entry = useCustomBuild(props.entry, props.buildCommand);
67
-
68
- const bundle = useEsbuild({
69
- entry,
70
- destination: directory,
71
- staticRoot: props.public,
72
- jsxFactory: props.jsxFactory,
73
- jsxFragment: props.jsxFragment,
74
- });
75
- if (bundle && bundle.type === "commonjs" && !props.format && props.public) {
76
- throw new Error(
77
- "You cannot use the service worker format with a `public` directory."
78
- );
79
- }
80
-
81
- const toggles = useHotkeys(
82
- {
83
- local: props.initialMode === "local",
84
- tunnel: false,
85
- },
86
- port
87
- );
88
-
89
- useTunnel(toggles.tunnel);
90
-
91
- return (
92
- <>
93
- {toggles.local ? (
94
- <Local
95
- name={props.name}
96
- bundle={bundle}
97
- format={props.format}
98
- bindings={props.bindings}
99
- site={props.site}
100
- public={props.public}
101
- port={props.port}
102
- />
103
- ) : (
104
- <Remote
105
- name={props.name}
106
- bundle={bundle}
107
- format={props.format}
108
- accountId={props.accountId}
109
- apiToken={apiToken}
110
- bindings={props.bindings}
111
- site={props.site}
112
- public={props.public}
113
- port={props.port}
114
- compatibilityDate={props.compatibilityDate}
115
- compatibilityFlags={props.compatibilityFlags}
116
- usageModel={props.usageModel}
117
- />
118
- )}
119
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
120
- <Text>
121
- {`B to open a browser, D to open Devtools, S to ${
122
- toggles.tunnel ? "turn off" : "turn on"
123
- } (experimental) sharing, L to ${
124
- toggles.local ? "turn off" : "turn on"
125
- } local mode, X to exit`}
126
- </Text>
127
- </Box>
128
- </>
129
- );
130
- }
131
-
132
- function Remote(props: {
133
- name: undefined | string;
134
- bundle: EsbuildBundle | undefined;
135
- format: CfScriptFormat;
136
- public: undefined | string;
137
- site: undefined | string;
138
- port: number;
139
- accountId: undefined | string;
140
- apiToken: undefined | string;
141
- bindings: CfWorkerInit["bindings"];
142
- compatibilityDate: string | undefined;
143
- compatibilityFlags: undefined | string[];
144
- usageModel: undefined | "bundled" | "unbound";
145
- }) {
146
- assert(props.accountId, "accountId is required");
147
- assert(props.apiToken, "apiToken is required");
148
- const previewToken = useWorker({
149
- name: props.name,
150
- bundle: props.bundle,
151
- format: props.format,
152
- modules: props.bundle ? props.bundle.modules : [],
153
- accountId: props.accountId,
154
- apiToken: props.apiToken,
155
- bindings: props.bindings,
156
- sitesFolder: props.site,
157
- port: props.port,
158
- compatibilityDate: props.compatibilityDate,
159
- compatibilityFlags: props.compatibilityFlags,
160
- usageModel: props.usageModel,
161
- });
162
-
163
- usePreviewServer({
164
- previewToken,
165
- publicRoot: props.public,
166
- port: props.port,
167
- });
168
-
169
- useInspector({
170
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
171
- port: 9229,
172
- logToTerminal: true,
173
- });
174
- return null;
175
- }
176
- function Local(props: {
177
- name: undefined | string;
178
- bundle: EsbuildBundle | undefined;
179
- format: CfScriptFormat;
180
- bindings: CfWorkerInit["bindings"];
181
- public: undefined | string;
182
- site: undefined | string;
183
- port: number;
184
- }) {
185
- const { inspectorUrl } = useLocalWorker({
186
- name: props.name,
187
- bundle: props.bundle,
188
- format: props.format,
189
- bindings: props.bindings,
190
- port: props.port,
191
- });
192
- useInspector({ inspectorUrl, port: 9229, logToTerminal: false });
193
- return null;
3
+ import getPort from "get-port";
4
+ import { render } from "ink";
5
+ import React from "react";
6
+ import { findWranglerToml, printBindings, readConfig } from "./config";
7
+ import Dev from "./dev/dev";
8
+ import { getVarsForDev } from "./dev/dev-vars";
9
+ import { getLocalPersistencePath } from "./dev/get-local-persistence-path";
10
+
11
+ import { startDevServer } from "./dev/start-server";
12
+ import { getEntry } from "./entry";
13
+ import { logger } from "./logger";
14
+ import * as metrics from "./metrics";
15
+ import { getAssetPaths, getSiteAssetPaths } from "./sites";
16
+ import { getAccountFromCache } from "./user";
17
+ import { collectKeyValues } from "./utils/collectKeyValues";
18
+ import { identifyD1BindingsAsBeta } from "./worker";
19
+ import { getHostFromRoute, getZoneForRoute, getZoneIdFromHost } from "./zones";
20
+ import {
21
+ type ConfigPath,
22
+ DEFAULT_INSPECTOR_PORT,
23
+ DEFAULT_LOCAL_PORT,
24
+ getDevCompatibilityDate,
25
+ getRules,
26
+ getScriptName,
27
+ isLegacyEnv,
28
+ printWranglerBanner,
29
+ } from "./index";
30
+ import type { Config, Environment } from "./config";
31
+ import type { Route } from "./config/environment";
32
+ import type { EnablePagesAssetsServiceBindingOptions } from "./miniflare-cli";
33
+ import type { CfWorkerInit } from "./worker";
34
+ import type { CommonYargsOptions } from "./yargs-types";
35
+ import type { Argv, ArgumentsCamelCase } from "yargs";
36
+
37
+ interface DevArgs {
38
+ config?: string;
39
+ script?: string;
40
+ name?: string;
41
+ bundle?: boolean;
42
+ build?: boolean;
43
+ format?: string;
44
+ env?: string;
45
+ "compatibility-date"?: string;
46
+ "compatibility-flags"?: string[];
47
+ latest?: boolean;
48
+ ip?: string;
49
+ inspect?: boolean;
50
+ port?: number;
51
+ "inspector-port"?: number;
52
+ routes?: string[];
53
+ host?: string;
54
+ "local-protocol"?: "http" | "https";
55
+ "local-upstream"?: string | undefined;
56
+ "experimental-public"?: string;
57
+ public?: string;
58
+ assets?: string;
59
+ site?: string;
60
+ "site-include"?: string[];
61
+ "site-exclude"?: string[];
62
+ "upstream-protocol"?: "http" | "https";
63
+ "jsx-factory"?: string;
64
+ "jsx-fragment"?: string;
65
+ tsconfig?: string;
66
+ local?: boolean;
67
+ "experimental-local"?: boolean;
68
+ minify?: boolean;
69
+ var?: string[];
70
+ define?: string[];
71
+ "node-compat"?: boolean;
72
+ "experimental-enable-local-persistence"?: boolean;
73
+ persist?: boolean;
74
+ "persist-to"?: string;
75
+ "live-reload"?: boolean;
76
+ onReady?: (ip: string, port: number) => void;
77
+ logLevel?: "none" | "info" | "error" | "log" | "warn" | "debug";
78
+ logPrefix?: string;
79
+ showInteractiveDevSession?: boolean;
80
+ "test-scheduled"?: boolean;
194
81
  }
195
82
 
196
- function useLocalWorker(props: {
197
- name: undefined | string;
198
- bundle: EsbuildBundle | undefined;
199
- format: CfScriptFormat;
200
- bindings: CfWorkerInit["bindings"];
201
- port: number;
202
- }) {
203
- // TODO: pass vars via command line
204
- const { bundle, format, bindings, port } = props;
205
- const local = useRef<ReturnType<typeof spawn>>();
206
- const removeSignalExitListener = useRef<() => void>();
207
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
208
- useEffect(() => {
209
- async function startLocalWorker() {
210
- if (!bundle) return;
211
- if (format === "modules" && bundle.type === "commonjs") {
212
- console.error("⎔ Cannot use modules with a commonjs bundle.");
213
- // TODO: a much better error message here, with what to do next
214
- return;
215
- }
216
- if (format === "service-worker" && bundle.type !== "esm") {
217
- console.error("⎔ Cannot use service-worker with a esm bundle.");
218
- // TODO: a much better error message here, with what to do next
219
- return;
220
- }
221
-
222
- console.log("⎔ Starting a local server...");
223
- // TODO: just use execa for this
224
- local.current = spawn("node", [
225
- "--experimental-vm-modules",
226
- "--inspect",
227
- require.resolve("miniflare/cli"),
228
- bundle.path,
229
- "--watch",
230
- "--wrangler-config",
231
- path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
232
- "--env",
233
- path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
234
- "--package",
235
- path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
236
- "--port",
237
- port.toString(),
238
- "--kv-persist",
239
- "--cache-persist",
240
- "--do-persist",
241
- ...Object.entries(bindings.vars || {}).flatMap(([key, value]) => {
242
- return ["--binding", `${key}=${value}`];
243
- }),
244
- ...(bindings.kv_namespaces || []).flatMap(({ binding }) => {
245
- return ["--kv", binding];
246
- }),
247
- ...(bindings.durable_objects?.bindings || []).flatMap(
248
- ({ name, class_name }) => {
249
- return ["--do", `${name}=${class_name}`];
250
- }
251
- ),
252
- "--modules",
253
- format ||
254
- (bundle.type === "esm" ? "modules" : "service-worker") === "modules"
255
- ? "true"
256
- : "false",
257
- ]);
258
- console.log(`⬣ Listening at http://localhost:${port}`);
259
-
260
- local.current.on("close", (code) => {
261
- if (code !== null) {
262
- console.log(`miniflare process exited with code ${code}`);
263
- }
264
- });
265
-
266
- local.current.stdout.on("data", (data: Buffer) => {
267
- console.log(`${data.toString()}`);
268
- });
269
-
270
- local.current.stderr.on("data", (data: Buffer) => {
271
- console.error(`${data.toString()}`);
272
- const matches =
273
- /Debugger listening on (ws:\/\/127\.0\.0\.1:9229\/[A-Za-z0-9-]+)/.exec(
274
- data.toString()
275
- );
276
- if (matches) {
277
- setInspectorUrl(matches[1]);
278
- }
279
- });
280
-
281
- local.current.on("exit", (code) => {
282
- if (code !== 0) {
283
- console.error(`miniflare process exited with code ${code}`);
284
- }
285
- });
286
-
287
- local.current.on("error", (error: Error) => {
288
- console.error(`miniflare process failed to spawn`);
289
- console.error(error);
290
- });
291
-
292
- removeSignalExitListener.current = onExit((_code, _signal) => {
293
- console.log("⎔ Shutting down local server.");
294
- local.current?.kill();
295
- local.current = undefined;
296
- });
297
- }
298
-
299
- startLocalWorker().catch((err) => {
300
- console.error("local worker:", err);
301
- });
302
-
303
- return () => {
304
- if (local.current) {
305
- console.log("⎔ Shutting down local server.");
306
- local.current?.kill();
307
- local.current = undefined;
308
- removeSignalExitListener.current && removeSignalExitListener.current();
309
- removeSignalExitListener.current = undefined;
310
- }
311
- };
312
- }, [
313
- bundle,
314
- format,
315
- port,
316
- bindings.durable_objects?.bindings,
317
- bindings.kv_namespaces,
318
- bindings.vars,
319
- ]);
320
- return { inspectorUrl };
83
+ export function devOptions(yargs: Argv<CommonYargsOptions>): Argv<DevArgs> {
84
+ return (
85
+ yargs
86
+ .positional("script", {
87
+ describe: "The path to an entry point for your worker",
88
+ type: "string",
89
+ })
90
+ .option("name", {
91
+ describe: "Name of the worker",
92
+ type: "string",
93
+ requiresArg: true,
94
+ })
95
+ // We want to have a --no-bundle flag, but yargs requires that
96
+ // we also have a --bundle flag (that it adds the --no to by itself)
97
+ // So we make a --bundle flag, but hide it, and then add a --no-bundle flag
98
+ // that's visible to the user but doesn't "do" anything.
99
+ .option("bundle", {
100
+ describe: "Run wrangler's compilation step before publishing",
101
+ type: "boolean",
102
+ hidden: true,
103
+ })
104
+ .option("no-bundle", {
105
+ describe: "Skip internal build steps and directly publish script",
106
+ type: "boolean",
107
+ default: false,
108
+ })
109
+ .option("format", {
110
+ choices: ["modules", "service-worker"] as const,
111
+ describe: "Choose an entry type",
112
+ hidden: true,
113
+ deprecated: true,
114
+ })
115
+ .option("compatibility-date", {
116
+ describe: "Date to use for compatibility checks",
117
+ type: "string",
118
+ requiresArg: true,
119
+ })
120
+ .option("compatibility-flags", {
121
+ describe: "Flags to use for compatibility checks",
122
+ alias: "compatibility-flag",
123
+ type: "string",
124
+ requiresArg: true,
125
+ array: true,
126
+ })
127
+ .option("latest", {
128
+ describe: "Use the latest version of the worker runtime",
129
+ type: "boolean",
130
+ default: true,
131
+ })
132
+ .option("ip", {
133
+ describe: "IP address to listen on",
134
+ type: "string",
135
+ })
136
+ .option("port", {
137
+ describe: "Port to listen on",
138
+ type: "number",
139
+ })
140
+ .option("inspector-port", {
141
+ describe: "Port for devtools to connect to",
142
+ type: "number",
143
+ })
144
+ .option("routes", {
145
+ describe: "Routes to upload",
146
+ alias: "route",
147
+ type: "string",
148
+ requiresArg: true,
149
+ array: true,
150
+ })
151
+ .option("host", {
152
+ type: "string",
153
+ requiresArg: true,
154
+ describe:
155
+ "Host to forward requests to, defaults to the zone of project",
156
+ })
157
+ .option("local-protocol", {
158
+ describe: "Protocol to listen to requests on, defaults to http.",
159
+ choices: ["http", "https"] as const,
160
+ })
161
+ .options("local-upstream", {
162
+ type: "string",
163
+ describe:
164
+ "Host to act as origin in local mode, defaults to dev.host or route",
165
+ })
166
+ .option("experimental-public", {
167
+ describe: "Static assets to be served",
168
+ type: "string",
169
+ requiresArg: true,
170
+ deprecated: true,
171
+ hidden: true,
172
+ })
173
+ .option("assets", {
174
+ describe: "Static assets to be served",
175
+ type: "string",
176
+ requiresArg: true,
177
+ })
178
+ .option("site", {
179
+ describe: "Root folder of static assets for Workers Sites",
180
+ type: "string",
181
+ requiresArg: true,
182
+ })
183
+ .option("site-include", {
184
+ describe:
185
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
186
+ type: "string",
187
+ requiresArg: true,
188
+ array: true,
189
+ })
190
+ .option("site-exclude", {
191
+ describe:
192
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
193
+ type: "string",
194
+ requiresArg: true,
195
+ array: true,
196
+ })
197
+ .option("upstream-protocol", {
198
+ describe: "Protocol to forward requests to host on, defaults to https.",
199
+ choices: ["http", "https"] as const,
200
+ })
201
+ .option("var", {
202
+ describe:
203
+ "A key-value pair to be injected into the script as a variable",
204
+ type: "string",
205
+ requiresArg: true,
206
+ array: true,
207
+ })
208
+ .option("define", {
209
+ describe: "A key-value pair to be substituted in the script",
210
+ type: "string",
211
+ requiresArg: true,
212
+ array: true,
213
+ })
214
+ .option("jsx-factory", {
215
+ describe: "The function that is called for each JSX element",
216
+ type: "string",
217
+ requiresArg: true,
218
+ })
219
+ .option("jsx-fragment", {
220
+ describe: "The function that is called for each JSX fragment",
221
+ type: "string",
222
+ requiresArg: true,
223
+ })
224
+ .option("tsconfig", {
225
+ describe: "Path to a custom tsconfig.json file",
226
+ type: "string",
227
+ requiresArg: true,
228
+ })
229
+ .option("local", {
230
+ alias: "l",
231
+ describe: "Run on my machine",
232
+ type: "boolean",
233
+ default: false, // I bet this will a point of contention. We'll revisit it.
234
+ })
235
+ .option("experimental-local", {
236
+ describe: "Run on my machine using the Cloudflare Workers runtime",
237
+ type: "boolean",
238
+ default: false,
239
+ })
240
+ .check((argv) => {
241
+ if (argv.local && argv["experimental-local"]) {
242
+ throw new Error(
243
+ "--local and --experimental-local are mutually exclusive. " +
244
+ "Please select one or the other."
245
+ );
246
+ }
247
+ return true;
248
+ })
249
+ .option("minify", {
250
+ describe: "Minify the script",
251
+ type: "boolean",
252
+ })
253
+ .option("node-compat", {
254
+ describe: "Enable node.js compatibility",
255
+ type: "boolean",
256
+ })
257
+ .option("experimental-enable-local-persistence", {
258
+ describe:
259
+ "Enable persistence for local mode (deprecated, use --persist)",
260
+ type: "boolean",
261
+ deprecated: true,
262
+ hidden: true,
263
+ })
264
+ .option("persist", {
265
+ describe:
266
+ "Enable persistence for local mode, using default path: .wrangler/state",
267
+ type: "boolean",
268
+ })
269
+ .option("persist-to", {
270
+ describe:
271
+ "Specify directory to use for local persistence (implies --persist)",
272
+ type: "string",
273
+ requiresArg: true,
274
+ })
275
+ .option("live-reload", {
276
+ // TODO: Add back in once we have remote `--live-reload`
277
+ hidden: true,
278
+ // describe: "Auto reload HTML pages when change is detected",
279
+ type: "boolean",
280
+ })
281
+ .option("inspect", {
282
+ describe: "Enable dev tools",
283
+ type: "boolean",
284
+ deprecated: true,
285
+ hidden: true,
286
+ })
287
+ .option("legacy-env", {
288
+ type: "boolean",
289
+ describe: "Use legacy environments",
290
+ hidden: true,
291
+ })
292
+ .option("test-scheduled", {
293
+ describe: "Test scheduled events by visiting /__scheduled in browser",
294
+ type: "boolean",
295
+ default: false,
296
+ })
297
+ .option("log-level", {
298
+ choices: ["debug", "info", "log", "warn", "error", "none"] as const,
299
+ describe: "Specify logging level",
300
+ default: "log",
301
+ })
302
+ );
321
303
  }
322
304
 
323
- function useTmpDir(): string | undefined {
324
- const [directory, setDirectory] = useState<DirectoryResult>();
325
- const handleError = useErrorHandler();
326
- useEffect(() => {
327
- let dir: DirectoryResult;
328
- async function create() {
329
- try {
330
- dir = await tmp.dir({ unsafeCleanup: true });
331
- setDirectory(dir);
332
- return;
333
- } catch (err) {
334
- console.error("failed to create tmp dir");
335
- throw err;
336
- }
337
- }
338
- create().catch((err) => {
339
- // we want to break here
340
- // we can't do much without a temp dir anyway
341
- handleError(err);
342
- });
343
- return () => {
344
- dir.cleanup().catch(() => {
345
- // extremely unlikely,
346
- // but it's 2021 after all
347
- console.error("failed to cleanup tmp dir");
348
- });
349
- };
350
- }, [handleError]);
351
- return directory?.path;
305
+ export async function devHandler(args: ArgumentsCamelCase<DevArgs>) {
306
+ let watcher;
307
+ try {
308
+ const devInstance = await startDev(args);
309
+ watcher = devInstance.watcher;
310
+ const { waitUntilExit } = devInstance.devReactElement;
311
+ await waitUntilExit();
312
+ } finally {
313
+ await watcher?.close();
314
+ }
352
315
  }
353
316
 
354
- function useCustomBuild(
355
- expectedEntry: string,
356
- props: {
357
- command?: undefined | string;
358
- cwd?: undefined | string;
359
- watch_dir?: undefined | string;
360
- }
361
- ): undefined | string {
362
- const [entry, setEntry] = useState<string | undefined>(
363
- // if there's no build command, just return the expected entry
364
- props.command ? null : expectedEntry
365
- );
366
- const { command, cwd, watch_dir } = props;
367
- useEffect(() => {
368
- if (!command) return;
369
- let cmd, interval;
370
- console.log("running:", command);
371
- const commandPieces = command.split(" ");
372
- cmd = execa(commandPieces[0], commandPieces.slice(1), {
373
- ...(cwd && { cwd }),
374
- stderr: "inherit",
375
- stdout: "inherit",
376
- });
377
- if (watch_dir) {
378
- watch(watch_dir, { persistent: true, ignoreInitial: true }).on(
379
- "all",
380
- (_event, _path) => {
381
- console.log(`The file ${path} changed, restarting build...`);
382
- cmd.kill();
383
- cmd = execa(commandPieces[0], commandPieces.slice(1), {
384
- ...(cwd && { cwd }),
385
- stderr: "inherit",
386
- stdout: "inherit",
387
- });
388
- }
389
- );
390
- }
391
-
392
- // check every so often whether `expectedEntry` exists
393
- // if it does, we're done
394
- const startedAt = Date.now();
395
- interval = setInterval(() => {
396
- if (existsSync(expectedEntry)) {
397
- clearInterval(interval);
398
- setEntry(expectedEntry);
399
- } else {
400
- const elapsed = Date.now() - startedAt;
401
- // timeout after 30 seconds of waiting
402
- if (elapsed > 1000 * 60 * 30) {
403
- console.error("⎔ Build timed out.");
404
- clearInterval(interval);
405
- cmd.kill();
406
- }
407
- }
408
- }, 200);
409
- // TODO: we could probably timeout here after a while
410
-
411
- return () => {
412
- if (cmd) {
413
- cmd.kill();
414
- cmd = undefined;
415
- }
416
- clearInterval(interval);
417
- interval = undefined;
418
- };
419
- }, [command, cwd, expectedEntry, watch_dir]);
420
- return entry;
421
- }
422
-
423
- type EsbuildBundle = {
424
- id: number;
425
- path: string;
426
- entry: string;
427
- type: "esm" | "commonjs";
428
- exports: string[];
429
- modules: CfModule[];
317
+ export type AdditionalDevProps = {
318
+ vars?: {
319
+ [key: string]: unknown;
320
+ };
321
+ kv?: {
322
+ binding: string;
323
+ id: string;
324
+ preview_id?: string;
325
+ }[];
326
+ durableObjects?: {
327
+ name: string;
328
+ class_name: string;
329
+ script_name?: string | undefined;
330
+ environment?: string | undefined;
331
+ }[];
332
+ r2?: {
333
+ binding: string;
334
+ bucket_name: string;
335
+ preview_bucket_name?: string;
336
+ }[];
337
+ d1Databases?: Environment["d1_databases"];
430
338
  };
431
339
 
432
- function useEsbuild(props: {
433
- entry: undefined | string;
434
- destination: string | undefined;
435
- staticRoot: undefined | string;
436
- jsxFactory: string | undefined;
437
- jsxFragment: string | undefined;
438
- }): EsbuildBundle | undefined {
439
- const { entry, destination, staticRoot, jsxFactory, jsxFragment } = props;
440
- const [bundle, setBundle] = useState<EsbuildBundle>();
441
- useEffect(() => {
442
- let result: esbuild.BuildResult;
443
- async function build() {
444
- if (!destination || !entry) return;
445
- const moduleCollector = makeModuleCollector();
446
- result = await esbuild.build({
447
- entryPoints: [entry],
448
- bundle: true,
449
- outdir: destination,
450
- metafile: true,
451
- format: "esm",
452
- sourcemap: true,
453
- loader: {
454
- ".js": "jsx",
455
- },
456
- ...(jsxFactory && { jsxFactory }),
457
- ...(jsxFragment && { jsxFragment }),
458
- external: ["__STATIC_CONTENT_MANIFEST"],
459
- conditions: ["worker", "browser"],
460
- plugins: [moduleCollector.plugin],
461
- // TODO: import.meta.url
462
- watch: {
463
- async onRebuild(error) {
464
- if (error) console.error("watch build failed:", error);
465
- else {
466
- // nothing really changes here, so let's increment the id
467
- // to change the return object's identity
468
- setBundle((previousBundle) => ({
469
- ...previousBundle,
470
- id: previousBundle.id + 1,
471
- }));
472
- }
473
- },
474
- },
475
- });
476
-
477
- const chunks = Object.entries(result.metafile.outputs).find(
478
- ([_path, { entryPoint }]) =>
479
- entryPoint === Object.keys(result.metafile.inputs)[0]
480
- ); // assumedly only one entry point
481
-
482
- setBundle({
483
- id: 0,
484
- entry,
485
- path: chunks[0],
486
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
487
- exports: chunks[1].exports,
488
- modules: moduleCollector.modules,
489
- });
490
- }
491
- build().catch((_err) => {
492
- // esbuild already logs errors to stderr
493
- // and we don't want to end the process
494
- // on build errors anyway
495
- // so this is a no-op error handler
496
- });
497
- return () => {
498
- result?.stop();
499
- };
500
- }, [entry, destination, staticRoot, jsxFactory, jsxFragment]);
501
- return bundle;
340
+ type StartDevOptions = ArgumentsCamelCase<DevArgs> &
341
+ // These options can be passed in directly when called with the `wrangler.dev()` API.
342
+ // They aren't exposed as CLI arguments.
343
+ AdditionalDevProps & {
344
+ forceLocal?: boolean;
345
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
346
+ };
347
+
348
+ export async function startDev(args: StartDevOptions) {
349
+ let watcher: ReturnType<typeof watch> | undefined;
350
+ let rerender: (node: React.ReactNode) => void | undefined;
351
+ try {
352
+ if (args.logLevel) {
353
+ logger.loggerLevel = args.logLevel;
354
+ }
355
+ await printWranglerBanner();
356
+
357
+ const configPath =
358
+ (args.config as ConfigPath) ||
359
+ ((args.script &&
360
+ findWranglerToml(path.dirname(args.script))) as ConfigPath);
361
+ let config = readConfig(configPath, args);
362
+
363
+ if (config.configPath) {
364
+ watcher = watch(config.configPath, {
365
+ persistent: true,
366
+ }).on("change", async (_event) => {
367
+ // TODO: Do we need to handle different `_event` types differently?
368
+ // e.g. what if the file is deleted, or added?
369
+ config = readConfig(configPath, args);
370
+ if (config.configPath) {
371
+ logger.log(`${path.basename(config.configPath)} changed...`);
372
+ rerender(await getDevReactElement(config));
373
+ }
374
+ });
375
+ }
376
+
377
+ const {
378
+ entry,
379
+ nodeCompat,
380
+ upstreamProtocol,
381
+ zoneId,
382
+ host,
383
+ routes,
384
+ getLocalPort,
385
+ getInspectorPort,
386
+ cliDefines,
387
+ localPersistencePath,
388
+ } = await validateDevServerSettings(args, config);
389
+
390
+ await metrics.sendMetricsEvent(
391
+ "run dev",
392
+ {
393
+ local: args.local,
394
+ usesTypeScript: /\.tsx?$/.test(entry.file),
395
+ },
396
+ { sendMetrics: config.send_metrics, offline: args.local }
397
+ );
398
+
399
+ // eslint-disable-next-line no-inner-declarations
400
+ async function getDevReactElement(configParam: Config) {
401
+ const { assetPaths, bindings } = await getBindingsAndAssetPaths(
402
+ args,
403
+ configParam
404
+ );
405
+
406
+ return (
407
+ <Dev
408
+ name={getScriptName({ name: args.name, env: args.env }, configParam)}
409
+ noBundle={!(args.bundle ?? !configParam.no_bundle)}
410
+ entry={entry}
411
+ env={args.env}
412
+ zone={zoneId}
413
+ host={host}
414
+ routes={routes}
415
+ rules={getRules(configParam)}
416
+ legacyEnv={isLegacyEnv(configParam)}
417
+ minify={args.minify ?? configParam.minify}
418
+ nodeCompat={nodeCompat}
419
+ build={configParam.build || {}}
420
+ define={{ ...configParam.define, ...cliDefines }}
421
+ initialMode={
422
+ args.local || args.experimentalLocal ? "local" : "remote"
423
+ }
424
+ jsxFactory={args["jsx-factory"] || configParam.jsx_factory}
425
+ jsxFragment={args["jsx-fragment"] || configParam.jsx_fragment}
426
+ tsconfig={args.tsconfig ?? configParam.tsconfig}
427
+ upstreamProtocol={upstreamProtocol}
428
+ localProtocol={args.localProtocol || configParam.dev.local_protocol}
429
+ localUpstream={args["local-upstream"] || host}
430
+ localPersistencePath={localPersistencePath}
431
+ liveReload={args.liveReload || false}
432
+ accountId={configParam.account_id || getAccountFromCache()?.id}
433
+ assetPaths={assetPaths}
434
+ assetsConfig={configParam.assets}
435
+ port={args.port || configParam.dev.port || (await getLocalPort())}
436
+ ip={args.ip || configParam.dev.ip}
437
+ inspectorPort={
438
+ args.inspectorPort ||
439
+ configParam.dev.inspector_port ||
440
+ (await getInspectorPort())
441
+ }
442
+ isWorkersSite={Boolean(args.site || configParam.site)}
443
+ compatibilityDate={getDevCompatibilityDate(
444
+ configParam,
445
+ args.compatibilityDate
446
+ )}
447
+ compatibilityFlags={
448
+ args.compatibilityFlags || configParam.compatibility_flags
449
+ }
450
+ usageModel={configParam.usage_model}
451
+ bindings={bindings}
452
+ crons={configParam.triggers.crons}
453
+ queueConsumers={configParam.queues.consumers}
454
+ logPrefix={args.logPrefix}
455
+ onReady={args.onReady}
456
+ inspect={args.inspect ?? true}
457
+ showInteractiveDevSession={args.showInteractiveDevSession}
458
+ forceLocal={args.forceLocal}
459
+ enablePagesAssetsServiceBinding={args.enablePagesAssetsServiceBinding}
460
+ firstPartyWorker={configParam.first_party_worker}
461
+ sendMetrics={configParam.send_metrics}
462
+ testScheduled={args["test-scheduled"]}
463
+ experimentalLocal={args.experimentalLocal}
464
+ />
465
+ );
466
+ }
467
+ const devReactElement = render(await getDevReactElement(config));
468
+ rerender = devReactElement.rerender;
469
+ return {
470
+ devReactElement,
471
+ watcher,
472
+ stop: async () => {
473
+ devReactElement.unmount();
474
+ await watcher?.close();
475
+ },
476
+ };
477
+ } finally {
478
+ await watcher?.close();
479
+ }
502
480
  }
503
481
 
504
- function useWorker(props: {
505
- name: undefined | string;
506
- bundle: EsbuildBundle | undefined;
507
- format: CfScriptFormat;
508
- modules: CfModule[];
509
- accountId: string;
510
- apiToken: string;
511
- bindings: CfWorkerInit["bindings"];
512
- sitesFolder: undefined | string;
513
- port: number;
514
- compatibilityDate: string | undefined;
515
- compatibilityFlags: string[] | undefined;
516
- usageModel: undefined | "bundled" | "unbound";
517
- }): CfPreviewToken | undefined {
518
- const {
519
- name,
520
- bundle,
521
- format,
522
- modules,
523
- accountId,
524
- apiToken,
525
- bindings,
526
- sitesFolder,
527
- compatibilityDate,
528
- compatibilityFlags,
529
- usageModel,
530
- port,
531
- } = props;
532
- const [token, setToken] = useState<CfPreviewToken | undefined>();
533
-
534
- // This is the most reliable way to detect whether
535
- // something's "happened" in our system; We make a ref and
536
- // mark it once we log our initial message. Refs are vars!
537
- const startedRef = useRef(false);
538
-
539
- useEffect(() => {
540
- async function start() {
541
- setToken(undefined); // reset token in case we're re-running
542
-
543
- if (!bundle) return;
544
- if (format === "modules" && bundle.type === "commonjs") {
545
- console.error("⎔ Cannot use modules with a commonjs bundle.");
546
- // TODO: a much better error message here, with what to do next
547
- return;
548
- }
549
- if (format === "service-worker" && bundle.type !== "esm") {
550
- console.error("⎔ Cannot use service-worker with a esm bundle.");
551
- // TODO: a much better error message here, with what to do next
552
- return;
553
- }
554
-
555
- if (!startedRef.current) {
556
- startedRef.current = true;
557
- } else {
558
- console.log("⎔ Detected changes, restarting server...");
559
- }
560
-
561
- const assets = sitesFolder
562
- ? await syncAssets(
563
- accountId,
564
- path.basename(bundle.path),
565
- sitesFolder,
566
- true,
567
- undefined // TODO: env
568
- )
569
- : {
570
- manifest: undefined,
571
- namespace: undefined,
572
- }; // TODO: cancellable?
573
-
574
- const content = await readFile(bundle.path, "utf-8");
575
- const init: CfWorkerInit = {
576
- name,
577
- main: {
578
- name: path.basename(bundle.path),
579
- type: format || bundle.type === "esm" ? "esm" : "commonjs",
580
- content,
581
- },
582
- modules: modules.concat(
583
- assets.manifest
584
- ? {
585
- name: "__STATIC_CONTENT_MANIFEST",
586
- content: JSON.stringify(assets.manifest),
587
- type: "text",
588
- }
589
- : []
590
- ),
591
- bindings: {
592
- ...bindings,
593
- kv_namespaces: (bindings.kv_namespaces || []).concat(
594
- assets.namespace
595
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
596
- : []
597
- ),
598
- },
599
- migrations: undefined, // no migrations in dev
600
- compatibility_date: compatibilityDate,
601
- compatibility_flags: compatibilityFlags,
602
- usage_model: usageModel,
603
- };
604
- setToken(
605
- await createWorker(init, {
606
- accountId,
607
- apiToken,
608
- })
609
- );
610
- }
611
- start().catch((err) => {
612
- // we want to log the error, but not end the process
613
- // since it could recover after the developer fixes whatever's wrong
614
- console.error("remote worker:", err);
615
- });
616
- }, [
617
- name,
618
- bundle,
619
- format,
620
- accountId,
621
- apiToken,
622
- port,
623
- sitesFolder,
624
- compatibilityDate,
625
- compatibilityFlags,
626
- usageModel,
627
- bindings,
628
- modules,
629
- ]);
630
- return token;
482
+ export async function startApiDev(args: StartDevOptions) {
483
+ if (args.logLevel) {
484
+ logger.loggerLevel = args.logLevel;
485
+ }
486
+ await printWranglerBanner();
487
+
488
+ const configPath =
489
+ (args.config as ConfigPath) ||
490
+ ((args.script &&
491
+ findWranglerToml(path.dirname(args.script))) as ConfigPath);
492
+ const config = readConfig(configPath, args);
493
+
494
+ const {
495
+ entry,
496
+ nodeCompat,
497
+ upstreamProtocol,
498
+ zoneId,
499
+ host,
500
+ routes,
501
+ getLocalPort,
502
+ getInspectorPort,
503
+ cliDefines,
504
+ localPersistencePath,
505
+ } = await validateDevServerSettings(args, config);
506
+
507
+ await metrics.sendMetricsEvent(
508
+ "run dev (api)",
509
+ { local: args.local },
510
+ { sendMetrics: config.send_metrics, offline: args.local }
511
+ );
512
+
513
+ // eslint-disable-next-line no-inner-declarations
514
+ async function getDevServer(configParam: Config) {
515
+ const { assetPaths, bindings } = await getBindingsAndAssetPaths(
516
+ args,
517
+ configParam
518
+ );
519
+
520
+ //if args.bundle is on, don't disable bundling
521
+ //if there's no args.bundle, and configParam.no_bundle is on, disable bundling
522
+ //otherwise, enable bundling
523
+ const enableBundling = args.bundle ?? !configParam.no_bundle;
524
+ return await startDevServer({
525
+ name: getScriptName({ name: args.name, env: args.env }, configParam),
526
+ noBundle: !enableBundling,
527
+ entry: entry,
528
+ env: args.env,
529
+ zone: zoneId,
530
+ host: host,
531
+ routes: routes,
532
+ rules: getRules(configParam),
533
+ legacyEnv: isLegacyEnv(configParam),
534
+ minify: args.minify ?? configParam.minify,
535
+ nodeCompat: nodeCompat,
536
+ build: configParam.build || {},
537
+ define: { ...config.define, ...cliDefines },
538
+ initialMode: args.local ? "local" : "remote",
539
+ jsxFactory: args["jsx-factory"] || configParam.jsx_factory,
540
+ jsxFragment: args["jsx-fragment"] || configParam.jsx_fragment,
541
+ tsconfig: args.tsconfig ?? configParam.tsconfig,
542
+ upstreamProtocol: upstreamProtocol,
543
+ localProtocol: args.localProtocol || configParam.dev.local_protocol,
544
+ localUpstream: args["local-upstream"] || host,
545
+ localPersistencePath,
546
+ liveReload: args.liveReload || false,
547
+ accountId: configParam.account_id || getAccountFromCache()?.id,
548
+ assetPaths: assetPaths,
549
+ assetsConfig: configParam.assets,
550
+ //port can be 0, which means to use a random port
551
+ port:
552
+ args.port === 0
553
+ ? args.port
554
+ : args.port || configParam.dev.port || (await getLocalPort()),
555
+ ip: args.ip || configParam.dev.ip,
556
+ inspectorPort:
557
+ args["inspector-port"] ||
558
+ configParam.dev.inspector_port ||
559
+ (await getInspectorPort()),
560
+ isWorkersSite: Boolean(args.site || configParam.site),
561
+ compatibilityDate: getDevCompatibilityDate(
562
+ config,
563
+ // Only `compatibilityDate` will be set when using `unstable_dev`
564
+ args["compatibility-date"] ?? args.compatibilityDate
565
+ ),
566
+ compatibilityFlags:
567
+ args["compatibility-flags"] ??
568
+ args.compatibilityFlags ??
569
+ configParam.compatibility_flags,
570
+ usageModel: configParam.usage_model,
571
+ bindings: bindings,
572
+ crons: configParam.triggers.crons,
573
+ queueConsumers: configParam.queues.consumers,
574
+ logPrefix: args.logPrefix,
575
+ onReady: args.onReady,
576
+ inspect: args.inspect ?? true,
577
+ showInteractiveDevSession: args.showInteractiveDevSession,
578
+ forceLocal: args.forceLocal,
579
+ enablePagesAssetsServiceBinding: args.enablePagesAssetsServiceBinding,
580
+ local: args.local ?? true,
581
+ firstPartyWorker: configParam.first_party_worker,
582
+ sendMetrics: configParam.send_metrics,
583
+ testScheduled: args.testScheduled,
584
+ experimentalLocal: args.experimentalLocal,
585
+ });
586
+ }
587
+
588
+ const devServer = await getDevServer(config);
589
+ if (!devServer) {
590
+ throw logger.error("Failed to start dev server.");
591
+ }
592
+
593
+ return {
594
+ stop: async () => {
595
+ await devServer.stop();
596
+ },
597
+ };
631
598
  }
632
-
633
- function sleep(period: number) {
634
- return new Promise((resolve) => setTimeout(resolve, period));
599
+ /**
600
+ * Avoiding calling `getPort()` multiple times by memoizing the first result.
601
+ */
602
+ function memoizeGetPort(defaultPort: number) {
603
+ let portValue: number;
604
+ return async () => {
605
+ return portValue || (portValue = await getPort({ port: defaultPort }));
606
+ };
635
607
  }
636
- const SLEEP_DURATION = 2000;
637
- // really need a first class api for this
638
- const hostNameRegex = /userHostname="(.*)"/g;
639
- async function findTunnelHostname() {
640
- let hostName: string | undefined;
641
- while (!hostName) {
642
- try {
643
- const resp = await fetch("http://localhost:8789/metrics");
644
- const data = await resp.text();
645
- const matches = Array.from(data.matchAll(hostNameRegex));
646
- hostName = matches[0][1];
647
- } catch (err) {
648
- await sleep(SLEEP_DURATION);
649
- }
650
- }
651
- return hostName;
608
+ /**
609
+ * mask anything that was overridden in .dev.vars
610
+ * so that we don't log potential secrets into the terminal
611
+ */
612
+ function maskVars(bindings: CfWorkerInit["bindings"], configParam: Config) {
613
+ const maskedVars = { ...bindings.vars };
614
+ for (const key of Object.keys(maskedVars)) {
615
+ if (maskedVars[key] !== configParam.vars[key]) {
616
+ // This means it was overridden in .dev.vars
617
+ // so let's mask it
618
+ maskedVars[key] = "(hidden)";
619
+ }
620
+ }
621
+ return maskedVars;
652
622
  }
653
623
 
654
- function useTunnel(toggle: boolean) {
655
- const tunnel = useRef<ReturnType<typeof spawn>>();
656
- const removeSignalExitListener = useRef<() => void>();
657
- // TODO: test if cloudflared is available, if not
658
- // point them to a url where they can get docs to install it
659
- useEffect(() => {
660
- async function startTunnel() {
661
- if (toggle) {
662
- try {
663
- await commandExists("cloudflared");
664
- } catch (e) {
665
- console.error(
666
- "To share your worker on the internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
667
- );
668
- return;
669
- }
670
- console.log("⎔ Starting a tunnel...");
671
- tunnel.current = spawn("cloudflared", [
672
- "tunnel",
673
- "--url",
674
- "http://localhost:8787",
675
- "--metrics",
676
- "localhost:8789",
677
- ]);
678
-
679
- tunnel.current.on("close", (code) => {
680
- if (code !== 0) {
681
- console.log(`Tunnel process exited with code ${code}`);
682
- }
683
- });
684
-
685
- removeSignalExitListener.current = onExit((_code, _signal) => {
686
- console.log("⎔ Shutting down local tunnel.");
687
- tunnel.current?.kill();
688
- tunnel.current = undefined;
689
- });
690
-
691
- const hostName = await findTunnelHostname();
692
- await clipboardy.write(hostName);
693
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
694
- }
695
- }
696
-
697
- startTunnel().catch((err) => {
698
- console.error("tunnel:", err);
699
- });
700
-
701
- return () => {
702
- if (tunnel.current) {
703
- console.log("⎔ Shutting down tunnel.");
704
- tunnel.current?.kill();
705
- tunnel.current = undefined;
706
- removeSignalExitListener.current && removeSignalExitListener.current();
707
- removeSignalExitListener.current = undefined;
708
- }
709
- };
710
- }, [toggle]);
624
+ async function getZoneIdHostAndRoutes(args: StartDevOptions, config: Config) {
625
+ // TODO: if worker_dev = false and no routes, then error (only for dev)
626
+ // Compute zone info from the `host` and `route` args and config;
627
+ let host = args.host || config.dev.host;
628
+ let zoneId: string | undefined;
629
+ const routes: Route[] | undefined =
630
+ args.routes || (config.route && [config.route]) || config.routes;
631
+
632
+ if (args.forceLocal) {
633
+ args.local = true;
634
+ }
635
+
636
+ if (!args.local) {
637
+ if (host) {
638
+ zoneId = await getZoneIdFromHost(host);
639
+ }
640
+ if (!zoneId && routes) {
641
+ const firstRoute = routes[0];
642
+ const zone = await getZoneForRoute(firstRoute);
643
+ if (zone) {
644
+ zoneId = zone.id;
645
+ host = zone.host;
646
+ }
647
+ }
648
+ } else if (!host) {
649
+ if (routes) {
650
+ const firstRoute = routes[0];
651
+ host = getHostFromRoute(firstRoute);
652
+ }
653
+ }
654
+ return { host, routes, zoneId };
711
655
  }
712
656
 
713
- type useHotkeysInitialState = {
714
- local: boolean;
715
- tunnel: boolean;
716
- };
717
- function useHotkeys(initial: useHotkeysInitialState, port: number) {
718
- // UGH, we should put port in context instead
719
- const [toggles, setToggles] = useState(initial);
720
- useInput(
721
- async (
722
- input,
723
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
724
- key
725
- ) => {
726
- switch (input) {
727
- case "b": // open browser
728
- await open(`http://localhost:${port}/`);
729
- break;
730
- case "d": // toggle inspector
731
- await open(
732
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:9229/ws`
733
- );
734
- break;
735
- case "s": // toggle tunnel
736
- setToggles((previousToggles) => ({
737
- ...previousToggles,
738
- tunnel: !previousToggles.tunnel,
739
- }));
740
- break;
741
- case "l": // toggle local
742
- setToggles((previousToggles) => ({
743
- ...previousToggles,
744
- local: !previousToggles.local,
745
- }));
746
- break;
747
- case "q": // shut down
748
- case "x": // shut down
749
- process.exit(0);
750
- break;
751
- default:
752
- // nothing?
753
- break;
754
- }
755
- }
756
- );
757
- return toggles;
657
+ async function validateDevServerSettings(
658
+ args: StartDevOptions,
659
+ config: Config
660
+ ) {
661
+ const entry = await getEntry(
662
+ { assets: args.assets, script: args.script },
663
+ config,
664
+ "dev"
665
+ );
666
+
667
+ const { zoneId, host, routes } = await getZoneIdHostAndRoutes(args, config);
668
+ const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
669
+ const getInspectorPort = memoizeGetPort(DEFAULT_INSPECTOR_PORT);
670
+
671
+ if (config.services && config.services.length > 0) {
672
+ logger.warn(
673
+ `This worker is bound to live services: ${config.services
674
+ .map(
675
+ (service) =>
676
+ `${service.binding} (${service.service}${
677
+ service.environment ? `@${service.environment}` : ""
678
+ })`
679
+ )
680
+ .join(", ")}`
681
+ );
682
+ }
683
+
684
+ if (args.inspect) {
685
+ //devtools are enabled by default, but we still need to disable them if the caller doesn't want them
686
+ logger.warn(
687
+ "Passing --inspect is unnecessary, now you can always connect to devtools."
688
+ );
689
+ }
690
+
691
+ if (args["experimental-public"]) {
692
+ throw new Error(
693
+ "The --experimental-public field has been renamed to --assets"
694
+ );
695
+ }
696
+
697
+ if (args.public) {
698
+ throw new Error("The --public field has been renamed to --assets");
699
+ }
700
+
701
+ if ((args.assets || config.assets) && (args.site || config.site)) {
702
+ throw new Error("Cannot use Assets and Workers Sites in the same Worker.");
703
+ }
704
+
705
+ if (args.assets) {
706
+ logger.warn(
707
+ "The --assets argument is experimental and may change or break at any time"
708
+ );
709
+ }
710
+ const upstreamProtocol =
711
+ args["upstream-protocol"] || config.dev.upstream_protocol;
712
+ if (upstreamProtocol === "http") {
713
+ logger.warn(
714
+ "Setting upstream-protocol to http is not currently implemented.\n" +
715
+ "If this is required in your project, please add your use case to the following issue:\n" +
716
+ "https://github.com/cloudflare/wrangler2/issues/583."
717
+ );
718
+ }
719
+ const nodeCompat = args.nodeCompat ?? config.node_compat;
720
+ if (nodeCompat) {
721
+ logger.warn(
722
+ "Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
723
+ );
724
+ }
725
+
726
+ if (args.experimentalEnableLocalPersistence) {
727
+ logger.warn(
728
+ `--experimental-enable-local-persistence is deprecated.\n` +
729
+ `Move any existing data to .wrangler/state and use --persist, or\n` +
730
+ `use --persist-to=./wrangler-local-state to keep using the old path.`
731
+ );
732
+ }
733
+
734
+ const localPersistencePath = getLocalPersistencePath(
735
+ args.persistTo,
736
+ Boolean(args.persist),
737
+ config.configPath
738
+ );
739
+
740
+ const cliDefines = collectKeyValues(args.define);
741
+
742
+ return {
743
+ entry,
744
+ upstreamProtocol,
745
+ nodeCompat,
746
+ getLocalPort,
747
+ getInspectorPort,
748
+ zoneId,
749
+ host,
750
+ routes,
751
+ cliDefines,
752
+ localPersistencePath,
753
+ };
758
754
  }
759
755
 
760
- function ErrorFallback(props: { error: Error }) {
761
- const { exit } = useApp();
762
- useEffect(() => exit(new Error()));
763
- return (
764
- <>
765
- <Text>Something went wrong:</Text>
766
- <Text>{props.error.message}</Text>
767
- </>
768
- );
756
+ async function getBindingsAndAssetPaths(
757
+ args: StartDevOptions,
758
+ configParam: Config
759
+ ) {
760
+ const cliVars = collectKeyValues(args.var);
761
+
762
+ // now log all available bindings into the terminal
763
+ const bindings = await getBindings(configParam, args.env, {
764
+ kv: args.kv,
765
+ vars: { ...args.vars, ...cliVars },
766
+ durableObjects: args.durableObjects,
767
+ r2: args.r2,
768
+ d1Databases: args.d1Databases,
769
+ });
770
+
771
+ const maskedVars = maskVars(bindings, configParam);
772
+
773
+ printBindings({
774
+ ...bindings,
775
+ vars: maskedVars,
776
+ });
777
+
778
+ const assetPaths =
779
+ args.assets || configParam.assets
780
+ ? getAssetPaths(configParam, args.assets)
781
+ : getSiteAssetPaths(
782
+ configParam,
783
+ args.site,
784
+ args.siteInclude,
785
+ args.siteExclude
786
+ );
787
+ return { assetPaths, bindings };
769
788
  }
770
789
 
771
- export default withErrorBoundary(Dev, { FallbackComponent: ErrorFallback });
790
+ async function getBindings(
791
+ configParam: Config,
792
+ env: string | undefined,
793
+ args: AdditionalDevProps
794
+ ): Promise<CfWorkerInit["bindings"]> {
795
+ const bindings = {
796
+ kv_namespaces: [
797
+ ...(configParam.kv_namespaces || []).map(
798
+ ({ binding, preview_id, id: _id }) => {
799
+ // In `dev`, we make folks use a separate kv namespace called
800
+ // `preview_id` instead of `id` so that they don't
801
+ // break production data. So here we check that a `preview_id`
802
+ // has actually been configured.
803
+ // This whole block of code will be obsoleted in the future
804
+ // when we have copy-on-write for previews on edge workers.
805
+ if (!preview_id) {
806
+ // TODO: This error has to be a _lot_ better, ideally just asking
807
+ // to create a preview namespace for the user automatically
808
+ throw new Error(
809
+ `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
810
+ ); // Ugh, I really don't like this message very much
811
+ }
812
+ return {
813
+ binding,
814
+ id: preview_id,
815
+ };
816
+ }
817
+ ),
818
+ ...(args.kv || []),
819
+ ],
820
+ // Use a copy of combinedVars since we're modifying it later
821
+ vars: {
822
+ ...getVarsForDev(configParam, env),
823
+ ...args.vars,
824
+ },
825
+ metadata_binding: configParam.metadata_binding,
826
+ wasm_modules: configParam.wasm_modules,
827
+ text_blobs: configParam.text_blobs,
828
+ data_blobs: configParam.data_blobs,
829
+ durable_objects: {
830
+ bindings: [
831
+ ...(configParam.durable_objects || { bindings: [] }).bindings,
832
+ ...(args.durableObjects || []),
833
+ ],
834
+ },
835
+ queues: [
836
+ ...(configParam.queues.producers || []).map((queue) => {
837
+ return { binding: queue.binding, queue_name: queue.queue };
838
+ }),
839
+ ],
840
+ r2_buckets: [
841
+ ...(configParam.r2_buckets?.map(
842
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
843
+ // same idea as kv namespace preview id,
844
+ // same copy-on-write TODO
845
+ if (!preview_bucket_name) {
846
+ throw new Error(
847
+ `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
848
+ );
849
+ }
850
+ return {
851
+ binding,
852
+ bucket_name: preview_bucket_name,
853
+ };
854
+ }
855
+ ) || []),
856
+ ...(args.r2 || []),
857
+ ],
858
+ dispatch_namespaces: configParam.dispatch_namespaces,
859
+ services: configParam.services,
860
+ unsafe: configParam.unsafe?.bindings,
861
+ logfwdr: configParam.logfwdr,
862
+ d1_databases: identifyD1BindingsAsBeta([
863
+ ...configParam.d1_databases,
864
+ ...(args.d1Databases || []),
865
+ ]),
866
+ };
867
+
868
+ return bindings;
869
+ }