An unskilled drawing of a short, dark wizard shooting a flaming “J” from one hand and a watery “S” from the other.

The Most Cursed JavaScript

A Motivating Example

define(function element_name(prop_1 = "Default 1", prop_2 = 5, checked = false) {
return html`
<h1>Heading</h1>
<p>${reactive_text(prop_1)}</p>
<p>${reactive_text(computed(() => Math.pow(prop_2(), 2)))}</p>
`;
});
<element-name prop-2="10"></element-name>

How Does it Work?

function(a = "Hello World", b = 5, c, d = { x: 2.2, y: 5.76 }) {
/* ... */
}
// Is like:const a, b, c, d;
a = "Hello World", b = 5, c, d = { x: 2.2, y: 5.76 };
// Another thing I tried that we won't use:const defaults = [a = "Hello World", b = 5, c, d = { x: 2.2, y: 5.76 }];
// Gives us:
["Hello World", 5, undefined, { x: 2.2, y: 5.76 }]

Slurping up Identifiers via Proxy + with

const arg_names = [], defaults = {};with (new Proxy({}, {
has(target, key) {
arg_names.push(key);
return true;
},
get(target, key) {
if (key == Symbol.unscopables) return {};
arg_names.pop();
return eval(key);
},
set(target, key, value) {
defaults[key] = value;
return true;
}
})) {
a = "Hello World", b = 5, d = new Date();
}
console.log(arg_names, defaults);

Sloppy Mode Script

// Within our module:
const script = document.createElement('script');
script.src = URL.createObjectUrl(new Blob([`
function collect_names(code) {
const proxy = /* ... */;
with(proxy) {
eval(code);
}
}
window._script_loaded();
`], { type: 'application/JavaScript' }));
document.body.appendChild(script);
// Top-Level await that pauses our module's evaluation until the script has finished loading.
await new Promise(resolve => window._script_loaded = resolve);

env_access_src

function collect_names(code) {
const arg_names = [], defaults = {};
with (new Proxy({}, {
has(target, key) {
if (key !== 'code') {
arg_names.push(key);
return true;
} else {
return false;
}
},
get(target, key) {
if (key == Symbol.unscopables) return {};
arg_names.pop();
return eval(key);
},
set(target, key, value) {
defaults[key] = value;
return true;
}
})) {
eval(code);
}
return [arg_names, defaults];
}
(function() {
const some_value = "Hello World";
class Date {
/* Not like the normal Date */
}
console.log(collect_names("a = some_value, b = 5, d = new Date()"));
})()
const different_eval = eval;
export function anadv(
func,
env_access = different_eval(env_access_src)
) { /* ... */ }
export const env_access_src = `(function(){ return function env_access() {
return eval(arguments[0]);
}; })()`;
import { anadv, env_access_src } from 'anadv';const some_value = "Hello World";class Date { /* Not like the normal Date */ }const access = eval(env_access_src);anadv(
function (a = some_value, b = 5, d = new Date()) { },
access
);

The Final Stretch: Finding the Arguments

// Get the function's source code (removing comments)
let source = func.toString().replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '');
source = source.substr(source.indexOf('(') + 1);
// Separate the arguments list
let rem = source;
const stack = [')'];
while (stack.length > 0) {
let re;
// Handle strings and stuff:
if (stack[0] == '"' || stack[0] == "'") {
re = new RegExp(`(?:^|[^\\\\])(?:\\\\\\\\)*${stack[0]}`, 'g');
} else if (stack[0] == '`') {
re = /(?:^|[^\\])(?:\\\\)*`|(?:^|[^\\])(?:\\\\)*$\{/g;
} else {
re = /[`'"{([\])}]/g;
}
const result = re.exec(rem);
if (result === null || re.lastIndex === 0) {
throw new Error("Failed to parse args list.");
}
const token = rem[re.lastIndex - 1];
rem = rem.substr(re.lastIndex);
if (stack[0] == token) {
stack.shift();
} else {
const opposite = { "'": "'", '"': '"', '`': '`', '(': ')', '{': '}', '[': ']' }[token];
stack.unshift(opposite);
}
}
// After the closing parenthesis, there should be the opening '{'
if (!rem.match(/^\s*{/)) {
throw new Error('Failed to parse args list. Was this an arrow function?');
}
const args_source = source.substr(0, source.length - rem.length - 1);

Very Narrow Usefulness

Security

Compatibility

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Evan Brass

Evan Brass

I write a lot of ECMAScript… enough to have plenty of mistakes to learn from.