"Code generation from strings disallowed for this context" error in custom math equation parsing command. Looking for suggestions

I’ve been trying to make the following IIFE functional as a NightBot !math command.

(() => {
  // const input = '$(query)';
  const input = '1,354,280 * .7';

  if (/[a-z]/gi.test(input))
    return 'Equation cannot contain letters';

  const cleanedInput: string = input.replace(/,+/g, '');
  let mathResult: number = Function(`'use strict';return (${cleanedInput});`)();
  mathResult = Math.trunc(mathResult * 100) / 100;

  let textResult: string;
  const [digits, ...decimals] = mathResult.toString().split('.');
  const commaSeparated: string = digits
    .split('')
    .reverse()
    .map((v, i, a) => i !== a.length - 1 && (i + 1) % 3 === 0 ? `,${v}` : v)
    .reverse()
    .join('');

  textResult = `${commaSeparated}`;
  if (decimals?.length)
    textResult += `.${decimals.join('')}`;
  textResult = `${input} = ${textResult}`;

  console.log(textResult);
  // return textResult;
})();

but I’m struggling to find a way around the error I’m running into that is quoted in the title.

Most of the posts surrounding this error involve urlFetch which I’m not using.

Really I’m just looking for suggestions on how to possibly proceed here.

I understand the offending line is

let mathResult: number = Function('use strict';return (${cleanedInput});)();

because I’m trying to programmatically generate a function to use during runtime.

Is there any kind of alternative to this behaviour? Maybe some NightBot functionality I’m unaware of? Or maybe a different way to accomplish the same functionality in JS that NightBot permits?

Maybe with the current approach it’s not possible and I’d have to write a more manual math equation parser and not lean on the JS language interpreting and doing the heavy lifting for me?

We disable code generation from strings for security reasons which usually stop eval and new Function () code generation. So the main “do the math” won’t work in a string context.

Also Nightbot supports JavaScript not TypeScript so all of the typings would cause quick errors. A lot of this also seems ‘extra’. I was able to reduce it down to the following.

const c = i => (/[a-z]/gi.test(i) ? 'Equation cannot contain letters' : `${i} = ${Function(`return ${i.replace(/,+/g, '')};`)().toLocaleString('en-US', {maximumFractionDigits: 2})}`);c('3432.34 + 33,343,234.3')

It won’t work in Nightbot for the reason above but I put some work into it so enjoy.

Yeah I just pass it through a online compiler then a minifier before dropping the IIFE into a $(eval ) on the NightBot site.

The TS was just the more legible code I had on hand when writing the post.

Thank you for the explanation around the Function ctor and eval being disabled.

I’ll expand the code to parse and process the symbology and scopes manually.

the !math command i made was far more simple… i let nightbot figure it out, lol… like this…

$(eval b=`$(eval a=$(query);`The answer to $(query) is ${a}`)`;c=b.split(` `);if(c[0]+c[1]==`Theanswer`){b}else{`I'm a bot from earth, if "$(query)" is math, then it must be some kinda alien math I wasn't programmed for.`})

because it’ll automatically calculate whatever expression u add to the a variable since it doesn’t have any quotes/backticks… and if they add anything other than a mathematical expression (excluding variables) it’ll error out and the outer $(eval) catches it and can respond with whatever u want :wink:

p.s. it doesn’t add the commas like u have tho, but plenty of room in the command to add that

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.