Skip to content

Instantly share code, notes, and snippets.

@petsel
Last active July 10, 2025 16:02
Show Gist options
  • Select an option

  • Save petsel/0d50fc1086b37060a79c011c5e180654 to your computer and use it in GitHub Desktop.

Select an option

Save petsel/0d50fc1086b37060a79c011c5e180654 to your computer and use it in GitHub Desktop.
Symbol.fnDirectives = Symbol.for('fnDirectives');
// const directivesSymbol = Symbol.fnDirectives;
// console.log(Symbol.for(Symbol.keyFor(directivesSymbol)) === Symbol.fnDirectives); // true
const functionPrototype = Function.prototype;
const toFunctionString = functionPrototype.toString;
function parseBodyFromFctString(fctString) {
const [ head ] = fctString
.trim()
.match(/^[^{]+\{|[^=]+=>\s*\(?/g) ?? [''];
return fctString
.slice(head.length)
.trim()
.replace(/^[(\s]+/s, '')
.replace(/[)\s]+$/s, '')
.replace(/^\{+/, '')
.replace(/\}+$/, '');
}
function parseDirectivesFromFctBody(fctBody) {
return new Set(
fctBody
// +++ remove all comments +++
// move every multiline comment terminator to a new line and add another new line to it.
.replace(/(\*\/)/gm, '\n$1\n')
// move every multiline comment opener to a new line and move everything after to a new line as well.
.replace(/(\/\*)/gm, '\n$1\n')
// remove everything from the beginning of a single line comment until the end of line.
.replace(/\/\/.*?$/gm, '')
// remove every whitespace sequence at the beginning of a new line - removes empty/blank lines entirely.
.replace(/^\s+/gm, '')
// remove every multiline comment block.
.replace(/(?:\n)?\/\*.*?\*\//gs, '')
// +++ sanitize/unify/group possibly relevant/valid directives +++
// - line up (at a single line) a sequence of possibly valid directives.
// - each possibly counting directive gets identified by its line start.
.replace(/^((['"])[^'"]+\1.*?)\n/gm, '$1')
.trim()
.split(/\n/)
// take just the first line off possibly relevant/valid directives.
.at(0)
// +++ finalize result +++
// capture any directive value.
.matchAll(/(['"])([^'"]+)\1/g)
// lift each captured directive value.
.map(([match, quote, directive]) => directive)
// - not needed
// - the above iterator automatically spreads its values into the `Set` constructor.
// .toArray()
);
}
const directivesRegistry = new WeakMap;
function getDirectives() {
// pragma-style (custom) directives.
/* for hiding source code */
'use hidden';
// this one too is for hiding source code
'use hidden-source';/*and that one as well // is for source
code hiding*/
'hide source';
const memoized = directivesRegistry.get(this);
// memoizing guard.
if (memoized) {
return memoized;
}
const fctBody = parseBodyFromFctString(
toFunctionString.call(this)
);
const directives = parseDirectivesFromFctBody(fctBody);
directivesRegistry.set(this, directives);
return directives;
}
if (!Object.hasOwn(functionPrototype, Symbol.fnDirectives)) {
Object.defineProperty(functionPrototype, Symbol.fnDirectives, {
enumerable: false,
configurable: false,
get: getDirectives,
});
}
const regXIsHideSource =
// see ... [https://regex101.com/r/wR11qH/8]
/^(?<head>[^{]+\{|[^=]+=>\s*\(?)\s*(?:['"]use\s+[^'"]+['"](?:\s*;)?\s*)*['"](?:use\s+(?:source-)?hidden|hide\s+source)['"]/u
const regXFctName = /(?<=^(?:function|class)).*?(?=\s?[({])/;
const functionPrototype = Function.prototype;
const builtInToString = functionPrototype.toString;
function toString() {
'hide source';
'use hidden';
'use source-hidden';
const fct = this;
const source = builtInToString.call(fct).trim();
const { groups } = regXIsHideSource.exec(source) ?? {};
if (!groups) {
return source;
}
let head = groups.head.trim();
const fctName =
Object.getOwnPropertyDescriptor(fct, 'name')?.value || fct.name;
if (!!fctName) {
/*
* - restore/provide otherwise empty names of e.g. function expressions of following form ...
*
* ```
* const myFunction = function() {
* 'use source-hidden';
* };
* console.log(myFunction+""); // logs ... 'function myFunction () { [hidden source] }'
*
* - is not only restricted to the above use case.
* - does also cover the scenario of minified code
* where a function's full name has been provided,
* and thus preserved, through ...
* `Object.defineProperty(fct, 'name', { value: fctName, ... })`
*/
head = head.replace(regXFctName, (match => ((!match && ` ${ fctName } `) || ` ${ fctName }`)));
}
if (head.endsWith('=>')) {
head = `${ head } (`;
}
const tail = ((head.endsWith('{') && '}') || ((head.endsWith('(') && ')') || ''));
return `${ head } [hidden source] ${ tail }`;
};
if (
builtInToString.call(_ => 'hide source') === "_ => 'hide source'" &&
builtInToString.call(builtInToString) === 'function toString() { [native code] }'
) {
Object.defineProperty(functionPrototype, 'toString', {
...Object.getOwnPropertyDescriptor(functionPrototype, 'toString'),
value: toString
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment