wrangler 0.0.0-e928f94 → 0.0.0-e978986

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