wrangler 0.0.0-e88a54e → 0.0.0-e8e684c7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +161 -29
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5484 -21
  6. package/package.json +173 -143
  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 +4016 -2786
  10. package/src/__tests__/dev.test.tsx +1305 -483
  11. package/src/__tests__/generate.test.ts +91 -0
  12. package/src/__tests__/guess-worker-format.test.ts +75 -48
  13. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  14. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  15. package/src/__tests__/helpers/mock-bin.ts +20 -20
  16. package/src/__tests__/helpers/mock-cfetch.ts +182 -93
  17. package/src/__tests__/helpers/mock-console.ts +59 -32
  18. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  19. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +74 -0
  22. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  23. package/src/__tests__/helpers/mock-kv.ts +26 -26
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  25. package/src/__tests__/helpers/mock-process.ts +39 -0
  26. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  27. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  28. package/src/__tests__/helpers/run-in-tmp.ts +28 -22
  29. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  30. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  31. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  32. package/src/__tests__/https-options.test.ts +144 -108
  33. package/src/__tests__/index.test.ts +229 -975
  34. package/src/__tests__/init.test.ts +2170 -0
  35. package/src/__tests__/jest.setup.ts +122 -34
  36. package/src/__tests__/kv.test.ts +1376 -1087
  37. package/src/__tests__/logger.test.ts +141 -0
  38. package/src/__tests__/metrics.test.ts +450 -0
  39. package/src/__tests__/package-manager.test.ts +312 -165
  40. package/src/__tests__/pages.test.ts +1270 -39
  41. package/src/__tests__/parse.test.ts +253 -245
  42. package/src/__tests__/publish.test.ts +6878 -2627
  43. package/src/__tests__/pubsub.test.ts +367 -0
  44. package/src/__tests__/r2.test.ts +328 -190
  45. package/src/__tests__/route.test.ts +22 -22
  46. package/src/__tests__/secret.test.ts +474 -407
  47. package/src/__tests__/tail.test.ts +679 -441
  48. package/src/__tests__/test-old-node-version.js +31 -0
  49. package/src/__tests__/user.test.ts +155 -0
  50. package/src/__tests__/validate-dev-props.test.ts +56 -0
  51. package/src/__tests__/version.test.ts +35 -0
  52. package/src/__tests__/whoami.test.tsx +276 -87
  53. package/src/__tests__/worker-namespace.test.ts +329 -0
  54. package/src/abort.d.ts +3 -0
  55. package/src/api/dev.ts +93 -0
  56. package/src/api/index.ts +1 -0
  57. package/src/bundle-reporter.tsx +29 -0
  58. package/src/bundle.ts +441 -110
  59. package/src/cfetch/index.ts +83 -66
  60. package/src/cfetch/internal.ts +251 -92
  61. package/src/cli.ts +22 -14
  62. package/src/config/README.md +1 -1
  63. package/src/config/config.ts +224 -179
  64. package/src/config/diagnostics.ts +61 -61
  65. package/src/config/environment.ts +430 -311
  66. package/src/config/index.ts +227 -38
  67. package/src/config/validation-helpers.ts +414 -303
  68. package/src/config/validation.ts +1745 -973
  69. package/src/config-cache.ts +85 -0
  70. package/src/create-worker-preview.ts +209 -118
  71. package/src/create-worker-upload-form.ts +275 -201
  72. package/src/dev/dev-vars.ts +36 -0
  73. package/src/dev/dev.tsx +488 -307
  74. package/src/dev/local.tsx +427 -210
  75. package/src/dev/remote.tsx +407 -188
  76. package/src/dev/use-esbuild.ts +156 -78
  77. package/src/dev/validate-dev-props.ts +31 -0
  78. package/src/dev-registry.tsx +160 -0
  79. package/src/dev.tsx +696 -0
  80. package/src/dialogs.tsx +115 -57
  81. package/src/dispatch-namespace.ts +206 -0
  82. package/src/durable.ts +102 -0
  83. package/src/entry.ts +267 -147
  84. package/src/environment-variables.ts +25 -23
  85. package/src/errors.ts +11 -0
  86. package/src/faye-websocket.d.ts +6 -0
  87. package/src/generate.ts +131 -0
  88. package/src/git-client.ts +42 -0
  89. package/src/global-wrangler-config-path.ts +26 -0
  90. package/src/https-options.ts +85 -80
  91. package/src/index.tsx +2191 -2304
  92. package/src/init.ts +622 -0
  93. package/src/inspect.ts +687 -557
  94. package/src/intl-polyfill.d.ts +139 -0
  95. package/src/is-ci.ts +14 -0
  96. package/src/is-interactive.ts +12 -0
  97. package/src/kv.ts +353 -242
  98. package/src/logger.ts +73 -0
  99. package/src/metrics/index.ts +5 -0
  100. package/src/metrics/metrics-config.ts +239 -0
  101. package/src/metrics/metrics-dispatcher.ts +96 -0
  102. package/src/metrics/metrics-usage-headers.ts +24 -0
  103. package/src/metrics/send-event.ts +92 -0
  104. package/src/miniflare-cli/assets.ts +554 -0
  105. package/src/miniflare-cli/enum-keys.ts +8 -8
  106. package/src/miniflare-cli/index.ts +199 -29
  107. package/src/miniflare-cli/request-context.ts +40 -0
  108. package/src/module-collection.ts +213 -213
  109. package/src/open-in-browser.ts +8 -16
  110. package/src/package-manager.ts +183 -90
  111. package/src/pages/build.tsx +238 -0
  112. package/src/pages/constants.ts +12 -0
  113. package/src/pages/deployments.tsx +106 -0
  114. package/src/pages/dev.tsx +528 -0
  115. package/src/pages/errors.ts +22 -0
  116. package/src/pages/functions/buildPlugin.ts +109 -0
  117. package/src/pages/functions/buildWorker.ts +155 -0
  118. package/src/pages/functions/filepath-routing.test.ts +234 -0
  119. package/src/pages/functions/filepath-routing.ts +189 -0
  120. package/src/pages/functions/identifiers.ts +78 -0
  121. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  122. package/src/pages/functions/routes-consolidation.ts +73 -0
  123. package/src/pages/functions/routes-transformation.test.ts +271 -0
  124. package/src/pages/functions/routes-transformation.ts +122 -0
  125. package/src/pages/functions/routes.ts +151 -0
  126. package/src/pages/functions.tsx +96 -0
  127. package/src/pages/index.tsx +94 -0
  128. package/src/pages/projects.tsx +169 -0
  129. package/src/pages/publish.tsx +391 -0
  130. package/src/pages/types.ts +49 -0
  131. package/src/pages/upload.tsx +413 -0
  132. package/src/pages/utils.ts +12 -0
  133. package/src/parse.ts +224 -121
  134. package/src/paths.ts +6 -6
  135. package/src/preview.ts +31 -0
  136. package/src/proxy.ts +416 -370
  137. package/src/publish.ts +796 -321
  138. package/src/pubsub/index.ts +286 -0
  139. package/src/pubsub/pubsub-commands.tsx +623 -0
  140. package/src/r2.ts +100 -19
  141. package/src/selfsigned.d.ts +23 -23
  142. package/src/sites.tsx +281 -189
  143. package/src/tail/filters.ts +111 -109
  144. package/src/tail/index.ts +230 -217
  145. package/src/tail/printing.ts +92 -47
  146. package/src/update-check.ts +19 -0
  147. package/src/user/choose-account.tsx +69 -0
  148. package/src/user/env-vars.ts +46 -0
  149. package/src/user/generate-auth-url.ts +33 -0
  150. package/src/user/generate-random-state.ts +16 -0
  151. package/src/user/index.ts +3 -0
  152. package/src/user/user.tsx +1191 -0
  153. package/src/whoami.tsx +142 -42
  154. package/src/worker.ts +135 -94
  155. package/src/zones.ts +167 -0
  156. package/templates/checked-fetch.js +17 -0
  157. package/templates/first-party-worker-module-facade.ts +18 -0
  158. package/templates/format-dev-errors.ts +32 -0
  159. package/templates/gitignore +171 -0
  160. package/templates/new-worker-scheduled.js +17 -0
  161. package/templates/new-worker-scheduled.ts +32 -0
  162. package/templates/new-worker.js +3 -3
  163. package/templates/new-worker.ts +18 -3
  164. package/templates/no-op-worker.js +10 -0
  165. package/templates/pages-shim.ts +9 -0
  166. package/templates/pages-template-plugin.ts +167 -0
  167. package/templates/pages-template-worker.ts +172 -0
  168. package/templates/serve-static-assets.ts +63 -0
  169. package/templates/service-bindings-module-facade.js +54 -0
  170. package/templates/service-bindings-sw-facade.js +42 -0
  171. package/templates/tsconfig.json +95 -95
  172. package/wrangler-dist/cli.d.ts +338 -0
  173. package/wrangler-dist/cli.js +124611 -112403
  174. package/miniflare-dist/index.mjs.map +0 -7
  175. package/pages/functions/buildWorker.ts +0 -62
  176. package/pages/functions/filepath-routing.test.ts +0 -223
  177. package/pages/functions/filepath-routing.ts +0 -181
  178. package/pages/functions/identifiers.ts +0 -78
  179. package/pages/functions/routes.ts +0 -151
  180. package/pages/functions/template-worker.ts +0 -130
  181. package/src/__tests__/dev2.test.tsx +0 -154
  182. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  183. package/src/__tests__/logout.test.ts +0 -52
  184. package/src/__tests__/sentry.test.ts +0 -146
  185. package/src/pages.tsx +0 -1047
  186. package/src/reporting.ts +0 -131
  187. package/src/user.tsx +0 -1118
  188. package/templates/static-asset-facade.js +0 -47
  189. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  190. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  191. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  192. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  193. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  194. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  195. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  196. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  197. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  198. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  199. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  200. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  201. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  202. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  203. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  204. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  205. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  206. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  207. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  208. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  209. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  210. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  211. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  212. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  213. package/vendor/wrangler-mime/LICENSE +0 -21
  214. package/vendor/wrangler-mime/Mime.js +0 -97
  215. package/vendor/wrangler-mime/README.md +0 -187
  216. package/vendor/wrangler-mime/cli.js +0 -46
  217. package/vendor/wrangler-mime/index.js +0 -4
  218. package/vendor/wrangler-mime/lite.js +0 -4
  219. package/vendor/wrangler-mime/package.json +0 -52
  220. package/vendor/wrangler-mime/types/other.js +0 -1
  221. package/vendor/wrangler-mime/types/standard.js +0 -1
  222. package/wrangler-dist/cli.js.map +0 -7
