wrangler 0.0.0-e9ab55a → 0.0.0-ea7ee45

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 (197) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +123 -25
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4893 -0
  6. package/package.json +156 -125
  7. package/src/__tests__/config-cache.test.ts +36 -0
  8. package/src/__tests__/configuration.test.ts +3829 -0
  9. package/src/__tests__/dev.test.tsx +1155 -63
  10. package/src/__tests__/guess-worker-format.test.ts +85 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  14. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  17. package/src/__tests__/helpers/mock-console.ts +97 -0
  18. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  20. package/src/__tests__/helpers/mock-istty.ts +74 -0
  21. package/src/__tests__/helpers/mock-kv.ts +33 -0
  22. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  23. package/src/__tests__/helpers/mock-process.ts +39 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +130 -0
  31. package/src/__tests__/index.test.ts +259 -284
  32. package/src/__tests__/init.test.ts +1992 -0
  33. package/src/__tests__/jest.setup.ts +95 -10
  34. package/src/__tests__/kv.test.ts +1402 -909
  35. package/src/__tests__/logger.test.ts +141 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1254 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6504 -93
  40. package/src/__tests__/pubsub.test.ts +276 -0
  41. package/src/__tests__/r2.test.ts +233 -0
  42. package/src/__tests__/route.test.ts +45 -0
  43. package/src/__tests__/secret.test.ts +486 -0
  44. package/src/__tests__/tail.test.ts +690 -0
  45. package/src/__tests__/user.test.ts +143 -0
  46. package/src/__tests__/whoami.test.tsx +220 -0
  47. package/src/__tests__/worker-namespace.test.ts +327 -0
  48. package/src/abort.d.ts +3 -0
  49. package/src/api/dev.ts +39 -0
  50. package/src/api/index.ts +1 -0
  51. package/src/bundle-reporter.tsx +29 -0
  52. package/src/bundle.ts +212 -0
  53. package/src/cfetch/index.ts +88 -69
  54. package/src/cfetch/internal.ts +124 -44
  55. package/src/cli.ts +24 -6
  56. package/src/config/README.md +107 -0
  57. package/src/config/config.ts +243 -0
  58. package/src/config/diagnostics.ts +80 -0
  59. package/src/config/environment.ts +430 -0
  60. package/src/config/index.ts +225 -0
  61. package/src/config/validation-helpers.ts +584 -0
  62. package/src/config/validation.ts +1693 -0
  63. package/src/config-cache.ts +44 -0
  64. package/src/create-worker-preview.ts +255 -0
  65. package/src/create-worker-upload-form.ts +254 -0
  66. package/src/dev/dev-vars.ts +36 -0
  67. package/src/dev/dev.tsx +417 -0
  68. package/src/dev/local.tsx +350 -0
  69. package/src/dev/remote.tsx +367 -0
  70. package/src/dev/use-esbuild.ts +150 -0
  71. package/src/dev.tsx +515 -773
  72. package/src/dialogs.tsx +117 -59
  73. package/src/durable.ts +102 -0
  74. package/src/entry.ts +328 -0
  75. package/src/environment-variables.ts +35 -0
  76. package/src/errors.ts +11 -0
  77. package/src/generate.ts +33 -0
  78. package/src/git-client.ts +42 -0
  79. package/src/https-options.ts +123 -0
  80. package/src/index.tsx +1844 -1901
  81. package/src/init.ts +549 -0
  82. package/src/inspect.ts +615 -496
  83. package/src/intl-polyfill.d.ts +139 -0
  84. package/src/kv.ts +408 -0
  85. package/src/logger.ts +73 -0
  86. package/src/miniflare-cli/README.md +30 -0
  87. package/src/miniflare-cli/enum-keys.ts +17 -0
  88. package/src/miniflare-cli/index.ts +52 -0
  89. package/src/miniflare-cli/request-context.ts +40 -0
  90. package/src/module-collection.ts +247 -53
  91. package/src/open-in-browser.ts +17 -0
  92. package/src/package-manager.ts +174 -0
  93. package/src/pages/build.tsx +202 -0
  94. package/src/pages/constants.ts +7 -0
  95. package/src/pages/deployments.tsx +101 -0
  96. package/src/pages/dev.tsx +964 -0
  97. package/src/pages/functions/buildPlugin.ts +105 -0
  98. package/src/pages/functions/buildWorker.ts +151 -0
  99. package/src/pages/functions/filepath-routing.test.ts +234 -0
  100. package/src/pages/functions/filepath-routing.ts +189 -0
  101. package/src/pages/functions/identifiers.ts +78 -0
  102. package/src/pages/functions/routes.ts +151 -0
  103. package/src/pages/index.tsx +84 -0
  104. package/src/pages/projects.tsx +157 -0
  105. package/src/pages/publish.tsx +335 -0
  106. package/src/pages/types.ts +40 -0
  107. package/src/pages/upload.tsx +384 -0
  108. package/src/pages/utils.ts +12 -0
  109. package/src/parse.ts +286 -0
  110. package/src/paths.ts +26 -0
  111. package/src/preview.ts +31 -0
  112. package/src/proxy.ts +428 -254
  113. package/src/publish.ts +750 -366
  114. package/src/pubsub/index.ts +286 -0
  115. package/src/pubsub/pubsub-commands.tsx +594 -0
  116. package/src/r2.ts +50 -0
  117. package/src/selfsigned.d.ts +29 -0
  118. package/src/sites.tsx +357 -103
  119. package/src/tail/filters.ts +279 -0
  120. package/src/tail/index.ts +299 -0
  121. package/src/tail/printing.ts +67 -0
  122. package/src/update-check.ts +19 -0
  123. package/src/user/choose-account.tsx +60 -0
  124. package/src/user/env-vars.ts +46 -0
  125. package/src/user/generate-auth-url.ts +33 -0
  126. package/src/user/generate-random-state.ts +16 -0
  127. package/src/user/index.ts +3 -0
  128. package/src/user/user.tsx +1130 -0
  129. package/src/whoami.tsx +90 -0
  130. package/src/worker-namespace.ts +190 -0
  131. package/src/worker.ts +185 -0
  132. package/src/zones.ts +76 -0
  133. package/templates/checked-fetch.js +17 -0
  134. package/templates/gitignore +171 -0
  135. package/templates/new-worker-scheduled.js +17 -0
  136. package/templates/new-worker-scheduled.ts +32 -0
  137. package/templates/new-worker.js +15 -0
  138. package/templates/new-worker.ts +30 -0
  139. package/templates/no-op-worker.js +10 -0
  140. package/templates/pages-template-plugin.ts +155 -0
  141. package/templates/pages-template-worker.ts +161 -0
  142. package/templates/static-asset-facade.js +43 -0
  143. package/templates/tsconfig.json +105 -0
  144. package/wrangler-dist/cli.js +107117 -103435
  145. package/pages/functions/buildWorker.ts +0 -62
  146. package/pages/functions/filepath-routing.test.ts +0 -39
  147. package/pages/functions/filepath-routing.ts +0 -228
  148. package/pages/functions/identifiers.ts +0 -78
  149. package/pages/functions/routes.ts +0 -158
  150. package/pages/functions/template-worker.ts +0 -136
  151. package/src/__tests__/mock-cfetch.ts +0 -171
  152. package/src/__tests__/mock-dialogs.ts +0 -65
  153. package/src/__tests__/run-in-tmp.ts +0 -19
  154. package/src/__tests__/run-wrangler.ts +0 -32
  155. package/src/api/form_data.ts +0 -131
  156. package/src/api/preview.ts +0 -128
  157. package/src/api/worker.ts +0 -155
  158. package/src/config.ts +0 -646
  159. package/src/kv.tsx +0 -276
  160. package/src/pages.tsx +0 -1040
  161. package/src/tail.tsx +0 -73
  162. package/src/user.tsx +0 -1027
  163. package/static-asset-facade.js +0 -47
  164. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  165. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  166. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  167. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  168. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  169. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  170. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  171. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  172. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  173. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  174. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  175. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  176. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  177. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  178. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  179. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  180. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  181. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  182. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  183. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  184. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  185. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  186. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  187. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  188. package/vendor/wrangler-mime/LICENSE +0 -21
  189. package/vendor/wrangler-mime/Mime.js +0 -97
  190. package/vendor/wrangler-mime/README.md +0 -187
  191. package/vendor/wrangler-mime/cli.js +0 -46
  192. package/vendor/wrangler-mime/index.js +0 -4
  193. package/vendor/wrangler-mime/lite.js +0 -4
  194. package/vendor/wrangler-mime/package.json +0 -52
  195. package/vendor/wrangler-mime/types/other.js +0 -1
  196. package/vendor/wrangler-mime/types/standard.js +0 -1
  197. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,350 @@
