wrangler 0.0.0-e95e5a0 → 0.0.0-e981d0be5

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 (184) hide show
  1. package/README.md +46 -34
  2. package/bin/wrangler.js +84 -39
  3. package/config-schema.json +2278 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +132 -99
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +2 -3
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +22 -4
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +33 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +679 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +22 -0
  41. package/templates/tsconfig.json +13 -103
  42. package/templates/tsconfig.tsbuildinfo +1 -0
  43. package/wrangler-dist/InspectorProxyWorker.js +471 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +238 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +26693 -0
  48. package/wrangler-dist/cli.js +148512 -106990
  49. package/import_meta_url.js +0 -3
  50. package/miniflare-config-stubs/.env.empty +0 -0
  51. package/miniflare-config-stubs/package.empty.json +0 -1
  52. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  53. package/miniflare-dist/index.mjs +0 -4886
  54. package/pages/functions/buildPlugin.ts +0 -92
  55. package/pages/functions/buildWorker.ts +0 -138
  56. package/pages/functions/filepath-routing.test.ts +0 -234
  57. package/pages/functions/filepath-routing.ts +0 -189
  58. package/pages/functions/identifiers.ts +0 -78
  59. package/pages/functions/routes.ts +0 -156
  60. package/pages/functions/template-plugin.ts +0 -146
  61. package/pages/functions/template-worker.ts +0 -143
  62. package/src/__tests__/config-cache.test.ts +0 -36
  63. package/src/__tests__/configuration.test.ts +0 -3125
  64. package/src/__tests__/dev.test.tsx +0 -762
  65. package/src/__tests__/guess-worker-format.test.ts +0 -85
  66. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  67. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  68. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  69. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  70. package/src/__tests__/helpers/mock-bin.ts +0 -36
  71. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  72. package/src/__tests__/helpers/mock-console.ts +0 -87
  73. package/src/__tests__/helpers/mock-dialogs.ts +0 -90
  74. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  75. package/src/__tests__/helpers/mock-istty.ts +0 -27
  76. package/src/__tests__/helpers/mock-kv.ts +0 -33
  77. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  78. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  79. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  80. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  81. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  82. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  83. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  84. package/src/__tests__/https-options.test.ts +0 -130
  85. package/src/__tests__/index.test.ts +0 -249
  86. package/src/__tests__/init.test.ts +0 -1516
  87. package/src/__tests__/jest.setup.ts +0 -69
  88. package/src/__tests__/kv.test.ts +0 -1454
  89. package/src/__tests__/logger.test.ts +0 -115
  90. package/src/__tests__/package-manager.test.ts +0 -206
  91. package/src/__tests__/pages.test.ts +0 -329
  92. package/src/__tests__/parse.test.ts +0 -322
  93. package/src/__tests__/publish.test.ts +0 -4875
  94. package/src/__tests__/r2.test.ts +0 -214
  95. package/src/__tests__/route.test.ts +0 -45
  96. package/src/__tests__/secret.test.ts +0 -446
  97. package/src/__tests__/tail.test.ts +0 -690
  98. package/src/__tests__/user.test.ts +0 -131
  99. package/src/__tests__/whoami.test.tsx +0 -105
  100. package/src/bundle.ts +0 -169
  101. package/src/cfetch/index.ts +0 -104
  102. package/src/cfetch/internal.ts +0 -137
  103. package/src/cli.ts +0 -13
  104. package/src/config/README.md +0 -107
  105. package/src/config/config.ts +0 -234
  106. package/src/config/diagnostics.ts +0 -80
  107. package/src/config/environment.ts +0 -394
  108. package/src/config/index.ts +0 -63
  109. package/src/config/validation-helpers.ts +0 -575
  110. package/src/config/validation.ts +0 -1424
  111. package/src/config-cache.ts +0 -45
  112. package/src/create-worker-preview.ts +0 -175
  113. package/src/create-worker-upload-form.ts +0 -240
  114. package/src/dev/dev-vars.ts +0 -36
  115. package/src/dev/dev.tsx +0 -418
  116. package/src/dev/local.tsx +0 -312
  117. package/src/dev/remote.tsx +0 -213
  118. package/src/dev/use-esbuild.ts +0 -118
  119. package/src/dialogs.tsx +0 -87
  120. package/src/entry.ts +0 -267
  121. package/src/environment-variables.ts +0 -35
  122. package/src/errors.ts +0 -11
  123. package/src/https-options.ts +0 -123
  124. package/src/index.tsx +0 -2668
  125. package/src/inspect.ts +0 -623
  126. package/src/intl-polyfill.d.ts +0 -139
  127. package/src/kv.ts +0 -319
  128. package/src/logger.ts +0 -66
  129. package/src/miniflare-cli/README.md +0 -30
  130. package/src/miniflare-cli/enum-keys.ts +0 -17
  131. package/src/miniflare-cli/index.ts +0 -41
  132. package/src/miniflare-cli/request-context.ts +0 -40
  133. package/src/module-collection.ts +0 -258
  134. package/src/open-in-browser.ts +0 -26
  135. package/src/package-manager.ts +0 -127
  136. package/src/pages.tsx +0 -1866
  137. package/src/parse.ts +0 -183
  138. package/src/paths.ts +0 -26
  139. package/src/proxy.ts +0 -449
  140. package/src/publish.ts +0 -469
  141. package/src/r2.ts +0 -50
  142. package/src/selfsigned.d.ts +0 -29
  143. package/src/sites.tsx +0 -293
  144. package/src/tail/filters.ts +0 -279
  145. package/src/tail/index.ts +0 -299
  146. package/src/tail/printing.ts +0 -67
  147. package/src/update-check.ts +0 -19
  148. package/src/user.tsx +0 -1193
  149. package/src/whoami.tsx +0 -70
  150. package/src/worker.ts +0 -172
  151. package/templates/static-asset-facade.js +0 -47
  152. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  153. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  154. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  155. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  156. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  157. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  158. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  159. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  160. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  161. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  166. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  167. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  168. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  169. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  170. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  171. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  172. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  173. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  174. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  175. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  176. package/vendor/wrangler-mime/LICENSE +0 -21
  177. package/vendor/wrangler-mime/Mime.js +0 -97
  178. package/vendor/wrangler-mime/README.md +0 -187
  179. package/vendor/wrangler-mime/cli.js +0 -46
  180. package/vendor/wrangler-mime/index.js +0 -4
  181. package/vendor/wrangler-mime/lite.js +0 -4
  182. package/vendor/wrangler-mime/package.json +0 -52
  183. package/vendor/wrangler-mime/types/other.js +0 -1
  184. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/dev/local.tsx DELETED
