From 5f017a8c7c182db3fe806ce48525b6ef83b88669 Mon Sep 17 00:00:00 2001 From: muhaoxing <571293251@qq.com> Date: Sat, 2 Sep 2023 11:00:08 +0800 Subject: [PATCH] fix: support for hermes --- packages/json-schema/src/compiler.ts | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/packages/json-schema/src/compiler.ts b/packages/json-schema/src/compiler.ts index 8d1fb85eb01..f1bb82123d9 100644 --- a/packages/json-schema/src/compiler.ts +++ b/packages/json-schema/src/compiler.ts @@ -21,17 +21,24 @@ const ExpRE = /^\s*\{\{([\s\S]*)\}\}\s*$/ const Registry = { silent: false, compile(expression: string, scope = {}) { - expression = expression.replaceAll(/(\$\w+)/g, '$root.$1'); + // 检查如果 scope 前缀都有 $ ,生成的 function 可以不使用 with 操作符 + const prefixed = Object.keys(scope).every((key) => key.startsWith('$')) + if (prefixed) { + expression = expression.replaceAll(/(\$\w+)/g, '$root.$1') + } + expression = prefixed + ? expression.replaceAll(/(\$\w+)/g, '$root.$1') + : expression + const funBody = prefixed + ? `return (${expression});` + : `with($root){ return (${expression});}` + if (Registry.silent) { try { - return new Function('$root', `return (${expression});`)( - scope - ) + return new Function('$root', funBody)(scope) } catch {} } else { - return new Function('$root', `return (${expression});`)( - scope - ) + return new Function('$root', funBody)(scope) } }, }