1
+ import { spawn } from "node:child_process";
2
+ import { realpathSync } from "node:fs";
3
+ import { writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { useState, useEffect, useRef } from "react";
6
+ import onExit from "signal-exit";
7
+ import useInspector from "../inspect";
8
+ import { logger } from "../logger";
9
+ import { DEFAULT_MODULE_RULES } from "../module-collection";
10
+ import { waitForPortToBeAvailable } from "../proxy";
11
+ import type { Config } from "../config";
12
+ import type { AssetPaths } from "../sites";
13
+ import type { CfWorkerInit, CfScriptFormat } from "../worker";
14
+ import type { EsbuildBundle } from "./use-esbuild";
15
+ import type { MiniflareOptions } from "miniflare";
16
+
17
+ interface LocalProps {
18
+ name: string | undefined;
19
+ bundle: EsbuildBundle | undefined;
20
+ format: CfScriptFormat | undefined;
21
+ compatibilityDate: string;
22
+ compatibilityFlags: string[] | undefined;
23
+ bindings: CfWorkerInit["bindings"];
24
+ assetPaths: AssetPaths | undefined;
25
+ isWorkersSite: boolean;
26
+ port: number;
27
+ ip: string;
28
+ rules: Config["rules"];
29
+ inspectorPort: number;
30
+ enableLocalPersistence: boolean;
31
+ crons: Config["triggers"]["crons"];
32
+ localProtocol: "http" | "https";
33
+ localUpstream: string | undefined;
34
+ inspect: boolean | undefined;
35
+ onReady: (() => void) | undefined;
36
+ logLevel: "none" | "error" | "log" | "warn" | "debug" | undefined;
37
+ }
38
+
39
+ export function Local(props: LocalProps) {
40
+ const { inspectorUrl } = useLocalWorker(props);
41
+ useInspector({
42
+ inspectorUrl,
43
+ port: props.inspectorPort,
44
+ logToTerminal: false,
45
+ });
46
+ return null;
47
+ }
48
+
49
+ function useLocalWorker({
50
+ name: workerName,
51
+ bundle,
52
+ format,
53
+ compatibilityDate,
54
+ compatibilityFlags,
55
+ bindings,
56
+ assetPaths,
57
+ isWorkersSite,
58
+ port,
59
+ rules,
60
+ enableLocalPersistence,
61
+ ip,
62
+ crons,
63
+ localProtocol,
64
+ localUpstream,
65
+ inspect,
66
+ onReady,
67
+ logLevel,
68
+ }: LocalProps) {
69
+ // TODO: pass vars via command line
70
+ const local = useRef<ReturnType<typeof spawn>>();
71
+ const removeSignalExitListener = useRef<() => void>();
72
+ const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
73
+ // if we're using local persistence for data, we should use the cwd
74
+ // as an explicit path, or else it'll use the temp dir
75
+ // which disappears when dev ends
76
+ const localPersistencePath = enableLocalPersistence
77
+ ? // Maybe we could make the path configurable as well?
78
+ path.join(process.cwd(), "wrangler-local-state")
79
+ : // We otherwise choose null, but choose true later
80
+ // so that it's persisted in the temp dir across a dev session
81
+ // even when we change source and reload
82
+ null;
83
+ useEffect(() => {
84
+ const abortController = new AbortController();
85
+ async function startLocalWorker() {
86
+ if (!bundle || !format) return;
87
+
88
+ // port for the worker
89
+ await waitForPortToBeAvailable(port, {
90
+ retryPeriod: 200,
91
+ timeout: 2000,
92
+ abortSignal: abortController.signal,
93
+ });
94
+
95
+ if (bindings.services && bindings.services.length > 0) {
96
+ throw new Error(
97
+ "⎔ Service bindings are not yet supported in local mode."
98
+ );
99
+ }
100
+
101
+ // In local mode, we want to copy all referenced modules into
102
+ // the output bundle directory before starting up
103
+ for (const module of bundle.modules) {
104
+ await writeFile(
105
+ path.join(path.dirname(bundle.path), module.name),
106
+ module.content
107
+ );
108
+ }
109
+
110
+ const scriptPath = realpathSync(bundle.path);
111
+
112
+ // the wasm_modules/text_blobs/data_blobs bindings are
113
+ // relative to process.cwd(), but the actual worker bundle
114
+ // is in the temp output directory; so we rewrite the paths to be absolute,
115
+ // letting miniflare resolve them correctly
116
+
117
+ // wasm
118
+ const wasmBindings: Record<string, string> = {};
119
+ for (const [name, filePath] of Object.entries(
120
+ bindings.wasm_modules || {}
121
+ )) {
122
+ wasmBindings[name] = path.join(process.cwd(), filePath);
123
+ }
124
+
125
+ // text
126
+ const textBlobBindings: Record<string, string> = {};
127
+ for (const [name, filePath] of Object.entries(
128
+ bindings.text_blobs || {}
129
+ )) {
130
+ textBlobBindings[name] = path.join(process.cwd(), filePath);
131
+ }
132
+
133
+ // data
134
+ const dataBlobBindings: Record<string, string> = {};
135
+ for (const [name, filePath] of Object.entries(
136
+ bindings.data_blobs || {}
137
+ )) {
138
+ dataBlobBindings[name] = path.join(process.cwd(), filePath);
139
+ }
140
+
141
+ if (format === "service-worker") {
142
+ for (const { type, name } of bundle.modules) {
143
+ if (type === "compiled-wasm") {
144
+ // In service-worker format, .wasm modules are referenced by global identifiers,
145
+ // so we convert it here.
146
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
147
+ // characters with an underscore.
148
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
149
+ wasmBindings[identifier] = name;
150
+ } else if (type === "text") {
151
+ // In service-worker format, text modules are referenced by global identifiers,
152
+ // so we convert it here.
153
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
154
+ // characters with an underscore.
155
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
156
+ textBlobBindings[identifier] = name;
157
+ } else if (type === "buffer") {
158
+ // In service-worker format, data blobs are referenced by global identifiers,
159
+ // so we convert it here.
160
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
161
+ // characters with an underscore.
162
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
163
+ dataBlobBindings[identifier] = name;
164
+ }
165
+ }
166
+ }
167
+
168
+ const upstream =
169
+ typeof localUpstream === "string"
170
+ ? `${localProtocol}://${localUpstream}`
171
+ : undefined;
172
+
173
+ const options: MiniflareOptions = {
174
+ name: workerName,
175
+ port,
176
+ scriptPath,
177
+ https: localProtocol === "https",
178
+ host: ip,
179
+ modules: format === "modules",
180
+ modulesRules: (rules || [])
181
+ .concat(DEFAULT_MODULE_RULES)
182
+ .map(({ type, globs: include, fallthrough }) => ({
183
+ type,
184
+ include,
185
+ fallthrough,
186
+ })),
187
+ compatibilityDate,
188
+ compatibilityFlags,
189
+ kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
190
+ durableObjects: Object.fromEntries(
191
+ (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
192
+ (value) => [value.name, value.class_name]
193
+ )
194
+ ),
195
+ ...(localPersistencePath
196
+ ? {
197
+ kvPersist: path.join(localPersistencePath, "kv"),
198
+ durableObjectsPersist: path.join(localPersistencePath, "do"),
199
+ cachePersist: path.join(localPersistencePath, "cache"),
200
+ }
201
+ : {
202
+ // We mark these as true, so that they'll
203
+ // persist in the temp directory.
204
+ // This means they'll persist across a dev session,
205
+ // even if we change source and reload,
206
+ // and be deleted when the dev session ends
207
+ durableObjectsPersist: true,
208
+ cachePersist: true,
209
+ kvPersist: true,
210
+ }),
211
+
212
+ sitePath: assetPaths?.assetDirectory
213
+ ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
214
+ : undefined,
215
+ siteInclude: assetPaths?.includePatterns.length
216
+ ? assetPaths?.includePatterns
217
+ : undefined,
218
+ siteExclude: assetPaths?.excludePatterns.length
219
+ ? assetPaths.excludePatterns
220
+ : undefined,
221
+ bindings: bindings.vars,
222
+ wasmBindings,
223
+ textBlobBindings,
224
+ dataBlobBindings,
225
+ sourceMap: true,
226
+ logUnhandledRejections: true,
227
+ crons,
228
+ upstream,
229
+ disableLogs: logLevel === "none",
230
+ };
231
+
232
+ // The path to the Miniflare CLI assumes that this file is being run from
233
+ // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
234
+ // If either of those paths change this line needs updating.
235
+ const miniflareCLIPath = path.resolve(
236
+ __dirname,
237
+ "../miniflare-dist/index.mjs"
238
+ );
239
+ const optionsArg = JSON.stringify(options, null);
240
+
241
+ logger.log("⎔ Starting a local server...");
242
+ const localServerOptions = [
243
+ "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
244
+ "--no-warnings", // hide annoying Node warnings
245
+ miniflareCLIPath,
246
+ optionsArg,
247
+ // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
248
+ ];
249
+ if (inspect) {
250
+ localServerOptions.push("--inspect"); // start Miniflare listening for a debugger to attach
251
+ }
252
+ // spawn isn't technically synchronous here
253
+ local.current = spawn("node", localServerOptions, {
254
+ cwd: path.dirname(scriptPath),
255
+ });
256
+ //TODO: instead of being lucky with spawn's timing, have miniflare-cli notify wrangler that it's ready in packages/wrangler/src/miniflare-cli/index.ts, after the mf.startScheduler promise resolves
257
+ if (onReady) {
258
+ await new Promise((resolve) => setTimeout(resolve, 200));
259
+ onReady();
260
+ }
261
+
262
+ local.current.on("close", (code) => {
263
+ if (code) {
264
+ logger.log(`Miniflare process exited with code ${code}`);
265
+ }
266
+ });
267
+
268
+ local.current.stdout?.on("data", (data: Buffer) => {
269
+ process.stdout.write(data);
270
+ });
271
+
272
+ // parse the node inspector url (which may be received in chunks) from stderr
273
+ let stderrData = "";
274
+ let inspectorUrlFound = false;
275
+ local.current.stderr?.on("data", (data: Buffer) => {
276
+ if (!inspectorUrlFound) {
277
+ stderrData += data.toString();
278
+ const matches =
279
+ /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)[\r|\n]/.exec(
280
+ stderrData
281
+ );
282
+ if (matches) {
283
+ inspectorUrlFound = true;
284
+ setInspectorUrl(matches[1]);
285
+ }
286
+ }
287
+
288
+ process.stderr.write(data);
289
+ });
290
+
291
+ local.current.on("exit", (code) => {
292
+ if (code) {
293
+ logger.error(`Miniflare process exited with code ${code}`);
294
+ }
295
+ });
296
+
297
+ local.current.on("error", (error: Error) => {
298
+ logger.error(`Miniflare process failed to spawn`);
299
+ logger.error(error);
300
+ });
301
+
302
+ removeSignalExitListener.current = onExit((_code, _signal) => {
303
+ logger.log("⎔ Shutting down local server.");
304
+ local.current?.kill();
305
+ local.current = undefined;
306
+ });
307
+ }
308
+
309
+ startLocalWorker().catch((err) => {
310
+ logger.error("local worker:", err);
311
+ });
312
+
313
+ return () => {
314
+ abortController.abort();
315
+ if (local.current) {
316
+ logger.log("⎔ Shutting down local server.");
317
+ local.current?.kill();
318
+ local.current = undefined;
319
+ removeSignalExitListener.current && removeSignalExitListener.current();
320
+ removeSignalExitListener.current = undefined;
321
+ }
322
+ };
323
+ }, [
324
+ bundle,
325
+ workerName,
326
+ format,
327
+ port,
328
+ ip,
329
+ bindings.durable_objects?.bindings,
330
+ bindings.kv_namespaces,
331
+ bindings.vars,
332
+ bindings.services,
333
+ compatibilityDate,
334
+ compatibilityFlags,
335
+ localPersistencePath,
336
+ assetPaths,
337
+ isWorkersSite,
338
+ rules,
339
+ bindings.wasm_modules,
340
+ bindings.text_blobs,
341
+ bindings.data_blobs,
342
+ crons,
343
+ localProtocol,
344
+ localUpstream,
345
+ inspect,
346
+ logLevel,
347
+ onReady,
348
+ ]);
349
+ return { inspectorUrl };
350
+ }
@@ -0,0 +1,367 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import React, { useState, useEffect, useRef } from "react";
4
+ import { useErrorHandler } from "react-error-boundary";
5
+ import { printBundleSize } from "../bundle-reporter";
6
+ import {
7
+ createPreviewSession,
8
+ createWorkerPreview,
9
+ } from "../create-worker-preview";
10
+ import useInspector from "../inspect";
11
+ import { logger } from "../logger";
12
+ import { usePreviewServer } from "../proxy";
13
+ import { syncAssets } from "../sites";
14
+ import { ChooseAccount, getAccountChoices, requireApiToken } from "../user";
15
+ import type { Route } from "../config/environment";
16
+ import type {
17
+ CfPreviewToken,
18
+ CfPreviewSession,
19
+ } from "../create-worker-preview";
20
+ import type { AssetPaths } from "../sites";
21
+ import type { ChooseAccountItem } from "../user";
22
+ import type {
23
+ CfModule,
24
+ CfWorkerInit,
25
+ CfScriptFormat,
26
+ CfAccount,
27
+ CfWorkerContext,
28
+ } from "../worker";
29
+ import type { EsbuildBundle } from "./use-esbuild";
30
+
31
+ export function Remote(props: {
32
+ name: string | undefined;
33
+ bundle: EsbuildBundle | undefined;
34
+ format: CfScriptFormat | undefined;
35
+ isWorkersSite: boolean;
36
+ assetPaths: AssetPaths | undefined;
37
+ port: number;
38
+ ip: string;
39
+ localProtocol: "https" | "http";
40
+ inspectorPort: number;
41
+ accountId: string | undefined;
42
+ bindings: CfWorkerInit["bindings"];
43
+ compatibilityDate: string;
44
+ compatibilityFlags: string[] | undefined;
45
+ usageModel: "bundled" | "unbound" | undefined;
46
+ env: string | undefined;
47
+ legacyEnv: boolean | undefined;
48
+ zone: string | undefined;
49
+ host: string | undefined;
50
+ routes: Route[] | undefined;
51
+ onReady?: () => void;
52
+ }) {
53
+ const [accountId, setAccountId] = useState(props.accountId);
54
+ const accountChoicesRef = useRef<Promise<ChooseAccountItem[]>>();
55
+ const [accountChoices, setAccountChoices] = useState<ChooseAccountItem[]>();
56
+
57
+ const previewToken = useWorker({
58
+ name: props.name,
59
+ bundle: props.bundle,
60
+ format: props.format,
61
+ modules: props.bundle ? props.bundle.modules : [],
62
+ accountId,
63
+ bindings: props.bindings,
64
+ assetPaths: props.assetPaths,
65
+ isWorkersSite: props.isWorkersSite,
66
+ port: props.port,
67
+ compatibilityDate: props.compatibilityDate,
68
+ compatibilityFlags: props.compatibilityFlags,
69
+ usageModel: props.usageModel,
70
+ env: props.env,
71
+ legacyEnv: props.legacyEnv,
72
+ zone: props.zone,
73
+ host: props.host,
74
+ routes: props.routes,
75
+ onReady: props.onReady,
76
+ });
77
+
78
+ usePreviewServer({
79
+ previewToken,
80
+ assetDirectory: props.isWorkersSite
81
+ ? undefined
82
+ : props.assetPaths?.assetDirectory,
83
+ localProtocol: props.localProtocol,
84
+ localPort: props.port,
85
+ ip: props.ip,
86
+ });
87
+
88
+ useInspector({
89
+ inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
90
+ port: props.inspectorPort,
91
+ logToTerminal: true,
92
+ });
93
+
94
+ const errorHandler = useErrorHandler();
95
+
96
+ // This effect handles the async step of fetching the available accounts for the current user.
97
+ // If only one account is available then it is just used by calling `setAccountId()`.
98
+ useEffect(() => {
99
+ if (accountChoicesRef.current !== undefined) {
100
+ return;
101
+ }
102
+ accountChoicesRef.current = getAccountChoices();
103
+ accountChoicesRef.current.then(
104
+ (accounts) => {
105
+ if (accounts.length === 1) {
106
+ setAccountId(accounts[0].id);
107
+ } else {
108
+ setAccountChoices(accounts);
109
+ }
110
+ },
111
+ (err) => {
112
+ errorHandler(err);
113
+ }
114
+ );
115
+ });
116
+
117
+ // If we have not already chosen an account and there are multiple accounts available
118
+ // allow the users to select one.
119
+ return accountId === undefined && accountChoices !== undefined ? (
120
+ <ChooseAccount
121
+ accounts={accountChoices}
122
+ onSelect={(selectedAccountId) => setAccountId(selectedAccountId)}
123
+ onError={(err) => errorHandler(err)}
124
+ ></ChooseAccount>
125
+ ) : null;
126
+ }
127
+
128
+ export function useWorker(props: {
129
+ name: string | undefined;
130
+ bundle: EsbuildBundle | undefined;
131
+ format: CfScriptFormat | undefined;
132
+ modules: CfModule[];
133
+ accountId: string | undefined;
134
+ bindings: CfWorkerInit["bindings"];
135
+ assetPaths: AssetPaths | undefined;
136
+ isWorkersSite: boolean;
137
+ port: number;
138
+ compatibilityDate: string | undefined;
139
+ compatibilityFlags: string[] | undefined;
140
+ usageModel: "bundled" | "unbound" | undefined;
141
+ env: string | undefined;
142
+ legacyEnv: boolean | undefined;
143
+ zone: string | undefined;
144
+ host: string | undefined;
145
+ routes: Route[] | undefined;
146
+ onReady?: () => void;
147
+ }): CfPreviewToken | undefined {
148
+ const {
149
+ name,
150
+ bundle,
151
+ format,
152
+ modules,
153
+ accountId,
154
+ bindings,
155
+ assetPaths,
156
+ compatibilityDate,
157
+ compatibilityFlags,
158
+ usageModel,
159
+ port,
160
+ onReady,
161
+ } = props;
162
+ const [session, setSession] = useState<CfPreviewSession | undefined>();
163
+ const [token, setToken] = useState<CfPreviewToken | undefined>();
164
+
165
+ // This is the most reliable way to detect whether
166
+ // something's "happened" in our system; We make a ref and
167
+ // mark it once we log our initial message. Refs are vars!
168
+ const startedRef = useRef(false);
169
+
170
+ // This effect sets up the preview session
171
+ useEffect(() => {
172
+ const abortController = new AbortController();
173
+ async function start() {
174
+ if (accountId === undefined) {
175
+ return;
176
+ }
177
+
178
+ const workerAccount: CfAccount = {
179
+ accountId,
180
+ apiToken: requireApiToken(),
181
+ };
182
+
183
+ const workerCtx: CfWorkerContext = {
184
+ env: props.env,
185
+ legacyEnv: props.legacyEnv,
186
+ zone: props.zone,
187
+ host: props.host,
188
+ routes: props.routes,
189
+ };
190
+
191
+ setSession(
192
+ await createPreviewSession(
193
+ workerAccount,
194
+ workerCtx,
195
+ abortController.signal
196
+ )
197
+ );
198
+ }
199
+ start().catch((err) => {
200
+ // we want to log the error, but not end the process
201
+ // since it could recover after the developer fixes whatever's wrong
202
+ if ((err as { code: string }).code !== "ABORT_ERR") {
203
+ logger.error("Error while creating remote dev session:", err);
204
+ }
205
+ });
206
+
207
+ return () => {
208
+ abortController.abort();
209
+ };
210
+ }, [
211
+ accountId,
212
+ props.env,
213
+ props.host,
214
+ props.legacyEnv,
215
+ props.routes,
216
+ props.zone,
217
+ ]);
218
+
219
+ // This effect uses the session to upload the worker and create a preview
220
+ useEffect(() => {
221
+ const abortController = new AbortController();
222
+ async function start() {
223
+ if (accountId === undefined) {
224
+ return;
225
+ }
226
+ if (session === undefined) {
227
+ return;
228
+ }
229
+ setToken(undefined); // reset token in case we're re-running
230
+
231
+ if (!bundle || !format) return;
232
+
233
+ if (!startedRef.current) {
234
+ startedRef.current = true;
235
+ } else {
236
+ logger.log("⎔ Detected changes, restarted server.");
237
+ }
238
+
239
+ const content = await readFile(bundle.path, "utf-8");
240
+
241
+ // TODO: For Dev we could show the reporter message in the interactive box.
242
+ void printBundleSize(
243
+ { name: path.basename(bundle.path), content: content },
244
+ modules
245
+ );
246
+
247
+ const assets = await syncAssets(
248
+ accountId,
249
+ // When we're using the newer service environments, we wouldn't
250
+ // have added the env name on to the script name. However, we must
251
+ // include it in the kv namespace name regardless (since there's no
252
+ // concept of service environments for kv namespaces yet).
253
+ name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
254
+ props.isWorkersSite ? assetPaths : undefined,
255
+ true,
256
+ false
257
+ ); // TODO: cancellable?
258
+
259
+ const init: CfWorkerInit = {
260
+ name,
261
+ main: {
262
+ name: path.basename(bundle.path),
263
+ type: format === "modules" ? "esm" : "commonjs",
264
+ content,
265
+ },
266
+ modules: modules.concat(
267
+ assets.manifest
268
+ ? {
269
+ name: "__STATIC_CONTENT_MANIFEST",
270
+ content: JSON.stringify(assets.manifest),
271
+ type: "text",
272
+ }
273
+ : []
274
+ ),
275
+ bindings: {
276
+ ...bindings,
277
+ kv_namespaces: (bindings.kv_namespaces || []).concat(
278
+ assets.namespace
279
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
280
+ : []
281
+ ),
282
+ text_blobs: {
283
+ ...bindings.text_blobs,
284
+ ...(assets.manifest &&
285
+ format === "service-worker" && {
286
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
287
+ }),
288
+ },
289
+ },
290
+ migrations: undefined, // no migrations in dev
291
+ compatibility_date: compatibilityDate,
292
+ compatibility_flags: compatibilityFlags,
293
+ usage_model: usageModel,
294
+ };
295
+
296
+ const workerAccount: CfAccount = {
297
+ accountId,
298
+ apiToken: requireApiToken(),
299
+ };
300
+
301
+ const workerCtx: CfWorkerContext = {
302
+ env: props.env,
303
+ legacyEnv: props.legacyEnv,
304
+ zone: props.zone,
305
+ host: props.host,
306
+ routes: props.routes,
307
+ };
308
+
309
+ setToken(
310
+ await createWorkerPreview(
311
+ init,
312
+ workerAccount,
313
+ workerCtx,
314
+ session,
315
+ abortController.signal
316
+ )
317
+ );
318
+ onReady?.();
319
+ }
320
+ start().catch((err) => {
321
+ // we want to log the error, but not end the process
322
+ // since it could recover after the developer fixes whatever's wrong
323
+ if ((err as { code: string }).code !== "ABORT_ERR") {
324
+ // instead of logging the raw API error to the user,
325
+ // give them friendly instructions
326
+ // for error 10063 (workers.dev subdomain required)
327
+ if (err.code === 10063) {
328
+ const errorMessage =
329
+ "Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
330
+ const solutionMessage =
331
+ "You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
332
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
333
+ logger.error(
334
+ `${errorMessage}\n${solutionMessage}\n${onboardingLink}`
335
+ );
336
+ } else {
337
+ logger.error("Error on remote worker:", err);
338
+ }
339
+ }
340
+ });
341
+
342
+ return () => {
343
+ abortController.abort();
344
+ };
345
+ }, [
346
+ name,
347
+ bundle,
348
+ format,
349
+ accountId,
350
+ port,
351
+ assetPaths,
352
+ props.isWorkersSite,
353
+ compatibilityDate,
354
+ compatibilityFlags,
355
+ usageModel,
356
+ bindings,
357
+ modules,
358
+ props.env,
359
+ props.legacyEnv,
360
+ props.zone,
361
+ props.host,
362
+ props.routes,
363
+ session,
364
+ onReady,
365
+ ]);
366
+ return token;
367
+ }