@@ -1,312 +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
- 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
-
91
- // In local mode, we want to copy all referenced modules into
92
- // the output bundle directory before starting up
93
- for (const module of bundle.modules) {
94
- await writeFile(
95
- path.join(path.dirname(bundle.path), module.name),
96
- module.content
97
- );
98
- }
99
-
100
- const scriptPath = realpathSync(bundle.path);
101
-
102
- // the wasm_modules/text_blobs/data_blobs bindings are
103
- // relative to process.cwd(), but the actual worker bundle
104
- // is in the temp output directory; so we rewrite the paths to be absolute,
105
- // letting miniflare resolve them correctly
106
-
107
- // wasm
108
- const wasmBindings: Record<string, string> = {};
109
- for (const [name, filePath] of Object.entries(
110
- bindings.wasm_modules || {}
111
- )) {
112
- wasmBindings[name] = path.join(process.cwd(), filePath);
113
- }
114
-
115
- // text
116
- const textBlobBindings: Record<string, string> = {};
117
- for (const [name, filePath] of Object.entries(
118
- bindings.text_blobs || {}
119
- )) {
120
- textBlobBindings[name] = path.join(process.cwd(), filePath);
121
- }
122
-
123
- // data
124
- const dataBlobBindings: Record<string, string> = {};
125
- for (const [name, filePath] of Object.entries(
126
- bindings.data_blobs || {}
127
- )) {
128
- dataBlobBindings[name] = path.join(process.cwd(), filePath);
129
- }
130
-
131
- if (format === "service-worker") {
132
- for (const { type, name } of bundle.modules) {
133
- if (type === "compiled-wasm") {
134
- // In service-worker format, .wasm modules are referenced by global identifiers,
135
- // so we convert it here.
136
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
137
- // characters with an underscore.
138
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
139
- wasmBindings[identifier] = name;
140
- } else if (type === "text") {
141
- // In service-worker format, text modules are referenced by global identifiers,
142
- // so we convert it here.
143
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
144
- // characters with an underscore.
145
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
146
- textBlobBindings[identifier] = name;
147
- } else if (type === "buffer") {
148
- // In service-worker format, data blobs are referenced by global identifiers,
149
- // so we convert it here.
150
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
151
- // characters with an underscore.
152
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
153
- dataBlobBindings[identifier] = name;
154
- }
155
- }
156
- }
157
-
158
- const options: MiniflareOptions = {
159
- name: workerName,
160
- port,
161
- scriptPath,
162
- host: ip,
163
- modules: format === "modules",
164
- modulesRules: (rules || [])
165
- .concat(DEFAULT_MODULE_RULES)
166
- .map(({ type, globs: include, fallthrough }) => ({
167
- type,
168
- include,
169
- fallthrough,
170
- })),
171
- compatibilityDate,
172
- compatibilityFlags,
173
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
174
- durableObjects: Object.fromEntries(
175
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
176
- (value) => [value.name, value.class_name]
177
- )
178
- ),
179
- ...(localPersistencePath
180
- ? {
181
- kvPersist: path.join(localPersistencePath, "kv"),
182
- durableObjectsPersist: path.join(localPersistencePath, "do"),
183
- cachePersist: path.join(localPersistencePath, "cache"),
184
- }
185
- : {
186
- // We mark these as true, so that they'll
187
- // persist in the temp directory.
188
- // This means they'll persist across a dev session,
189
- // even if we change source and reload,
190
- // and be deleted when the dev session ends
191
- durableObjectsPersist: true,
192
- cachePersist: true,
193
- kvPersist: true,
194
- }),
195
-
196
- sitePath: assetPaths?.assetDirectory
197
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
198
- : undefined,
199
- siteInclude: assetPaths?.includePatterns.length
200
- ? assetPaths?.includePatterns
201
- : undefined,
202
- siteExclude: assetPaths?.excludePatterns.length
203
- ? assetPaths.excludePatterns
204
- : undefined,
205
- bindings: bindings.vars,
206
- wasmBindings,
207
- textBlobBindings,
208
- dataBlobBindings,
209
- sourceMap: true,
210
- logUnhandledRejections: true,
211
- crons,
212
- };
213
-
214
- // The path to the Miniflare CLI assumes that this file is being run from
215
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
216
- // If either of those paths change this line needs updating.
217
- const miniflareCLIPath = path.resolve(
218
- __dirname,
219
- "../miniflare-dist/index.mjs"
220
- );
221
- const optionsArg = JSON.stringify(options, null);
222
-
223
- logger.log("⎔ Starting a local server...");
224
- local.current = spawn(
225
- "node",
226
- [
227
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
228
- "--no-warnings", // hide annoying Node warnings
229
- "--inspect", // start Miniflare listening for a debugger to attach
230
- miniflareCLIPath,
231
- optionsArg,
232
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
233
- ],
234
- {
235
- cwd: path.dirname(scriptPath),
236
- }
237
- );
238
-
239
- local.current.on("close", (code) => {
240
- if (code) {
241
- logger.log(`Miniflare process exited with code ${code}`);
242
- }
243
- });
244
-
245
- local.current.stdout?.on("data", (data: Buffer) => {
246
- process.stdout.write(data);
247
- });
248
-
249
- local.current.stderr?.on("data", (data: Buffer) => {
250
- const matches =
251
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
252
- data.toString()
253
- );
254
- if (matches) {
255
- setInspectorUrl(matches[1]);
256
- }
257
- });
258
-
259
- local.current.on("exit", (code) => {
260
- if (code) {
261
- logger.error(`Miniflare process exited with code ${code}`);
262
- }
263
- });
264
-
265
- local.current.on("error", (error: Error) => {
266
- logger.error(`Miniflare process failed to spawn`);
267
- logger.error(error);
268
- });
269
-
270
- removeSignalExitListener.current = onExit((_code, _signal) => {
271
- logger.log("⎔ Shutting down local server.");
272
- local.current?.kill();
273
- local.current = undefined;
274
- });
275
- }
276
-
277
- startLocalWorker().catch((err) => {
278
- logger.error("local worker:", err);
279
- });
280
-
281
- return () => {
282
- abortController.abort();
283
- if (local.current) {
284
- logger.log("⎔ Shutting down local server.");
285
- local.current?.kill();
286
- local.current = undefined;
287
- removeSignalExitListener.current && removeSignalExitListener.current();
288
- removeSignalExitListener.current = undefined;
289
- }
290
- };
291
- }, [
292
- bundle,
293
- workerName,
294
- format,
295
- port,
296
- ip,
297
- bindings.durable_objects?.bindings,
298
- bindings.kv_namespaces,
299
- bindings.vars,
300
- compatibilityDate,
301
- compatibilityFlags,
302
- localPersistencePath,
303
- assetPaths,
304
- publicDirectory,
305
- rules,
306
- bindings.wasm_modules,
307
- bindings.text_blobs,
308
- bindings.data_blobs,
309
- crons,
310
- ]);
311
- return { inspectorUrl };
312
- }
@@ -1,213 +0,0 @@
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
- logger.error("Error on remote worker:", err);
189
- }
190
- });
191
-
192
- return () => {
193
- abortController.abort();
194
- };
195
- }, [
196
- name,
197
- bundle,
198
- format,
199
- accountId,
200
- apiToken,
201
- port,
202
- assetPaths,
203
- compatibilityDate,
204
- compatibilityFlags,
205
- usageModel,
206
- bindings,
207
- modules,
208
- props.env,
209
- props.legacyEnv,
210
- props.zone,
211
- ]);
212
- return token;
213
- }
@@ -1,118 +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
- 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
- }