wrangler 0.0.0-ece06ea → 0.0.0-ecfbb0c

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 (190) 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 +157 -116
  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 +1159 -0
  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 +255 -148
  32. package/src/__tests__/init.test.ts +1992 -0
  33. package/src/__tests__/jest.setup.ts +107 -0
  34. package/src/__tests__/kv.test.ts +1619 -0
  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 +6513 -0
  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/abort.d.ts +3 -0
  48. package/src/api/dev.ts +39 -0
  49. package/src/api/index.ts +1 -0
  50. package/src/bundle-reporter.tsx +29 -0
  51. package/src/bundle.ts +212 -0
  52. package/src/cfetch/index.ts +121 -0
  53. package/src/cfetch/internal.ts +149 -0
  54. package/src/cli.ts +25 -8
  55. package/src/config/README.md +107 -0
  56. package/src/config/config.ts +243 -0
  57. package/src/config/diagnostics.ts +80 -0
  58. package/src/config/environment.ts +430 -0
  59. package/src/config/index.ts +225 -0
  60. package/src/config/validation-helpers.ts +584 -0
  61. package/src/config/validation.ts +1693 -0
  62. package/src/config-cache.ts +44 -0
  63. package/src/create-worker-preview.ts +199 -0
  64. package/src/create-worker-upload-form.ts +254 -0
  65. package/src/dev/dev-vars.ts +36 -0
  66. package/src/dev/dev.tsx +417 -0
  67. package/src/dev/local.tsx +350 -0
  68. package/src/dev/remote.tsx +294 -0
  69. package/src/dev/use-esbuild.ts +150 -0
  70. package/src/dev.tsx +517 -727
  71. package/src/dialogs.tsx +116 -66
  72. package/src/durable.ts +102 -0
  73. package/src/entry.ts +328 -0
  74. package/src/environment-variables.ts +35 -0
  75. package/src/errors.ts +11 -0
  76. package/src/generate.ts +33 -0
  77. package/src/git-client.ts +42 -0
  78. package/src/https-options.ts +123 -0
  79. package/src/index.tsx +1845 -1828
  80. package/src/init.ts +549 -0
  81. package/src/inspect.ts +662 -0
  82. package/src/intl-polyfill.d.ts +139 -0
  83. package/src/kv.ts +408 -0
  84. package/src/logger.ts +73 -0
  85. package/src/miniflare-cli/README.md +30 -0
  86. package/src/miniflare-cli/enum-keys.ts +17 -0
  87. package/src/miniflare-cli/index.ts +52 -0
  88. package/src/miniflare-cli/request-context.ts +40 -0
  89. package/src/module-collection.ts +258 -0
  90. package/src/open-in-browser.ts +17 -0
  91. package/src/package-manager.ts +174 -0
  92. package/src/pages/build.tsx +202 -0
  93. package/src/pages/constants.ts +7 -0
  94. package/src/pages/deployments.tsx +101 -0
  95. package/src/pages/dev.tsx +964 -0
  96. package/src/pages/functions/buildPlugin.ts +105 -0
  97. package/src/pages/functions/buildWorker.ts +151 -0
  98. package/src/pages/functions/filepath-routing.test.ts +234 -0
  99. package/src/pages/functions/filepath-routing.ts +189 -0
  100. package/src/pages/functions/identifiers.ts +78 -0
  101. package/src/pages/functions/routes.ts +151 -0
  102. package/src/pages/index.tsx +84 -0
  103. package/src/pages/projects.tsx +157 -0
  104. package/src/pages/publish.tsx +335 -0
  105. package/src/pages/types.ts +40 -0
  106. package/src/pages/upload.tsx +384 -0
  107. package/src/pages/utils.ts +12 -0
  108. package/src/parse.ts +286 -0
  109. package/src/paths.ts +26 -0
  110. package/src/preview.ts +31 -0
  111. package/src/proxy.ts +476 -0
  112. package/src/publish.ts +755 -343
  113. package/src/pubsub/index.ts +286 -0
  114. package/src/pubsub/pubsub-commands.tsx +594 -0
  115. package/src/r2.ts +50 -0
  116. package/src/selfsigned.d.ts +29 -0
  117. package/src/sites.tsx +357 -100
  118. package/src/tail/filters.ts +279 -0
  119. package/src/tail/index.ts +299 -0
  120. package/src/tail/printing.ts +67 -0
  121. package/src/update-check.ts +19 -0
  122. package/src/user/choose-account.tsx +60 -0
  123. package/src/user/env-vars.ts +46 -0
  124. package/src/user/generate-auth-url.ts +33 -0
  125. package/src/user/generate-random-state.ts +16 -0
  126. package/src/user/index.ts +3 -0
  127. package/src/user/user.tsx +1130 -0
  128. package/src/whoami.tsx +90 -0
  129. package/src/worker.ts +185 -0
  130. package/src/zones.ts +76 -0
  131. package/templates/checked-fetch.js +17 -0
  132. package/templates/gitignore +171 -0
  133. package/templates/new-worker-scheduled.js +17 -0
  134. package/templates/new-worker-scheduled.ts +32 -0
  135. package/templates/new-worker.js +15 -0
  136. package/templates/new-worker.ts +30 -0
  137. package/templates/no-op-worker.js +10 -0
  138. package/templates/pages-template-plugin.ts +155 -0
  139. package/templates/pages-template-worker.ts +161 -0
  140. package/templates/static-asset-facade.js +43 -0
  141. package/templates/tsconfig.json +105 -0
  142. package/wrangler-dist/cli.js +104118 -113381
  143. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  144. package/src/__tests__/mock-cfetch.js +0 -46
  145. package/src/api/form_data.ts +0 -158
  146. package/src/api/inspect.ts +0 -441
  147. package/src/api/preview.ts +0 -123
  148. package/src/api/worker.ts +0 -161
  149. package/src/cfetch.ts +0 -72
  150. package/src/config.ts +0 -124
  151. package/src/kv.tsx +0 -211
  152. package/src/pages.tsx +0 -344
  153. package/src/tail.tsx +0 -71
  154. package/src/user.tsx +0 -1029
  155. package/src/util/fetch.ts +0 -74
  156. package/static-asset-facade.js +0 -47
  157. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  158. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  159. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  160. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  161. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  162. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  163. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  164. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  166. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  167. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  168. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  169. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  170. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  171. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  172. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  173. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  174. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  175. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  176. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  177. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  178. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  179. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  180. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  181. package/vendor/wrangler-mime/LICENSE +0 -21
  182. package/vendor/wrangler-mime/Mime.js +0 -97
  183. package/vendor/wrangler-mime/README.md +0 -187
  184. package/vendor/wrangler-mime/cli.js +0 -46
  185. package/vendor/wrangler-mime/index.js +0 -4
  186. package/vendor/wrangler-mime/lite.js +0 -4
  187. package/vendor/wrangler-mime/package.json +0 -52
  188. package/vendor/wrangler-mime/types/other.js +0 -1
  189. package/vendor/wrangler-mime/types/standard.js +0 -1
  190. 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,294 @@
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 { createWorkerPreview } from "../create-worker-preview";
7
+ import useInspector from "../inspect";
8
+ import { logger } from "../logger";
9
+ import { usePreviewServer } from "../proxy";
10
+ import { syncAssets } from "../sites";
11
+ import { ChooseAccount, getAccountChoices, requireApiToken } from "../user";
12
+ import type { Route } from "../config/environment";
13
+ import type { CfPreviewToken } from "../create-worker-preview";
14
+ import type { AssetPaths } from "../sites";
15
+ import type { ChooseAccountItem } from "../user";
16
+ import type { CfModule, CfWorkerInit, CfScriptFormat } from "../worker";
17
+ import type { EsbuildBundle } from "./use-esbuild";
18
+
19
+ export function Remote(props: {
20
+ name: string | undefined;
21
+ bundle: EsbuildBundle | undefined;
22
+ format: CfScriptFormat | undefined;
23
+ isWorkersSite: boolean;
24
+ assetPaths: AssetPaths | undefined;
25
+ port: number;
26
+ ip: string;
27
+ localProtocol: "https" | "http";
28
+ inspectorPort: number;
29
+ accountId: string | undefined;
30
+ bindings: CfWorkerInit["bindings"];
31
+ compatibilityDate: string;
32
+ compatibilityFlags: string[] | undefined;
33
+ usageModel: "bundled" | "unbound" | undefined;
34
+ env: string | undefined;
35
+ legacyEnv: boolean | undefined;
36
+ zone: string | undefined;
37
+ host: string | undefined;
38
+ routes: Route[] | undefined;
39
+ onReady?: () => void;
40
+ }) {
41
+ const [accountId, setAccountId] = useState(props.accountId);
42
+ const accountChoicesRef = useRef<Promise<ChooseAccountItem[]>>();
43
+ const [accountChoices, setAccountChoices] = useState<ChooseAccountItem[]>();
44
+
45
+ const previewToken = useWorker({
46
+ name: props.name,
47
+ bundle: props.bundle,
48
+ format: props.format,
49
+ modules: props.bundle ? props.bundle.modules : [],
50
+ accountId,
51
+ bindings: props.bindings,
52
+ assetPaths: props.assetPaths,
53
+ isWorkersSite: props.isWorkersSite,
54
+ port: props.port,
55
+ compatibilityDate: props.compatibilityDate,
56
+ compatibilityFlags: props.compatibilityFlags,
57
+ usageModel: props.usageModel,
58
+ env: props.env,
59
+ legacyEnv: props.legacyEnv,
60
+ zone: props.zone,
61
+ host: props.host,
62
+ routes: props.routes,
63
+ onReady: props.onReady,
64
+ });
65
+
66
+ usePreviewServer({
67
+ previewToken,
68
+ assetDirectory: props.isWorkersSite
69
+ ? undefined
70
+ : props.assetPaths?.assetDirectory,
71
+ localProtocol: props.localProtocol,
72
+ localPort: props.port,
73
+ ip: props.ip,
74
+ });
75
+
76
+ useInspector({
77
+ inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
78
+ port: props.inspectorPort,
79
+ logToTerminal: true,
80
+ });
81
+
82
+ const errorHandler = useErrorHandler();
83
+
84
+ // This effect handles the async step of fetching the available accounts for the current user.
85
+ // If only one account is available then it is just used by calling `setAccountId()`.
86
+ useEffect(() => {
87
+ if (accountChoicesRef.current !== undefined) {
88
+ return;
89
+ }
90
+ accountChoicesRef.current = getAccountChoices();
91
+ accountChoicesRef.current.then(
92
+ (accounts) => {
93
+ if (accounts.length === 1) {
94
+ setAccountId(accounts[0].id);
95
+ } else {
96
+ setAccountChoices(accounts);
97
+ }
98
+ },
99
+ (err) => {
100
+ errorHandler(err);
101
+ }
102
+ );
103
+ });
104
+
105
+ // If we have not already chosen an account and there are multiple accounts available
106
+ // allow the users to select one.
107
+ return accountId === undefined && accountChoices !== undefined ? (
108
+ <ChooseAccount
109
+ accounts={accountChoices}
110
+ onSelect={(selectedAccountId) => setAccountId(selectedAccountId)}
111
+ onError={(err) => errorHandler(err)}
112
+ ></ChooseAccount>
113
+ ) : null;
114
+ }
115
+
116
+ export function useWorker(props: {
117
+ name: string | undefined;
118
+ bundle: EsbuildBundle | undefined;
119
+ format: CfScriptFormat | undefined;
120
+ modules: CfModule[];
121
+ accountId: string | undefined;
122
+ bindings: CfWorkerInit["bindings"];
123
+ assetPaths: AssetPaths | undefined;
124
+ isWorkersSite: boolean;
125
+ port: number;
126
+ compatibilityDate: string | undefined;
127
+ compatibilityFlags: string[] | undefined;
128
+ usageModel: "bundled" | "unbound" | undefined;
129
+ env: string | undefined;
130
+ legacyEnv: boolean | undefined;
131
+ zone: string | undefined;
132
+ host: string | undefined;
133
+ routes: Route[] | undefined;
134
+ onReady?: () => void;
135
+ }): CfPreviewToken | undefined {
136
+ const {
137
+ name,
138
+ bundle,
139
+ format,
140
+ modules,
141
+ accountId,
142
+ bindings,
143
+ assetPaths,
144
+ compatibilityDate,
145
+ compatibilityFlags,
146
+ usageModel,
147
+ port,
148
+ onReady,
149
+ } = props;
150
+ const [token, setToken] = useState<CfPreviewToken | undefined>();
151
+
152
+ // This is the most reliable way to detect whether
153
+ // something's "happened" in our system; We make a ref and
154
+ // mark it once we log our initial message. Refs are vars!
155
+ const startedRef = useRef(false);
156
+
157
+ useEffect(() => {
158
+ const abortController = new AbortController();
159
+ async function start() {
160
+ if (accountId === undefined) {
161
+ return;
162
+ }
163
+ setToken(undefined); // reset token in case we're re-running
164
+
165
+ if (!bundle || !format) return;
166
+
167
+ if (!startedRef.current) {
168
+ startedRef.current = true;
169
+ } else {
170
+ logger.log("⎔ Detected changes, restarted server.");
171
+ }
172
+
173
+ const content = await readFile(bundle.path, "utf-8");
174
+
175
+ // TODO: For Dev we could show the reporter message in the interactive box.
176
+ void printBundleSize(
177
+ { name: path.basename(bundle.path), content: content },
178
+ modules
179
+ );
180
+
181
+ const assets = await syncAssets(
182
+ accountId,
183
+ // When we're using the newer service environments, we wouldn't
184
+ // have added the env name on to the script name. However, we must
185
+ // include it in the kv namespace name regardless (since there's no
186
+ // concept of service environments for kv namespaces yet).
187
+ name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
188
+ props.isWorkersSite ? assetPaths : undefined,
189
+ true,
190
+ false
191
+ ); // TODO: cancellable?
192
+
193
+ const init: CfWorkerInit = {
194
+ name,
195
+ main: {
196
+ name: path.basename(bundle.path),
197
+ type: format === "modules" ? "esm" : "commonjs",
198
+ content,
199
+ },
200
+ modules: modules.concat(
201
+ assets.manifest
202
+ ? {
203
+ name: "__STATIC_CONTENT_MANIFEST",
204
+ content: JSON.stringify(assets.manifest),
205
+ type: "text",
206
+ }
207
+ : []
208
+ ),
209
+ bindings: {
210
+ ...bindings,
211
+ kv_namespaces: (bindings.kv_namespaces || []).concat(
212
+ assets.namespace
213
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
214
+ : []
215
+ ),
216
+ text_blobs: {
217
+ ...bindings.text_blobs,
218
+ ...(assets.manifest &&
219
+ format === "service-worker" && {
220
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
221
+ }),
222
+ },
223
+ },
224
+ migrations: undefined, // no migrations in dev
225
+ compatibility_date: compatibilityDate,
226
+ compatibility_flags: compatibilityFlags,
227
+ usage_model: usageModel,
228
+ };
229
+ setToken(
230
+ await createWorkerPreview(
231
+ init,
232
+ {
233
+ accountId,
234
+ apiToken: requireApiToken(),
235
+ },
236
+ {
237
+ env: props.env,
238
+ legacyEnv: props.legacyEnv,
239
+ zone: props.zone,
240
+ host: props.host,
241
+ routes: props.routes,
242
+ },
243
+ abortController.signal
244
+ )
245
+ );
246
+ onReady?.();
247
+ }
248
+ start().catch((err) => {
249
+ // we want to log the error, but not end the process
250
+ // since it could recover after the developer fixes whatever's wrong
251
+ if ((err as { code: string }).code !== "ABORT_ERR") {
252
+ // instead of logging the raw API error to the user,
253
+ // give them friendly instructions
254
+ // for error 10063 (workers.dev subdomain required)
255
+ if (err.code === 10063) {
256
+ const errorMessage =
257
+ "Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
258
+ const solutionMessage =
259
+ "You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
260
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
261
+ logger.error(
262
+ `${errorMessage}\n${solutionMessage}\n${onboardingLink}`
263
+ );
264
+ } else {
265
+ logger.error("Error on remote worker:", err);
266
+ }
267
+ }
268
+ });
269
+
270
+ return () => {
271
+ abortController.abort();
272
+ };
273
+ }, [
274
+ name,
275
+ bundle,
276
+ format,
277
+ accountId,
278
+ port,
279
+ assetPaths,
280
+ props.isWorkersSite,
281
+ compatibilityDate,
282
+ compatibilityFlags,
283
+ usageModel,
284
+ bindings,
285
+ modules,
286
+ props.env,
287
+ props.legacyEnv,
288
+ props.zone,
289
+ props.host,
290
+ props.routes,
291
+ onReady,
292
+ ]);
293
+ return token;
294
+ }