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
package/src/inspect.ts ADDED
@@ -0,0 +1,623 @@
1
+ import assert from "node:assert";
2
+ import { createServer } from "node:http";
3
+ import { URL } from "node:url";
4
+
5
+ import { useEffect, useRef, useState } from "react";
6
+ import WebSocket, { WebSocketServer } from "ws";
7
+ import { version } from "../package.json";
8
+ import { logger } from "./logger";
9
+ import { waitForPortToBeAvailable } from "./proxy";
10
+ import type Protocol from "devtools-protocol";
11
+ import type { IncomingMessage, Server, ServerResponse } from "node:http";
12
+ import type { MessageEvent } from "ws";
13
+
14
+ /**
15
+ * `useInspector` is a hook for debugging Workers applications
16
+ * when using `wrangler dev`.
17
+ *
18
+ * When we start a session with `wrangler dev`, the Workers platform
19
+ * also exposes a debugging websocket that implements the DevTools
20
+ * Protocol. While we could just start up DevTools and connect to this
21
+ * URL, that URL changes every time we make a change to the
22
+ * worker, or when the session expires. Instead, we start up a proxy
23
+ * server locally that acts as a bridge between the remote DevTools
24
+ * server and the local DevTools instance. So whenever the URL changes,
25
+ * we can can silently connect to it and keep the local DevTools instance
26
+ * up to date. Further, we also intercept these messages and selectively
27
+ * log them directly to the terminal (namely, calls to `console.<x>`,
28
+ * and exceptions)
29
+ */
30
+
31
+ /**
32
+ * TODO:
33
+ * - clear devtools whenever we save changes to the worker
34
+ * - clear devtools when we switch between local/remote modes
35
+ * - handle more methods from console
36
+ */
37
+
38
+ interface InspectorProps {
39
+ /**
40
+ * The port that the local proxy server should listen on.
41
+ */
42
+ port: number;
43
+ /**
44
+ * The websocket URL exposed by Workers that the inspector should connect to.
45
+ */
46
+ inspectorUrl: string | undefined;
47
+ /**
48
+ * Whether console statements and exceptions should be logged to the terminal.
49
+ * (We don't log them in local mode because they're already getting
50
+ * logged to the terminal by nature of them actually running in node locally.)
51
+ */
52
+ logToTerminal: boolean;
53
+ }
54
+
55
+ export default function useInspector(props: InspectorProps) {
56
+ /** A unique ID for this session. */
57
+ const inspectorIdRef = useRef(randomId());
58
+
59
+ /** The websocket from the devtools instance. */
60
+ const [localWebSocket, setLocalWebSocket] = useState<WebSocket>();
61
+ /** The websocket from the edge */
62
+ const [remoteWebSocket, setRemoteWebSocket] = useState<WebSocket>();
63
+
64
+ /**
65
+ * The local proxy server that acts as the bridge between
66
+ * the remote websocket and the local DevTools instance.
67
+ */
68
+ const serverRef = useRef<Server>();
69
+ if (serverRef.current === undefined) {
70
+ serverRef.current = createServer(
71
+ (req: IncomingMessage, res: ServerResponse) => {
72
+ switch (req.url) {
73
+ // We implement a couple of well known end points
74
+ // that are queried for metadata by chrome://inspect
75
+ case "/json/version":
76
+ res.setHeader("Content-Type", "application/json");
77
+ res.end(
78
+ JSON.stringify({
79
+ Browser: `wrangler/v${version}`,
80
+ // TODO: (someday): The DevTools protocol should match that of Edge Worker.
81
+ // This could be exposed by the preview API.
82
+ "Protocol-Version": "1.3",
83
+ })
84
+ );
85
+ return;
86
+ case "/json":
87
+ case "/json/list":
88
+ {
89
+ res.setHeader("Content-Type", "application/json");
90
+ const localHost = `localhost:${props.port}/ws`;
91
+ const devtoolsFrontendUrl = `devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=${localHost}`;
92
+ const devtoolsFrontendUrlCompat = `devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=${localHost}`;
93
+ res.end(
94
+ JSON.stringify([
95
+ {
96
+ id: inspectorIdRef.current,
97
+ type: "node",
98
+ description: "workers",
99
+ webSocketDebuggerUrl: `ws://${localHost}`,
100
+ devtoolsFrontendUrl,
101
+ devtoolsFrontendUrlCompat,
102
+ // Below are fields that are visible in the DevTools UI.
103
+ title: "Cloudflare Worker",
104
+ faviconUrl: "https://workers.cloudflare.com/favicon.ico",
105
+ url:
106
+ "https://" +
107
+ (remoteWebSocket
108
+ ? new URL(remoteWebSocket.url).host
109
+ : "workers.dev"),
110
+ },
111
+ ])
112
+ );
113
+ }
114
+ return;
115
+ default:
116
+ break;
117
+ }
118
+ }
119
+ );
120
+ }
121
+ const server = serverRef.current;
122
+
123
+ /**
124
+ * The websocket server that runs on top of the proxy server.
125
+ */
126
+ const wsServerRef = useRef<WebSocketServer>();
127
+ if (wsServerRef.current === undefined) {
128
+ wsServerRef.current = new WebSocketServer({
129
+ server,
130
+ clientTracking: true,
131
+ });
132
+ }
133
+ const wsServer = wsServerRef.current;
134
+
135
+ wsServer.on("connection", (ws: WebSocket) => {
136
+ if (wsServer.clients.size > 1) {
137
+ /** We only want to have one active Devtools instance at a time. */
138
+ logger.error(
139
+ "Tried to open a new devtools window when a previous one was already open."
140
+ );
141
+ ws.close(1013, "Too many clients; only one can be connected at a time");
142
+ } else {
143
+ // As promised, save the created websocket in a state hook
144
+ setLocalWebSocket(ws);
145
+
146
+ ws.addEventListener("close", () => {
147
+ // And and cleanup when devtools closes
148
+ setLocalWebSocket(undefined);
149
+ });
150
+ }
151
+ });
152
+
153
+ /**
154
+ * We start and stop the server in an effect to take advantage
155
+ * of the component lifecycle. Convenient.
156
+ */
157
+ useEffect(() => {
158
+ const abortController = new AbortController();
159
+ async function startInspectorProxy() {
160
+ await waitForPortToBeAvailable(props.port, {
161
+ retryPeriod: 200,
162
+ timeout: 2000,
163
+ abortSignal: abortController.signal,
164
+ });
165
+ server.listen(props.port);
166
+ }
167
+ startInspectorProxy().catch((err) => {
168
+ if ((err as { code: string }).code !== "ABORT_ERR") {
169
+ logger.error("Failed to start inspector:", err);
170
+ }
171
+ });
172
+ return () => {
173
+ server.close();
174
+ // Also disconnect any open websockets/devtools connections
175
+ wsServer.clients.forEach((ws) => ws.close());
176
+ wsServer.close();
177
+ abortController.abort();
178
+ };
179
+ }, [props.port, server, wsServer]);
180
+
181
+ /**
182
+ * When connecting to the remote websocket, if we don't start either
183
+ * the devtools instance or make an actual request to the worker in time,
184
+ * then the connecting process can error out. When this happens, we
185
+ * want to simply retry the connection. We use a state hook to trigger retries
186
+ * of the effect that connects to the remote websocket.
187
+ */
188
+ const [
189
+ retryRemoteWebSocketConnectionSigil,
190
+ setRetryRemoteWebSocketConnectionSigil,
191
+ ] = useState<number>(0);
192
+ function retryRemoteWebSocketConnection() {
193
+ setRetryRemoteWebSocketConnectionSigil((x) => x + 1);
194
+ }
195
+
196
+ /** A simple incrementing id to attach to messages we send to devtools */
197
+ const messageCounterRef = useRef(1);
198
+
199
+ // This effect tracks the connection to the remote websocket
200
+ // (stored in, no surprises here, `remoteWebSocket`)
201
+ useEffect(() => {
202
+ if (!props.inspectorUrl) {
203
+ return;
204
+ }
205
+ // The actual websocket instance
206
+ const ws = new WebSocket(props.inspectorUrl);
207
+ setRemoteWebSocket(ws);
208
+
209
+ /**
210
+ * A handle to the interval we run to keep the websocket alive
211
+ */
212
+ let keepAliveInterval: NodeJS.Timer;
213
+
214
+ /**
215
+ * Test if the websocket is closed
216
+ */
217
+ function isClosed() {
218
+ return (
219
+ ws.readyState === WebSocket.CLOSED ||
220
+ ws.readyState === WebSocket.CLOSING
221
+ );
222
+ }
223
+
224
+ /**
225
+ * Send a message to the remote websocket
226
+ */
227
+ function send(event: Record<string, unknown>): void {
228
+ if (!isClosed()) {
229
+ ws.send(JSON.stringify(event));
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Closes the inspector.
235
+ */
236
+ function close(): void {
237
+ if (!isClosed()) {
238
+ try {
239
+ ws.close();
240
+ } catch (err) {
241
+ // Closing before the websocket is ready will throw an error.
242
+ }
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Since we have a handle on the remote websocket, we can tap
248
+ * into its events, and log any pertinent ones directly to
249
+ * the terminal (which means you have insight into your worker
250
+ * without having to open the devtools).
251
+ */
252
+ if (props.logToTerminal) {
253
+ ws.addEventListener("message", (event: MessageEvent) => {
254
+ if (typeof event.data === "string") {
255
+ const evt = JSON.parse(event.data);
256
+ if (evt.method === "Runtime.exceptionThrown") {
257
+ const params = evt.params as Protocol.Runtime.ExceptionThrownEvent;
258
+ logger.error(
259
+ params.exceptionDetails.text,
260
+ params.exceptionDetails.exception?.description ?? ""
261
+ );
262
+ }
263
+ if (evt.method === "Runtime.consoleAPICalled") {
264
+ logConsoleMessage(
265
+ evt.params as Protocol.Runtime.ConsoleAPICalledEvent
266
+ );
267
+ }
268
+ } else {
269
+ // We should never get here, but who know is 2022...
270
+ logger.error("Unrecognised devtools event:", event);
271
+ }
272
+ });
273
+ }
274
+
275
+ ws.addEventListener("open", () => {
276
+ send({ method: "Runtime.enable", id: messageCounterRef.current });
277
+ // TODO: This doesn't actually work. Must fix.
278
+ send({ method: "Network.enable", id: messageCounterRef.current++ });
279
+
280
+ keepAliveInterval = setInterval(() => {
281
+ send({
282
+ method: "Runtime.getIsolateId",
283
+ id: messageCounterRef.current++,
284
+ });
285
+ }, 10_000);
286
+ });
287
+
288
+ ws.on("unexpected-response", () => {
289
+ logger.log("Waiting for connection...");
290
+ /**
291
+ * This usually means the worker is not "ready" yet
292
+ * so we'll just retry the connection process
293
+ */
294
+ retryRemoteWebSocketConnection();
295
+ });
296
+
297
+ ws.addEventListener("close", () => {
298
+ clearInterval(keepAliveInterval);
299
+ });
300
+
301
+ return () => {
302
+ // clean up! Let's first stop the heartbeat interval
303
+ clearInterval(keepAliveInterval);
304
+ // Then we'll send a message to the devtools instance to
305
+ // tell it to clear the console.
306
+ wsServer.clients.forEach((client) => {
307
+ // We could've used `localSocket` here, but
308
+ // then we would have had to add it to the effect
309
+ // change detection array, which would have made a
310
+ // bunch of other stuff complicated. So we'll just
311
+ // cycle through all of the server's connected clients
312
+ // (in practice, there should only be one or zero) and send
313
+ // the Log.clear message.
314
+ client.send(
315
+ JSON.stringify({
316
+ // TODO: This doesn't actually work. Must fix.
317
+ method: "Log.clear",
318
+ // we can disable the next eslint warning since
319
+ // we're referencing a ref that stays alive
320
+ // eslint-disable-next-line react-hooks/exhaustive-deps
321
+ id: messageCounterRef.current++,
322
+ params: {},
323
+ })
324
+ );
325
+ });
326
+ // Finally, we'll close the websocket
327
+ close();
328
+ // And we'll clear `remoteWebsocket`
329
+ setRemoteWebSocket(undefined);
330
+ };
331
+ }, [
332
+ props.inspectorUrl,
333
+ props.logToTerminal,
334
+ wsServer,
335
+ // We use a state value as a sigil to trigger a retry of the
336
+ // remote websocket connection. It's not used inside the effect,
337
+ // so react-hooks/exhaustive-deps doesn't complain if it's not
338
+ // included in the dependency array. But its presence is critical,
339
+ // so do NOT remove it from the dependency list.
340
+ retryRemoteWebSocketConnectionSigil,
341
+ ]);
342
+
343
+ /**
344
+ * We want to make sure we don't lose any messages we receive from the
345
+ * remote websocket before devtools connects. So we use a ref to buffer
346
+ * messages, and flush them whenever devtools connects.
347
+ */
348
+ const messageBufferRef = useRef<MessageEvent[]>([]);
349
+
350
+ // This effect tracks the state changes _between_ the local
351
+ // and remote websockets, and handles how messages flow between them.
352
+ useEffect(() => {
353
+ /**
354
+ * This event listener is used for buffering messages from
355
+ * the remote websocket, and flushing them
356
+ * when the local websocket connects.
357
+ */
358
+ function bufferMessageFromRemoteSocket(event: MessageEvent) {
359
+ messageBufferRef.current.push(event);
360
+ // TODO: maybe we should have a max limit on this?
361
+ // if so, we should be careful when removing messages
362
+ // from the front, because they could be critical for
363
+ // devtools (like execution context creation, etc)
364
+ }
365
+
366
+ if (remoteWebSocket && !localWebSocket) {
367
+ // The local websocket hasn't connected yet, so we'll
368
+ // buffer messages until it does.
369
+ remoteWebSocket.addEventListener(
370
+ "message",
371
+ bufferMessageFromRemoteSocket
372
+ );
373
+ }
374
+
375
+ /** Send a message from the local websocket to the remote websocket */
376
+ function sendMessageToRemoteWebSocket(event: MessageEvent) {
377
+ try {
378
+ assert(
379
+ remoteWebSocket,
380
+ "Trying to send a message to an undefined `remoteWebSocket`"
381
+ );
382
+ remoteWebSocket.send(event.data);
383
+ } catch (e) {
384
+ if (
385
+ (e as Error).message !==
386
+ "WebSocket is not open: readyState 0 (CONNECTING)"
387
+ ) {
388
+ /**
389
+ * ^ this just means we haven't opened a websocket yet
390
+ * usually happens until there's at least one request
391
+ * which is weird, because we may miss something that
392
+ * happens on the first request. Maybe we should buffer
393
+ * these messages too?
394
+ */
395
+ logger.error(e);
396
+ }
397
+ }
398
+ }
399
+
400
+ /** Send a message from the local websocket to the remote websocket */
401
+ function sendMessageToLocalWebSocket(event: MessageEvent) {
402
+ assert(
403
+ localWebSocket,
404
+ "Trying to send a message to an undefined `localWebSocket`"
405
+ );
406
+ localWebSocket.send(event.data);
407
+ }
408
+
409
+ if (localWebSocket && remoteWebSocket) {
410
+ // Both the remote and local websockets are connected, so let's
411
+ // start sending messages between them.
412
+ localWebSocket.addEventListener("message", sendMessageToRemoteWebSocket);
413
+ remoteWebSocket.addEventListener("message", sendMessageToLocalWebSocket);
414
+
415
+ // Also, let's flush any buffered messages
416
+ messageBufferRef.current.forEach(sendMessageToLocalWebSocket);
417
+ messageBufferRef.current = [];
418
+ }
419
+
420
+ return () => {
421
+ // Cleanup like good citizens
422
+ if (remoteWebSocket) {
423
+ remoteWebSocket.removeEventListener(
424
+ "message",
425
+ bufferMessageFromRemoteSocket
426
+ );
427
+ remoteWebSocket.removeEventListener(
428
+ "message",
429
+ sendMessageToLocalWebSocket
430
+ );
431
+ }
432
+ if (localWebSocket) {
433
+ localWebSocket.removeEventListener(
434
+ "message",
435
+ sendMessageToRemoteWebSocket
436
+ );
437
+ }
438
+ };
439
+ }, [localWebSocket, remoteWebSocket]);
440
+ }
441
+
442
+ // Credit: https://stackoverflow.com/a/2117523
443
+ function randomId(): string {
444
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
445
+ const r = (Math.random() * 16) | 0,
446
+ v = c == "x" ? r : (r & 0x3) | 0x8;
447
+ return v.toString(16);
448
+ });
449
+ }
450
+
451
+ /**
452
+ * This function converts a message serialised as a devtools event
453
+ * into arguments suitable to be called by a console method, and
454
+ * then actually calls the method with those arguments. Effectively,
455
+ * we're just doing a little bit of the work of the devtools console,
456
+ * directly in the terminal.
457
+ */
458
+
459
+ export const mapConsoleAPIMessageTypeToConsoleMethod: {
460
+ [key in Protocol.Runtime.ConsoleAPICalledEvent["type"]]: Exclude<
461
+ keyof Console,
462
+ "Console"
463
+ >;
464
+ } = {
465
+ log: "log",
466
+ debug: "debug",
467
+ info: "info",
468
+ warning: "warn",
469
+ error: "error",
470
+ dir: "dir",
471
+ dirxml: "dirxml",
472
+ table: "table",
473
+ trace: "trace",
474
+ clear: "clear",
475
+ count: "count",
476
+ assert: "assert",
477
+ profile: "profile",
478
+ profileEnd: "profileEnd",
479
+ timeEnd: "timeEnd",
480
+ startGroup: "group",
481
+ startGroupCollapsed: "groupCollapsed",
482
+ endGroup: "groupEnd",
483
+ };
484
+
485
+ function logConsoleMessage(evt: Protocol.Runtime.ConsoleAPICalledEvent): void {
486
+ const args: string[] = [];
487
+ for (const ro of evt.args) {
488
+ switch (ro.type) {
489
+ case "string":
490
+ case "number":
491
+ case "boolean":
492
+ case "undefined":
493
+ case "symbol":
494
+ case "bigint":
495
+ args.push(ro.value);
496
+ break;
497
+ case "function":
498
+ args.push(`[Function: ${ro.description ?? "<no-description>"}]`);
499
+ break;
500
+ case "object":
501
+ if (!ro.preview) {
502
+ args.push(
503
+ ro.subtype === "null"
504
+ ? "null"
505
+ : ro.description ?? "<no-description>"
506
+ );
507
+ } else {
508
+ args.push(ro.preview.description ?? "<no-description>");
509
+
510
+ switch (ro.preview.subtype) {
511
+ case "array":
512
+ args.push(
513
+ "[ " +
514
+ ro.preview.properties
515
+ .map(({ value }) => {
516
+ return value;
517
+ })
518
+ .join(", ") +
519
+ (ro.preview.overflow ? "..." : "") +
520
+ " ]"
521
+ );
522
+
523
+ break;
524
+ case "weakmap":
525
+ case "map":
526
+ args.push(
527
+ "{\n" +
528
+ // Maps always have entries
529
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
530
+ ro.preview
531
+ .entries!.map(({ key, value }) => {
532
+ return ` ${key?.description ?? "<unknown>"} => ${
533
+ value.description
534
+ }`;
535
+ })
536
+ .join(",\n") +
537
+ (ro.preview.overflow ? "\n ..." : "") +
538
+ "\n}"
539
+ );
540
+
541
+ break;
542
+ case "weakset":
543
+ case "set":
544
+ args.push(
545
+ "{ " +
546
+ // Sets always have entries
547
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
548
+ ro.preview
549
+ .entries!.map(({ value }) => {
550
+ return `${value.description}`;
551
+ })
552
+ .join(", ") +
553
+ (ro.preview.overflow ? ", ..." : "") +
554
+ " }"
555
+ );
556
+ break;
557
+ case "regexp":
558
+ break;
559
+ case "date":
560
+ break;
561
+ case "generator":
562
+ args.push(ro.preview.properties[0].value || "");
563
+ break;
564
+ case "promise":
565
+ if (ro.preview.properties[0].value === "pending") {
566
+ args.push(`{<${ro.preview.properties[0].value}>}`);
567
+ } else {
568
+ args.push(
569
+ `{<${ro.preview.properties[0].value}>: ${ro.preview.properties[1].value}}`
570
+ );
571
+ }
572
+ break;
573
+ case "node":
574
+ case "iterator":
575
+ case "proxy":
576
+ case "typedarray":
577
+ case "arraybuffer":
578
+ case "dataview":
579
+ case "webassemblymemory":
580
+ case "wasmvalue":
581
+ break;
582
+ case "error":
583
+ default:
584
+ // just a pojo
585
+ args.push(
586
+ "{\n" +
587
+ ro.preview.properties
588
+ .map(({ name, value }) => {
589
+ return ` ${name}: ${value}`;
590
+ })
591
+ .join(",\n") +
592
+ (ro.preview.overflow ? "\n ..." : "") +
593
+ "\n}"
594
+ );
595
+ }
596
+ }
597
+ break;
598
+ default:
599
+ args.push(ro.description || ro.unserializableValue || "🦋");
600
+ break;
601
+ }
602
+ }
603
+
604
+ const method = mapConsoleAPIMessageTypeToConsoleMethod[evt.type];
605
+
606
+ if (method in console) {
607
+ switch (method) {
608
+ case "dir":
609
+ console.dir(args);
610
+ break;
611
+ case "table":
612
+ console.table(args);
613
+ break;
614
+ default:
615
+ // eslint-disable-next-line prefer-spread
616
+ console[method].apply(console, args);
617
+ break;
618
+ }
619
+ } else {
620
+ logger.warn(`Unsupported console method: ${method}`);
621
+ logger.warn("console event:", evt);
622
+ }
623
+ }