wrangler 0.0.0-e64812e → 0.0.0-e8e684c7

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 (214) hide show
  1. package/README.md +27 -3
  2. package/bin/wrangler.js +150 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +663 -7
  5. package/package.json +173 -152
  6. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  7. package/src/__tests__/config-cache.test.ts +30 -24
  8. package/src/__tests__/configuration.test.ts +4015 -3363
  9. package/src/__tests__/dev.test.tsx +1290 -952
  10. package/src/__tests__/generate.test.ts +91 -0
  11. package/src/__tests__/guess-worker-format.test.ts +68 -68
  12. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  13. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  14. package/src/__tests__/helpers/mock-bin.ts +20 -20
  15. package/src/__tests__/helpers/mock-cfetch.ts +179 -94
  16. package/src/__tests__/helpers/mock-console.ts +49 -39
  17. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  18. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  20. package/src/__tests__/helpers/mock-istty.ts +65 -18
  21. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  22. package/src/__tests__/helpers/mock-kv.ts +26 -26
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +223 -228
  24. package/src/__tests__/helpers/mock-process.ts +39 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  26. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  27. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  28. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  29. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  30. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  31. package/src/__tests__/https-options.test.ts +142 -109
  32. package/src/__tests__/index.test.ts +222 -233
  33. package/src/__tests__/init.test.ts +2139 -1603
  34. package/src/__tests__/jest.setup.ts +114 -34
  35. package/src/__tests__/kv.test.ts +1222 -1032
  36. package/src/__tests__/logger.test.ts +100 -74
  37. package/src/__tests__/metrics.test.ts +450 -0
  38. package/src/__tests__/package-manager.test.ts +303 -303
  39. package/src/__tests__/pages.test.ts +1173 -652
  40. package/src/__tests__/parse.test.ts +252 -252
  41. package/src/__tests__/publish.test.ts +6788 -5301
  42. package/src/__tests__/pubsub.test.ts +367 -0
  43. package/src/__tests__/r2.test.ts +328 -225
  44. package/src/__tests__/route.test.ts +18 -18
  45. package/src/__tests__/secret.test.ts +470 -459
  46. package/src/__tests__/tail.test.ts +676 -564
  47. package/src/__tests__/test-old-node-version.js +31 -0
  48. package/src/__tests__/user.test.ts +136 -112
  49. package/src/__tests__/validate-dev-props.test.ts +56 -0
  50. package/src/__tests__/version.test.ts +35 -0
  51. package/src/__tests__/whoami.test.tsx +267 -83
  52. package/src/__tests__/worker-namespace.test.ts +329 -0
  53. package/src/abort.d.ts +1 -1
  54. package/src/api/dev.ts +93 -0
  55. package/src/api/index.ts +1 -0
  56. package/src/bundle-reporter.tsx +29 -0
  57. package/src/bundle.ts +430 -157
  58. package/src/cfetch/index.ts +80 -80
  59. package/src/cfetch/internal.ts +244 -91
  60. package/src/cli.ts +21 -7
  61. package/src/config/config.ts +224 -195
  62. package/src/config/diagnostics.ts +61 -61
  63. package/src/config/environment.ts +422 -357
  64. package/src/config/index.ts +219 -193
  65. package/src/config/validation-helpers.ts +379 -357
  66. package/src/config/validation.ts +1690 -1367
  67. package/src/config-cache.ts +81 -41
  68. package/src/create-worker-preview.ts +208 -136
  69. package/src/create-worker-upload-form.ts +275 -238
  70. package/src/dev/dev-vars.ts +13 -13
  71. package/src/dev/dev.tsx +477 -351
  72. package/src/dev/local.tsx +426 -295
  73. package/src/dev/remote.tsx +406 -211
  74. package/src/dev/use-esbuild.ts +154 -94
  75. package/src/dev/validate-dev-props.ts +31 -0
  76. package/src/dev-registry.tsx +160 -0
  77. package/src/dev.tsx +696 -0
  78. package/src/dialogs.tsx +97 -97
  79. package/src/dispatch-namespace.ts +206 -0
  80. package/src/durable.ts +87 -87
  81. package/src/entry.ts +234 -228
  82. package/src/environment-variables.ts +23 -23
  83. package/src/errors.ts +6 -6
  84. package/src/faye-websocket.d.ts +6 -0
  85. package/src/generate.ts +131 -0
  86. package/src/git-client.ts +42 -0
  87. package/src/global-wrangler-config-path.ts +26 -0
  88. package/src/https-options.ts +84 -80
  89. package/src/index.tsx +2164 -2768
  90. package/src/init.ts +622 -0
  91. package/src/inspect.ts +678 -593
  92. package/src/intl-polyfill.d.ts +123 -123
  93. package/src/is-ci.ts +14 -0
  94. package/src/is-interactive.ts +12 -0
  95. package/src/kv.ts +299 -277
  96. package/src/logger.ts +46 -39
  97. package/src/metrics/index.ts +5 -0
  98. package/src/metrics/metrics-config.ts +239 -0
  99. package/src/metrics/metrics-dispatcher.ts +96 -0
  100. package/src/metrics/metrics-usage-headers.ts +24 -0
  101. package/src/metrics/send-event.ts +92 -0
  102. package/src/miniflare-cli/assets.ts +554 -0
  103. package/src/miniflare-cli/enum-keys.ts +8 -8
  104. package/src/miniflare-cli/index.ts +198 -32
  105. package/src/miniflare-cli/request-context.ts +18 -18
  106. package/src/module-collection.ts +212 -212
  107. package/src/open-in-browser.ts +4 -6
  108. package/src/package-manager.ts +173 -128
  109. package/src/pages/build.tsx +238 -0
  110. package/src/pages/constants.ts +12 -0
  111. package/src/pages/deployments.tsx +106 -0
  112. package/src/pages/dev.tsx +528 -0
  113. package/src/pages/errors.ts +22 -0
  114. package/src/pages/functions/buildPlugin.ts +109 -0
  115. package/src/pages/functions/buildWorker.ts +155 -0
  116. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  117. package/src/pages/functions/filepath-routing.ts +189 -0
  118. package/src/pages/functions/identifiers.ts +78 -0
  119. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  120. package/src/pages/functions/routes-consolidation.ts +73 -0
  121. package/src/pages/functions/routes-transformation.test.ts +271 -0
  122. package/src/pages/functions/routes-transformation.ts +122 -0
  123. package/src/pages/functions/routes.ts +151 -0
  124. package/src/pages/functions.tsx +96 -0
  125. package/src/pages/index.tsx +94 -0
  126. package/src/pages/projects.tsx +169 -0
  127. package/src/pages/publish.tsx +391 -0
  128. package/src/pages/types.ts +49 -0
  129. package/src/pages/upload.tsx +413 -0
  130. package/src/pages/utils.ts +12 -0
  131. package/src/parse.ts +209 -125
  132. package/src/paths.ts +6 -6
  133. package/src/preview.ts +31 -0
  134. package/src/proxy.ts +410 -389
  135. package/src/publish.ts +773 -534
  136. package/src/pubsub/index.ts +286 -0
  137. package/src/pubsub/pubsub-commands.tsx +623 -0
  138. package/src/r2.ts +100 -19
  139. package/src/selfsigned.d.ts +23 -23
  140. package/src/sites.tsx +278 -201
  141. package/src/tail/filters.ts +111 -109
  142. package/src/tail/index.ts +230 -217
  143. package/src/tail/printing.ts +86 -46
  144. package/src/update-check.ts +11 -11
  145. package/src/user/choose-account.tsx +69 -0
  146. package/src/user/env-vars.ts +46 -0
  147. package/src/user/generate-auth-url.ts +33 -0
  148. package/src/user/generate-random-state.ts +16 -0
  149. package/src/user/index.ts +3 -0
  150. package/src/user/user.tsx +1191 -0
  151. package/src/whoami.tsx +141 -42
  152. package/src/worker.ts +123 -99
  153. package/src/zones.ts +167 -0
  154. package/templates/checked-fetch.js +17 -0
  155. package/templates/first-party-worker-module-facade.ts +18 -0
  156. package/templates/format-dev-errors.ts +32 -0
  157. package/templates/new-worker-scheduled.js +3 -3
  158. package/templates/new-worker-scheduled.ts +15 -15
  159. package/templates/new-worker.js +3 -3
  160. package/templates/new-worker.ts +15 -15
  161. package/templates/no-op-worker.js +10 -0
  162. package/templates/pages-shim.ts +9 -0
  163. package/templates/pages-template-plugin.ts +167 -0
  164. package/templates/pages-template-worker.ts +172 -0
  165. package/templates/serve-static-assets.ts +63 -0
  166. package/templates/service-bindings-module-facade.js +54 -0
  167. package/templates/service-bindings-sw-facade.js +42 -0
  168. package/templates/tsconfig.json +95 -95
  169. package/wrangler-dist/cli.d.ts +338 -0
  170. package/wrangler-dist/cli.js +95449 -67524
  171. package/pages/functions/buildPlugin.ts +0 -105
  172. package/pages/functions/buildWorker.ts +0 -151
  173. package/pages/functions/filepath-routing.ts +0 -189
  174. package/pages/functions/identifiers.ts +0 -78
  175. package/pages/functions/routes.ts +0 -156
  176. package/pages/functions/template-plugin.ts +0 -147
  177. package/pages/functions/template-worker.ts +0 -143
  178. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  179. package/src/pages.tsx +0 -2038
  180. package/src/user.tsx +0 -1203
  181. package/templates/static-asset-facade.js +0 -47
  182. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  183. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  184. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  185. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  186. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  187. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  188. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  189. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  190. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  191. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  192. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  193. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  194. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  195. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  196. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  197. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  198. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  199. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  200. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  201. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  202. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  203. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  204. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  205. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  206. package/vendor/wrangler-mime/LICENSE +0 -21
  207. package/vendor/wrangler-mime/Mime.js +0 -97
  208. package/vendor/wrangler-mime/README.md +0 -187
  209. package/vendor/wrangler-mime/cli.js +0 -46
  210. package/vendor/wrangler-mime/index.js +0 -4
  211. package/vendor/wrangler-mime/lite.js +0 -4
  212. package/vendor/wrangler-mime/package.json +0 -52
  213. package/vendor/wrangler-mime/types/other.js +0 -1
  214. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/dev.tsx ADDED
