From 2a618b42b7f51895e86652e4abdbe5a67d3805a4 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Tue, 17 May 2022 00:31:20 +0200 Subject: [PATCH] add evalScope + deprecate extend --- packages/eval/README.md | 2 ++ packages/eval/evaluate.mjs | 18 +++++++++++++++--- packages/eval/test/evaluate.test.mjs | 1 + 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/eval/README.md b/packages/eval/README.md index 6119daea..2909d3c5 100644 --- a/packages/eval/README.md +++ b/packages/eval/README.md @@ -11,6 +11,8 @@ npm i @strudel.cycles/eval --save ## Example +TODO: -extend +evalScope + ```js import { evaluate, extend } from '@strudel.cycles/eval'; import * as strudel from '@strudel.cycles/core'; diff --git a/packages/eval/evaluate.mjs b/packages/eval/evaluate.mjs index 9588ad7d..aeff7bdd 100644 --- a/packages/eval/evaluate.mjs +++ b/packages/eval/evaluate.mjs @@ -7,19 +7,31 @@ This program is free software: you can redistribute it and/or modify it under th import shapeshifter from './shapeshifter.mjs'; import * as strudel from '@strudel.cycles/core'; -const { isPattern } = strudel; +const { isPattern, Pattern } = strudel; export const extend = (...args) => { - // TODO: find a way to make args available to eval without adding it to global scope... - // sadly, "with" does not work in strict mode + console.warn('@strudel.cycles/eval extend is deprecated, please use evalScopep instead'); Object.assign(globalThis, ...args); }; +let scoped = false; +export const evalScope = async (...args) => { + if (scoped) { + console.warn('@strudel.cycles/eval evalScope was called more than once.'); + } + scoped = true; + const modules = await Promise.all(args); + Object.assign(globalThis, ...modules, Pattern.prototype.bootstrap()); +}; + function safeEval(str) { return Function('"use strict";return (' + str + ')')(); } export const evaluate = async (code) => { + if (!scoped) { + await evalScope(); // at least scope Pattern.prototype.boostrap + } const shapeshifted = shapeshifter(code); // transform syntactically correct js code to semantically usable code let evaluated = await safeEval(shapeshifted); if (!isPattern(evaluated)) { diff --git a/packages/eval/test/evaluate.test.mjs b/packages/eval/test/evaluate.test.mjs index b1ef004b..b8c4d2f2 100644 --- a/packages/eval/test/evaluate.test.mjs +++ b/packages/eval/test/evaluate.test.mjs @@ -12,6 +12,7 @@ import * as strudel from '@strudel.cycles/core'; const { fastcat } = strudel; extend({ mini }, strudel); +// TODO: test evalScope describe('evaluate', () => { const ev = async (code) => (await evaluate(code)).pattern._firstCycleValues;