Monday, 22 March 2021

How to statically validate JS construction statement by statement

I have JS as defined below (JS File). On push to a repo I want to statically validate things defined below (Validate This). I've been researching this and my first idea is to validate items 1-4 using https://www.npmjs.com/package/espree. Appreciate it if someone can confirm if this would do the job (be the best method) and if so an example validating the returned AST.

Validating item 5 is a little more interesting I need to extract the contents that w.abc.myobj is set which will effectively always equate to JSON and validate it's contents against rules using something like https://www.npmjs.com/package/ajv. Appreciate any insights on how best to do this as well especially the extraction of the JSON from the static code file.

Validate This

/* 
1. Is the first statement a try/catch block
2. Is the first statement within the try/catch block an anonymous function with a "w" arg
3. Is the second statement what is shown
4. Is the anonymous function called with the window object
5. Next i'd like to grab w.abc.myobj and validate it using schema validation.
*/

JS File

try {
  (function (w) {
    w.abc = w.abc || {};
    w.abc.myobj = {
      "prop1": {
        "enabled": true,
        "type": "non-fiction",
        "params: {
          "serverInfo": {
            "url": "{arg} ? https://www.url1.com : https://www.url2.com",
            "path": "/some/directory"
          },
          "accountInfo: {
            "user": "someUser1"
          }
        }
      },
      "prop2: {
        "enabled": true,
        "type": "fiction",
        "params": {
          "serverInfo": {
            "url": "https://www.url2.com",
            "path": "/some/directory"
          },
          "accountInfo: {
            "user": "someUser2"
          }
        }
      }
    };
  })(window);
} catch (e) { /* do nothing */ }


from How to statically validate JS construction statement by statement

No comments:

Post a Comment