wrangler 0.0.0-ece06ea → 0.0.0-ed08df4

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 (121) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +34 -2
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +71 -36
  6. package/pages/functions/buildPlugin.ts +92 -0
  7. package/pages/functions/buildWorker.ts +138 -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 +3125 -0
  16. package/src/__tests__/dev.test.tsx +829 -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 +90 -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 +221 -132
  38. package/src/__tests__/init.test.ts +1516 -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 +206 -0
  43. package/src/__tests__/pages.test.ts +327 -0
  44. package/src/__tests__/parse.test.ts +326 -0
  45. package/src/__tests__/publish.test.ts +4996 -0
  46. package/src/__tests__/r2.test.ts +210 -0
  47. package/src/__tests__/route.test.ts +45 -0
  48. package/src/__tests__/secret.test.ts +446 -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/bundle.ts +169 -0
  53. package/src/cfetch/index.ts +104 -0
  54. package/src/cfetch/internal.ts +140 -0
  55. package/src/cli.ts +10 -7
  56. package/src/config/README.md +107 -0
  57. package/src/config/config.ts +234 -0
  58. package/src/config/diagnostics.ts +80 -0
  59. package/src/config/environment.ts +394 -0
  60. package/src/config/index.ts +63 -0
  61. package/src/config/validation-helpers.ts +575 -0
  62. package/src/config/validation.ts +1424 -0
  63. package/src/config-cache.ts +45 -0
  64. package/src/create-worker-preview.ts +175 -0
  65. package/src/create-worker-upload-form.ts +240 -0
  66. package/src/dev/dev-vars.ts +36 -0
  67. package/src/dev/dev.tsx +421 -0
  68. package/src/dev/local.tsx +312 -0
  69. package/src/dev/remote.tsx +213 -0
  70. package/src/dev/use-esbuild.ts +118 -0
  71. package/src/dialogs.tsx +22 -20
  72. package/src/entry.ts +322 -0
  73. package/src/environment-variables.ts +35 -0
  74. package/src/errors.ts +11 -0
  75. package/src/https-options.ts +123 -0
  76. package/src/index.tsx +1869 -1020
  77. package/src/inspect.ts +623 -0
  78. package/src/intl-polyfill.d.ts +139 -0
  79. package/src/kv.ts +344 -0
  80. package/src/logger.ts +66 -0
  81. package/src/miniflare-cli/README.md +30 -0
  82. package/src/miniflare-cli/enum-keys.ts +17 -0
  83. package/src/miniflare-cli/index.ts +41 -0
  84. package/src/miniflare-cli/request-context.ts +40 -0
  85. package/src/module-collection.ts +258 -0
  86. package/src/open-in-browser.ts +26 -0
  87. package/src/package-manager.ts +127 -0
  88. package/src/pages.tsx +1756 -218
  89. package/src/parse.ts +185 -0
  90. package/src/paths.ts +26 -0
  91. package/src/proxy.ts +449 -0
  92. package/src/publish.ts +377 -262
  93. package/src/r2.ts +50 -0
  94. package/src/selfsigned.d.ts +29 -0
  95. package/src/sites.tsx +237 -59
  96. package/src/tail/filters.ts +279 -0
  97. package/src/tail/index.ts +299 -0
  98. package/src/tail/printing.ts +67 -0
  99. package/src/update-check.ts +19 -0
  100. package/src/user.tsx +395 -221
  101. package/src/whoami.tsx +70 -0
  102. package/src/worker.ts +172 -0
  103. package/templates/gitignore +171 -0
  104. package/templates/new-worker.js +15 -0
  105. package/templates/new-worker.ts +15 -0
  106. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  107. package/templates/tsconfig.json +105 -0
  108. package/wrangler-dist/cli.js +108921 -132528
  109. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  110. package/src/__tests__/mock-cfetch.js +0 -46
  111. package/src/api/form_data.ts +0 -158
  112. package/src/api/inspect.ts +0 -441
  113. package/src/api/preview.ts +0 -123
  114. package/src/api/worker.ts +0 -161
  115. package/src/cfetch.ts +0 -72
  116. package/src/config.ts +0 -124
  117. package/src/dev.tsx +0 -736
  118. package/src/kv.tsx +0 -211
  119. package/src/tail.tsx +0 -71
  120. package/src/util/fetch.ts +0 -74
  121. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,421 @@
