wrangler 0.0.0-e98613f8 → 0.0.0-e9a45766c

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 (244) hide show
  1. package/README.md +10 -4
  2. package/bin/wrangler.js +10 -2
  3. package/miniflare-dist/index.mjs +257 -132
  4. package/package.json +26 -19
  5. package/src/__tests__/api-dev.test.ts +65 -36
  6. package/src/__tests__/api-devregistry.test.ts +121 -0
  7. package/src/__tests__/api.test.ts +27 -5
  8. package/src/__tests__/configuration.test.ts +575 -39
  9. package/src/__tests__/constellation.test.ts +371 -0
  10. package/src/__tests__/d1/d1.test.ts +82 -0
  11. package/src/__tests__/d1/execute.test.ts +66 -0
  12. package/src/__tests__/d1/migrate.test.ts +257 -0
  13. package/src/__tests__/d1/splitter.test.ts +255 -0
  14. package/src/__tests__/delete.test.ts +11 -2
  15. package/src/__tests__/deployments.test.ts +330 -52
  16. package/src/__tests__/dev.test.tsx +146 -82
  17. package/src/__tests__/generate.test.ts +10 -8
  18. package/src/__tests__/guess-worker-format.test.ts +35 -0
  19. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  20. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  21. package/src/__tests__/helpers/mock-console.ts +6 -0
  22. package/src/__tests__/helpers/mock-dialogs.ts +71 -85
  23. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  24. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -5
  25. package/src/__tests__/helpers/mock-known-routes.ts +7 -2
  26. package/src/__tests__/helpers/mock-kv.ts +29 -16
  27. package/src/__tests__/helpers/mock-oauth-flow.ts +99 -92
  28. package/src/__tests__/helpers/mock-process.ts +8 -13
  29. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  30. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  31. package/src/__tests__/helpers/msw/handlers/deployments.ts +127 -26
  32. package/src/__tests__/helpers/msw/handlers/namespaces.ts +18 -41
  33. package/src/__tests__/helpers/msw/handlers/r2.ts +14 -34
  34. package/src/__tests__/helpers/msw/handlers/script.ts +9 -28
  35. package/src/__tests__/helpers/msw/handlers/user.ts +13 -24
  36. package/src/__tests__/helpers/msw/handlers/zones.ts +6 -8
  37. package/src/__tests__/helpers/msw/index.ts +32 -1
  38. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  39. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  40. package/src/__tests__/helpers/worker-scripts/parent-worker.js +4 -1
  41. package/src/__tests__/index.test.ts +92 -74
  42. package/src/__tests__/init.test.ts +909 -628
  43. package/src/__tests__/jest.setup.ts +19 -42
  44. package/src/__tests__/kv.test.ts +355 -231
  45. package/src/__tests__/logger.test.ts +68 -2
  46. package/src/__tests__/logout.test.ts +1 -1
  47. package/src/__tests__/metrics.test.ts +93 -50
  48. package/src/__tests__/middleware.scheduled.test.ts +42 -32
  49. package/src/__tests__/middleware.test.ts +212 -122
  50. package/src/__tests__/mtls-certificates.test.ts +589 -0
  51. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  52. package/src/__tests__/pages/functions-build.test.ts +528 -0
  53. package/src/__tests__/pages/pages.test.ts +81 -0
  54. package/src/__tests__/pages/project-create.test.ts +63 -0
  55. package/src/__tests__/pages/project-list.test.ts +110 -0
  56. package/src/__tests__/pages/project-upload.test.ts +500 -0
  57. package/src/__tests__/pages/publish.test.ts +2864 -0
  58. package/src/__tests__/pages-deployment-tail.test.ts +239 -102
  59. package/src/__tests__/parse.test.ts +106 -0
  60. package/src/__tests__/publish.test.ts +2218 -1002
  61. package/src/__tests__/pubsub.test.ts +226 -100
  62. package/src/__tests__/queues.test.ts +42 -32
  63. package/src/__tests__/r2.test.ts +37 -56
  64. package/src/__tests__/secret.test.ts +179 -130
  65. package/src/__tests__/tail.test.ts +113 -23
  66. package/src/__tests__/test-old-node-version.js +3 -3
  67. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  68. package/src/__tests__/tsconfig-sanity.ts +12 -0
  69. package/src/__tests__/tsconfig.json +8 -0
  70. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  71. package/src/__tests__/type-generation.test.ts +8 -0
  72. package/src/__tests__/user.test.ts +7 -18
  73. package/src/__tests__/whoami.test.tsx +8 -114
  74. package/src/__tests__/worker-namespace.test.ts +83 -69
  75. package/src/api/dev.ts +172 -61
  76. package/src/api/index.ts +10 -1
  77. package/src/api/mtls-certificate.ts +148 -0
  78. package/src/api/pages/create-worker-bundle-contents.ts +77 -0
  79. package/src/api/pages/index.ts +5 -0
  80. package/src/api/pages/publish.tsx +371 -0
  81. package/src/bundle.ts +139 -33
  82. package/src/cfetch/index.ts +0 -2
  83. package/src/cfetch/internal.ts +16 -21
  84. package/src/cli.ts +4 -4
  85. package/src/config/config.ts +14 -7
  86. package/src/config/environment.ts +80 -16
  87. package/src/config/index.ts +99 -30
  88. package/src/config/validation-helpers.ts +1 -1
  89. package/src/config/validation.ts +275 -9
  90. package/src/constellation/createProject.tsx +51 -0
  91. package/src/constellation/deleteProject.ts +51 -0
  92. package/src/constellation/deleteProjectModel.ts +68 -0
  93. package/src/constellation/index.ts +75 -0
  94. package/src/constellation/listCatalog.tsx +35 -0
  95. package/src/constellation/listModel.tsx +41 -0
  96. package/src/constellation/listProject.tsx +28 -0
  97. package/src/constellation/listRuntime.tsx +28 -0
  98. package/src/constellation/options.ts +17 -0
  99. package/src/constellation/types.ts +17 -0
  100. package/src/constellation/uploadModel.tsx +64 -0
  101. package/src/constellation/utils.ts +90 -0
  102. package/src/create-worker-preview.ts +19 -8
  103. package/src/create-worker-upload-form.ts +52 -5
  104. package/src/d1/backups.tsx +40 -44
  105. package/src/d1/create.tsx +50 -43
  106. package/src/d1/{delete.tsx → delete.ts} +8 -11
  107. package/src/d1/execute.tsx +171 -166
  108. package/src/d1/index.ts +5 -6
  109. package/src/d1/list.tsx +27 -13
  110. package/src/d1/migrations/apply.tsx +92 -64
  111. package/src/d1/migrations/create.tsx +31 -29
  112. package/src/d1/migrations/helpers.ts +66 -44
  113. package/src/d1/migrations/list.tsx +47 -31
  114. package/src/d1/migrations/options.ts +7 -2
  115. package/src/d1/options.ts +3 -3
  116. package/src/d1/splitter.ts +161 -0
  117. package/src/d1/{types.tsx → types.ts} +1 -0
  118. package/src/d1/utils.ts +2 -1
  119. package/src/delete.ts +8 -16
  120. package/src/deployments.ts +333 -42
  121. package/src/deprecated/index.ts +8 -302
  122. package/src/dev/dev.tsx +13 -22
  123. package/src/dev/local.tsx +131 -69
  124. package/src/dev/remote.tsx +35 -3
  125. package/src/dev/start-server.ts +83 -77
  126. package/src/dev/use-esbuild.ts +63 -52
  127. package/src/dev/validate-dev-props.ts +9 -0
  128. package/src/{dev-registry.tsx → dev-registry.ts} +9 -8
  129. package/src/dev.tsx +131 -110
  130. package/src/dialogs.ts +136 -0
  131. package/src/dispatch-namespace.ts +21 -17
  132. package/src/docs/helpers.ts +50 -0
  133. package/src/docs/index.ts +54 -0
  134. package/src/entry.ts +26 -11
  135. package/src/environment-variables/factory.ts +89 -0
  136. package/src/environment-variables/misc-variables.ts +30 -0
  137. package/src/generate/index.ts +298 -0
  138. package/src/{index.tsx → index.ts} +137 -56
  139. package/src/init.ts +254 -187
  140. package/src/inspect.ts +170 -9
  141. package/src/jest.d.ts +4 -0
  142. package/src/kv/helpers.ts +7 -4
  143. package/src/kv/index.ts +15 -17
  144. package/src/logger.ts +36 -5
  145. package/src/metrics/metrics-config.ts +1 -1
  146. package/src/metrics/send-event.ts +4 -1
  147. package/src/miniflare-cli/assets.ts +66 -31
  148. package/src/miniflare-cli/index.ts +5 -8
  149. package/src/miniflare-cli/tsconfig.json +9 -0
  150. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  151. package/src/miniflare-cli/types.ts +11 -0
  152. package/src/module-collection.ts +92 -26
  153. package/src/mtls-certificate/cli.ts +155 -0
  154. package/src/pages/build.ts +423 -0
  155. package/src/pages/buildFunctions.ts +140 -0
  156. package/src/pages/{deployment-tails.tsx → deployment-tails.ts} +7 -10
  157. package/src/pages/deployments.tsx +9 -9
  158. package/src/pages/{dev.tsx → dev.ts} +167 -139
  159. package/src/pages/errors.ts +1 -0
  160. package/src/pages/functions/buildPlugin.ts +61 -54
  161. package/src/pages/functions/buildWorker.ts +217 -33
  162. package/src/pages/functions/tsconfig.json +8 -0
  163. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  164. package/src/pages/{functions.tsx → functions.ts} +8 -4
  165. package/src/pages/{index.tsx → index.ts} +3 -3
  166. package/src/pages/projects.tsx +12 -22
  167. package/src/pages/publish.tsx +43 -227
  168. package/src/pages/types.ts +5 -0
  169. package/src/pages/upload.tsx +57 -14
  170. package/src/pages/utils.ts +1 -1
  171. package/src/parse.ts +23 -1
  172. package/src/paths.ts +1 -1
  173. package/src/publish/index.ts +20 -16
  174. package/src/publish/publish.ts +76 -46
  175. package/src/pubsub/{pubsub-commands.tsx → pubsub-commands.ts} +19 -20
  176. package/src/queues/cli/commands/consumer/add.ts +24 -24
  177. package/src/queues/cli/commands/consumer/index.ts +3 -6
  178. package/src/queues/cli/commands/consumer/remove.ts +11 -18
  179. package/src/queues/cli/commands/create.ts +8 -8
  180. package/src/queues/cli/commands/delete.ts +8 -8
  181. package/src/queues/cli/commands/index.ts +3 -4
  182. package/src/queues/cli/commands/list.ts +8 -8
  183. package/src/queues/client.ts +1 -0
  184. package/src/r2/helpers.ts +1 -0
  185. package/src/r2/index.ts +28 -28
  186. package/src/secret/index.ts +15 -16
  187. package/src/{sites.tsx → sites.ts} +165 -53
  188. package/src/tail/createTail.ts +37 -1
  189. package/src/tail/filters.ts +1 -1
  190. package/src/tail/index.ts +8 -11
  191. package/src/tail/printing.ts +25 -0
  192. package/src/traverse-module-graph.ts +54 -0
  193. package/src/tsconfig-sanity.ts +16 -0
  194. package/src/type-generation.ts +11 -3
  195. package/src/user/access.ts +0 -1
  196. package/src/user/auth-variables.ts +113 -0
  197. package/src/user/choose-account.tsx +1 -31
  198. package/src/user/index.ts +0 -1
  199. package/src/user/{user.tsx → user.ts} +114 -77
  200. package/src/utils/render.ts +93 -0
  201. package/src/{whoami.tsx → whoami.ts} +37 -71
  202. package/src/worker.ts +35 -1
  203. package/src/yargs-types.ts +18 -5
  204. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  205. package/templates/__tests__/tsconfig.json +8 -0
  206. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  207. package/templates/checked-fetch.js +9 -3
  208. package/templates/d1-beta-facade.js +42 -3
  209. package/templates/facade.d.ts +14 -0
  210. package/templates/first-party-worker-module-facade.ts +4 -3
  211. package/templates/format-dev-errors.ts +8 -6
  212. package/templates/gitignore +1 -0
  213. package/templates/init-tests/test-jest-new-worker.js +3 -5
  214. package/templates/init-tests/test-vitest-new-worker.js +3 -5
  215. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  216. package/templates/middleware/loader-modules.ts +2 -2
  217. package/templates/middleware/loader-sw.ts +6 -0
  218. package/templates/middleware/middleware-miniflare3-json-error.ts +17 -5
  219. package/templates/new-worker.ts +3 -0
  220. package/templates/pages-dev-pipeline.ts +4 -1
  221. package/templates/pages-shim.ts +4 -1
  222. package/templates/pages-template-plugin.ts +19 -10
  223. package/templates/serve-static-assets.ts +17 -14
  224. package/templates/service-bindings-module-facade.js +1 -0
  225. package/templates/tsconfig-sanity.ts +11 -0
  226. package/templates/tsconfig.init.json +105 -0
  227. package/templates/tsconfig.json +5 -103
  228. package/templates/tsconfig.tsbuildinfo +1 -0
  229. package/wrangler-dist/cli.d.ts +871 -73
  230. package/wrangler-dist/cli.js +80512 -90686
  231. package/wrangler-dist/wasm-sync.wasm +0 -0
  232. package/src/__tests__/api-devregistry.test.js +0 -56
  233. package/src/__tests__/d1.test.ts +0 -80
  234. package/src/__tests__/dialogs.test.tsx +0 -40
  235. package/src/__tests__/helpers/mock-cfetch.ts +0 -333
  236. package/src/__tests__/pages.test.ts +0 -2442
  237. package/src/dialogs.tsx +0 -168
  238. package/src/environment-variables.ts +0 -50
  239. package/src/pages/build.tsx +0 -270
  240. package/src/user/env-vars.ts +0 -46
  241. /package/src/{bundle-reporter.tsx → bundle-reporter.ts} +0 -0
  242. /package/src/d1/migrations/{index.tsx → index.ts} +0 -0
  243. /package/src/dev/{get-local-persistence-path.tsx → get-local-persistence-path.ts} +0 -0
  244. /package/src/pages/{hash.tsx → hash.ts} +0 -0
