diff --git a/tests/repl.spec.ts b/tests/repl.spec.ts new file mode 100644 index 0000000000..abb4691355 --- /dev/null +++ b/tests/repl.spec.ts @@ -0,0 +1,49 @@ +import { expect, test, type Page } from "@playwright/test"; + +test.setTimeout(60_000); + +async function openReplConsole(page: Page, code: string, evaluate: boolean) { + const response = await page.goto( + `/repl#?evaluate=${evaluate}&code=${encodeURIComponent(code)}`, + { waitUntil: "domcontentloaded" } + ); + expect(response?.status()).toBe(200); + + await page + .locator(".pills__item", { hasText: /^console$/ }) + .click({ timeout: 30_000 }); +} + +test("repl console shows the output of the evaluated code", async ({ + page, +}) => { + await openReplConsole( + page, + [ + 'console.log("answer:", { value: 42, list: [1, "two"] });', + 'console.warn("%s is deprecated", "foo");', + "setTimeout(() => { throw new Error('async'); });", + "throw new TypeError('sync');", + ].join("\n"), + true + ); + + const entries = page.getByRole("log").locator("pre"); + await expect(entries).toHaveText( + [ + 'answer: { value: 42, list: [ 1, "two" ] }', + "foo is deprecated", + "Uncaught TypeError: sync", + "Uncaught Error: async", + ], + { timeout: 30_000 } + ); +}); + +test("repl console asks to enable evaluation", async ({ page }) => { + await openReplConsole(page, 'console.log("hello");', false); + + await expect( + page.getByText('Enable "Evaluate" in the settings') + ).toBeVisible(); +}); diff --git a/website/src/components/repl/ConsolePanel.module.css b/website/src/components/repl/ConsolePanel.module.css new file mode 100644 index 0000000000..ad5bd088dd --- /dev/null +++ b/website/src/components/repl/ConsolePanel.module.css @@ -0,0 +1,40 @@ +@import "./lib/styles.css"; + +.console { + flex: 1; + min-height: 0; + overflow: auto; + font-family: var(--ifm-font-family-monospace); + font-size: 13px; + line-height: 18px; + -webkit-overflow-scrolling: touch; +} + +.placeholder { + padding: 0.5rem 0.75rem; + color: var(--colors-foregroundLight); +} + +.entry { + margin: 0; + padding: 0.25rem 0.75rem; + border-radius: 0; + border-bottom: 1px solid var(--ifm-scrollbar-track-background-color); + background: transparent; + color: inherit; + font: inherit; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.warn { + background-color: var(--colors-infoBackground); + border-bottom-color: var(--colors-infoBorder); + color: var(--colors-infoForeground); +} + +.error { + background-color: var(--colors-errorBackground); + border-bottom-color: var(--colors-errorBorder); + color: var(--colors-errorForeground); +} diff --git a/website/src/components/repl/ConsolePanel.tsx b/website/src/components/repl/ConsolePanel.tsx new file mode 100644 index 0000000000..e0695b6a9f --- /dev/null +++ b/website/src/components/repl/ConsolePanel.tsx @@ -0,0 +1,54 @@ +import React, { useEffect, useRef } from "react"; + +import styles from "./ConsolePanel.module.css"; + +import type { ConsoleEntry, ConsoleLevel } from "./lib/types"; + +type Props = { + entries: ReadonlyArray; + isEvaluateEnabled: boolean; +}; + +const levelClassNames: Partial> = { + warn: styles.warn, + error: styles.error, +}; + +export default function ConsolePanel({ entries, isEvaluateEnabled }: Props) { + const container = useRef(null); + + useEffect(() => { + // Keep the latest messages visible. + container.current.scrollTop = container.current.scrollHeight; + }, [entries]); + + let placeholder: string | null = null; + if (!isEvaluateEnabled) { + placeholder = + 'Enable "Evaluate" in the settings to run the compiled code and see its console output here'; + } else if (entries.length === 0) { + placeholder = "Console output will be shown here"; + } + + return ( +
+ {placeholder ? ( +
{placeholder}
+ ) : ( + entries.map((entry, index) => ( +
+            {entry.message}
+          
+ )) + )} +
+ ); +} diff --git a/website/src/components/repl/Repl.tsx b/website/src/components/repl/Repl.tsx index 3c0bddae7c..7ec77d4818 100644 --- a/website/src/components/repl/Repl.tsx +++ b/website/src/components/repl/Repl.tsx @@ -7,6 +7,7 @@ import React, { type ChangeEvent } from "react"; import { prettySize, compareVersions } from "./lib/utils"; import ErrorBoundary from "./ErrorBoundary"; import { load as loadMonaco, Monaco } from "./Monaco"; +import ConsolePanel from "./ConsolePanel"; import ReplOptions from "./ReplOptions"; import StorageService from "./lib/storageService"; import UriUtils from "./lib/uriUtils"; @@ -42,6 +43,7 @@ import { toCamelCase, hasOwnProperty } from "./lib/utils"; import type { BabelState, BabelPlugin, + ConsoleEntry, EnvState, ShippedProposalsState, EnvConfig, @@ -66,6 +68,7 @@ type State = { inputAst: File; astSelectedRange: [number, number] | null; compileErrorMessage: string | undefined | null; + consoleEntries: ReadonlyArray; envConfig: EnvConfig; envPresetState: EnvState; shippedProposalsState: ShippedProposalsState; @@ -132,6 +135,7 @@ class Repl extends React.Component { astSelectedRange: null, pluginSearch: "", compileErrorMessage: null, + consoleEntries: [], presetsOptions, envConfig, envPresetState: persistedStateToEnvState( @@ -173,6 +177,14 @@ class Repl extends React.Component { this._setupBabel(defaultPresets); } + componentDidMount() { + scopedEval.setConsoleListener(this._onConsoleChange); + } + + componentWillUnmount() { + scopedEval.setConsoleListener(null); + } + _configToState = (configObject: any) => { const state = this.state; const newState: Pick = {} as any; @@ -402,7 +414,7 @@ class Repl extends React.Component {
{ this.setState({ rightTab }); }} @@ -427,6 +439,12 @@ class Repl extends React.Component { value={this.state.inputAst} /> )} + {state.rightTab === "console" && ( + + )}
{state.timeTravel && ( @@ -754,6 +772,10 @@ class Repl extends React.Component { ); }; + _onConsoleChange = (consoleEntries: ReadonlyArray) => { + this.setState({ consoleEntries }); + }; + _onIsSidebarExpandedChange = (isExpanded: boolean) => { this.setState( { diff --git a/website/src/components/repl/lib/formatConsoleArgs.ts b/website/src/components/repl/lib/formatConsoleArgs.ts new file mode 100644 index 0000000000..2f5b5b14f2 --- /dev/null +++ b/website/src/components/repl/lib/formatConsoleArgs.ts @@ -0,0 +1,224 @@ +// Values logged by the evaluated code come from the sandbox iframe, so they +// belong to another realm: `instanceof` checks against this window's +// constructors would fail. Rely on realm-independent checks instead. + +const MAX_DEPTH = 2; +const MAX_ITEMS = 100; + +const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/; + +const getTag = (value: object) => Object.prototype.toString.call(value); + +function getConstructorName(value: object): string { + try { + const name = Object.getPrototypeOf(value)?.constructor?.name; + return typeof name === "string" ? name : ""; + } catch { + return ""; + } +} + +function formatKey(key: string): string { + return IDENTIFIER_RE.test(key) ? key : JSON.stringify(key); +} + +function formatFunction(fn: (...args: unknown[]) => unknown): string { + let isClass = false; + try { + isClass = Function.prototype.toString.call(fn).startsWith("class"); + } catch { + // Some exotic functions (e.g. revoked proxies) can't be stringified. + } + if (isClass) return fn.name ? `[class ${fn.name}]` : "[class (anonymous)]"; + return fn.name ? `[Function: ${fn.name}]` : "[Function (anonymous)]"; +} + +function formatError(error: { name?: unknown; message?: unknown }): string { + const name = String(error.name ?? "Error"); + const message = String(error.message ?? ""); + return message ? `${name}: ${message}` : name; +} + +function formatProperty( + object: object, + key: string, + depth: number, + seen: Set +): string { + const descriptor = Object.getOwnPropertyDescriptor(object, key); + // Don't run getters: they could have side effects, or even log the object + // being formatted again. + if (descriptor?.get) return descriptor.set ? "[Getter/Setter]" : "[Getter]"; + if (descriptor?.set) return "[Setter]"; + return inspect(descriptor?.value, depth, seen); +} + +function formatEntries( + open: string, + close: string, + items: string[], + total: number +): string { + if (total > items.length) { + items.push(`... ${total - items.length} more items`); + } + return items.length ? `${open} ${items.join(", ")} ${close}` : open + close; +} + +function formatObject(value: object, depth: number, seen: Set) { + if (seen.has(value)) return "[Circular]"; + + const tag = getTag(value); + + switch (tag) { + case "[object Error]": + case "[object DOMException]": + return depth === 0 ? formatError(value) : `[${formatError(value)}]`; + case "[object Date]": { + const time = (value as Date).getTime(); + return Number.isNaN(time) ? "Invalid Date" : new Date(time).toISOString(); + } + case "[object RegExp]": + return String(value); + case "[object Symbol]": + case "[object Number]": + case "[object String]": + case "[object Boolean]": + case "[object BigInt]": + return `[${getConstructorName(value) || "Object"}: ${inspect( + value.valueOf(), + depth + 1, + seen + )}]`; + } + + const isArray = + Array.isArray(value) || + // Typed arrays + (ArrayBuffer.isView(value) && tag !== "[object DataView]"); + const name = getConstructorName(value); + + if (depth > MAX_DEPTH) { + return isArray ? "[Array]" : `[${name || "Object"}]`; + } + + seen.add(value); + try { + if (isArray) { + const array = value as ArrayLike; + const items = []; + for (let i = 0; i < Math.min(array.length, MAX_ITEMS); i++) { + items.push(inspect(array[i], depth + 1, seen)); + } + const prefix = + name && name !== "Array" ? `${name}(${array.length}) ` : ""; + return prefix + formatEntries("[", "]", items, array.length); + } + + if (tag === "[object Map]") { + const map = value as Map; + const items = []; + for (const [key, item] of map) { + if (items.length === MAX_ITEMS) break; + items.push( + `${inspect(key, depth + 1, seen)} => ${inspect(item, depth + 1, seen)}` + ); + } + return `${name || "Map"}(${map.size}) ${formatEntries("{", "}", items, map.size)}`; + } + + if (tag === "[object Set]") { + const set = value as Set; + const items = []; + for (const item of set) { + if (items.length === MAX_ITEMS) break; + items.push(inspect(item, depth + 1, seen)); + } + return `${name || "Set"}(${set.size}) ${formatEntries("{", "}", items, set.size)}`; + } + + const keys = Object.keys(value); + const items = []; + for (const key of keys.slice(0, MAX_ITEMS)) { + items.push( + `${formatKey(key)}: ${formatProperty(value, key, depth + 1, seen)}` + ); + } + const prefix = name && name !== "Object" ? `${name} ` : ""; + return prefix + formatEntries("{", "}", items, keys.length); + } finally { + seen.delete(value); + } +} + +/** + * Converts any value to a human-readable string, similarly to how browser + * consoles and Node.js's `util.inspect` display them. + */ +function inspect( + value: unknown, + depth = 0, + seen: Set = new Set() +): string { + switch (typeof value) { + case "string": + return depth === 0 ? value : JSON.stringify(value); + case "number": + return Object.is(value, -0) ? "-0" : String(value); + case "bigint": + return `${value}n`; + case "symbol": + return value.toString(); + case "function": + return formatFunction(value as (...args: unknown[]) => unknown); + case "object": + return value === null ? "null" : formatObject(value, depth, seen); + default: + return String(value); + } +} + +/** + * Formats the arguments of a `console` method call into a single line, + * applying printf-style substitutions (`%s`, `%d`, `%i`, `%f`, `%o`, `%O`, + * `%c` and `%%`) when the first argument is a string. + */ +export default function formatConsoleArgs(args: readonly unknown[]): string { + const parts: string[] = []; + let rest = args; + + if (typeof args[0] === "string") { + let index = 1; + parts.push( + args[0].replace(/%([sdifoOc%])/g, (match, specifier: string) => { + if (specifier === "%") return "%"; + if (index >= args.length) return match; + const arg = args[index++]; + switch (specifier) { + case "s": + return inspect(arg); + case "d": + case "i": + return typeof arg === "symbol" + ? "NaN" + : String(Math.trunc(Number(arg))); + case "f": + return typeof arg === "symbol" ? "NaN" : String(Number(arg)); + case "o": + case "O": + return typeof arg === "string" ? JSON.stringify(arg) : inspect(arg); + case "c": + // CSS styles can't be applied to the plain text output. + return ""; + } + }) + ); + rest = args.slice(index); + } + + for (const arg of rest) { + parts.push(inspect(arg)); + } + + return parts.join(" "); +} diff --git a/website/src/components/repl/lib/scopedEval.ts b/website/src/components/repl/lib/scopedEval.ts index 8dce3a3c05..2183ac1bbf 100644 --- a/website/src/components/repl/lib/scopedEval.ts +++ b/website/src/components/repl/lib/scopedEval.ts @@ -1,4 +1,90 @@ +import formatConsoleArgs from "./formatConsoleArgs"; + +import type { ConsoleEntry, ConsoleLevel } from "./types"; + +type ConsoleListener = (entries: ReadonlyArray) => void; + +const CONSOLE_LEVELS: ReadonlyArray = [ + "log", + "info", + "warn", + "error", + "debug", +]; + +// Keep only the most recent messages so that logging in a long loop doesn't +// freeze the page. +const MAX_CONSOLE_ENTRIES = 1000; + let iframe = null; +let consoleEntries: ConsoleEntry[] = []; +let consoleListener: ConsoleListener | null = null; +let isNotifyScheduled = false; + +function notifyConsoleListener() { + isNotifyScheduled = false; + if (consoleListener) consoleListener(consoleEntries.slice()); +} + +function scheduleConsoleNotification() { + // Batch the messages logged synchronously by the evaluated code. + if (isNotifyScheduled) return; + isNotifyScheduled = true; + queueMicrotask(notifyConsoleListener); +} + +function addConsoleEntry(level: ConsoleLevel, args: readonly unknown[]) { + let message: string; + try { + message = formatConsoleArgs(args); + } catch { + // e.g. revoked proxies, or objects whose methods throw when inspected. + // Never make the evaluated code's `console` calls throw. + message = "[Unable to display the logged value]"; + } + + if (consoleEntries.length >= MAX_CONSOLE_ENTRIES) consoleEntries.shift(); + consoleEntries.push({ level, message }); + scheduleConsoleNotification(); +} + +function clearConsole() { + consoleEntries = []; + scheduleConsoleNotification(); +} + +function captureConsole(contentWindow) { + const console = contentWindow.console; + + // Calls are still forwarded to the original methods, so that the messages + // keep showing up in the browser's developer tools. + for (const level of CONSOLE_LEVELS) { + const original = console[level]; + console[level] = function (...args) { + addConsoleEntry(level, args); + return original.apply(this, args); + }; + } + + const originalClear = console.clear; + console.clear = function (...args) { + clearConsole(); + return originalClear.apply(this, args); + }; + + // Errors thrown synchronously are rethrown by `scopedEval`, but errors + // thrown in callbacks (e.g. timers or promises) only reach these events. + contentWindow.addEventListener("error", (event) => { + addConsoleEntry( + "error", + // `event.message` already starts with "Uncaught". + event.error == null ? [event.message] : ["Uncaught", event.error] + ); + }); + contentWindow.addEventListener("unhandledrejection", (event) => { + addConsoleEntry("error", ["Uncaught (in promise)", event.reason]); + }); +} function getIframe() { if (iframe === null) { @@ -7,6 +93,8 @@ function getIframe() { // $FlowFixMe document.body.append(iframe); + + captureConsole(iframe.contentWindow); } return iframe; @@ -22,11 +110,30 @@ function scopedEval(code: string, sourceMap?: string | null) { )}`; } + const contentWindow = getIframe().contentWindow; + + // Every evaluation starts with an empty console. + clearConsole(); + // Eval code within an iframe so that it can't eg unmount the REPL. - getIframe().contentWindow.eval(code); + try { + contentWindow.eval(code); + } catch (error) { + addConsoleEntry("error", ["Uncaught", error]); + throw error; + } +} + +/** + * Registers a function called with the messages logged by the evaluated code + * every time they change. Pass `null` to unregister it. + */ +function setConsoleListener(listener: ConsoleListener | null) { + consoleListener = listener; } export default { execute: scopedEval, getIframe, + setConsoleListener, }; diff --git a/website/src/components/repl/lib/types.ts b/website/src/components/repl/lib/types.ts index aa719062c0..9ed6d2a3a6 100644 --- a/website/src/components/repl/lib/types.ts +++ b/website/src/components/repl/lib/types.ts @@ -154,6 +154,13 @@ export type ReplState = { meta?: { compiledSize: number; rawSize: number }; }; +export type ConsoleLevel = "log" | "info" | "warn" | "error" | "debug"; + +export type ConsoleEntry = { + level: ConsoleLevel; + message: string; +}; + export type SidebarTabSection = | "env" | "plugins"