0

I am working on a custom editor which uses Monaco editor to accept the user snippets (pre-defined in JS lang) and I am using JSHint to evaluate their validity before submitting it to the backend.

There are a set number of custom functions acceptable for a data type as per my app. Let's take an example of String to provide some more clarity on my situation.

I have initialized JSHint using the following script:

String.prototype.myFunc = param => {};
String.prototype.myAnotherFunc = paramTwo => {};

So the two acceptable functions in my program for all strings are myFunc and myAnotherFunc.

However JSHint doesn't throw any TypeErrors if a user enters/calls any other function like

"testString".invalidFunc();

I would like it to throw errors like browser console would do.

enter image description here

I have checked the 'errors' array inside jsHintData variable as well. Could somebody please help me understand where I am going wrong?

Here's my JSHint config if that helps:

    const script = [
    'String.prototype.myFunc = param => {};',
'String.prototype.myAnotherFunc = paramTwo => {};',
'"testString".invalidFunc();'
  ];

  try {
    JSHINT(script, { maxerr: Infinity, asi: true, latedef: true });
    const jsHintData = JSHINT.data();
   } catch (error) {
    return error;
  }
Naser Mohd Baig
  • 155
  • 1
  • 13
  • 1
    That’s not what JSHint is for. It only checks syntax and scoping issues, not types. Try TypeScript instead. – user3840170 Jan 12 '22 at 12:28
  • @user3840170 cool! My codebase is in TS, so I guess I can try this. Are you suggesting the use of eval or Function to evaluate the snippet entered by user? Or are you aware of any repository or npm package that'd help my scenario above? – Naser Mohd Baig Jan 12 '22 at 12:33
  • Note that even with Typescript, you don't have a guarantee that it does not throw errors on runtime. Also it would require the user to also add types to the snippet – A_A Jan 12 '22 at 12:35
  • Afaik, the only way to check if the snippet would produce errors, is to run it (and if the snippet depends on the environment, then you would also need to have identical runtime environments). Depending on what you want to do, idk if that's possible – A_A Jan 12 '22 at 12:37
  • @A_A, yeah I have the types which user needs to enter shown to him via autocomplete suggestions in monaco editor but sometimes they make mistakes. I want to catch that. – Naser Mohd Baig Jan 12 '22 at 12:38

0 Answers0