package/src/inspect.ts CHANGED
@@ -1,9 +1,10 @@
1
+ import { readFileSync } from "fs";
1
2
  import { readFile } from "fs/promises";
2
3
  import assert from "node:assert";
3
4
  import { createServer } from "node:http";
4
5
  import os from "node:os";
5
6
  import { URL } from "node:url";
6
-
7
+ import path from "path";
7
8
  import open from "open";
8
9
  import { useEffect, useRef, useState } from "react";
9
10
  import { SourceMapConsumer } from "source-map";
@@ -40,6 +41,13 @@ import type { MessageEvent } from "ws";
40
41
  * - handle more methods from console
41
42
  */
42
43
 
44
+ // Information about Wrangler's bundling process that needs passsed through
45
+ // for DevTools sourcemap transformation
46
+ export interface SourceMapMetadata {
47
+ tmpDir: string;
48
+ entryDirectory: string;
49
+ }
50
+
43
51
  interface InspectorProps {
44
52
  /**
45
53
  * The port that the local proxy server should listen on.
@@ -58,9 +66,53 @@ interface InspectorProps {
58
66
  /**
59
67
  * Sourcemap path, so that stacktraces can be interpretted
60
68
  */
61
- sourceMapPath?: string | undefined;
69
+ sourceMapPath: string | undefined;
70
+
71
+ sourceMapMetadata: SourceMapMetadata | undefined;
62
72
 
63
73
  host?: string;
74
+
75
+ name?: string;
76
+ }
77
+
78
+ const ALLOWED_HOST_HOSTNAMES = ["127.0.0.1", "[::1]", "localhost"];
79
+ const ALLOWED_ORIGIN_HOSTNAMES = [
80
+ "devtools.devprod.cloudflare.dev",
81
+ "cloudflare-devtools.pages.dev",
82
+ /^[a-z0-9]+\.cloudflare-devtools\.pages\.dev$/,
83
+ "127.0.0.1",
84
+ "[::1]",
85
+ "localhost",
86
+ ];
87
+ function validateWebSocketHandshake(req: IncomingMessage) {
88
+ // Validate `Host` header
89
+ const hostHeader = req.headers.host;
90
+ if (hostHeader == null) return false;
91
+ try {
92
+ const host = new URL(`http://${hostHeader}`);
93
+ if (!ALLOWED_HOST_HOSTNAMES.includes(host.hostname)) return false;
94
+ } catch {
95
+ return false;
96
+ }
97
+ // Validate `Origin` header
98
+ let originHeader = req.headers.origin;
99
+ if (originHeader === null && req.headers["user-agent"] === undefined) {
100
+ // VSCode doesn't send an `Origin` header, but also doesn't send a
101
+ // `User-Agent` header, so allow an empty origin in this case.
102
+ originHeader = "http://localhost";
103
+ }
104
+ if (originHeader == null) return false;
105
+ try {
106
+ const origin = new URL(originHeader);
107
+ const allowed = ALLOWED_ORIGIN_HOSTNAMES.some((rule) => {
108
+ if (typeof rule === "string") return origin.hostname === rule;
109
+ else return rule.test(origin.hostname);
110
+ });
111
+ if (!allowed) return false;
112
+ } catch {
113
+ return false;
114
+ }
115
+ return true;
64
116
  }
