MCPcopy Create free account
hub / github.com/Openpanel-dev/openpanel / validate

Function validate

packages/js-runtime/src/validate.ts:18–280  ·  view source on GitHub ↗
(code: string)

Source from the content-addressed store, hash-verified

16 * by checking the AST for allowed operations only (allowlist approach)
17 */
18export function validate(code: string): {
19 valid: boolean;
20 error?: string;
21} {
22 if (!code || typeof code !== 'string') {
23 return { valid: false, error: 'Code must be a non-empty string' };
24 }
25
26 try {
27 // Parse the code to AST
28 const ast = parse(code, {
29 sourceType: 'module',
30 allowReturnOutsideFunction: true,
31 plugins: ['typescript'],
32 });
33
34 // Validate root structure: must be exactly one function expression
35 const program = ast.program;
36 const body = program.body;
37
38 if (body.length === 0) {
39 return { valid: false, error: 'Code cannot be empty' };
40 }
41
42 if (body.length > 1) {
43 return {
44 valid: false,
45 error:
46 'Code must contain only a single function. Multiple statements are not allowed.',
47 };
48 }
49
50 const rootStatement = body[0]!;
51
52 // Must be an expression statement containing a function
53 if (rootStatement.type !== 'ExpressionStatement') {
54 if (rootStatement.type === 'VariableDeclaration') {
55 return {
56 valid: false,
57 error:
58 'Variable declarations (const, let, var) are not allowed. Use a direct function expression instead.',
59 };
60 }
61 if (rootStatement.type === 'FunctionDeclaration') {
62 return {
63 valid: false,
64 error:
65 'Function declarations are not allowed. Use an arrow function or function expression instead: (payload) => { ... } or function(payload) { ... }',
66 };
67 }
68 return {
69 valid: false,
70 error: 'Code must be a function expression or arrow function',
71 };
72 }
73
74 const rootExpression = rootStatement.expression;
75 if (rootExpression.type !== 'ArrowFunctionExpression') {

Callers 1

validate.test.tsFile · 0.85

Calls 5

parseFunction · 0.90
walkNodeFunction · 0.90
isPropertyKeyFunction · 0.90
hasMethod · 0.80

Tested by

no test coverage detected