Finds the top level named val that triggered the execution of this val. (Ignores any untitled vals, since those are sometimes created as an execution context.)

By passing a function as the first argument you receive all references as arguments, and can pick or transform them, e.g.

Possible Limitation: https://discord.com/channels/1020432421243592714/1143386413748994143

Readme
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
export function mainReference<T = ValRef>(transform?: Transform<T>): T {
const stack = new Error().stack;
let refs: ValRef[] = stack.match(/@@({.+?})@@/g).reverse().map((e) =>
JSON.parse(e.slice(2, -2))
);
const splitStack = stack.split("\n ");
//console.log("mainReference:stack", splitStack.length, splitStack);
//console.log("mainReference:all", refs);
refs = refs.filter(({ userHandle, valName, callNumber }) => {
if (
typeof userHandle !== "string" || typeof valName !== "string" ||
typeof callNumber !== "number"
)
return false;
// sometimes a dynamic val is created on the top level
if (valName.startsWith("untitled_"))
return false;
return true;
});
// console.log('mainReference:filtered', refs);
if (transform)
return transform(...refs);
return refs[0] as T;
}
type ValRef = {
userHandle: string;
valName: string;
callNumber?: number;
};
type Transform<T> = (...ref: ValRef[]) => T;
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.