wrangler 0.0.0-cd66b67 → 0.0.0-ce00a44c

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