Public
Script
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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 async function extractArgs(code: string) {
const { default: ts } = await import("npm:typescript");
// Create a source file from the code string
const sourceFile = ts.createSourceFile(
"dummy.ts",
code,
ts.ScriptTarget.Latest,
);
// Traverse the abstract syntax tree (AST) to find the function declaration
function findFunctionDeclaration(
node: ts.Node,
): ts.FunctionDeclaration | undefined {
if (ts.isFunctionDeclaration(node)) {
return node;
}
return node.forEachChild(findFunctionDeclaration);
}
// Find the function declaration
const functionDeclaration = findFunctionDeclaration(sourceFile);
if (!functionDeclaration) {
return null;
}
// Extract argument names and types
return functionDeclaration.parameters.map((param) => ({
name: code.slice(param.name.pos, param.name.end).trim(),
type: param.type
? code.slice(param.type.pos, param.type.end).trim()
: "any",
}));
}
October 23, 2023