wrangler 0.0.0-bfbb0be → 0.0.0-bfbe49d0

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