wrangler 0.0.0-e61fba8 → 0.0.0-e665ccc3

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 (339) hide show
  1. package/README.md +24 -4
  2. package/bin/wrangler.js +170 -62
  3. package/miniflare-dist/index.mjs +1643 -83
  4. package/package.json +198 -154
  5. package/src/__tests__/access.test.ts +25 -0
  6. package/src/__tests__/api-dev.test.ts +238 -0
  7. package/src/__tests__/api-devregistry.test.ts +121 -0
  8. package/src/__tests__/api.test.ts +102 -0
  9. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  10. package/src/__tests__/config-cache.test.ts +30 -24
  11. package/src/__tests__/configuration.test.ts +4506 -3476
  12. package/src/__tests__/constellation.test.ts +371 -0
  13. package/src/__tests__/d1/d1.test.ts +82 -0
  14. package/src/__tests__/d1/execute.test.ts +66 -0
  15. package/src/__tests__/d1/migrate.test.ts +257 -0
  16. package/src/__tests__/d1/splitter.test.ts +255 -0
  17. package/src/__tests__/delete.test.ts +272 -0
  18. package/src/__tests__/deployments.test.ts +369 -0
  19. package/src/__tests__/dev.test.tsx +1590 -983
  20. package/src/__tests__/generate.test.ts +237 -0
  21. package/src/__tests__/get-host-from-url.test.ts +16 -0
  22. package/src/__tests__/guess-worker-format.test.ts +103 -68
  23. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  24. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  25. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  26. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  27. package/src/__tests__/helpers/mock-bin.ts +20 -20
  28. package/src/__tests__/helpers/mock-console.ts +64 -39
  29. package/src/__tests__/helpers/mock-dialogs.ts +88 -79
  30. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  31. package/src/__tests__/helpers/mock-get-zone-from-host.ts +11 -0
  32. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  33. package/src/__tests__/helpers/mock-istty.ts +65 -18
  34. package/src/__tests__/helpers/mock-known-routes.ts +12 -0
  35. package/src/__tests__/helpers/mock-kv.ts +41 -28
  36. package/src/__tests__/helpers/mock-oauth-flow.ts +241 -233
  37. package/src/__tests__/helpers/mock-process.ts +34 -0
  38. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  39. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  40. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  41. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  42. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  43. package/src/__tests__/helpers/msw/handlers/deployments.ts +160 -0
  44. package/src/__tests__/helpers/msw/handlers/namespaces.ts +81 -0
  45. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  46. package/src/__tests__/helpers/msw/handlers/r2.ts +60 -0
  47. package/src/__tests__/helpers/msw/handlers/script.ts +56 -0
  48. package/src/__tests__/helpers/msw/handlers/user.ts +52 -0
  49. package/src/__tests__/helpers/msw/handlers/zones.ts +20 -0
  50. package/src/__tests__/helpers/msw/index.ts +52 -0
  51. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  52. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  53. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  54. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  55. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  56. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  57. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  58. package/src/__tests__/helpers/worker-scripts/parent-worker.js +11 -0
  59. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  60. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  61. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  62. package/src/__tests__/https-options.test.ts +142 -109
  63. package/src/__tests__/index.test.ts +262 -237
  64. package/src/__tests__/init.test.ts +3167 -1608
  65. package/src/__tests__/jest.setup.ts +152 -50
  66. package/src/__tests__/kv.test.ts +1789 -1492
  67. package/src/__tests__/logger.test.ts +167 -75
  68. package/src/__tests__/logout.test.ts +47 -0
  69. package/src/__tests__/metrics.test.ts +493 -0
  70. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  71. package/src/__tests__/middleware.test.ts +816 -0
  72. package/src/__tests__/mtls-certificates.test.ts +589 -0
  73. package/src/__tests__/package-manager.test.ts +303 -303
  74. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  75. package/src/__tests__/pages/functions-build.test.ts +528 -0
  76. package/src/__tests__/pages/pages.test.ts +81 -0
  77. package/src/__tests__/pages/project-create.test.ts +63 -0
  78. package/src/__tests__/pages/project-list.test.ts +110 -0
  79. package/src/__tests__/pages/project-upload.test.ts +500 -0
  80. package/src/__tests__/pages/publish.test.ts +2864 -0
  81. package/src/__tests__/pages-deployment-tail.test.ts +957 -0
  82. package/src/__tests__/parse.test.ts +358 -252
  83. package/src/__tests__/paths.test.ts +39 -0
  84. package/src/__tests__/publish.test.ts +8716 -5687
  85. package/src/__tests__/pubsub.test.ts +496 -0
  86. package/src/__tests__/queues.test.ts +532 -0
  87. package/src/__tests__/r2.test.ts +369 -228
  88. package/src/__tests__/route.test.ts +18 -18
  89. package/src/__tests__/secret.test.ts +681 -469
  90. package/src/__tests__/tail.test.ts +866 -567
  91. package/src/__tests__/test-old-node-version.js +31 -0
  92. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  93. package/src/__tests__/tsconfig-sanity.ts +12 -0
  94. package/src/__tests__/tsconfig.json +8 -0
  95. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  96. package/src/__tests__/type-generation.test.ts +234 -0
  97. package/src/__tests__/user.test.ts +107 -120
  98. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  99. package/src/__tests__/validate-dev-props.test.ts +56 -0
  100. package/src/__tests__/version.test.ts +35 -0
  101. package/src/__tests__/whoami.test.tsx +165 -132
  102. package/src/__tests__/worker-namespace.test.ts +340 -0
  103. package/src/abort.d.ts +1 -1
  104. package/src/api/dev.ts +321 -0
  105. package/src/api/index.ts +11 -0
  106. package/src/api/mtls-certificate.ts +148 -0
  107. package/src/api/pages/create-worker-bundle-contents.ts +77 -0
  108. package/src/api/pages/index.ts +5 -0
  109. package/src/api/pages/publish.tsx +371 -0
  110. package/src/bundle-reporter.ts +68 -0
  111. package/src/bundle.ts +890 -165
  112. package/src/cfetch/index.ts +120 -83
  113. package/src/cfetch/internal.ts +208 -92
  114. package/src/cli.ts +23 -8
  115. package/src/config/config.ts +244 -196
  116. package/src/config/diagnostics.ts +61 -61
  117. package/src/config/environment.ts +562 -357
  118. package/src/config/index.ts +374 -196
  119. package/src/config/validation-helpers.ts +379 -366
  120. package/src/config/validation.ts +2197 -1376
  121. package/src/config-cache.ts +81 -41
  122. package/src/constellation/createProject.tsx +51 -0
  123. package/src/constellation/deleteProject.ts +51 -0
  124. package/src/constellation/deleteProjectModel.ts +68 -0
  125. package/src/constellation/index.ts +75 -0
  126. package/src/constellation/listCatalog.tsx +35 -0
  127. package/src/constellation/listModel.tsx +41 -0
  128. package/src/constellation/listProject.tsx +28 -0
  129. package/src/constellation/listRuntime.tsx +28 -0
  130. package/src/constellation/options.ts +17 -0
  131. package/src/constellation/types.ts +17 -0
  132. package/src/constellation/uploadModel.tsx +64 -0
  133. package/src/constellation/utils.ts +90 -0
  134. package/src/create-worker-preview.ts +250 -142
  135. package/src/create-worker-upload-form.ts +347 -238
  136. package/src/d1/backups.tsx +219 -0
  137. package/src/d1/constants.ts +2 -0
  138. package/src/d1/create.tsx +70 -0
  139. package/src/d1/delete.ts +53 -0
  140. package/src/d1/execute.tsx +357 -0
  141. package/src/d1/formatTimeAgo.ts +14 -0
  142. package/src/d1/index.ts +100 -0
  143. package/src/d1/list.tsx +62 -0
  144. package/src/d1/migrations/apply.tsx +212 -0
  145. package/src/d1/migrations/create.tsx +79 -0
  146. package/src/d1/migrations/helpers.ts +169 -0
  147. package/src/d1/migrations/index.ts +3 -0
  148. package/src/d1/migrations/list.tsx +95 -0
  149. package/src/d1/migrations/options.ts +23 -0
  150. package/src/d1/options.ts +22 -0
  151. package/src/d1/splitter.ts +161 -0
  152. package/src/d1/types.ts +25 -0
  153. package/src/d1/utils.ts +49 -0
  154. package/src/delete.ts +100 -0
  155. package/src/deployments.ts +368 -0
  156. package/src/deprecated/index.ts +144 -0
  157. package/src/dev/dev-vars.ts +20 -17
  158. package/src/dev/dev.tsx +535 -325
  159. package/src/dev/get-local-persistence-path.ts +31 -0
  160. package/src/dev/local.tsx +932 -301
  161. package/src/dev/remote.tsx +623 -228
  162. package/src/dev/start-server.ts +545 -0
  163. package/src/dev/use-esbuild.ts +194 -94
  164. package/src/dev/validate-dev-props.ts +40 -0
  165. package/src/dev-registry.ts +202 -0
  166. package/src/dev.tsx +934 -0
  167. package/src/dialogs.ts +136 -0
  168. package/src/dispatch-namespace.ts +211 -0
  169. package/src/docs/helpers.ts +50 -0
  170. package/src/docs/index.ts +54 -0
  171. package/src/durable.ts +87 -87
  172. package/src/entry.ts +253 -231
  173. package/src/environment-variables/factory.ts +89 -0
  174. package/src/environment-variables/misc-variables.ts +30 -0
  175. package/src/errors.ts +6 -6
  176. package/src/generate/index.ts +298 -0
  177. package/src/git-client.ts +135 -0
  178. package/src/global-wrangler-config-path.ts +26 -0
  179. package/src/https-options.ts +84 -80
  180. package/src/index.ts +768 -0
  181. package/src/init.ts +1037 -0
  182. package/src/inspect.ts +816 -595
  183. package/src/intl-polyfill.d.ts +123 -123
  184. package/src/is-ci.ts +14 -0
  185. package/src/is-interactive.ts +16 -0
  186. package/src/jest.d.ts +4 -0
  187. package/src/kv/helpers.ts +433 -0
  188. package/src/kv/index.ts +594 -0
  189. package/src/logger.ts +100 -43
  190. package/src/metrics/index.ts +5 -0
  191. package/src/metrics/metrics-config.ts +239 -0
  192. package/src/metrics/metrics-dispatcher.ts +96 -0
  193. package/src/metrics/metrics-usage-headers.ts +24 -0
  194. package/src/metrics/send-event.ts +99 -0
  195. package/src/miniflare-cli/assets.ts +255 -0
  196. package/src/miniflare-cli/index.ts +202 -33
  197. package/src/miniflare-cli/request-context.ts +18 -18
  198. package/src/miniflare-cli/tsconfig.json +9 -0
  199. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  200. package/src/miniflare-cli/types.ts +11 -0
  201. package/src/module-collection.ts +290 -215
  202. package/src/mtls-certificate/cli.ts +155 -0
  203. package/src/open-in-browser.ts +4 -6
  204. package/src/package-manager.ts +173 -128
  205. package/src/pages/build.ts +423 -0
  206. package/src/pages/buildFunctions.ts +140 -0
  207. package/src/pages/constants.ts +18 -0
  208. package/src/pages/deployment-tails.ts +281 -0
  209. package/src/pages/deployments.tsx +84 -0
  210. package/src/pages/dev.ts +734 -0
  211. package/src/pages/errors.ts +67 -0
  212. package/src/pages/functions/buildPlugin.ts +114 -0
  213. package/src/pages/functions/buildWorker.ts +350 -0
  214. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  215. package/src/pages/functions/filepath-routing.ts +189 -0
  216. package/src/pages/functions/identifiers.ts +78 -0
  217. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  218. package/src/pages/functions/routes-consolidation.ts +73 -0
  219. package/src/pages/functions/routes-transformation.test.ts +282 -0
  220. package/src/pages/functions/routes-transformation.ts +115 -0
  221. package/src/pages/functions/routes-validation.test.ts +403 -0
  222. package/src/pages/functions/routes-validation.ts +202 -0
  223. package/src/pages/functions/routes.ts +151 -0
  224. package/src/pages/functions/tsconfig.json +8 -0
  225. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  226. package/src/pages/functions.ts +86 -0
  227. package/src/pages/hash.ts +13 -0
  228. package/src/pages/index.ts +102 -0
  229. package/src/pages/projects.tsx +159 -0
  230. package/src/pages/prompt-select-project.tsx +31 -0
  231. package/src/pages/publish.tsx +267 -0
  232. package/src/pages/types.ts +46 -0
  233. package/src/pages/upload.tsx +469 -0
  234. package/src/pages/utils.ts +23 -0
  235. package/src/parse.ts +225 -139
  236. package/src/paths.ts +53 -8
  237. package/src/proxy.ts +623 -407
  238. package/src/publish/index.ts +274 -0
  239. package/src/publish/publish.ts +1065 -0
  240. package/src/pubsub/index.ts +286 -0
  241. package/src/pubsub/pubsub-commands.ts +623 -0
  242. package/src/queues/cli/commands/consumer/add.ts +71 -0
  243. package/src/queues/cli/commands/consumer/index.ts +19 -0
  244. package/src/queues/cli/commands/consumer/remove.ts +31 -0
  245. package/src/queues/cli/commands/create.ts +25 -0
  246. package/src/queues/cli/commands/delete.ts +26 -0
  247. package/src/queues/cli/commands/index.ts +35 -0
  248. package/src/queues/cli/commands/list.ts +25 -0
  249. package/src/queues/client.ts +136 -0
  250. package/src/queues/utils.ts +18 -0
  251. package/src/r2/constants.ts +4 -0
  252. package/src/r2/helpers.ts +132 -0
  253. package/src/r2/index.ts +289 -0
  254. package/src/routes.ts +140 -0
  255. package/src/secret/index.ts +377 -0
  256. package/src/selfsigned.d.ts +23 -23
  257. package/src/sites.ts +484 -0
  258. package/src/tail/createTail.ts +415 -0
  259. package/src/tail/filters.ts +109 -111
  260. package/src/tail/index.ts +208 -296
  261. package/src/tail/printing.ts +116 -51
  262. package/src/traverse-module-graph.ts +54 -0
  263. package/src/tsconfig-sanity.ts +16 -0
  264. package/src/type-generation.ts +181 -0
  265. package/src/update-check.ts +11 -11
  266. package/src/user/access.ts +68 -0
  267. package/src/user/auth-variables.ts +113 -0
  268. package/src/user/choose-account.tsx +39 -0
  269. package/src/user/generate-auth-url.ts +33 -0
  270. package/src/user/generate-random-state.ts +16 -0
  271. package/src/user/index.ts +2 -0
  272. package/src/user/user.ts +1234 -0
  273. package/src/utils/collectKeyValues.ts +14 -0
  274. package/src/utils/render.ts +93 -0
  275. package/src/whoami.ts +135 -0
  276. package/src/worker.ts +205 -107
  277. package/src/yargs-types.ts +37 -0
  278. package/src/zones.ts +158 -40
  279. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  280. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  281. package/templates/__tests__/tsconfig.json +8 -0
  282. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  283. package/templates/checked-fetch.js +23 -0
  284. package/templates/d1-beta-facade.js +244 -0
  285. package/templates/facade.d.ts +14 -0
  286. package/templates/first-party-worker-module-facade.ts +19 -0
  287. package/templates/format-dev-errors.ts +34 -0
  288. package/templates/gitignore +1 -0
  289. package/templates/init-tests/test-jest-new-worker.js +23 -0
  290. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  291. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  292. package/templates/middleware/common.ts +62 -0
  293. package/templates/middleware/loader-modules.ts +84 -0
  294. package/templates/middleware/loader-sw.ts +233 -0
  295. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  296. package/templates/middleware/middleware-pretty-error.ts +40 -0
  297. package/templates/middleware/middleware-scheduled.ts +15 -0
  298. package/templates/new-worker-scheduled.js +3 -3
  299. package/templates/new-worker-scheduled.ts +15 -15
  300. package/templates/new-worker.js +3 -3
  301. package/templates/new-worker.ts +18 -15
  302. package/templates/no-op-worker.js +10 -0
  303. package/templates/pages-dev-pipeline.ts +31 -0
  304. package/templates/pages-dev-util.ts +52 -0
  305. package/templates/pages-shim.ts +12 -0
  306. package/templates/pages-template-plugin.ts +180 -0
  307. package/templates/pages-template-worker.ts +189 -0
  308. package/templates/serve-static-assets.ts +66 -0
  309. package/templates/service-bindings-module-facade.js +55 -0
  310. package/templates/service-bindings-sw-facade.js +42 -0
  311. package/templates/tsconfig-sanity.ts +11 -0
  312. package/templates/tsconfig.init.json +105 -0
  313. package/templates/tsconfig.json +6 -103
  314. package/templates/tsconfig.tsbuildinfo +1 -0
  315. package/wrangler-dist/cli.d.ts +1652 -0
  316. package/wrangler-dist/cli.js +139094 -111923
  317. package/wrangler-dist/wasm-sync.wasm +0 -0
  318. package/pages/functions/buildPlugin.ts +0 -105
  319. package/pages/functions/buildWorker.ts +0 -151
  320. package/pages/functions/filepath-routing.ts +0 -189
  321. package/pages/functions/identifiers.ts +0 -78
  322. package/pages/functions/routes.ts +0 -156
  323. package/pages/functions/template-plugin.ts +0 -147
  324. package/pages/functions/template-worker.ts +0 -143
  325. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  326. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  327. package/src/__tests__/pages.test.ts +0 -754
  328. package/src/dialogs.tsx +0 -135
  329. package/src/environment-variables.ts +0 -35
  330. package/src/index.tsx +0 -2859
  331. package/src/kv.ts +0 -408
  332. package/src/miniflare-cli/enum-keys.ts +0 -17
  333. package/src/pages.tsx +0 -2093
  334. package/src/publish.ts +0 -721
  335. package/src/r2.ts +0 -50
  336. package/src/sites.tsx +0 -326
  337. package/src/user.tsx +0 -1214
  338. package/src/whoami.tsx +0 -71
  339. package/templates/static-asset-facade.js +0 -43