1
+ import { spawn } from "node:child_process";
2
+ import * as path from "node:path";
3
+ import { watch } from "chokidar";
4
+ import clipboardy from "clipboardy";
5
+ import commandExists from "command-exists";
6
+ import { Box, Text, useApp, useInput, useStdin } from "ink";
7
+ import React, { useState, useEffect, useRef } from "react";
8
+ import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
9
+ import onExit from "signal-exit";
10
+ import tmp from "tmp-promise";
11
+ import { fetch } from "undici";
12
+ import { runCustomBuild } from "../entry";
13
+ import { logger } from "../logger";
14
+ import openInBrowser from "../open-in-browser";
15
+ import { getAPIToken } from "../user";
16
+ import { Local } from "./local";
17
+ import { Remote } from "./remote";
18
+ import { useEsbuild } from "./use-esbuild";
19
+ import type { Config } from "../config";
20
+ import type { Entry } from "../entry";
21
+ import type { AssetPaths } from "../sites";
22
+ import type { CfWorkerInit } from "../worker";
23
+ import type { EsbuildBundle } from "./use-esbuild";
24
+
25
+ export type DevProps = {
26
+ name?: string;
27
+ entry: Entry;
28
+ port: number;
29
+ ip: string;
30
+ inspectorPort: number;
31
+ rules: Config["rules"];
32
+ accountId: string | undefined;
33
+ initialMode: "local" | "remote";
34
+ jsxFactory: string | undefined;
35
+ jsxFragment: string | undefined;
36
+ tsconfig: string | undefined;
37
+ upstreamProtocol: "https" | "http";
38
+ localProtocol: "https" | "http";
39
+ enableLocalPersistence: boolean;
40
+ bindings: CfWorkerInit["bindings"];
41
+ crons: Config["triggers"]["crons"];
42
+ public: string | undefined;
43
+ assetPaths: AssetPaths | undefined;
44
+ compatibilityDate: string;
45
+ compatibilityFlags: string[] | undefined;
46
+ usageModel: "bundled" | "unbound" | undefined;
47
+ minify: boolean | undefined;
48
+ nodeCompat: boolean | undefined;
49
+ build: {
50
+ command?: string | undefined;
51
+ cwd?: string | undefined;
52
+ watch_dir?: string | undefined;
53
+ };
54
+ env: string | undefined;
55
+ legacyEnv: boolean;
56
+ zone:
57
+ | {
58
+ id: string;
59
+ host: string;
60
+ }
61
+ | undefined;
62
+ };
63
+
64
+ export function DevImplementation(props: DevProps): JSX.Element {
65
+ const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
66
+ const directory = useTmpDir();
67
+
68
+ useCustomBuild(props.entry, props.build);
69
+
70
+ if (props.public && props.entry.format === "service-worker") {
71
+ throw new Error(
72
+ "You cannot use the service-worker format with a `public` directory."
73
+ );
74
+ }
75
+
76
+ if (props.bindings.wasm_modules && props.entry.format === "modules") {
77
+ throw new Error(
78
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
79
+ );
80
+ }
81
+
82
+ if (props.bindings.text_blobs && props.entry.format === "modules") {
83
+ throw new Error(
84
+ "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
85
+ );
86
+ }
87
+
88
+ if (props.bindings.data_blobs && props.entry.format === "modules") {
89
+ throw new Error(
90
+ "You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
91
+ );
92
+ }
93
+
94
+ const bundle = useEsbuild({
95
+ entry: props.entry,
96
+ destination: directory,
97
+ staticRoot: props.public,
98
+ jsxFactory: props.jsxFactory,
99
+ rules: props.rules,
100
+ jsxFragment: props.jsxFragment,
101
+ serveAssetsFromWorker: !!props.public,
102
+ tsconfig: props.tsconfig,
103
+ minify: props.minify,
104
+ nodeCompat: props.nodeCompat,
105
+ });
106
+
107
+ // only load the UI if we're running in a supported environment
108
+ const { isRawModeSupported } = useStdin();
109
+ return isRawModeSupported ? (
110
+ <InteractiveDevSession {...props} bundle={bundle} apiToken={apiToken} />
111
+ ) : (
112
+ <DevSession
113
+ {...props}
114
+ bundle={bundle}
115
+ apiToken={apiToken}
116
+ local={props.initialMode === "local"}
117
+ />
118
+ );
119
+ }
120
+
121
+ type InteractiveDevSessionProps = DevProps & {
122
+ apiToken: string | undefined;
123
+ bundle: EsbuildBundle | undefined;
124
+ };
125
+
126
+ function InteractiveDevSession(props: InteractiveDevSessionProps) {
127
+ const toggles = useHotkeys(
128
+ {
129
+ local: props.initialMode === "local",
130
+ tunnel: false,
131
+ },
132
+ props.port,
133
+ props.ip,
134
+ props.inspectorPort,
135
+ props.localProtocol
136
+ );
137
+
138
+ useTunnel(toggles.tunnel);
139
+
140
+ return (
141
+ <>
142
+ <DevSession {...props} local={toggles.local} />
143
+ <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
144
+ <Text bold={true}>[b]</Text>
145
+ <Text> open a browser, </Text>
146
+ <Text bold={true}>[d]</Text>
147
+ <Text> open Devtools, </Text>
148
+ <Text bold={true}>[l]</Text>
149
+ <Text> {toggles.local ? "turn off" : "turn on"} local mode, </Text>
150
+ <Text bold={true}>[c]</Text>
151
+ <Text> clear console, </Text>
152
+ <Text bold={true}>[x]</Text>
153
+ <Text> to exit</Text>
154
+ </Box>
155
+ </>
156
+ );
157
+ }
158
+
159
+ type DevSessionProps = InteractiveDevSessionProps & { local: boolean };
160
+
161
+ function DevSession(props: DevSessionProps) {
162
+ return props.local ? (
163
+ <Local
164
+ name={props.name}
165
+ bundle={props.bundle}
166
+ format={props.entry.format}
167
+ compatibilityDate={props.compatibilityDate}
168
+ compatibilityFlags={props.compatibilityFlags}
169
+ bindings={props.bindings}
170
+ assetPaths={props.assetPaths}
171
+ public={props.public}
172
+ port={props.port}
173
+ ip={props.ip}
174
+ rules={props.rules}
175
+ inspectorPort={props.inspectorPort}
176
+ enableLocalPersistence={props.enableLocalPersistence}
177
+ crons={props.crons}
178
+ />
179
+ ) : (
180
+ <Remote
181
+ name={props.name}
182
+ bundle={props.bundle}
183
+ format={props.entry.format}
184
+ accountId={props.accountId}
185
+ apiToken={props.apiToken}
186
+ bindings={props.bindings}
187
+ assetPaths={props.assetPaths}
188
+ public={props.public}
189
+ port={props.port}
190
+ ip={props.ip}
191
+ localProtocol={props.localProtocol}
192
+ inspectorPort={props.inspectorPort}
193
+ compatibilityDate={props.compatibilityDate}
194
+ compatibilityFlags={props.compatibilityFlags}
195
+ usageModel={props.usageModel}
196
+ env={props.env}
197
+ legacyEnv={props.legacyEnv}
198
+ zone={props.zone}
199
+ />
200
+ );
201
+ }
202
+
203
+ export interface DirectorySyncResult {
204
+ name: string;
205
+ removeCallback: () => void;
206
+ }
207
+
208
+ function useTmpDir(): string | undefined {
209
+ const [directory, setDirectory] = useState<DirectorySyncResult>();
210
+ const handleError = useErrorHandler();
211
+ useEffect(() => {
212
+ let dir: DirectorySyncResult | undefined;
213
+ try {
214
+ dir = tmp.dirSync({ unsafeCleanup: true });
215
+ setDirectory(dir);
216
+ return;
217
+ } catch (err) {
218
+ logger.error(
219
+ "Failed to create temporary directory to store built files."
220
+ );
221
+ handleError(err);
222
+ }
223
+ return () => {
224
+ dir?.removeCallback();
225
+ };
226
+ }, [handleError]);
227
+ return directory?.name;
228
+ }
229
+
230
+ function useCustomBuild(
231
+ expectedEntry: Entry,
232
+ build: {
233
+ command?: string | undefined;
234
+ cwd?: string | undefined;
235
+ watch_dir?: string | undefined;
236
+ }
237
+ ): void {
238
+ useEffect(() => {
239
+ if (!build.command) return;
240
+ let watcher: ReturnType<typeof watch> | undefined;
241
+ if (build.watch_dir) {
242
+ watcher = watch(build.watch_dir, {
243
+ persistent: true,
244
+ ignoreInitial: true,
245
+ }).on("all", (_event, filePath) => {
246
+ const relativeFile =
247
+ path.relative(expectedEntry.directory, expectedEntry.file) || ".";
248
+ //TODO: we should buffer requests to the proxy until this completes
249
+ logger.log(`The file ${filePath} changed, restarting build...`);
250
+ runCustomBuild(expectedEntry.file, relativeFile, build).catch((err) => {
251
+ logger.error("Custom build failed:", err);
252
+ });
253
+ });
254
+ }
255
+
256
+ return () => {
257
+ watcher?.close();
258
+ };
259
+ }, [build, expectedEntry]);
260
+ }
261
+
262
+ function sleep(period: number) {
263
+ return new Promise((resolve) => setTimeout(resolve, period));
264
+ }
265
+ const SLEEP_DURATION = 2000;
266
+ // really need a first class api for this
267
+ const hostNameRegex = /userHostname="(.*)"/g;
268
+ async function findTunnelHostname() {
269
+ let hostName: string | undefined;
270
+ while (!hostName) {
271
+ try {
272
+ const resp = await fetch("http://localhost:8789/metrics");
273
+ const data = await resp.text();
274
+ const matches = Array.from(data.matchAll(hostNameRegex));
275
+ hostName = matches[0][1];
276
+ } catch (err) {
277
+ await sleep(SLEEP_DURATION);
278
+ }
279
+ }
280
+ return hostName;
281
+ }
282
+
283
+ /**
284
+ * Create a tunnel to the remote worker.
285
+ * We've disabled this for now until we figure out a better user experience.
286
+ */
287
+ function useTunnel(toggle: boolean) {
288
+ const tunnel = useRef<ReturnType<typeof spawn>>();
289
+ const removeSignalExitListener = useRef<() => void>();
290
+ // TODO: test if cloudflared is available, if not
291
+ // point them to a url where they can get docs to install it
292
+ useEffect(() => {
293
+ async function startTunnel() {
294
+ if (toggle) {
295
+ try {
296
+ await commandExists("cloudflared");
297
+ } catch (e) {
298
+ logger.warn(
299
+ "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
300
+ );
301
+ return;
302
+ }
303
+ logger.log("⎔ Starting a tunnel...");
304
+ tunnel.current = spawn("cloudflared", [
305
+ "tunnel",
306
+ "--url",
307
+ "http://localhost:8787",
308
+ "--metrics",
309
+ "localhost:8789",
310
+ ]);
311
+
312
+ tunnel.current.on("close", (code) => {
313
+ if (code) {
314
+ logger.log(`Tunnel process exited with code ${code}`);
315
+ }
316
+ });
317
+
318
+ removeSignalExitListener.current = onExit((_code, _signal) => {
319
+ logger.log("⎔ Shutting down local tunnel.");
320
+ tunnel.current?.kill();
321
+ tunnel.current = undefined;
322
+ });
323
+
324
+ const hostName = await findTunnelHostname();
325
+ await clipboardy.write(hostName);
326
+ logger.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
327
+ }
328
+ }
329
+
330
+ startTunnel().catch(async (err) => {
331
+ logger.error("tunnel:", err);
332
+ });
333
+
334
+ return () => {
335
+ if (tunnel.current) {
336
+ logger.log("⎔ Shutting down tunnel.");
337
+ tunnel.current?.kill();
338
+ tunnel.current = undefined;
339
+ removeSignalExitListener.current && removeSignalExitListener.current();
340
+ removeSignalExitListener.current = undefined;
341
+ }
342
+ };
343
+ }, [toggle]);
344
+ }
345
+
346
+ type useHotkeysInitialState = {
347
+ local: boolean;
348
+ tunnel: boolean;
349
+ };
350
+ function useHotkeys(
351
+ initial: useHotkeysInitialState,
352
+ port: number,
353
+ ip: string,
354
+ inspectorPort: number,
355
+ localProtocol: "http" | "https"
356
+ ) {
357
+ // UGH, we should put port in context instead
358
+ const [toggles, setToggles] = useState(initial);
359
+ const { exit } = useApp();
360
+ useInput(
361
+ async (
362
+ input,
363
+ // eslint-disable-next-line unused-imports/no-unused-vars
364
+ key
365
+ ) => {
366
+ switch (input.toLowerCase()) {
367
+ // clear console
368
+ case "c":
369
+ console.clear();
370
+ // This console.log causes Ink to re-render the `DevSession` component.
371
+ // Couldn't find a better way to tell it to do so...
372
+ console.log();
373
+ break;
374
+ // open browser
375
+ case "b": {
376
+ await openInBrowser(`${localProtocol}://${ip}:${port}`);
377
+ break;
378
+ }
379
+ // toggle inspector
380
+ case "d": {
381
+ await openInBrowser(
382
+ `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`,
383
+ { forceChromium: true }
384
+ );
385
+ break;
386
+ }
387
+ // toggle local
388
+ case "l":
389
+ setToggles((previousToggles) => ({
390
+ ...previousToggles,
391
+ local: !previousToggles.local,
392
+ }));
393
+ break;
394
+ // shut down
395
+ case "q":
396
+ case "x":
397
+ exit();
398
+ break;
399
+ default:
400
+ // nothing?
401
+ break;
402
+ }
403
+ }
404
+ );
405
+ return toggles;
406
+ }
407
+
408
+ function ErrorFallback(props: { error: Error }) {
409
+ const { exit } = useApp();
410
+ useEffect(() => exit(props.error));
411
+ return (
412
+ <>
413
+ <Text>Something went wrong:</Text>
414
+ <Text>{props.error.stack}</Text>
415
+ </>
416
+ );
417
+ }
418
+
419
+ export default withErrorBoundary(DevImplementation, {
420
+ FallbackComponent: ErrorFallback,
421
+ });