import { jsx as _jsx } from "react/jsx-runtime";
import { useSandpackConsole } from "@codesandbox/sandpack-react";
import { Console, Decode } from "console-feed";
import { useEffect, useState } from "react";
const encodeLog = (log) => {
    // deep copy the log.data array
    if (!log.data) {
        return Decode([]);
    }
    const modifiedDataArray = log.data;
    if (Array.isArray(modifiedDataArray)) {
        // Due to formatting changes with console-feed's encode function in v3.4
        // we need to manually add in the remainder key to note that there
        // are no more items remaining
        modifiedDataArray.push("__console_feed_remaining__0");
        // Objects all need to have a constructor property now too
        // unless it is null
        modifiedDataArray.forEach((dataItem) => {
            if (typeof dataItem !== "string" &&
                dataItem?.["@t"]) {
                const sandpackEncodedLog = dataItem;
                if (sandpackEncodedLog["@t"] === "[[undefined]]") {
                    return;
                }
                // Hey keep going and actually write this as a function to note
                // that we are essentially an adapter for v3.3 and the newest version of console-feed
                const constructorType = sandpackEncodedLog?.["@t"]?.slice(2, -2);
                Object.assign(dataItem, {
                    constructor: {
                        name: constructorType,
                    },
                });
                delete sandpackEncodedLog["@t"];
            }
        });
    }
    return Decode([{ ...log, data: modifiedDataArray }]);
};
export const ConsoleOutput = () => {
    const [logs, setLogs] = useState([]);
    const { logs: sandpackLogs } = useSandpackConsole({
        resetOnPreviewRestart: true,
    });
    useEffect(() => {
        const encodedLogArr = sandpackLogs.map(encodeLog);
        setLogs(encodedLogArr);
    }, [sandpackLogs]);
    return (_jsx("div", { style: {
            flex: "1 1 0px",
            display: "flex",
            flexDirection: "column",
            gap: "1px",
            overflow: "hidden",
            background: "var(--sp-colors-surface1)",
            lineHeight: "var(--sp-font-lineHeight)",
        }, children: _jsx("div", { style: {
                overflow: "auto",
                flex: "1 1 0px",
                fontSize: "1em",
            }, children: _jsx("div", { style: {
                    width: "100%",
                    padding: "var(--sp-space-3) var(--sp-space-2)",
                }, children: _jsx(Console, { logs: logs }) }) }) }));
};
//# sourceMappingURL=index.js.map