package/src/dev/local.tsx CHANGED
@@ -1,232 +1,449 @@
1
- import { spawn } from "node:child_process";
1
+ import { fork } from "node:child_process";
2
2
  import { realpathSync } from "node:fs";
3
3
  import { writeFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { useState, useEffect, useRef } from "react";
6
6
  import onExit from "signal-exit";
7
+ import { registerWorker } from "../dev-registry";
7
8
  import useInspector from "../inspect";
9
+ import { logger } from "../logger";
8
10
  import { DEFAULT_MODULE_RULES } from "../module-collection";
9
11
  import { waitForPortToBeAvailable } from "../proxy";
10
12
  import type { Config } from "../config";
13
+ import type { WorkerRegistry } from "../dev-registry";
14
+ import type { EnablePagesAssetsServiceBindingOptions } from "../miniflare-cli";
11
15
  import type { AssetPaths } from "../sites";
12
16
  import type { CfWorkerInit, CfScriptFormat } from "../worker";
13
17
  import type { EsbuildBundle } from "./use-esbuild";
14
18
  import type { MiniflareOptions } from "miniflare";
15
-
19
+ import type { ChildProcess } from "node:child_process";
16
20
  interface LocalProps {
17
- name: undefined | string;
18
- bundle: EsbuildBundle | undefined;
19
- format: CfScriptFormat | undefined;
20
- compatibilityDate: string | undefined;
21
- compatibilityFlags: undefined | string[];
22
- bindings: CfWorkerInit["bindings"];
23
- assetPaths: undefined | AssetPaths;
24
- public: undefined | string;
25
- port: number;
26
- ip: string;
27
- rules: Config["rules"];
28
- inspectorPort: number;
29
- enableLocalPersistence: boolean;
21
+ name: string | undefined;
22
+ bundle: EsbuildBundle | undefined;
23
+ format: CfScriptFormat | undefined;
24
+ compatibilityDate: string;
25
+ compatibilityFlags: string[] | undefined;
26
+ usageModel: "bundled" | "unbound" | undefined;
27
+ bindings: CfWorkerInit["bindings"];
28
+ workerDefinitions: WorkerRegistry;
29
+ assetPaths: AssetPaths | undefined;
30
+ port: number;
31
+ ip: string;
32
+ rules: Config["rules"];
33
+ inspectorPort: number;
34
+ enableLocalPersistence: boolean;
35
+ liveReload: boolean;
36
+ crons: Config["triggers"]["crons"];
37
+ localProtocol: "http" | "https";
38
+ localUpstream: string | undefined;
39
+ inspect: boolean;
40
+ onReady: (() => void) | undefined;
41
+ logLevel: "none" | "error" | "log" | "warn" | "debug" | undefined;
42
+ logPrefix?: string;
43
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
30
44
  }
31
45
 
32
46
  export function Local(props: LocalProps) {
33
- const { inspectorUrl } = useLocalWorker(props);
34
- useInspector({
35
- inspectorUrl,
36
- port: props.inspectorPort,
37
- logToTerminal: false,
38
- });
39
- return null;
47
+ const { inspectorUrl } = useLocalWorker(props);
48
+ useInspector({
49
+ inspectorUrl,
50
+ port: props.inspectorPort,
51
+ logToTerminal: false,
52
+ });
53
+ return null;
40
54
  }
41
55
 
42
56
  function useLocalWorker({
43
- name: workerName,
44
- bundle,
45
- format,
46
- compatibilityDate,
47
- compatibilityFlags,
48
- bindings,
49
- assetPaths,
50
- public: publicDirectory,
51
- port,
52
- rules,
53
- enableLocalPersistence,
54
- ip,
57
+ name: workerName,
58
+ bundle,
59
+ format,
60
+ compatibilityDate,
61
+ compatibilityFlags,
62
+ usageModel,
63
+ bindings,
64
+ workerDefinitions,
65
+ assetPaths,
66
+ port,
67
+ inspectorPort,
68
+ rules,
69
+ enableLocalPersistence,
70
+ liveReload,
71
+ ip,
72
+ crons,
73
+ localProtocol,
74
+ localUpstream,
75
+ inspect,
76
+ onReady,
77
+ logLevel,
78
+ logPrefix,
79
+ enablePagesAssetsServiceBinding,
55
80
  }: LocalProps) {
56
- // TODO: pass vars via command line
57
- const local = useRef<ReturnType<typeof spawn>>();
58
- const removeSignalExitListener = useRef<() => void>();
59
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
60
- useEffect(() => {
61
- async function startLocalWorker() {
62
- if (!bundle || !format) return;
63
-
64
- // port for the worker
65
- await waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 });
66
-
67
- if (publicDirectory) {
68
- throw new Error(
69
- '⎔ A "public" folder is not yet supported in local mode.'
70
- );
71
- }
72
-
73
- // In local mode, we want to copy all referenced modules into
74
- // the output bundle directory before starting up
75
- for (const module of bundle.modules) {
76
- await writeFile(
77
- path.join(path.dirname(bundle.path), module.name),
78
- module.content
79
- );
80
- }
81
-
82
- const scriptPath = realpathSync(bundle.path);
83
-
84
- const wasmBindings = { ...bindings.wasm_modules };
85
- if (format === "service-worker") {
86
- for (const { type, name } of bundle.modules) {
87
- if (type === "compiled-wasm") {
88
- // In service-worker format, .wasm modules are referenced by global identifiers,
89
- // so we convert it here.
90
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
91
- // characters with an underscore.
92
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
93
- wasmBindings[identifier] = name;
94
- }
95
- }
96
- }
97
-
98
- const options: MiniflareOptions = {
99
- name: workerName,
100
- port,
101
- scriptPath,
102
- host: ip,
103
- modules: format === "modules",
104
- modulesRules: (rules || [])
105
- .concat(DEFAULT_MODULE_RULES)
106
- .map(({ type, globs: include, fallthrough }) => ({
107
- type,
108
- include,
109
- fallthrough,
110
- })),
111
- compatibilityDate,
112
- compatibilityFlags,
113
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
114
- kvPersist: enableLocalPersistence,
115
- durableObjects: Object.fromEntries(
116
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
117
- (value) => [value.name, value.class_name]
118
- )
119
- ),
120
- durableObjectsPersist: enableLocalPersistence,
121
- cachePersist: enableLocalPersistence,
122
- sitePath: assetPaths?.assetDirectory
123
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
124
- : undefined,
125
- siteInclude: assetPaths?.includePatterns.length
126
- ? assetPaths?.includePatterns
127
- : undefined,
128
- siteExclude: assetPaths?.excludePatterns.length
129
- ? assetPaths.excludePatterns
130
- : undefined,
131
- bindings: bindings.vars,
132
- wasmBindings,
133
- sourceMap: true,
134
- logUnhandledRejections: true,
135
- };
136
-
137
- // The path to the Miniflare CLI assumes that this file is being run from
138
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
139
- // If either of those paths change this line needs updating.
140
- const miniflareCLIPath = path.resolve(
141
- __dirname,
142
- "../miniflare-dist/index.mjs"
143
- );
144
- const optionsArg = JSON.stringify(options, null);
145
-
146
- console.log("⎔ Starting a local server...");
147
- local.current = spawn(
148
- "node",
149
- [
150
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
151
- "--no-warnings", // hide annoying Node warnings
152
- "--inspect", // start Miniflare listening for a debugger to attach
153
- miniflareCLIPath,
154
- optionsArg,
155
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
156
- ],
157
- {
158
- cwd: path.dirname(scriptPath),
159
- }
160
- );
161
-
162
- local.current.on("close", (code) => {
163
- if (code) {
164
- console.log(`Miniflare process exited with code ${code}`);
165
- }
166
- });
167
-
168
- local.current.stdout?.on("data", (data: Buffer) => {
169
- console.log(`${data.toString()}`);
170
- });
171
-
172
- local.current.stderr?.on("data", (data: Buffer) => {
173
- console.error(`${data.toString()}`);
174
- const matches =
175
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
176
- data.toString()
177
- );
178
- if (matches) {
179
- setInspectorUrl(matches[1]);
180
- }
181
- });
182
-
183
- local.current.on("exit", (code) => {
184
- if (code) {
185
- console.error(`Miniflare process exited with code ${code}`);
186
- }
187
- });
188
-
189
- local.current.on("error", (error: Error) => {
190
- console.error(`Miniflare process failed to spawn`);
191
- console.error(error);
192
- });
193
-
194
- removeSignalExitListener.current = onExit((_code, _signal) => {
195
- console.log("⎔ Shutting down local server.");
196
- local.current?.kill();
197
- local.current = undefined;
198
- });
199
- }
200
-
201
- startLocalWorker().catch((err) => {
202
- console.error("local worker:", err);
203
- });
204
-
205
- return () => {
206
- if (local.current) {
207
- console.log("⎔ Shutting down local server.");
208
- local.current?.kill();
209
- local.current = undefined;
210
- removeSignalExitListener.current && removeSignalExitListener.current();
211
- removeSignalExitListener.current = undefined;
212
- }
213
- };
214
- }, [
215
- bundle,
216
- workerName,
217
- format,
218
- port,
219
- ip,
220
- bindings.durable_objects?.bindings,
221
- bindings.kv_namespaces,
222
- bindings.vars,
223
- compatibilityDate,
224
- compatibilityFlags,
225
- enableLocalPersistence,
226
- assetPaths,
227
- publicDirectory,
228
- rules,
229
- bindings.wasm_modules,
230
- ]);
231
- return { inspectorUrl };
81
+ // TODO: pass vars via command line
82
+ const local = useRef<ChildProcess>();
83
+ const removeSignalExitListener = useRef<() => void>();
84
+ const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
85
+ // if we're using local persistence for data, we should use the cwd
86
+ // as an explicit path, or else it'll use the temp dir
87
+ // which disappears when dev ends
88
+ const localPersistencePath = enableLocalPersistence
89
+ ? // Maybe we could make the path configurable as well?
90
+ path.join(process.cwd(), "wrangler-local-state")
91
+ : // We otherwise choose null, but choose true later
92
+ // so that it's persisted in the temp dir across a dev session
93
+ // even when we change source and reload
94
+ null;
95
+
96
+ useEffect(() => {
97
+ if (bindings.services && bindings.services.length > 0) {
98
+ logger.warn(
99
+ "⎔ Support for service bindings in local mode is experimental and may change."
100
+ );
101
+ }
102
+ }, [bindings.services]);
103
+
104
+ useEffect(() => {
105
+ const externalDurableObjects = (
106
+ bindings.durable_objects?.bindings || []
107
+ ).filter((binding) => binding.script_name);
108
+
109
+ if (externalDurableObjects.length > 0) {
110
+ logger.warn(
111
+ "⎔ Support for external Durable Objects in local mode is experimental and may change."
112
+ );
113
+ }
114
+ }, [bindings.durable_objects?.bindings]);
115
+
116
+ useEffect(() => {
117
+ const abortController = new AbortController();
118
+ async function startLocalWorker() {
119
+ if (!bundle || !format) return;
120
+
121
+ // port for the worker
122
+ await waitForPortToBeAvailable(port, {
123
+ retryPeriod: 200,
124
+ timeout: 2000,
125
+ abortSignal: abortController.signal,
126
+ });
127
+
128
+ // In local mode, we want to copy all referenced modules into
129
+ // the output bundle directory before starting up
130
+ for (const module of bundle.modules) {
131
+ await writeFile(
132
+ path.join(path.dirname(bundle.path), module.name),
133
+ module.content
134
+ );
135
+ }
136
+
137
+ const scriptPath = realpathSync(bundle.path);
138
+
139
+ // the wasm_modules/text_blobs/data_blobs bindings are
140
+ // relative to process.cwd(), but the actual worker bundle
141
+ // is in the temp output directory; so we rewrite the paths to be absolute,
142
+ // letting miniflare resolve them correctly
143
+
144
+ // wasm
145
+ const wasmBindings: Record<string, string> = {};
146
+ for (const [name, filePath] of Object.entries(
147
+ bindings.wasm_modules || {}
148
+ )) {
149
+ wasmBindings[name] = path.join(process.cwd(), filePath);
150
+ }
151
+
152
+ // text
153
+ const textBlobBindings: Record<string, string> = {};
154
+ for (const [name, filePath] of Object.entries(
155
+ bindings.text_blobs || {}
156
+ )) {
157
+ textBlobBindings[name] = path.join(process.cwd(), filePath);
158
+ }
159
+
160
+ // data
161
+ const dataBlobBindings: Record<string, string> = {};
162
+ for (const [name, filePath] of Object.entries(
163
+ bindings.data_blobs || {}
164
+ )) {
165
+ dataBlobBindings[name] = path.join(process.cwd(), filePath);
166
+ }
167
+
168
+ if (format === "service-worker") {
169
+ for (const { type, name } of bundle.modules) {
170
+ if (type === "compiled-wasm") {
171
+ // In service-worker format, .wasm modules are referenced by global identifiers,
172
+ // so we convert it here.
173
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
174
+ // characters with an underscore.
175
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
176
+ wasmBindings[identifier] = name;
177
+ } else if (type === "text") {
178
+ // In service-worker format, text modules are referenced by global identifiers,
179
+ // so we convert it here.
180
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
181
+ // characters with an underscore.
182
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
183
+ textBlobBindings[identifier] = name;
184
+ } else if (type === "buffer") {
185
+ // In service-worker format, data blobs are referenced by global identifiers,
186
+ // so we convert it here.
187
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
188
+ // characters with an underscore.
189
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
190
+ dataBlobBindings[identifier] = name;
191
+ }
192
+ }
193
+ }
194
+
195
+ const upstream =
196
+ typeof localUpstream === "string"
197
+ ? `${localProtocol}://${localUpstream}`
198
+ : undefined;
199
+
200
+ const internalDurableObjects = (
201
+ bindings.durable_objects?.bindings || []
202
+ ).filter((binding) => !binding.script_name);
203
+ const externalDurableObjects = (
204
+ bindings.durable_objects?.bindings || []
205
+ ).filter((binding) => binding.script_name);
206
+
207
+ // TODO: This was already messy with the custom `disableLogs` and `logOptions`.
208
+ // It's now getting _really_ messy now with Pages ASSETS binding outside and the external Durable Objects inside.
209
+ const options: MiniflareOptions = {
210
+ name: workerName,
211
+ port,
212
+ scriptPath,
213
+ https: localProtocol === "https",
214
+ host: ip,
215
+ modules: format === "modules",
216
+ modulesRules: (rules || [])
217
+ .concat(DEFAULT_MODULE_RULES)
218
+ .map(({ type, globs: include, fallthrough }) => ({
219
+ type,
220
+ include,
221
+ fallthrough,
222
+ })),
223
+ compatibilityDate,
224
+ compatibilityFlags,
225
+ usageModel,
226
+ kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
227
+ r2Buckets: bindings.r2_buckets?.map((r2) => r2.binding),
228
+ durableObjects: Object.fromEntries(
229
+ internalDurableObjects.map((binding) => [
230
+ binding.name,
231
+ binding.class_name,
232
+ ])
233
+ ),
234
+ externalDurableObjects: Object.fromEntries(
235
+ externalDurableObjects
236
+ .map((binding) => {
237
+ const service = workerDefinitions[binding.script_name as string];
238
+ if (!service) return [binding.name, undefined];
239
+
240
+ const name = service.durableObjects.find(
241
+ (durableObject) =>
242
+ durableObject.className === binding.class_name
243
+ )?.name;
244
+ if (!name) return [binding.name, undefined];
245
+
246
+ return [
247
+ binding.name,
248
+ {
249
+ name,
250
+ host: service.durableObjectsHost,
251
+ port: service.durableObjectsPort,
252
+ },
253
+ ];
254
+ })
255
+ .filter(([_, details]) => !!details)
256
+ ),
257
+ ...(localPersistencePath
258
+ ? {
259
+ cachePersist: path.join(localPersistencePath, "cache"),
260
+ durableObjectsPersist: path.join(localPersistencePath, "do"),
261
+ kvPersist: path.join(localPersistencePath, "kv"),
262
+ r2Persist: path.join(localPersistencePath, "r2"),
263
+ }
264
+ : {
265
+ // We mark these as true, so that they'll
266
+ // persist in the temp directory.
267
+ // This means they'll persist across a dev session,
268
+ // even if we change source and reload,
269
+ // and be deleted when the dev session ends
270
+ cachePersist: true,
271
+ durableObjectsPersist: true,
272
+ kvPersist: true,
273
+ r2Persist: true,
274
+ }),
275
+
276
+ liveReload,
277
+ sitePath: assetPaths?.assetDirectory
278
+ ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
279
+ : undefined,
280
+ siteInclude: assetPaths?.includePatterns.length
281
+ ? assetPaths?.includePatterns
282
+ : undefined,
283
+ siteExclude: assetPaths?.excludePatterns.length
284
+ ? assetPaths.excludePatterns
285
+ : undefined,
286
+ bindings: bindings.vars,
287
+ wasmBindings,
288
+ textBlobBindings,
289
+ dataBlobBindings,
290
+ sourceMap: true,
291
+ logUnhandledRejections: true,
292
+ crons,
293
+ upstream,
294
+ disableLogs: logLevel === "none",
295
+ logOptions: logPrefix ? { prefix: logPrefix } : undefined,
296
+ };
297
+
298
+ // The path to the Miniflare CLI assumes that this file is being run from
299
+ // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
300
+ // If either of those paths change this line needs updating.
301
+ const miniflareCLIPath = path.resolve(
302
+ __dirname,
303
+ "../miniflare-dist/index.mjs"
304
+ );
305
+ const miniflareOptions = JSON.stringify(options, null);
306
+
307
+ logger.log("⎔ Starting a local server...");
308
+ const nodeOptions = [
309
+ "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
310
+ "--no-warnings", // hide annoying Node warnings
311
+ // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
312
+ ];
313
+ if (inspect) {
314
+ nodeOptions.push("--inspect=" + `${ip}:${inspectorPort}`); // start Miniflare listening for a debugger to attach
315
+ }
316
+
317
+ const forkOptions = [miniflareOptions];
318
+
319
+ if (enablePagesAssetsServiceBinding) {
320
+ forkOptions.push(JSON.stringify(enablePagesAssetsServiceBinding));
321
+ }
322
+
323
+ const child = (local.current = fork(miniflareCLIPath, forkOptions, {
324
+ cwd: path.dirname(scriptPath),
325
+ execArgv: nodeOptions,
326
+ stdio: "pipe",
327
+ }));
328
+
329
+ child.on("message", async (messageString) => {
330
+ const message = JSON.parse(messageString as string);
331
+ if (message.ready) {
332
+ // Let's register our presence in the dev registry
333
+ if (workerName) {
334
+ await registerWorker(workerName, {
335
+ protocol: localProtocol,
336
+ mode: "local",
337
+ port,
338
+ host: ip,
339
+ durableObjects: internalDurableObjects.map((binding) => ({
340
+ name: binding.name,
341
+ className: binding.class_name,
342
+ })),
343
+ ...(message.durableObjectsPort
344
+ ? {
345
+ durableObjectsHost: ip,
346
+ durableObjectsPort: message.durableObjectsPort,
347
+ }
348
+ : {}),
349
+ });
350
+ }
351
+ onReady?.();
352
+ }
353
+ });
354
+
355
+ child.on("close", (code) => {
356
+ if (code) {
357
+ logger.log(`Miniflare process exited with code ${code}`);
358
+ }
359
+ });
360
+
361
+ child.stdout?.on("data", (data: Buffer) => {
362
+ process.stdout.write(data);
363
+ });
364
+
365
+ // parse the node inspector url (which may be received in chunks) from stderr
366
+ let stderrData = "";
367
+ let inspectorUrlFound = false;
368
+ child.stderr?.on("data", (data: Buffer) => {
369
+ if (!inspectorUrlFound) {
370
+ stderrData += data.toString();
371
+ const matches =
372
+ /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)[\r|\n]/.exec(
373
+ stderrData
374
+ );
375
+ if (matches) {
376
+ inspectorUrlFound = true;
377
+ setInspectorUrl(matches[1]);
378
+ }
379
+ }
380
+
381
+ process.stderr.write(data);
382
+ });
383
+
384
+ child.on("exit", (code) => {
385
+ if (code) {
386
+ logger.error(`Miniflare process exited with code ${code}`);
387
+ }
388
+ });
389
+
390
+ child.on("error", (error: Error) => {
391
+ logger.error(`Miniflare process failed to spawn`);
392
+ logger.error(error);
393
+ });
394
+
395
+ removeSignalExitListener.current = onExit((_code, _signal) => {
396
+ logger.log("⎔ Shutting down local server.");
397
+ child.kill();
398
+ local.current = undefined;
399
+ });
400
+ }
401
+
402
+ startLocalWorker().catch((err) => {
403
+ logger.error("local worker:", err);
404
+ });
405
+
406
+ return () => {
407
+ abortController.abort();
408
+ if (local.current) {
409
+ logger.log("⎔ Shutting down local server.");
410
+ local.current?.kill();
411
+ local.current = undefined;
412
+ removeSignalExitListener.current && removeSignalExitListener.current();
413
+ removeSignalExitListener.current = undefined;
414
+ }
415
+ };
416
+ }, [
417
+ bundle,
418
+ workerName,
419
+ format,
420
+ port,
421
+ inspectorPort,
422
+ ip,
423
+ bindings.durable_objects?.bindings,
424
+ bindings.kv_namespaces,
425
+ bindings.r2_buckets,
426
+ bindings.vars,
427
+ bindings.services,
428
+ workerDefinitions,
429
+ compatibilityDate,
430
+ compatibilityFlags,
431
+ usageModel,
432
+ localPersistencePath,
433
+ liveReload,
434
+ assetPaths,
435
+ rules,
436
+ bindings.wasm_modules,
437
+ bindings.text_blobs,
438
+ bindings.data_blobs,
439
+ crons,
440
+ localProtocol,
441
+ localUpstream,
442
+ inspect,
443
+ logLevel,
444
+ logPrefix,
445
+ onReady,
446
+ enablePagesAssetsServiceBinding,
447
+ ]);
448
+ return { inspectorUrl };
232
449
  }