@@ -0,0 +1,696 @@
1
+ import path from "node:path";
2
+ import { watch } from "chokidar";
3
+ import getPort from "get-port";
4
+ import { render } from "ink";
5
+ import React from "react";
6
+ import { fetch } from "undici";
7
+ import { findWranglerToml, printBindings, readConfig } from "./config";
8
+ import Dev from "./dev/dev";
9
+ import { getVarsForDev } from "./dev/dev-vars";
10
+
11
+ import { getEntry } from "./entry";
12
+ import { logger } from "./logger";
13
+ import * as metrics from "./metrics";
14
+ import { getAssetPaths, getSiteAssetPaths } from "./sites";
15
+ import { getAccountFromCache } from "./user";
16
+ import { getZoneIdFromHost, getZoneForRoute, getHostFromRoute } from "./zones";
17
+ import {
18
+ printWranglerBanner,
19
+ DEFAULT_LOCAL_PORT,
20
+ type ConfigPath,
21
+ getScriptName,
22
+ getDevCompatibilityDate,
23
+ getRules,
24
+ isLegacyEnv,
25
+ DEFAULT_INSPECTOR_PORT,
26
+ } from "./index";
27
+
28
+ import type { Config } from "./config";
29
+ import type { Route } from "./config/environment";
30
+ import type { EnablePagesAssetsServiceBindingOptions } from "./miniflare-cli";
31
+ import type { CfWorkerInit } from "./worker";
32
+ import type { RequestInit } from "undici";
33
+ import type { Argv, ArgumentsCamelCase } from "yargs";
34
+
35
+ interface DevArgs {
36
+ config?: string;
37
+ script?: string;
38
+ name?: string;
39
+ bundle?: boolean;
40
+ build?: boolean;
41
+ format?: string;
42
+ env?: string;
43
+ "compatibility-date"?: string;
44
+ "compatibility-flags"?: string[];
45
+ latest?: boolean;
46
+ ip?: string;
47
+ inspect?: boolean;
48
+ port?: number;
49
+ "inspector-port"?: number;
50
+ routes?: string[];
51
+ host?: string;
52
+ "local-protocol"?: "http" | "https";
53
+ "local-upstream"?: string | undefined;
54
+ "experimental-public"?: string;
55
+ public?: string;
56
+ assets?: string;
57
+ site?: string;
58
+ "site-include"?: string[];
59
+ "site-exclude"?: string[];
60
+ "upstream-protocol"?: "http" | "https";
61
+ "jsx-factory"?: string;
62
+ "jsx-fragment"?: string;
63
+ tsconfig?: string;
64
+ local?: boolean;
65
+ minify?: boolean;
66
+ var?: string[];
67
+ define?: string[];
68
+ "node-compat"?: boolean;
69
+ "experimental-enable-local-persistence"?: boolean;
70
+ "live-reload"?: boolean;
71
+ onReady?: () => void;
72
+ logLevel?: "none" | "error" | "log" | "warn" | "debug";
73
+ logPrefix?: string;
74
+ showInteractiveDevSession?: boolean;
75
+ }
76
+
77
+ export function devOptions(yargs: Argv): Argv<DevArgs> {
78
+ return (
79
+ yargs
80
+ .positional("script", {
81
+ describe: "The path to an entry point for your worker",
82
+ type: "string",
83
+ })
84
+ .option("name", {
85
+ describe: "Name of the worker",
86
+ type: "string",
87
+ requiresArg: true,
88
+ })
89
+ // We want to have a --no-bundle flag, but yargs requires that
90
+ // we also have a --bundle flag (that it adds the --no to by itself)
91
+ // So we make a --bundle flag, but hide it, and then add a --no-bundle flag
92
+ // that's visible to the user but doesn't "do" anything.
93
+ .option("bundle", {
94
+ describe: "Run wrangler's compilation step before publishing",
95
+ type: "boolean",
96
+ hidden: true,
97
+ })
98
+ .option("no-bundle", {
99
+ describe: "Skip internal build steps and directly publish script",
100
+ type: "boolean",
101
+ default: false,
102
+ })
103
+ .option("format", {
104
+ choices: ["modules", "service-worker"] as const,
105
+ describe: "Choose an entry type",
106
+ deprecated: true,
107
+ })
108
+ .option("env", {
109
+ describe: "Perform on a specific environment",
110
+ type: "string",
111
+ requiresArg: true,
112
+ alias: "e",
113
+ })
114
+ .option("compatibility-date", {
115
+ describe: "Date to use for compatibility checks",
116
+ type: "string",
117
+ requiresArg: true,
118
+ })
119
+ .option("compatibility-flags", {
120
+ describe: "Flags to use for compatibility checks",
121
+ alias: "compatibility-flag",
122
+ type: "string",
123
+ requiresArg: true,
124
+ array: true,
125
+ })
126
+ .option("latest", {
127
+ describe: "Use the latest version of the worker runtime",
128
+ type: "boolean",
129
+ default: true,
130
+ })
131
+ .option("ip", {
132
+ describe: "IP address to listen on",
133
+ type: "string",
134
+ })
135
+ .option("port", {
136
+ describe: "Port to listen on",
137
+ type: "number",
138
+ })
139
+ .option("inspector-port", {
140
+ describe: "Port for devtools to connect to",
141
+ type: "number",
142
+ })
143
+ .option("routes", {
144
+ describe: "Routes to upload",
145
+ alias: "route",
146
+ type: "string",
147
+ requiresArg: true,
148
+ array: true,
149
+ })
150
+ .option("host", {
151
+ type: "string",
152
+ requiresArg: true,
153
+ describe:
154
+ "Host to forward requests to, defaults to the zone of project",
155
+ })
156
+ .option("local-protocol", {
157
+ describe: "Protocol to listen to requests on, defaults to http.",
158
+ choices: ["http", "https"] as const,
159
+ })
160
+ .options("local-upstream", {
161
+ type: "string",
162
+ describe:
163
+ "Host to act as origin in local mode, defaults to dev.host or route",
164
+ })
165
+ .option("experimental-public", {
166
+ describe: "Static assets to be served",
167
+ type: "string",
168
+ requiresArg: true,
169
+ deprecated: true,
170
+ hidden: true,
171
+ })
172
+ .option("assets", {
173
+ describe: "Static assets to be served",
174
+ type: "string",
175
+ requiresArg: true,
176
+ })
177
+ .option("site", {
178
+ describe: "Root folder of static assets for Workers Sites",
179
+ type: "string",
180
+ requiresArg: true,
181
+ })
182
+ .option("site-include", {
183
+ describe:
184
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
185
+ type: "string",
186
+ requiresArg: true,
187
+ array: true,
188
+ })
189
+ .option("site-exclude", {
190
+ describe:
191
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
192
+ type: "string",
193
+ requiresArg: true,
194
+ array: true,
195
+ })
196
+ .option("upstream-protocol", {
197
+ describe: "Protocol to forward requests to host on, defaults to https.",
198
+ choices: ["http", "https"] as const,
199
+ })
200
+ .option("var", {
201
+ describe:
202
+ "A key-value pair to be injected into the script as a variable",
203
+ type: "string",
204
+ requiresArg: true,
205
+ array: true,
206
+ })
207
+ .option("define", {
208
+ describe: "A key-value pair to be substituted in the script",
209
+ type: "string",
210
+ requiresArg: true,
211
+ array: true,
212
+ })
213
+ .option("jsx-factory", {
214
+ describe: "The function that is called for each JSX element",
215
+ type: "string",
216
+ requiresArg: true,
217
+ })
218
+ .option("jsx-fragment", {
219
+ describe: "The function that is called for each JSX fragment",
220
+ type: "string",
221
+ requiresArg: true,
222
+ })
223
+ .option("tsconfig", {
224
+ describe: "Path to a custom tsconfig.json file",
225
+ type: "string",
226
+ requiresArg: true,
227
+ })
228
+ .option("local", {
229
+ alias: "l",
230
+ describe: "Run on my machine",
231
+ type: "boolean",
232
+ default: false, // I bet this will a point of contention. We'll revisit it.
233
+ })
234
+ .option("minify", {
235
+ describe: "Minify the script",
236
+ type: "boolean",
237
+ })
238
+ .option("node-compat", {
239
+ describe: "Enable node.js compatibility",
240
+ type: "boolean",
241
+ })
242
+ .option("experimental-enable-local-persistence", {
243
+ describe: "Enable persistence for this session (only for local mode)",
244
+ type: "boolean",
245
+ })
246
+ .option("live-reload", {
247
+ // TODO: Add back in once we have remote `--live-reload`
248
+ hidden: true,
249
+ // describe: "Auto reload HTML pages when change is detected",
250
+ type: "boolean",
251
+ })
252
+ .option("inspect", {
253
+ describe: "Enable dev tools",
254
+ type: "boolean",
255
+ deprecated: true,
256
+ })
257
+ .option("legacy-env", {
258
+ type: "boolean",
259
+ describe: "Use legacy environments",
260
+ hidden: true,
261
+ })
262
+ );
263
+ }
264
+
265
+ export async function devHandler(args: ArgumentsCamelCase<DevArgs>) {
266
+ let watcher;
267
+ try {
268
+ const devInstance = await startDev(args);
269
+ watcher = devInstance.watcher;
270
+ const { waitUntilExit } = devInstance.devReactElement;
271
+ await waitUntilExit();
272
+ } finally {
273
+ await watcher?.close();
274
+ }
275
+ }
276
+
277
+ export type AdditionalDevProps = {
278
+ vars?: {
279
+ [key: string]: unknown;
280
+ };
281
+ kv?: {
282
+ binding: string;
283
+ id: string;
284
+ preview_id?: string;
285
+ }[];
286
+ durableObjects?: {
287
+ name: string;
288
+ class_name: string;
289
+ script_name?: string | undefined;
290
+ environment?: string | undefined;
291
+ }[];
292
+ r2?: {
293
+ binding: string;
294
+ bucket_name: string;
295
+ preview_bucket_name?: string;
296
+ }[];
297
+ };
298
+ type StartDevOptions = ArgumentsCamelCase<DevArgs> &
299
+ // These options can be passed in directly when called with the `wrangler.dev()` API.
300
+ // They aren't exposed as CLI arguments.
301
+ AdditionalDevProps & {
302
+ forceLocal?: boolean;
303
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
304
+ };
305
+
306
+ export async function startDev(args: StartDevOptions) {
307
+ let watcher: ReturnType<typeof watch> | undefined;
308
+ let rerender: (node: React.ReactNode) => void | undefined;
309
+ try {
310
+ if (args.logLevel) {
311
+ // we don't define a "none" logLevel, so "error" will do for now.
312
+ logger.loggerLevel = args.logLevel === "none" ? "error" : args.logLevel;
313
+ }
314
+ await printWranglerBanner();
315
+
316
+ const configPath =
317
+ (args.config as ConfigPath) ||
318
+ ((args.script &&
319
+ findWranglerToml(path.dirname(args.script))) as ConfigPath);
320
+ let config = readConfig(configPath, args);
321
+
322
+ if (config.configPath) {
323
+ watcher = watch(config.configPath, {
324
+ persistent: true,
325
+ }).on("change", async (_event) => {
326
+ // TODO: Do we need to handle different `_event` types differently?
327
+ // e.g. what if the file is deleted, or added?
328
+ config = readConfig(configPath, args);
329
+ if (config.configPath) {
330
+ logger.log(`${path.basename(config.configPath)} changed...`);
331
+ rerender(await getDevReactElement(config));
332
+ }
333
+ });
334
+ }
335
+
336
+ const {
337
+ entry,
338
+ nodeCompat,
339
+ upstreamProtocol,
340
+ zoneId,
341
+ host,
342
+ routes,
343
+ getLocalPort,
344
+ getInspectorPort,
345
+ cliDefines,
346
+ } = await commonDev(args, config);
347
+
348
+ await metrics.sendMetricsEvent(
349
+ "run dev",
350
+ {
351
+ local: args.local,
352
+ usesTypeScript: /\.tsx?$/.test(entry.file),
353
+ },
354
+ { sendMetrics: config.send_metrics, offline: args.local }
355
+ );
356
+
357
+ // eslint-disable-next-line no-inner-declarations
358
+ async function getDevReactElement(configParam: Config) {
359
+ const { assetPaths, bindings } = await getBindingsAndAssetPaths(
360
+ args,
361
+ configParam
362
+ );
363
+
364
+ return (
365
+ <Dev
366
+ name={getScriptName({ name: args.name, env: args.env }, configParam)}
367
+ noBundle={!(args.bundle ?? !configParam.no_bundle)}
368
+ entry={entry}
369
+ env={args.env}
370
+ zone={zoneId}
371
+ host={host}
372
+ routes={routes}
373
+ rules={getRules(configParam)}
374
+ legacyEnv={isLegacyEnv(configParam)}
375
+ minify={args.minify ?? configParam.minify}
376
+ nodeCompat={nodeCompat}
377
+ build={configParam.build || {}}
378
+ define={{ ...configParam.define, ...cliDefines }}
379
+ initialMode={args.local ? "local" : "remote"}
380
+ jsxFactory={args["jsx-factory"] || configParam.jsx_factory}
381
+ jsxFragment={args["jsx-fragment"] || configParam.jsx_fragment}
382
+ tsconfig={args.tsconfig ?? configParam.tsconfig}
383
+ upstreamProtocol={upstreamProtocol}
384
+ localProtocol={args.localProtocol || configParam.dev.local_protocol}
385
+ localUpstream={args["local-upstream"] || host}
386
+ enableLocalPersistence={
387
+ args.experimentalEnableLocalPersistence || false
388
+ }
389
+ liveReload={args.liveReload || false}
390
+ accountId={configParam.account_id || getAccountFromCache()?.id}
391
+ assetPaths={assetPaths}
392
+ assetsConfig={configParam.assets}
393
+ port={args.port || configParam.dev.port || (await getLocalPort())}
394
+ ip={args.ip || configParam.dev.ip}
395
+ inspectorPort={
396
+ args.inspectorPort ||
397
+ configParam.dev.inspector_port ||
398
+ (await getInspectorPort())
399
+ }
400
+ isWorkersSite={Boolean(args.site || configParam.site)}
401
+ compatibilityDate={getDevCompatibilityDate(
402
+ configParam,
403
+ args.compatibilityDate
404
+ )}
405
+ compatibilityFlags={
406
+ args.compatibilityFlags || configParam.compatibility_flags
407
+ }
408
+ usageModel={configParam.usage_model}
409
+ bindings={bindings}
410
+ crons={configParam.triggers.crons}
411
+ logLevel={args.logLevel}
412
+ logPrefix={args.logPrefix}
413
+ onReady={args.onReady}
414
+ inspect={args.inspect ?? true}
415
+ showInteractiveDevSession={args.showInteractiveDevSession}
416
+ forceLocal={args.forceLocal}
417
+ enablePagesAssetsServiceBinding={args.enablePagesAssetsServiceBinding}
418
+ firstPartyWorker={configParam.first_party_worker}
419
+ sendMetrics={configParam.send_metrics}
420
+ />
421
+ );
422
+ }
423
+ const devReactElement = render(await getDevReactElement(config));
424
+ rerender = devReactElement.rerender;
425
+ return {
426
+ devReactElement,
427
+ watcher,
428
+ stop: async () => {
429
+ devReactElement.unmount();
430
+ await watcher?.close();
431
+ },
432
+ fetch: async (init?: RequestInit) => {
433
+ //TODO: we are not guaranteed to be assigned this port, we should fix this ASAP
434
+ const port = args.port || config.dev.port || (await getLocalPort());
435
+ const address = args.ip || config.dev.ip || "localhost";
436
+
437
+ return await fetch(`http://${address}:${port}/`, init);
438
+ },
439
+ };
440
+ } finally {
441
+ await watcher?.close();
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Avoiding calling `getPort()` multiple times by memoizing the first result.
447
+ */
448
+ function memoizeGetPort(defaultPort: number) {
449
+ let portValue: number;
450
+ return async () => {
451
+ return portValue || (portValue = await getPort({ port: defaultPort }));
452
+ };
453
+ }
454
+ /**
455
+ * mask anything that was overridden in .dev.vars
456
+ * so that we don't log potential secrets into the terminal
457
+ */
458
+ function maskVars(bindings: CfWorkerInit["bindings"], configParam: Config) {
459
+ const maskedVars = { ...bindings.vars };
460
+ for (const key of Object.keys(maskedVars)) {
461
+ if (maskedVars[key] !== configParam.vars[key]) {
462
+ // This means it was overridden in .dev.vars
463
+ // so let's mask it
464
+ maskedVars[key] = "(hidden)";
465
+ }
466
+ }
467
+ return maskedVars;
468
+ }
469
+
470
+ async function getZoneIdHostAndRoutes(args: StartDevOptions, config: Config) {
471
+ // TODO: if worker_dev = false and no routes, then error (only for dev)
472
+ // Compute zone info from the `host` and `route` args and config;
473
+ let host = args.host || config.dev.host;
474
+ let zoneId: string | undefined;
475
+ const routes: Route[] | undefined =
476
+ args.routes || (config.route && [config.route]) || config.routes;
477
+
478
+ if (args.forceLocal) {
479
+ args.local = true;
480
+ }
481
+
482
+ if (!args.local) {
483
+ if (host) {
484
+ zoneId = await getZoneIdFromHost(host);
485
+ }
486
+ if (!zoneId && routes) {
487
+ const firstRoute = routes[0];
488
+ const zone = await getZoneForRoute(firstRoute);
489
+ if (zone) {
490
+ zoneId = zone.id;
491
+ host = zone.host;
492
+ }
493
+ }
494
+ } else if (!host) {
495
+ if (routes) {
496
+ const firstRoute = routes[0];
497
+ host = getHostFromRoute(firstRoute);
498
+ }
499
+ }
500
+ return { host, routes, zoneId };
501
+ }
502
+
503
+ async function commonDev(args: StartDevOptions, config: Config) {
504
+ const entry = await getEntry(
505
+ { assets: args.assets, script: args.script },
506
+ config,
507
+ "dev"
508
+ );
509
+
510
+ const { zoneId, host, routes } = await getZoneIdHostAndRoutes(args, config);
511
+ const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
512
+ const getInspectorPort = memoizeGetPort(DEFAULT_INSPECTOR_PORT);
513
+
514
+ if (config.services && config.services.length > 0) {
515
+ logger.warn(
516
+ `This worker is bound to live services: ${config.services
517
+ .map(
518
+ (service) =>
519
+ `${service.binding} (${service.service}${
520
+ service.environment ? `@${service.environment}` : ""
521
+ })`
522
+ )
523
+ .join(", ")}`
524
+ );
525
+ }
526
+
527
+ if (args.inspect) {
528
+ //devtools are enabled by default, but we still need to disable them if the caller doesn't want them
529
+ logger.warn(
530
+ "Passing --inspect is unnecessary, now you can always connect to devtools."
531
+ );
532
+ }
533
+
534
+ if (args["experimental-public"]) {
535
+ throw new Error(
536
+ "The --experimental-public field has been renamed to --assets"
537
+ );
538
+ }
539
+
540
+ if (args.public) {
541
+ throw new Error("The --public field has been renamed to --assets");
542
+ }
543
+
544
+ if ((args.assets || config.assets) && (args.site || config.site)) {
545
+ throw new Error("Cannot use Assets and Workers Sites in the same Worker.");
546
+ }
547
+
548
+ if (args.assets) {
549
+ logger.warn(
550
+ "The --assets argument is experimental and may change or break at any time"
551
+ );
552
+ }
553
+
554
+ const upstreamProtocol =
555
+ args["upstream-protocol"] || config.dev.upstream_protocol;
556
+ if (upstreamProtocol === "http") {
557
+ logger.warn(
558
+ "Setting upstream-protocol to http is not currently implemented.\n" +
559
+ "If this is required in your project, please add your use case to the following issue:\n" +
560
+ "https://github.com/cloudflare/wrangler2/issues/583."
561
+ );
562
+ }
563
+ const nodeCompat = args.nodeCompat ?? config.node_compat;
564
+ if (nodeCompat) {
565
+ logger.warn(
566
+ "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."
567
+ );
568
+ }
569
+
570
+ const cliDefines =
571
+ args.define?.reduce<Record<string, string>>((collectDefines, d) => {
572
+ const [key, ...value] = d.split(":");
573
+ collectDefines[key] = value.join("");
574
+ return collectDefines;
575
+ }, {}) || {};
576
+
577
+ return {
578
+ entry,
579
+ upstreamProtocol,
580
+ nodeCompat,
581
+ getLocalPort,
582
+ getInspectorPort,
583
+ zoneId,
584
+ host,
585
+ routes,
586
+ cliDefines,
587
+ };
588
+ }
589
+
590
+ async function getBindingsAndAssetPaths(
591
+ args: StartDevOptions,
592
+ configParam: Config
593
+ ) {
594
+ const cliVars =
595
+ args.var?.reduce<Record<string, string>>((collectVars, v) => {
596
+ const [key, ...value] = v.split(":");
597
+ collectVars[key] = value.join("");
598
+ return collectVars;
599
+ }, {}) || {};
600
+
601
+ // now log all available bindings into the terminal
602
+ const bindings = await getBindings(configParam, {
603
+ kv: args.kv,
604
+ vars: { ...args.vars, ...cliVars },
605
+ durableObjects: args.durableObjects,
606
+ r2: args.r2,
607
+ });
608
+
609
+ const maskedVars = maskVars(bindings, configParam);
610
+
611
+ printBindings({
612
+ ...bindings,
613
+ vars: maskedVars,
614
+ });
615
+
616
+ const assetPaths =
617
+ args.assets || configParam.assets
618
+ ? getAssetPaths(configParam, args.assets)
619
+ : getSiteAssetPaths(
620
+ configParam,
621
+ args.site,
622
+ args.siteInclude,
623
+ args.siteExclude
624
+ );
625
+ return { assetPaths, bindings };
626
+ }
627
+
628
+ async function getBindings(
629
+ configParam: Config,
630
+ args: AdditionalDevProps
631
+ ): Promise<CfWorkerInit["bindings"]> {
632
+ const bindings = {
633
+ kv_namespaces: [
634
+ ...(configParam.kv_namespaces || []).map(
635
+ ({ binding, preview_id, id: _id }) => {
636
+ // In `dev`, we make folks use a separate kv namespace called
637
+ // `preview_id` instead of `id` so that they don't
638
+ // break production data. So here we check that a `preview_id`
639
+ // has actually been configured.
640
+ // This whole block of code will be obsoleted in the future
641
+ // when we have copy-on-write for previews on edge workers.
642
+ if (!preview_id) {
643
+ // TODO: This error has to be a _lot_ better, ideally just asking
644
+ // to create a preview namespace for the user automatically
645
+ throw new Error(
646
+ `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`
647
+ ); // Ugh, I really don't like this message very much
648
+ }
649
+ return {
650
+ binding,
651
+ id: preview_id,
652
+ };
653
+ }
654
+ ),
655
+ ...(args.kv || []),
656
+ ],
657
+ // Use a copy of combinedVars since we're modifying it later
658
+ vars: {
659
+ ...getVarsForDev(configParam),
660
+ ...args.vars,
661
+ },
662
+ wasm_modules: configParam.wasm_modules,
663
+ text_blobs: configParam.text_blobs,
664
+ data_blobs: configParam.data_blobs,
665
+ durable_objects: {
666
+ bindings: [
667
+ ...(configParam.durable_objects || { bindings: [] }).bindings,
668
+ ...(args.durableObjects || []),
669
+ ],
670
+ },
671
+ r2_buckets: [
672
+ ...(configParam.r2_buckets?.map(
673
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
674
+ // same idea as kv namespace preview id,
675
+ // same copy-on-write TODO
676
+ if (!preview_bucket_name) {
677
+ throw new Error(
678
+ `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`
679
+ );
680
+ }
681
+ return {
682
+ binding,
683
+ bucket_name: preview_bucket_name,
684
+ };
685
+ }
686
+ ) || []),
687
+ ...(args.r2 || []),
688
+ ],
689
+ dispatch_namespaces: configParam.dispatch_namespaces,
690
+ services: configParam.services,
691
+ unsafe: configParam.unsafe?.bindings,
692
+ logfwdr: configParam.logfwdr,
693
+ };
694
+
695
+ return bindings;
696
+ }