From c8eb9cfc64925f25c2ffcaee68e232e242484f15 Mon Sep 17 00:00:00 2001 From: Kei Kamikawa Date: Sat, 6 Apr 2024 19:48:01 +0900 Subject: [PATCH] fixed #602 --- src/directive.ts | 17 ++++++++++++++- tests/directive.spec.ts | 48 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/directive.ts b/src/directive.ts index 25efdb1d..944585f4 100644 --- a/src/directive.ts +++ b/src/directive.ts @@ -182,10 +182,15 @@ function stringify(arg: any, quoteString?: boolean): string { if (isConvertableRegexp(arg)) return arg; + const v = tryEval(arg) + if (v !== undefined) + arg = v + if (quoteString) return JSON.stringify(arg); } - if (typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'bigint') + + if (typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'bigint' || arg === 'undefined' || arg === null) return `${arg}`; return JSON.stringify(arg); @@ -199,6 +204,16 @@ function apiArgsFromConstValueNode(value: ConstValueNode): any[] { return [val]; } +function tryEval(maybeValidJavaScript: string): any | undefined { + try { + // eslint-disable-next-line no-eval + return eval(maybeValidJavaScript) + } + catch { + return undefined + } +} + export const exportedForTesting = { applyArgToApiSchemaTemplate, buildApiFromDirectiveObjectArguments, diff --git a/tests/directive.spec.ts b/tests/directive.spec.ts index dfd76345..73059e6e 100644 --- a/tests/directive.spec.ts +++ b/tests/directive.spec.ts @@ -190,6 +190,38 @@ describe('format directive config', () => { }, want: 'true', }, + { + name: 'eval number', + args: { + template: '$1', + apiArgs: ['10 + 1'], + }, + want: '11', + }, + { + name: 'eval boolean', + args: { + template: '$1', + apiArgs: ['!true'], + }, + want: 'false', + }, + { + name: 'eval template with number', + args: { + template: '$1 + 1', + apiArgs: [10], + }, + want: '11', + }, + { + name: 'eval template with boolean', + args: { + template: '$1 && false', + apiArgs: [true], + }, + want: 'false', + }, { name: 'array', args: { @@ -206,6 +238,22 @@ describe('format directive config', () => { }, want: `{"hello":"world"}`, }, + { + name: 'undefined', + args: { + template: '$1', + apiArgs: ['undefined'], + }, + want: 'undefined', + }, + { + name: 'null', + args: { + template: '$1', + apiArgs: ['null'], + }, + want: 'null', + }, { name: 'multiple', args: {