65
117
 
66
118
  export default function useInspector(props: InspectorProps) {
@@ -98,7 +150,7 @@ export default function useInspector(props: InspectorProps) {
98
150
  case "/json/list":
99
151
  {
100
152
  res.setHeader("Content-Type", "application/json");
101
- const localHost = `localhost:${props.port}/ws`;
153
+ const localHost = `127.0.0.1:${props.port}/ws`;
102
154
  const devtoolsFrontendUrl = `devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=${localHost}`;
103
155
  const devtoolsFrontendUrlCompat = `devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=${localHost}`;
104
156
  res.end(
@@ -143,7 +195,12 @@ export default function useInspector(props: InspectorProps) {
143
195
  }
144
196
  const wsServer = wsServerRef.current;
145
197
 
146
- wsServer.on("connection", (ws: WebSocket) => {
198
+ wsServer.on("connection", (ws: WebSocket, req: IncomingMessage) => {
199
+ if (!validateWebSocketHandshake(req)) {
200
+ ws.close(1008, "Unauthorised");
201
+ return;
202
+ }
203
+
147
204
  if (wsServer.clients.size > 1) {
148
205
  /** We only want to have one active Devtools instance at a time. */
149
206
  logger.error(
@@ -151,6 +208,18 @@ export default function useInspector(props: InspectorProps) {
151
208
  );
152
209
  ws.close(1013, "Too many clients; only one can be connected at a time");
153
210
  } else {
211
+ // Since Wrangler proxies the inspector, reloading Chrome DevTools won't trigger debugger initialisation events (because it's connecting to an extant session).
212
+ // This sends a `Debugger.disable` message to the remote when a new WebSocket connection is initialised,
213
+ // with the assumption that the new connection will shortly send a `Debugger.enable` event and trigger re-initialisation.
214
+ // The key initialisation messages that are needed are the `Debugger.scriptParsed events`.
215
+ remoteWebSocket?.send(
216
+ JSON.stringify({
217
+ // This number is arbitrary, and is chosen to be high so as not to conflict with messages that DevTools might actually send.
218
+ // For completeness, these options don't work: 0, -1, or Number.MAX_SAFE_INTEGER
219
+ id: 100_000_000,
220
+ method: "Debugger.disable",
221
+ })
222
+ );
154
223
  // As promised, save the created websocket in a state hook
155
224
  setLocalWebSocket(ws);
156
225
 
@@ -173,7 +242,7 @@ export default function useInspector(props: InspectorProps) {
173
242
  timeout: 2000,
174
243
  abortSignal: abortController.signal,
175
244
  });
176
- server.listen(props.port);
245
+ server.listen(props.port, "127.0.0.1");
177
246
  }
178
247
  startInspectorProxy().catch((err) => {
179
248
  if ((err as { code: string }).code !== "ABORT_ERR") {
@@ -481,6 +550,65 @@ export default function useInspector(props: InspectorProps) {
481
550
 
482
551
  /** Send a message from the local websocket to the remote websocket */
483
552
  function sendMessageToRemoteWebSocket(event: MessageEvent) {
553
+ try {
554
+ // Intercept Network.loadNetworkResource to load sourcemaps
555
+ const message = JSON.parse(event.data as string);
556
+ if (
557
+ message.method === "Network.loadNetworkResource" &&
558
+ props.sourceMapPath !== undefined &&
559
+ props.sourceMapMetadata !== undefined
560
+ ) {
561
+ // Read the generated source map from esbuild
562
+ const sourceMap = JSON.parse(
563
+ readFileSync(props.sourceMapPath, "utf-8")
564
+ );
565
+
566
+ // The source root is a temporary directory (`tmpDir`), and so shouldn't be user-visible
567
+ // It provides no useful info to the user
568
+ sourceMap.sourceRoot = "";
569
+
570
+ const tmpDir = props.sourceMapMetadata.tmpDir;
571
+
572
+ // See https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.mt2g20loc2ct
573
+ // The above link documents the x_google_ignoreList property, which is intended to mark code that shouldn't be visible in DevTools
574
+ // Here we use it to indicate specifically Wrangler-injected code (facades & middleware)
575
+ sourceMap.x_google_ignoreList = sourceMap.sources
576
+ // Filter anything in the generated tmpDir, and anything from Wrangler's templates
577
+ // This should cover facades and middleware, but intentionally doesn't include all non-user code e.g. node_modules
578
+ .map((s: string, idx: number) =>
579
+ s.includes(tmpDir) || s.includes("wrangler/templates")
580
+ ? idx
581
+ : null
582
+ )
583
+ .filter((i: number | null) => i !== null);
584
+
585
+ const entryDirectory = props.sourceMapMetadata.entryDirectory;
586
+
587
+ sourceMap.sources = sourceMap.sources.map(
588
+ (s: string) =>
589
+ // These are never loaded by Wrangler or DevTools. However, the presence of a scheme is required for DevTools to show the path as folders in the Sources view
590
+ // The scheme is intentially not the same as for the sourceMappingURL
591
+ // Without this difference in scheme, DevTools will not strip prefix `../` path elements from top level folders (../node_modules -> node_modules, for instance)
592
+ `worker://${props.name}/${path.relative(entryDirectory, s)}`
593
+ );
594
+
595
+ sendMessageToLocalWebSocket({
596
+ data: JSON.stringify({
597
+ id: message.id,
598
+ result: {
599
+ resource: {
600
+ success: true,
601
+ text: JSON.stringify(sourceMap),
602
+ },
603
+ },
604
+ }),
605
+ });
606
+ return;
607
+ }
608
+ } catch (e) {
609
+ logger.debug(e);
610
+ // Ignore errors, fallthrough to the remote inspector
611
+ }
484
612
  try {
485
613
  assert(
486
614
  remoteWebSocket,
@@ -505,11 +633,28 @@ export default function useInspector(props: InspectorProps) {
505
633
  }
506
634
 
507
635
  /** Send a message from the local websocket to the remote websocket */
508
- function sendMessageToLocalWebSocket(event: MessageEvent) {
636
+ function sendMessageToLocalWebSocket(event: Pick<MessageEvent, "data">) {
509
637
  assert(
510
638
  localWebSocket,
511
639
  "Trying to send a message to an undefined `localWebSocket`"
512
640
  );
641
+ try {
642
+ // Intercept Debugger.scriptParsed responses to inject URL schemes
643
+ const message = JSON.parse(event.data as string);
644
+ if (message.method === "Debugger.scriptParsed") {
645
+ // Add the worker:// scheme conditionally, since some module types already have schemes (e.g. wasm)
646
+ message.params.url = new URL(
647
+ message.params.url,
648
+ `worker://${props.name}`
649
+ ).href;
650
+ localWebSocket.send(JSON.stringify(message));
651
+ return;
652
+ }
653
+ } catch (e) {
654
+ logger.debug(e);
655
+ // Ignore errors, fallthrough to the local websocket
656
+ }
657
+
513
658
  localWebSocket.send(event.data);
514
659
  }
515
660
 
@@ -543,7 +688,13 @@ export default function useInspector(props: InspectorProps) {
543
688
  );
544
689
  }
545
690
  };
546
- }, [localWebSocket, remoteWebSocket]);
691
+ }, [
692
+ localWebSocket,
693
+ remoteWebSocket,
694
+ props.name,
695
+ props.sourceMapMetadata,
696
+ props.sourceMapPath,
697
+ ]);
547
698
  }
548
699
 
549
700
  // Credit: https://stackoverflow.com/a/2117523
@@ -732,8 +883,15 @@ function logConsoleMessage(evt: Protocol.Runtime.ConsoleAPICalledEvent): void {
732
883
  /**
733
884
  * Opens the chrome debugger
734
885
  */
735
- export const openInspector = async (inspectorPort: number) => {
736
- const url = `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`;
886
+ export const openInspector = async (
887
+ inspectorPort: number,
888
+ worker: string | undefined
889
+ ) => {
890
+ const query = new URLSearchParams();
891
+ query.set("theme", "systemPreferred");
892
+ query.set("ws", `127.0.0.1:${inspectorPort}/ws`);
893
+ if (worker) query.set("domain", worker);
894
+ const url = `https://devtools.devprod.cloudflare.dev/js_app?${query.toString()}`;
737
895
  const errorMessage =
738
896
  "Failed to open inspector.\nInspector depends on having a Chromium-based browser installed, maybe you need to install one?";
739
897
 
@@ -759,6 +917,9 @@ export const openInspector = async (inspectorPort: number) => {
759
917
  {
760
918
  name: open.apps.edge,
761
919
  },
920
+ {
921
+ name: open.apps.firefox,
922
+ },
762
923
  ],
763
924
  });
764
925
  childProcess.on("error", () => {
package/src/jest.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ declare global {
2
+ const jest: unknown;
3
+ }
4
+ export {};
package/src/kv/helpers.ts CHANGED
@@ -8,7 +8,7 @@ import type { Config } from "../config";
8
8
  const API_MAX = 10000;
9
9
  // The const below are halved from the API's true capacity to help avoid
10
10
  // hammering it with large requests.
11
- const BATCH_KEY_MAX = API_MAX / 2;
11
+ export const BATCH_KEY_MAX = API_MAX / 2;
12
12
 
13
13
  type KvArgs = {
14
14
  binding?: string;
@@ -256,7 +256,7 @@ export async function deleteKVKeyValue(
256
256
  /**
257
257
  * Formatter for converting e.g. 5328 --> 5,328
258
258
  */
259
- const formatNumber = new Intl.NumberFormat("en-US", {
259
+ export const formatNumber = new Intl.NumberFormat("en-US", {
260
260
  notation: "standard",
261
261
  }).format;
262
262
 
@@ -279,7 +279,8 @@ export async function putKVBulkKeyValue(
279
279
  accountId: string,
280
280
  namespaceId: string,
281
281
  keyValues: KeyValue[],
282
- quiet = false
282
+ quiet = false,
283
+ abortSignal?: AbortSignal
283
284
  ) {
284
285
  for (let index = 0; index < keyValues.length; index += BATCH_KEY_MAX) {
285
286
  if (!quiet && keyValues.length > BATCH_KEY_MAX) {
@@ -292,7 +293,9 @@ export async function putKVBulkKeyValue(
292
293
  method: "PUT",
293
294
  body: JSON.stringify(keyValues.slice(index, index + BATCH_KEY_MAX)),
294
295
  headers: { "Content-Type": "application/json" },
295
- }
296
+ },
297
+ undefined,
298
+ abortSignal
296
299
  );
297
300
  }
298
301
 
package/src/kv/index.ts CHANGED
@@ -25,12 +25,10 @@ import {
25
25
  putKVKeyValue,
26
26
  unexpectedKVKeyValueProps,
27
27
  } from "./helpers";
28
- import type { ConfigPath } from "../index";
29
- import type { CommonYargsOptions } from "../yargs-types";
28
+ import type { CommonYargsArgv } from "../yargs-types";
30
29
  import type { KeyValue } from "./helpers";
31
- import type { Argv } from "yargs";
32
30
 
33
- export const kvNamespace = (kvYargs: Argv<CommonYargsOptions>) => {
31
+ export function kvNamespace(kvYargs: CommonYargsArgv) {
34
32
  return kvYargs
35
33
  .command(
36
34
  "create <namespace>",
@@ -56,7 +54,7 @@ export const kvNamespace = (kvYargs: Argv<CommonYargsOptions>) => {
56
54
  );
57
55
  }
58
56
 
59
- const config = readConfig(args.config as ConfigPath, args);
57
+ const config = readConfig(args.config, args);
60
58
  if (!config.name) {
61
59
  logger.warn(
62
60
  "No configured name present, using `worker` as a prefix for the title"
@@ -94,9 +92,9 @@ export const kvNamespace = (kvYargs: Argv<CommonYargsOptions>) => {
94
92
  .command(
95
93
  "list",
96
94
  "Outputs a list of all KV namespaces associated with your account id.",
97
- {},
95
+ (listArgs) => listArgs,
98
96
  async (args) => {
99
- const config = readConfig(args.config as ConfigPath, args);
97
+ const config = readConfig(args.config, args);
100
98
 
101
99
  const accountId = await requireAuth(config);
102
100
 
@@ -133,7 +131,7 @@ export const kvNamespace = (kvYargs: Argv<CommonYargsOptions>) => {
133
131
  },
134
132
  async (args) => {
135
133
  await printWranglerBanner();
136
- const config = readConfig(args.config as ConfigPath, args);
134
+ const config = readConfig(args.config, args);
137
135
 
138
136
  let id;
139
137
  try {
@@ -172,9 +170,9 @@ export const kvNamespace = (kvYargs: Argv<CommonYargsOptions>) => {
172
170
  // TODO: delete the preview namespace as well?
173
171
  }
174
172
  );
175
- };
173
+ }
176
174
 
177
- export const kvKey = (kvYargs: Argv<CommonYargsOptions>) => {
175
+ export const kvKey = (kvYargs: CommonYargsArgv) => {
178
176
  return kvYargs
179
177
  .command(
180
178
  "put <key> [value]",
@@ -231,7 +229,7 @@ export const kvKey = (kvYargs: Argv<CommonYargsOptions>) => {
231
229
  },
232
230
  async ({ key, ttl, expiration, metadata, ...args }) => {
233
231
  await printWranglerBanner();
234
- const config = readConfig(args.config as ConfigPath, args);
232
+ const config = readConfig(args.config, args);
235
233
  const namespaceId = getKVNamespaceId(args, config);
236
234
  // One of `args.path` and `args.value` must be defined
237
235
  const value = args.path
@@ -297,7 +295,7 @@ export const kvKey = (kvYargs: Argv<CommonYargsOptions>) => {
297
295
  },
298
296
  async ({ prefix, ...args }) => {
299
297
  // TODO: support for limit+cursor (pagination)
300
- const config = readConfig(args.config as ConfigPath, args);
298
+ const config = readConfig(args.config, args);
301
299
  const namespaceId = getKVNamespaceId(args, config);
302
300
 
303
301
  const accountId = await requireAuth(config);
@@ -351,7 +349,7 @@ export const kvKey = (kvYargs: Argv<CommonYargsOptions>) => {
351
349
  });
352
350
  },
353
351
  async ({ key, ...args }) => {
354
- const config = readConfig(args.config as ConfigPath, args);
352
+ const config = readConfig(args.config, args);
355
353
  const namespaceId = getKVNamespaceId(args, config);
356
354
 
357
355
  const accountId = await requireAuth(config);
@@ -398,7 +396,7 @@ export const kvKey = (kvYargs: Argv<CommonYargsOptions>) => {
398
396
  },
399
397
  async ({ key, ...args }) => {
400
398
  await printWranglerBanner();
401
- const config = readConfig(args.config as ConfigPath, args);
399
+ const config = readConfig(args.config, args);
402
400
  const namespaceId = getKVNamespaceId(args, config);
403
401
 
404
402
  logger.log(`Deleting the key "${key}" on namespace ${namespaceId}.`);
@@ -413,7 +411,7 @@ export const kvKey = (kvYargs: Argv<CommonYargsOptions>) => {
413
411
  );
414
412
  };
415
413
 
416
- export const kvBulk = (kvYargs: Argv<CommonYargsOptions>) => {
414
+ export const kvBulk = (kvYargs: CommonYargsArgv) => {
417
415
  return kvYargs
418
416
  .command(
419
417
  "put <filename>",
@@ -447,7 +445,7 @@ export const kvBulk = (kvYargs: Argv<CommonYargsOptions>) => {
447
445
  // This could be made more efficient with a streaming parser/uploader
448
446
  // but we'll do that in the future if needed.
449
447
 
450
- const config = readConfig(args.config as ConfigPath, args);
448
+ const config = readConfig(args.config, args);
451
449
  const namespaceId = getKVNamespaceId(args, config);
452
450
  const content = parseJSON(readFileSync(filename), filename);
453
451
 
@@ -541,7 +539,7 @@ export const kvBulk = (kvYargs: Argv<CommonYargsOptions>) => {
541
539
  },
542
540
  async ({ filename, ...args }) => {
543
541
  await printWranglerBanner();
544
- const config = readConfig(args.config as ConfigPath, args);
542
+ const config = readConfig(args.config, args);
545
543
  const namespaceId = getKVNamespaceId(args, config);
546
544
 
547
545
  if (!args.force) {
package/src/logger.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { format } from "node:util";
2
+ import chalk from "chalk";
3
+ import CLITable from "cli-table3";
2
4
  import { formatMessagesSync } from "esbuild";
3
- import { getEnvironmentVariableFactory } from "./environment-variables";
5
+ import { getEnvironmentVariableFactory } from "./environment-variables/factory";
4
6
  import type { BuildFailure } from "esbuild";
5
-
6
7
  export const LOGGER_LEVELS = {
7
8
  none: -1,
8
9
  error: 0,
@@ -25,13 +26,30 @@ const LOGGER_LEVEL_FORMAT_TYPE_MAP = {
25
26
 
26
27
  const getLogLevelFromEnv = getEnvironmentVariableFactory({
27
28
  variableName: "WRANGLER_LOG",
28
- defaultValue: "log",
29
29
  });
30
30
 
31
- class Logger {
31
+ function getLoggerLevel(): LoggerLevel {
32
+ const fromEnv = getLogLevelFromEnv()?.toLowerCase();
33
+ if (fromEnv !== undefined) {
34
+ if (fromEnv in LOGGER_LEVELS) return fromEnv as LoggerLevel;
35
+ const expected = Object.keys(LOGGER_LEVELS)
36
+ .map((level) => `"${level}"`)
37
+ .join(" | ");
38
+ console.warn(
39
+ `Unrecognised WRANGLER_LOG value ${JSON.stringify(
40
+ fromEnv
41
+ )}, expected ${expected}, defaulting to "log"...`
42
+ );
43
+ }
44
+ return "log";
45
+ }
46
+
47
+ export type TableRow<Keys extends string> = Record<Keys, string>;
48
+
49
+ export class Logger {
32
50
  constructor() {}
33
51
 
34
- loggerLevel: LoggerLevel = (getLogLevelFromEnv() as LoggerLevel) ?? "log";
52
+ loggerLevel = getLoggerLevel();
35
53
  columns = process.stdout.columns;
36
54
 
37
55
  debug = (...args: unknown[]) => this.doLog("debug", args);
@@ -39,6 +57,19 @@ class Logger {
39
57
  log = (...args: unknown[]) => this.doLog("log", args);
40
58
  warn = (...args: unknown[]) => this.doLog("warn", args);
41
59
  error = (...args: unknown[]) => this.doLog("error", args);
60
+ table<Keys extends string>(data: TableRow<Keys>[]) {
61
+ const keys: Keys[] =
62
+ data.length === 0 ? [] : (Object.keys(data[0]) as Keys[]);
63
+ const t = new CLITable({
64
+ head: keys,
65
+ style: {
66
+ head: chalk.level ? ["blue"] : [],
67
+ border: chalk.level ? ["gray"] : [],
68
+ },
69
+ });
70
+ t.push(...data.map((row) => keys.map((k) => row[k])));
71
+ return this.doLog("log", [t.toString()]);
72
+ }
42
73
 
43
74
  private doLog(messageLevel: Exclude<LoggerLevel, "none">, args: unknown[]) {
44
75
  if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[messageLevel]) {
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import { fetchResult } from "../cfetch";
5
5
  import { getConfigCache, saveToConfigCache } from "../config-cache";
6
6
  import { confirm } from "../dialogs";
7
- import { getEnvironmentVariableFactory } from "../environment-variables";
7
+ import { getEnvironmentVariableFactory } from "../environment-variables/factory";
8
8
  import { getGlobalWranglerConfigPath } from "../global-wrangler-config-path";
9
9
  import { CI } from "../is-ci";
10
10
  import isInteractive from "../is-interactive";
@@ -55,7 +55,10 @@ export type EventNames =
55
55
  | "build pages functions"
56
56
  | "run dev"
57
57
  | "run dev (api)"
58
- | "run pages dev";
58
+ | "run pages dev"
59
+ | "view docs"
60
+ | "view deployments"
61
+ | "rollback deployments";
59
62
 
60
63
  /**
61
64
  * Send a metrics event, with no extra properties, to Cloudflare, if usage tracking is enabled.
@@ -1,61 +1,72 @@
1
1
  import { existsSync, lstatSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { join, resolve } from "node:path";
3
3
  import { createMetadataObject } from "@cloudflare/pages-shared/metadata-generator/createMetadataObject";
4
4
  import { parseHeaders } from "@cloudflare/pages-shared/metadata-generator/parseHeaders";
5
5
  import { parseRedirects } from "@cloudflare/pages-shared/metadata-generator/parseRedirects";
6
- import {
7
- Response as MiniflareResponse,
8
- Request as MiniflareRequest,
9
- } from "@miniflare/core";
10
- import { upgradingFetch as miniflareFetch } from "@miniflare/web-sockets";
11
6
  import { watch } from "chokidar";
12
7
  import { getType } from "mime";
13
8
  import { hashFile } from "../pages/hash";
14
9
  import type { Metadata } from "@cloudflare/pages-shared/asset-server/metadata";
15
- import type {
16
- fetch,
17
- Request,
18
- } from "@cloudflare/pages-shared/environment-polyfills/types";
19
10
  import type {
20
11
  ParsedRedirects,
21
12
  ParsedHeaders,
22
13
  } from "@cloudflare/pages-shared/metadata-generator/types";
23
- import type { RequestInfo, RequestInit, FetcherFetch } from "@miniflare/core";
24
- import type { Log } from "miniflare";
14
+ import type {
15
+ Request as MiniflareRequest,
16
+ RequestInfo as MiniflareRequestInfo,
17
+ RequestInit as MiniflareRequestInit,
18
+ } from "@miniflare/core";
19
+
20
+ interface Logger {
21
+ log: (message: string) => void;
22
+ warn: (message: string) => void;
23
+ error: (error: Error) => void;
24
+ }
25
25
 
26
26
  export interface Options {
27
- log: Log;
27
+ log: Logger;
28
28
  proxyPort?: number;
29
29
  directory?: string;
30
+ tre: boolean;
30
31
  }
31
32
 
32
33
  export default async function generateASSETSBinding(options: Options) {
33
34
  const assetsFetch =
34
35
  options.directory !== undefined
35
- ? await generateAssetsFetch(options.directory, options.log)
36
+ ? await generateAssetsFetch(options.directory, options.log, options.tre)
36
37
  : invalidAssetsFetch;
37
38
 
38
- return async function (miniflareRequest: MiniflareRequest) {
39
+ const miniflare = options.tre
40
+ ? await import("@miniflare/tre")
41
+ : await import("@miniflare/core");
42
+
43
+ const Request = miniflare.Request as typeof MiniflareRequest;
44
+ const Response = miniflare.Response;
45
+ // WebSockets won't work with `--experimental-local` until we expose something like `upgradingFetch` from `@miniflare/tre`.
46
+ const fetch = (
47
+ options.tre
48
+ ? miniflare.fetch
49
+ : (await import("@miniflare/web-sockets")).upgradingFetch
50
+ ) as (request: Request) => Promise<Response>;
51
+
52
+ return async function (miniflareRequest: Request) {
39
53
  if (options.proxyPort) {
40
54
  try {
41
55
  const url = new URL(miniflareRequest.url);
42
56
  url.host = `localhost:${options.proxyPort}`;
43
- const proxyRequest = new MiniflareRequest(url, miniflareRequest);
57
+ const proxyRequest = new Request(url, miniflareRequest);
44
58
  if (proxyRequest.headers.get("Upgrade") === "websocket") {
45
59
  proxyRequest.headers.delete("Sec-WebSocket-Accept");
46
60
  proxyRequest.headers.delete("Sec-WebSocket-Key");
47
61
  }
48
- return await miniflareFetch(proxyRequest);
62
+ return await fetch(proxyRequest as Request);
49
63
  } catch (thrown) {
50
64
  options.log.error(new Error(`Could not proxy request: ${thrown}`));
51
65
 
52
66
  // TODO: Pretty error page
53
- return new MiniflareResponse(
54
- `[wrangler] Could not proxy request: ${thrown}`,
55
- {
56
- status: 502,
57
- }
58
- );
67
+ return new Response(`[wrangler] Could not proxy request: ${thrown}`, {
68
+ status: 502,
69
+ });
59
70
  }
60
71
  } else {
61
72
  try {
@@ -64,21 +75,42 @@ export default async function generateASSETSBinding(options: Options) {
64
75
  options.log.error(new Error(`Could not serve static asset: ${thrown}`));
65
76
 
66
77
  // TODO: Pretty error page
67
- return new MiniflareResponse(
78
+ return new Response(
68
79
  `[wrangler] Could not serve static asset: ${thrown}`,
69
80
  { status: 502 }
70
81
  );
71
82
  }
72
83
  }
73
- } as FetcherFetch;
84
+ };
74
85
  }
75
86
 
76
87
  async function generateAssetsFetch(
77
88
  directory: string,
78
- log: Log
89
+ log: Logger,
90
+ tre: boolean
79
91
  ): Promise<typeof fetch> {
92
+ directory = resolve(directory);
80
93
  // Defer importing miniflare until we really need it
81
- await import("@cloudflare/pages-shared/environment-polyfills/miniflare");
94
+
95
+ // NOTE: These dynamic imports bring in `global` type augmentations from
96
+ // `@cloudflare/pages-shared/environment-polyfills/types.ts`, allowing us to
97
+ // use `fetch`, `Headers`, `Request` and `Response` as globals in this file
98
+ // and the *entire* `miniflare-cli` TypeScript project.
99
+ const polyfill = tre
100
+ ? (
101
+ await import(
102
+ "@cloudflare/pages-shared/environment-polyfills/miniflare-tre"
103
+ )
104
+ ).default
105
+ : (await import("@cloudflare/pages-shared/environment-polyfills/miniflare"))
106
+ .default;
107
+
108
+ await polyfill();
109
+
110
+ const miniflare = tre
111
+ ? await import("@miniflare/tre")
112
+ : await import("@miniflare/core");
113
+ const Request = miniflare.Request as typeof MiniflareRequest;
82
114
 
83
115
  const { generateHandler, parseQualityWeightedList } = await import(
84
116
  "@cloudflare/pages-shared/asset-server/handler"
@@ -143,7 +175,10 @@ async function generateAssetsFetch(
143
175
  xServerEnvHeader: "dev",
144
176
  logError: console.error,
145
177
  findAssetEntryForPath: async (path) => {
146
- const filepath = join(directory, path);
178
+ const filepath = resolve(join(directory, path));
179
+ if (!filepath.startsWith(directory)) {
180
+ return null;
181
+ }
147
182
 
148
183
  if (
149
184
  existsSync(filepath) &&
@@ -189,7 +224,7 @@ async function generateAssetsFetch(
189
224
  const filepath = assetKeyEntryMap.get(assetKey);
190
225
  if (!filepath) {
191
226
  throw new Error(
192
- "Could not fetch asset. Please file an issue on GitHub (https://github.com/cloudflare/wrangler2/issues/new/choose) with reproduction steps."
227
+ "Could not fetch asset. Please file an issue on GitHub (https://github.com/cloudflare/workers-sdk/issues/new/choose) with reproduction steps."
193
228
  );
194
229
  }
195
230
  const body = readFileSync(filepath) as unknown as ReadableStream;
@@ -207,8 +242,8 @@ async function generateAssetsFetch(
207
242
  });
208
243
  };
209
244
 
210
- return async (input: RequestInfo, init?: RequestInit) => {
211
- const request = new MiniflareRequest(input, init);
245
+ return async (input: MiniflareRequestInfo, init?: MiniflareRequestInit) => {
246
+ const request = new Request(input, init);
212
247
  return await generateResponse(request as unknown as Request);
213
248
  };
214
249
  }