package/src/dev.tsx ADDED
@@ -0,0 +1,934 @@
1
+ import path from "node:path";
2
+ import chalk from "chalk";
3
+ import { watch } from "chokidar";
4
+ import getPort from "get-port";
5
+ import { render } from "ink";
6
+ import React from "react";
7
+ import { findWranglerToml, printBindings, readConfig } from "./config";
8
+ import Dev from "./dev/dev";
9
+ import { getVarsForDev } from "./dev/dev-vars";
10
+ import { getLocalPersistencePath } from "./dev/get-local-persistence-path";
11
+
12
+ import { startDevServer } from "./dev/start-server";
13
+ import { getEntry } from "./entry";
14
+ import { logger } from "./logger";
15
+ import * as metrics from "./metrics";
16
+ import { getAssetPaths, getSiteAssetPaths } from "./sites";
17
+ import { getAccountFromCache, loginOrRefreshIfRequired } from "./user";
18
+ import { collectKeyValues } from "./utils/collectKeyValues";
19
+ import { identifyD1BindingsAsBeta } from "./worker";
20
+ import { getHostFromRoute, getZoneForRoute, getZoneIdFromHost } from "./zones";
21
+ import {
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, Rule } from "./config/environment";
32
+ import type { LoggerLevel } from "./logger";
33
+ import type { EnablePagesAssetsServiceBindingOptions } from "./miniflare-cli/types";
34
+ import type { CfWorkerInit } from "./worker";
35
+ import type {
36
+ CommonYargsArgv,
37
+ StrictYargsOptionsToInterface,
38
+ } from "./yargs-types";
39
+
40
+ export function devOptions(yargs: CommonYargsArgv) {
41
+ return (
42
+ yargs
43
+ .positional("script", {
44
+ describe: "The path to an entry point for your worker",
45
+ type: "string",
46
+ })
47
+ .option("name", {
48
+ describe: "Name of the worker",
49
+ type: "string",
50
+ requiresArg: true,
51
+ })
52
+ // We want to have a --no-bundle flag, but yargs requires that
53
+ // we also have a --bundle flag (that it adds the --no to by itself)
54
+ // So we make a --bundle flag, but hide it, and then add a --no-bundle flag
55
+ // that's visible to the user but doesn't "do" anything.
56
+ .option("bundle", {
57
+ describe: "Run wrangler's compilation step before publishing",
58
+ type: "boolean",
59
+ hidden: true,
60
+ })
61
+ .option("no-bundle", {
62
+ describe: "Skip internal build steps and directly publish script",
63
+ type: "boolean",
64
+ default: false,
65
+ })
66
+ .option("format", {
67
+ choices: ["modules", "service-worker"] as const,
68
+ describe: "Choose an entry type",
69
+ hidden: true,
70
+ deprecated: true,
71
+ })
72
+ .option("compatibility-date", {
73
+ describe: "Date to use for compatibility checks",
74
+ type: "string",
75
+ requiresArg: true,
76
+ })
77
+ .option("compatibility-flags", {
78
+ describe: "Flags to use for compatibility checks",
79
+ alias: "compatibility-flag",
80
+ type: "string",
81
+ requiresArg: true,
82
+ array: true,
83
+ })
84
+ .option("latest", {
85
+ describe: "Use the latest version of the worker runtime",
86
+ type: "boolean",
87
+ default: true,
88
+ })
89
+ .option("ip", {
90
+ describe: "IP address to listen on",
91
+ type: "string",
92
+ })
93
+ .option("port", {
94
+ describe: "Port to listen on",
95
+ type: "number",
96
+ })
97
+ .option("inspector-port", {
98
+ describe: "Port for devtools to connect to",
99
+ type: "number",
100
+ })
101
+ .option("routes", {
102
+ describe: "Routes to upload",
103
+ alias: "route",
104
+ type: "string",
105
+ requiresArg: true,
106
+ array: true,
107
+ })
108
+ .option("host", {
109
+ type: "string",
110
+ requiresArg: true,
111
+ describe:
112
+ "Host to forward requests to, defaults to the zone of project",
113
+ })
114
+ .option("local-protocol", {
115
+ describe: "Protocol to listen to requests on, defaults to http.",
116
+ choices: ["http", "https"] as const,
117
+ })
118
+ .options("local-upstream", {
119
+ type: "string",
120
+ describe:
121
+ "Host to act as origin in local mode, defaults to dev.host or route",
122
+ })
123
+ .option("experimental-public", {
124
+ describe: "Static assets to be served",
125
+ type: "string",
126
+ requiresArg: true,
127
+ deprecated: true,
128
+ hidden: true,
129
+ })
130
+ .option("assets", {
131
+ describe: "Static assets to be served",
132
+ type: "string",
133
+ requiresArg: true,
134
+ })
135
+ .option("public", {
136
+ describe: "(Deprecated) Static assets to be served",
137
+ type: "string",
138
+ requiresArg: true,
139
+ deprecated: true,
140
+ hidden: true,
141
+ })
142
+ .option("site", {
143
+ describe: "Root folder of static assets for Workers Sites",
144
+ type: "string",
145
+ requiresArg: true,
146
+ })
147
+ .option("site-include", {
148
+ describe:
149
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
150
+ type: "string",
151
+ requiresArg: true,
152
+ array: true,
153
+ })
154
+ .option("site-exclude", {
155
+ describe:
156
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
157
+ type: "string",
158
+ requiresArg: true,
159
+ array: true,
160
+ })
161
+ .option("upstream-protocol", {
162
+ describe: "Protocol to forward requests to host on, defaults to https.",
163
+ choices: ["http", "https"] as const,
164
+ })
165
+ .option("var", {
166
+ describe:
167
+ "A key-value pair to be injected into the script as a variable",
168
+ type: "string",
169
+ requiresArg: true,
170
+ array: true,
171
+ })
172
+ .option("define", {
173
+ describe: "A key-value pair to be substituted in the script",
174
+ type: "string",
175
+ requiresArg: true,
176
+ array: true,
177
+ })
178
+ .option("jsx-factory", {
179
+ describe: "The function that is called for each JSX element",
180
+ type: "string",
181
+ requiresArg: true,
182
+ })
183
+ .option("jsx-fragment", {
184
+ describe: "The function that is called for each JSX fragment",
185
+ type: "string",
186
+ requiresArg: true,
187
+ })
188
+ .option("tsconfig", {
189
+ describe: "Path to a custom tsconfig.json file",
190
+ type: "string",
191
+ requiresArg: true,
192
+ })
193
+ .option("local", {
194
+ alias: "l",
195
+ describe: "Run on my machine",
196
+ type: "boolean",
197
+ default: false, // I bet this will a point of contention. We'll revisit it.
198
+ })
199
+ .option("experimental-local", {
200
+ describe: "Run on my machine using the Cloudflare Workers runtime",
201
+ type: "boolean",
202
+ default: false,
203
+ })
204
+ .option("experimental-local-remote-kv", {
205
+ describe:
206
+ "Read/write KV data from/to real namespaces on the Cloudflare network",
207
+ type: "boolean",
208
+ default: false,
209
+ })
210
+ .check((argv) => {
211
+ if (argv.local && argv["experimental-local"]) {
212
+ throw new Error(
213
+ "--local and --experimental-local are mutually exclusive. " +
214
+ "Please enable one or the other."
215
+ );
216
+ }
217
+ if (
218
+ argv["experimental-local-remote-kv"] &&
219
+ !argv["experimental-local"]
220
+ ) {
221
+ throw new Error(
222
+ "--experimental-local-remote-kv requires --experimental-local to be enabled."
223
+ );
224
+ }
225
+ return true;
226
+ })
227
+ .option("minify", {
228
+ describe: "Minify the script",
229
+ type: "boolean",
230
+ })
231
+ .option("node-compat", {
232
+ describe: "Enable Node.js compatibility",
233
+ type: "boolean",
234
+ })
235
+ .option("experimental-enable-local-persistence", {
236
+ describe:
237
+ "Enable persistence for local mode (deprecated, use --persist)",
238
+ type: "boolean",
239
+ deprecated: true,
240
+ hidden: true,
241
+ })
242
+ .option("persist", {
243
+ describe:
244
+ "Enable persistence for local mode, using default path: .wrangler/state",
245
+ type: "boolean",
246
+ })
247
+ .option("persist-to", {
248
+ describe:
249
+ "Specify directory to use for local persistence (implies --persist)",
250
+ type: "string",
251
+ requiresArg: true,
252
+ })
253
+ .option("live-reload", {
254
+ describe:
255
+ "Auto reload HTML pages when change is detected in local mode",
256
+ type: "boolean",
257
+ })
258
+ .check((argv) => {
259
+ const local = argv["local"] || argv["experimental-local"];
260
+ if (argv["live-reload"] && !local) {
261
+ throw new Error(
262
+ "--live-reload is only supported in local mode. " +
263
+ "Please enable either --local or --experimental-local."
264
+ );
265
+ }
266
+ return true;
267
+ })
268
+ .option("inspect", {
269
+ describe: "Enable dev tools",
270
+ type: "boolean",
271
+ deprecated: true,
272
+ hidden: true,
273
+ })
274
+ .option("legacy-env", {
275
+ type: "boolean",
276
+ describe: "Use legacy environments",
277
+ hidden: true,
278
+ })
279
+ .option("test-scheduled", {
280
+ describe: "Test scheduled events by visiting /__scheduled in browser",
281
+ type: "boolean",
282
+ default: false,
283
+ })
284
+ .option("log-level", {
285
+ choices: ["debug", "info", "log", "warn", "error", "none"] as const,
286
+ describe: "Specify logging level",
287
+ // Yargs requires this to type log-level properly
288
+ default: "log" as LoggerLevel,
289
+ })
290
+ );
291
+ }
292
+
293
+ type DevArguments = StrictYargsOptionsToInterface<typeof devOptions>;
294
+
295
+ export async function devHandler(args: DevArguments) {
296
+ if (!(args.local || args.experimentalLocal)) {
297
+ const isLoggedIn = await loginOrRefreshIfRequired();
298
+ if (!isLoggedIn) {
299
+ throw new Error(
300
+ "You must be logged in to use wrangler dev in remote mode. Try logging in, or run wrangler dev --local."
301
+ );
302
+ }
303
+ }
304
+
305
+ let watcher;
306
+ try {
307
+ const devInstance = await startDev(args);
308
+ watcher = devInstance.watcher;
309
+ const { waitUntilExit } = devInstance.devReactElement;
310
+ await waitUntilExit();
311
+ } finally {
312
+ await watcher?.close();
313
+ }
314
+ }
315
+
316
+ export type AdditionalDevProps = {
317
+ vars?: {
318
+ [key: string]: unknown;
319
+ };
320
+ kv?: {
321
+ binding: string;
322
+ id: string;
323
+ preview_id?: string;
324
+ }[];
325
+ durableObjects?: {
326
+ name: string;
327
+ class_name: string;
328
+ script_name?: string | undefined;
329
+ environment?: string | undefined;
330
+ }[];
331
+ r2?: {
332
+ binding: string;
333
+ bucket_name: string;
334
+ preview_bucket_name?: string;
335
+ }[];
336
+ d1Databases?: Environment["d1_databases"];
337
+ processEntrypoint?: boolean;
338
+ moduleRoot?: string;
339
+ rules?: Rule[];
340
+ };
341
+
342
+ type StartDevOptions = DevArguments &
343
+ // These options can be passed in directly when called with the `wrangler.dev()` API.
344
+ // They aren't exposed as CLI arguments.
345
+ AdditionalDevProps & {
346
+ forceLocal?: boolean;
347
+ disableDevRegistry?: boolean;
348
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
349
+ onReady?: (ip: string, port: number) => void;
350
+ showInteractiveDevSession?: boolean;
351
+ };
352
+
353
+ export async function startDev(args: StartDevOptions) {
354
+ let watcher: ReturnType<typeof watch> | undefined;
355
+ let rerender: (node: React.ReactNode) => void | undefined;
356
+ try {
357
+ if (args.logLevel) {
358
+ logger.loggerLevel = args.logLevel;
359
+ }
360
+ await printWranglerBanner();
361
+
362
+ if (args.local && process.platform !== "win32") {
363
+ logger.info(
364
+ chalk.magenta(
365
+ `Want to try out the next version of local mode using the open-source Workers runtime?\nSwitch out --local for ${chalk.bold(
366
+ "--experimental-local"
367
+ )} and let us know what you think at https://discord.gg/cloudflaredev !`
368
+ )
369
+ );
370
+ }
371
+
372
+ const configPath =
373
+ args.config ||
374
+ (args.script && findWranglerToml(path.dirname(args.script)));
375
+ let config = readConfig(configPath, args);
376
+
377
+ if (config.configPath) {
378
+ watcher = watch(config.configPath, {
379
+ persistent: true,
380
+ }).on("change", async (_event) => {
381
+ // TODO: Do we need to handle different `_event` types differently?
382
+ // e.g. what if the file is deleted, or added?
383
+ config = readConfig(configPath, args);
384
+ if (config.configPath) {
385
+ logger.log(`${path.basename(config.configPath)} changed...`);
386
+ rerender(await getDevReactElement(config));
387
+ }
388
+ });
389
+ }
390
+
391
+ const {
392
+ entry,
393
+ legacyNodeCompat,
394
+ nodejsCompat,
395
+ upstreamProtocol,
396
+ zoneId,
397
+ host,
398
+ routes,
399
+ getLocalPort,
400
+ getInspectorPort,
401
+ cliDefines,
402
+ localPersistencePath,
403
+ } = await validateDevServerSettings(args, config);
404
+
405
+ await metrics.sendMetricsEvent(
406
+ "run dev",
407
+ {
408
+ local: args.local,
409
+ usesTypeScript: /\.tsx?$/.test(entry.file),
410
+ },
411
+ { sendMetrics: config.send_metrics, offline: args.local }
412
+ );
413
+
414
+ // eslint-disable-next-line no-inner-declarations
415
+ async function getDevReactElement(configParam: Config) {
416
+ const { assetPaths, bindings } = getBindingsAndAssetPaths(
417
+ args,
418
+ configParam
419
+ );
420
+
421
+ return (
422
+ <Dev
423
+ name={getScriptName({ name: args.name, env: args.env }, configParam)}
424
+ noBundle={!(args.bundle ?? !configParam.no_bundle)}
425
+ entry={entry}
426
+ env={args.env}
427
+ zone={zoneId}
428
+ host={host}
429
+ routes={routes}
430
+ processEntrypoint={!!args.processEntrypoint}
431
+ rules={args.rules ?? getRules(configParam)}
432
+ legacyEnv={isLegacyEnv(configParam)}
433
+ minify={args.minify ?? configParam.minify}
434
+ legacyNodeCompat={legacyNodeCompat}
435
+ nodejsCompat={nodejsCompat}
436
+ build={configParam.build || {}}
437
+ define={{ ...configParam.define, ...cliDefines }}
438
+ initialMode={
439
+ args.local || args.experimentalLocal ? "local" : "remote"
440
+ }
441
+ jsxFactory={args.jsxFactory || configParam.jsx_factory}
442
+ jsxFragment={args.jsxFragment || configParam.jsx_fragment}
443
+ tsconfig={args.tsconfig ?? configParam.tsconfig}
444
+ upstreamProtocol={upstreamProtocol}
445
+ localProtocol={args.localProtocol || configParam.dev.local_protocol}
446
+ localUpstream={args.localUpstream ?? host}
447
+ localPersistencePath={localPersistencePath}
448
+ liveReload={args.liveReload || false}
449
+ accountId={configParam.account_id || getAccountFromCache()?.id}
450
+ assetPaths={assetPaths}
451
+ assetsConfig={configParam.assets}
452
+ initialPort={
453
+ args.port ?? configParam.dev.port ?? (await getLocalPort())
454
+ }
455
+ initialIp={args.ip || configParam.dev.ip}
456
+ inspectorPort={
457
+ args.inspectorPort ??
458
+ configParam.dev.inspector_port ??
459
+ (await getInspectorPort())
460
+ }
461
+ isWorkersSite={Boolean(args.site || configParam.site)}
462
+ compatibilityDate={getDevCompatibilityDate(
463
+ configParam,
464
+ args.compatibilityDate
465
+ )}
466
+ compatibilityFlags={
467
+ args.compatibilityFlags || configParam.compatibility_flags
468
+ }
469
+ usageModel={configParam.usage_model}
470
+ bindings={bindings}
471
+ crons={configParam.triggers.crons}
472
+ queueConsumers={configParam.queues.consumers}
473
+ onReady={args.onReady}
474
+ inspect={args.inspect ?? true}
475
+ showInteractiveDevSession={args.showInteractiveDevSession}
476
+ forceLocal={args.forceLocal}
477
+ enablePagesAssetsServiceBinding={args.enablePagesAssetsServiceBinding}
478
+ firstPartyWorker={configParam.first_party_worker}
479
+ sendMetrics={configParam.send_metrics}
480
+ testScheduled={args.testScheduled}
481
+ experimentalLocal={args.experimentalLocal}
482
+ experimentalLocalRemoteKv={args.experimentalLocalRemoteKv}
483
+ />
484
+ );
485
+ }
486
+ const devReactElement = render(await getDevReactElement(config));
487
+
488
+ // In the bootstrapper script `bin/wrangler.js`, we open an IPC channel, so
489
+ // IPC messages from this process are propagated through the bootstrapper.
490
+ // Normally, Node's SIGINT handler would close this for us, but interactive
491
+ // mode enables raw mode on stdin which disables the built-in handler. The
492
+ // following line disconnects from the IPC channel when we press `x` or
493
+ // CTRL-C in interactive mode, ensuring no open handles, and allowing for a
494
+ // clean exit. Note, if we called `stop()` using the dev API, we don't want
495
+ // to disconnect here, as the user may still need IPC. We also don't want
496
+ // to disconnect if this file was imported in Jest (not the case with E2E
497
+ // tests), as that would stop communication with the test runner.
498
+ let apiStopped = false;
499
+ void devReactElement.waitUntilExit().then(() => {
500
+ if (!apiStopped && typeof jest === "undefined") process.disconnect?.();
501
+ });
502
+
503
+ rerender = devReactElement.rerender;
504
+ return {
505
+ devReactElement,
506
+ watcher,
507
+ stop: async () => {
508
+ apiStopped = true;
509
+ devReactElement.unmount();
510
+ await watcher?.close();
511
+ },
512
+ };
513
+ } finally {
514
+ await watcher?.close();
515
+ }
516
+ }
517
+
518
+ export async function startApiDev(args: StartDevOptions) {
519
+ if (args.logLevel) {
520
+ logger.loggerLevel = args.logLevel;
521
+ }
522
+ await printWranglerBanner();
523
+
524
+ const configPath =
525
+ args.config || (args.script && findWranglerToml(path.dirname(args.script)));
526
+ const config = readConfig(configPath, args);
527
+
528
+ const {
529
+ entry,
530
+ legacyNodeCompat,
531
+ nodejsCompat,
532
+ upstreamProtocol,
533
+ zoneId,
534
+ host,
535
+ routes,
536
+ getLocalPort,
537
+ getInspectorPort,
538
+ cliDefines,
539
+ localPersistencePath,
540
+ } = await validateDevServerSettings(args, config);
541
+
542
+ await metrics.sendMetricsEvent(
543
+ "run dev (api)",
544
+ { local: args.local },
545
+ { sendMetrics: config.send_metrics, offline: args.local }
546
+ );
547
+
548
+ // eslint-disable-next-line no-inner-declarations
549
+ async function getDevServer(configParam: Config) {
550
+ const { assetPaths, bindings } = getBindingsAndAssetPaths(
551
+ args,
552
+ configParam
553
+ );
554
+
555
+ //if args.bundle is on, don't disable bundling
556
+ //if there's no args.bundle, and configParam.no_bundle is on, disable bundling
557
+ //otherwise, enable bundling
558
+ const enableBundling = args.bundle ?? !configParam.no_bundle;
559
+ return await startDevServer({
560
+ name: getScriptName({ name: args.name, env: args.env }, configParam),
561
+ noBundle: !enableBundling,
562
+ entry: entry,
563
+ env: args.env,
564
+ zone: zoneId,
565
+ host: host,
566
+ routes: routes,
567
+ processEntrypoint: !!args.processEntrypoint,
568
+ rules: args.rules ?? getRules(configParam),
569
+ legacyEnv: isLegacyEnv(configParam),
570
+ minify: args.minify ?? configParam.minify,
571
+ legacyNodeCompat,
572
+ nodejsCompat,
573
+ build: configParam.build || {},
574
+ define: { ...config.define, ...cliDefines },
575
+ initialMode: args.local ? "local" : "remote",
576
+ jsxFactory: args.jsxFactory ?? configParam.jsx_factory,
577
+ jsxFragment: args.jsxFragment ?? configParam.jsx_fragment,
578
+ tsconfig: args.tsconfig ?? configParam.tsconfig,
579
+ upstreamProtocol: upstreamProtocol,
580
+ localProtocol: args.localProtocol ?? configParam.dev.local_protocol,
581
+ localUpstream: args.localUpstream ?? host,
582
+ localPersistencePath,
583
+ liveReload: args.liveReload ?? false,
584
+ accountId: configParam.account_id ?? getAccountFromCache()?.id,
585
+ assetPaths: assetPaths,
586
+ assetsConfig: configParam.assets,
587
+ //port can be 0, which means to use a random port
588
+ initialPort: args.port ?? configParam.dev.port ?? (await getLocalPort()),
589
+ initialIp: args.ip ?? configParam.dev.ip,
590
+ inspectorPort:
591
+ args.inspectorPort ??
592
+ configParam.dev.inspector_port ??
593
+ (await getInspectorPort()),
594
+ isWorkersSite: Boolean(args.site || configParam.site),
595
+ compatibilityDate: getDevCompatibilityDate(
596
+ config,
597
+ // Only `compatibilityDate` will be set when using `unstable_dev`
598
+ args.compatibilityDate
599
+ ),
600
+ compatibilityFlags:
601
+ args.compatibilityFlags ?? configParam.compatibility_flags,
602
+ usageModel: configParam.usage_model,
603
+ bindings: bindings,
604
+ crons: configParam.triggers.crons,
605
+ queueConsumers: configParam.queues.consumers,
606
+ onReady: args.onReady,
607
+ inspect: args.inspect ?? true,
608
+ showInteractiveDevSession: args.showInteractiveDevSession,
609
+ forceLocal: args.forceLocal,
610
+ enablePagesAssetsServiceBinding: args.enablePagesAssetsServiceBinding,
611
+ local: args.local ?? true,
612
+ firstPartyWorker: configParam.first_party_worker,
613
+ sendMetrics: configParam.send_metrics,
614
+ testScheduled: args.testScheduled,
615
+ experimentalLocal: args.experimentalLocal,
616
+ experimentalLocalRemoteKv: args.experimentalLocalRemoteKv,
617
+ disableDevRegistry: args.disableDevRegistry ?? false,
618
+ });
619
+ }
620
+
621
+ const devServer = await getDevServer(config);
622
+ if (!devServer) {
623
+ throw logger.error("Failed to start dev server.");
624
+ }
625
+
626
+ return {
627
+ stop: async () => {
628
+ await devServer.stop();
629
+ },
630
+ };
631
+ }
632
+ /**
633
+ * Avoiding calling `getPort()` multiple times by memoizing the first result.
634
+ */
635
+ function memoizeGetPort(defaultPort: number) {
636
+ let portValue: number;
637
+ return async () => {
638
+ return portValue || (portValue = await getPort({ port: defaultPort }));
639
+ };
640
+ }
641
+ /**
642
+ * mask anything that was overridden in .dev.vars
643
+ * so that we don't log potential secrets into the terminal
644
+ */
645
+ function maskVars(bindings: CfWorkerInit["bindings"], configParam: Config) {
646
+ const maskedVars = { ...bindings.vars };
647
+ for (const key of Object.keys(maskedVars)) {
648
+ if (maskedVars[key] !== configParam.vars[key]) {
649
+ // This means it was overridden in .dev.vars
650
+ // so let's mask it
651
+ maskedVars[key] = "(hidden)";
652
+ }
653
+ }
654
+ return maskedVars;
655
+ }
656
+
657
+ async function getZoneIdHostAndRoutes(args: StartDevOptions, config: Config) {
658
+ // TODO: if worker_dev = false and no routes, then error (only for dev)
659
+ // Compute zone info from the `host` and `route` args and config;
660
+ let host = args.host || config.dev.host;
661
+ let zoneId: string | undefined;
662
+ const routes: Route[] | undefined =
663
+ args.routes || (config.route && [config.route]) || config.routes;
664
+
665
+ if (args.forceLocal) {
666
+ args.local = true;
667
+ }
668
+
669
+ if (!args.local && !args.experimentalLocal) {
670
+ if (host) {
671
+ zoneId = await getZoneIdFromHost(host);
672
+ }
673
+ if (!zoneId && routes) {
674
+ const firstRoute = routes[0];
675
+ const zone = await getZoneForRoute(firstRoute);
676
+ if (zone) {
677
+ zoneId = zone.id;
678
+ host = zone.host;
679
+ }
680
+ }
681
+ } else if (!host) {
682
+ if (routes) {
683
+ const firstRoute = routes[0];
684
+ host = getHostFromRoute(firstRoute);
685
+ }
686
+ }
687
+ return { host, routes, zoneId };
688
+ }
689
+
690
+ async function validateDevServerSettings(
691
+ args: StartDevOptions,
692
+ config: Config
693
+ ) {
694
+ const entry = await getEntry(
695
+ { assets: args.assets, script: args.script, moduleRoot: args.moduleRoot },
696
+ config,
697
+ "dev"
698
+ );
699
+
700
+ const { zoneId, host, routes } = await getZoneIdHostAndRoutes(args, config);
701
+ const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
702
+ const getInspectorPort = memoizeGetPort(DEFAULT_INSPECTOR_PORT);
703
+
704
+ if (config.services && config.services.length > 0) {
705
+ logger.warn(
706
+ `This worker is bound to live services: ${config.services
707
+ .map(
708
+ (service) =>
709
+ `${service.binding} (${service.service}${
710
+ service.environment ? `@${service.environment}` : ""
711
+ })`
712
+ )
713
+ .join(", ")}`
714
+ );
715
+ }
716
+
717
+ if (args.inspect) {
718
+ //devtools are enabled by default, but we still need to disable them if the caller doesn't want them
719
+ logger.warn(
720
+ "Passing --inspect is unnecessary, now you can always connect to devtools."
721
+ );
722
+ }
723
+ if (args.experimentalPublic) {
724
+ throw new Error(
725
+ "The --experimental-public field has been renamed to --assets"
726
+ );
727
+ }
728
+
729
+ if (args.public) {
730
+ throw new Error("The --public field has been renamed to --assets");
731
+ }
732
+
733
+ if ((args.assets ?? config.assets) && (args.site ?? config.site)) {
734
+ throw new Error("Cannot use Assets and Workers Sites in the same Worker.");
735
+ }
736
+
737
+ if (args.assets) {
738
+ logger.warn(
739
+ "The --assets argument is experimental and may change or break at any time"
740
+ );
741
+ }
742
+ const upstreamProtocol =
743
+ args.upstreamProtocol ?? config.dev.upstream_protocol;
744
+ if (upstreamProtocol === "http") {
745
+ logger.warn(
746
+ "Setting upstream-protocol to http is not currently implemented.\n" +
747
+ "If this is required in your project, please add your use case to the following issue:\n" +
748
+ "https://github.com/cloudflare/workers-sdk/issues/583."
749
+ );
750
+ }
751
+ const legacyNodeCompat = args.nodeCompat ?? config.node_compat;
752
+ if (legacyNodeCompat) {
753
+ logger.warn(
754
+ "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."
755
+ );
756
+ }
757
+
758
+ const compatibilityFlags =
759
+ args.compatibilityFlags ?? config.compatibility_flags;
760
+ const nodejsCompat = compatibilityFlags?.includes("nodejs_compat");
761
+ if (legacyNodeCompat && nodejsCompat) {
762
+ throw new Error(
763
+ "The `nodejs_compat` compatibility flag cannot be used in conjunction with the legacy `--node-compat` flag. If you want to use the Workers runtime Node.js compatibility features, please remove the `--node-compat` argument from your CLI command or `node_compat = true` from your config file."
764
+ );
765
+ }
766
+
767
+ if (args.experimentalEnableLocalPersistence) {
768
+ logger.warn(
769
+ `--experimental-enable-local-persistence is deprecated.\n` +
770
+ `Move any existing data to .wrangler/state and use --persist, or\n` +
771
+ `use --persist-to=./wrangler-local-state to keep using the old path.`
772
+ );
773
+ }
774
+
775
+ const localPersistencePath = getLocalPersistencePath(
776
+ args.persistTo,
777
+ Boolean(args.persist),
778
+ config.configPath
779
+ );
780
+
781
+ const cliDefines = collectKeyValues(args.define);
782
+
783
+ return {
784
+ entry,
785
+ upstreamProtocol,
786
+ legacyNodeCompat,
787
+ nodejsCompat,
788
+ getLocalPort,
789
+ getInspectorPort,
790
+ zoneId,
791
+ host,
792
+ routes,
793
+ cliDefines,
794
+ localPersistencePath,
795
+ };
796
+ }
797
+
798
+ function getBindingsAndAssetPaths(args: StartDevOptions, configParam: Config) {
799
+ const cliVars = collectKeyValues(args.var);
800
+
801
+ // now log all available bindings into the terminal
802
+ const bindings = getBindings(configParam, args.env, args.local ?? false, {
803
+ kv: args.kv,
804
+ vars: { ...args.vars, ...cliVars },
805
+ durableObjects: args.durableObjects,
806
+ r2: args.r2,
807
+ d1Databases: args.d1Databases,
808
+ });
809
+
810
+ const maskedVars = maskVars(bindings, configParam);
811
+
812
+ printBindings({
813
+ ...bindings,
814
+ vars: maskedVars,
815
+ });
816
+
817
+ const assetPaths =
818
+ args.assets || configParam.assets
819
+ ? getAssetPaths(configParam, args.assets)
820
+ : getSiteAssetPaths(
821
+ configParam,
822
+ args.site,
823
+ args.siteInclude,
824
+ args.siteExclude
825
+ );
826
+ return { assetPaths, bindings };
827
+ }
828
+
829
+ function getBindings(
830
+ configParam: Config,
831
+ env: string | undefined,
832
+ local: boolean,
833
+ args: AdditionalDevProps
834
+ ): CfWorkerInit["bindings"] {
835
+ const bindings = {
836
+ kv_namespaces: [
837
+ ...(configParam.kv_namespaces || []).map(
838
+ ({ binding, preview_id, id: _id }) => {
839
+ // In `dev`, we make folks use a separate kv namespace called
840
+ // `preview_id` instead of `id` so that they don't
841
+ // break production data. So here we check that a `preview_id`
842
+ // has actually been configured.
843
+ // This whole block of code will be obsoleted in the future
844
+ // when we have copy-on-write for previews on edge workers.
845
+ if (!preview_id) {
846
+ // TODO: This error has to be a _lot_ better, ideally just asking
847
+ // to create a preview namespace for the user automatically
848
+ throw new Error(
849
+ `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`
850
+ ); // Ugh, I really don't like this message very much
851
+ }
852
+ return {
853
+ binding,
854
+ id: preview_id,
855
+ };
856
+ }
857
+ ),
858
+ ...(args.kv || []),
859
+ ],
860
+ send_email: configParam.send_email,
861
+ // Use a copy of combinedVars since we're modifying it later
862
+ vars: {
863
+ ...getVarsForDev(configParam, env),
864
+ ...args.vars,
865
+ },
866
+ wasm_modules: configParam.wasm_modules,
867
+ text_blobs: configParam.text_blobs,
868
+ data_blobs: configParam.data_blobs,
869
+ durable_objects: {
870
+ bindings: [
871
+ ...(configParam.durable_objects || { bindings: [] }).bindings,
872
+ ...(args.durableObjects || []),
873
+ ],
874
+ },
875
+ queues: [
876
+ ...(configParam.queues.producers || []).map((queue) => {
877
+ return { binding: queue.binding, queue_name: queue.queue };
878
+ }),
879
+ ],
880
+ r2_buckets: [
881
+ ...(configParam.r2_buckets?.map(
882
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
883
+ // same idea as kv namespace preview id,
884
+ // same copy-on-write TODO
885
+ if (!preview_bucket_name) {
886
+ throw new Error(
887
+ `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`
888
+ );
889
+ }
890
+ return {
891
+ binding,
892
+ bucket_name: preview_bucket_name,
893
+ };
894
+ }
895
+ ) || []),
896
+ ...(args.r2 || []),
897
+ ],
898
+ dispatch_namespaces: configParam.dispatch_namespaces,
899
+ mtls_certificates: configParam.mtls_certificates,
900
+ services: configParam.services,
901
+ analytics_engine_datasets: configParam.analytics_engine_datasets,
902
+ unsafe: {
903
+ bindings: configParam.unsafe.bindings,
904
+ metadata: configParam.unsafe.metadata,
905
+ },
906
+ logfwdr: configParam.logfwdr,
907
+ d1_databases: identifyD1BindingsAsBeta([
908
+ ...(configParam.d1_databases ?? []).map((d1Db) => {
909
+ //in local dev, bindings don't matter
910
+ if (local) {
911
+ return {
912
+ ...d1Db,
913
+ database_id: "local",
914
+ };
915
+ }
916
+ // if you have a preview_database_id, we'll use it, but we shouldn't force people to use it.
917
+ if (!d1Db.preview_database_id && !process.env.NO_D1_WARNING) {
918
+ logger.log(
919
+ `--------------------\nšŸ’” Recommendation: for development, use a preview D1 database rather than the one you'd use in production.\nšŸ’” Create a new D1 database with "wrangler d1 create <name>" and add its id as preview_database_id to the d1_database "${d1Db.binding}" in your wrangler.toml\n--------------------\n`
920
+ );
921
+ }
922
+ return {
923
+ ...d1Db,
924
+ database_id: d1Db.preview_database_id
925
+ ? d1Db.preview_database_id
926
+ : d1Db.database_id,
927
+ };
928
+ }),
929
+ ...(args.d1Databases || []),
930
+ ]),
931
+ };
932
+
933
+ return bindings;
934
+ }