wrangler 0.0.0-fb43821 → 0.0.0-fbfc24d7

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