Skip to content

Instantly share code, notes, and snippets.

@cyan-2048
Created August 4, 2022 13:35
Show Gist options
  • Save cyan-2048/e5a1cdc12227ac9da4b6457e360be041 to your computer and use it in GitHub Desktop.
Save cyan-2048/e5a1cdc12227ac9da4b6457e360be041 to your computer and use it in GitHub Desktop.
a super crappy attempt on making a "repl" to simulate nodejs on the browser... basically you can stringify stuff to look more "console-like".
let global$1 = null;
if (typeof document !== "undefined") {
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
iframe.style.display = "none";
global$1 = iframe.contentWindow;
} else {
global$1 = global;
}
(async function () {
var window = this.window = undefined, self = this,
global = this,
exports = undefined,
module = this.module = {}, destroy = null;
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function objectStringify(object) {
function strip(element) {
if (typeof element === "object" || typeof element === "function") {
return `[${capitalizeFirstLetter(typeof element)} ${element.name || element.constructor.name || key}]`
} else if (typeof element === "string") {
return `'${element}'`
} else if (typeof element === "symbol") {
return element.toString()
} else {
return element;
}
}
if (object instanceof Promise) {
return (async () => {
const template = (state) => `Promise { ${state} }`
try {
const symbol = Symbol();
const race = await Promise.race([object, symbol]);
if (race === symbol) {
return template("<pending>")
}
return template(typeof race === "object" ? objectStringify(race) : strip(race))
} catch (error) {
return template(`<rejected> ${typeof error === "object" ? objectStringify(error) : strip(error)}`)
}
})();
}
if (object instanceof Array) {
return JSON.stringify(object)
}
if (object instanceof Map) {
const { size } = object;
return `Map(${object.size}) {${size > 3 ? "\n " : ""} ${[...object].map(([a, b]) => {
return `${strip(a)} => ${strip(b)}`
}).join(`, ${size > 3 ? "\n " : ""}`)} ${size > 3 ? "\n" : ""}}`
}
const obj = {};
for (const key in object) {
const element = object[key]
obj[key] = strip(element);
}
const name = object.constructor.name
return `Object${name === "Object" ? "" : ` [${name}]`} ` + JSON.stringify(obj, null, 2).replaceAll(`"`, "")
}
class Test {
number = 0
constructor() {
}
}
console.log(objectStringify({
test: "hewo",
arrow: () => { },
function: function name() { },
obj: {},
symbol: Symbol("test"),
boolean: !0,
number: 0
}))
console.log(global.eval("const testo = false; testo"))
}).call(global$1)
@cyan-2048
Copy link
Author

i basically gave up because i did not know "eval" doesn't work the same way as running code in devtools
so let and const doesn't work properly
this would also probably mean i can't do global variables...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment