@oracle/oraclejet-audit 12.0.0 → 13.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/jaf-amd.js +2 -20
- package/jaf.js +1 -1
- package/jafapi.js +1 -1
- package/lib/AST_Ts.js +1 -1
- package/lib/AstJson.js +1 -1
- package/lib/AstMd.js +1 -1
- package/lib/AstNodeTypes.js +1 -1
- package/lib/Cli.js +6 -0
- package/lib/Color.js +6 -0
- package/lib/Comments.js +1 -1
- package/lib/ComponentSvcs.js +1 -1
- package/lib/Components.js +1 -1
- package/lib/Config.js +1 -1
- package/lib/ConfigLib.js +1 -1
- package/lib/CssUtils.js +1 -1
- package/lib/DomUtils.js +1 -1
- package/lib/FileSet.js +1 -1
- package/lib/FsUtils.js +1 -1
- package/lib/Issue.js +1 -1
- package/lib/JafEvents.js +1 -1
- package/lib/JafLib.js +1 -1
- package/lib/Json.js +1 -1
- package/lib/JsonLoader.js +1 -1
- package/lib/Md.js +1 -1
- package/lib/MetaLib.js +1 -1
- package/lib/OjCPack.js +6 -0
- package/lib/OjetLib.js +6 -0
- package/lib/Registry.js +1 -1
- package/lib/RuleSet.js +1 -1
- package/lib/Rules.js +1 -1
- package/lib/Scope.js +1 -1
- package/lib/Utils.js +1 -1
- package/lib/ZipUtils.js +1 -1
- package/lib/amdlist.js +6 -0
- package/lib/api.js +1 -1
- package/lib/betalist.js +6 -0
- package/lib/builtinpacks.js +1 -1
- package/lib/checkage.js +6 -0
- package/lib/cliStats.js +1 -1
- package/lib/cmdline.js +1 -1
- package/lib/defaults.js +1 -1
- package/lib/deflist.js +1 -1
- package/lib/dislist.js +1 -1
- package/lib/exportRules.js +1 -1
- package/lib/extends.js +1 -1
- package/lib/grouplist.js +1 -1
- package/lib/groups.js +1 -1
- package/lib/help.js +1 -1
- package/lib/jetver.js +1 -1
- package/lib/manpage.js +6 -0
- package/lib/manual.js +1 -1
- package/lib/metaLoader.js +1 -1
- package/lib/metahist.js +1 -1
- package/lib/msgidLoader.js +1 -1
- package/lib/ns.js +1 -1
- package/lib/outfile.js +1 -1
- package/lib/proflist.js +6 -0
- package/lib/rlolist.js +6 -0
- package/lib/scaffold.js +1 -1
- package/lib/scaffoldRule.js +1 -1
- package/lib/schema.js +1 -1
- package/lib/scopewalker.js +1 -1
- package/meta/12.1.0/jetauditmeta.js +9 -0
- package/meta/13.0.0/jetauditmeta.js +9 -0
- package/meta/metaverlist.json +1 -1
- package/package.json +6 -4
- package/profiles/best-practice.json +146 -0
- package/profiles/redwood-strict.json +31 -0
- package/rulepacks/jetwc/jetwc-bootstrap.js +1 -1
- package/rulepacks/jetwc/jetwc-css-oj-complete.js +1 -1
- package/rulepacks/jetwc/jetwc-pack-children.js +1 -1
- package/rulepacks/jetwc/jetwc-schema.js +1 -1
- package/rulepacks/jetwc/jetwc-supproperty-propagation.js +6 -0
- package/rulepacks/jetwc/msgid.json +1 -1
- package/rulepacks/jetwc/rules.json +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-componentFinder.js +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-preCompiler.js +1 -1
- package/rulepacks/jetwco/jetwco-bootstrap.js +1 -1
- package/rulepacks/jetwco/jetwco-component-api-controlled-changes.js +1 -1
- package/rulepacks/jetwco/rules.json +1 -1
- package/rules/jaf/jaf-sys-age.js +6 -0
- package/rules/jaf/jaf-ts-walk.js +6 -0
- package/rules/jaf/msgid.json +1 -1
- package/rules/jaf/rules.json +1 -1
- package/rules/jet/helpers/extractStylesFromClass.js +1 -1
- package/rules/jet/msgid.json +1 -1
- package/rules/jet/oj-acc-aria-ojselector-labelledby.js +6 -0
- package/rules/jet/oj-acc-aria-prop.js +1 -1
- package/rules/jet/oj-c-acc-avatar-aria-role.js +6 -0
- package/rules/jet/oj-cca-compjson-bp-jetver.js +1 -1
- package/rules/jet/oj-css-style-override.js +1 -1
- package/rules/jet/oj-css-var-override.js +1 -1
- package/rules/jet/oj-html-alta-deprecated.js +1 -1
- package/rules/jet/oj-html-attr-2def.js +1 -1
- package/rules/jet/oj-html-attr-req.js +1 -1
- package/rules/jet/oj-html-cca-tagname.js +1 -1
- package/rules/jet/oj-html-cdn.js +1 -1
- package/rules/jet/oj-html-combo-converter.js +1 -1
- package/rules/jet/oj-html-file-pick-accept.js +1 -1
- package/rules/jet/oj-html-notag-style.js +1 -1
- package/rules/jet/oj-html-ojattr-deprecated.js +1 -1
- package/rules/jet/oj-html-ojattr-enum-deprecated.js +1 -1
- package/rules/jet/oj-html-ojattr-evt-syntax.js +1 -1
- package/rules/jet/oj-html-ojattr-value.js +1 -1
- package/rules/jet/oj-html-ojattr.js +1 -1
- package/rules/jet/oj-html-ojtag-deprecated.js +1 -1
- package/rules/jet/oj-html-pageopts-type.js +6 -0
- package/rules/jet/oj-html-rating-gauge-size.js +6 -0
- package/rules/jet/oj-html-redwood-bp-endslot.js +6 -0
- package/rules/jet/oj-html-slot-deprecated.js +6 -0
- package/rules/jet/oj-html-slot-pref-content.js +1 -1
- package/rules/jet/oj-html-wctag-maintenance.js +6 -0
- package/rules/jet/rules.json +1 -1
- package/schema/component-schema.json +1 -1482
- package/src/JafCore.js +1 -1
- package/types/index.d.ts +38 -9
- package/lib/colors.js +0 -6
package/lib/OjetLib.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2022, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
function OJetLib(ojetConfig,tsConfig,appPath){this._ojetConfig=ojetConfig;this._tsConfig=tsConfig;this._appPath=appPath;this._isVDom=false;let arch;if(arch=this.getConfigProperty("architecture")){this._isVDom=arch==="vdom"}};OJetLib.prototype.getConfig=function(){return this._ojetConfig};OJetLib.prototype.getTsConfig=function(){return this._tsConfig};OJetLib.prototype.getConfigProperty=function(prop){return _getProp(this._ojetConfig,prop)};OJetLib.prototype.getTsConfigProperty=function(prop){return _getProp(this._tsConfig,prop)};OJetLib.prototype.getAppPath=function(){return this._appPath};OJetLib.prototype.isVDom=function(){return this._isVDom};function _getProp(obj,prop){var ret;if(obj){let props=prop.split(".");let p;for(let i=0;i<props.length;i++){p=props[i];if(obj.hasOwnProperty(p)){ret=obj[p];if(i+1<props.length){if(Array.isArray(ret)||typeof ret!=="object"){ret=null;break}obj=ret}continue}ret=null;break}}return ret};module.exports=OJetLib;
|
package/lib/Registry.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const RULE_RE=new RegExp(/[~`!#$%\^&*+\[\]\\';,/{}|\\"\?]/);var Registry=function(appCtx){this._registry={};this._regexps={};this._reObjs={};this._appCtx=appCtx;this._info=appCtx.info;this._assert=appCtx.assert};Registry.prototype.getRegisteredCallbacks=function(type){var reo,ret;ret=this._registry[type];if(!type.startsWith("css-")&&type.indexOf("-")>0&&type.indexOf("|")<0){ret={...ret};type=type.substring(1,type.length-1).trim();for(re in this._regexps){reo=this._reObjs[re];if(reo&&reo.test(type)){if(!ret){ret={}}for(x in this._regexps[re]){ret[x]=this._regexps[re][x]}}};}return ret};Registry.prototype.isRegisteredCallback=function(type){return!!this._registry[type]};Registry.prototype.isRegisteredCallbackRE=function(elem){var ret,i;if(ret=this.isRegisteredCallback(elem)){return ret}elem=elem.startsWith("<")?elem.substring(1,elem.length-1):elem;for(re in this._regexps){if(this._reObjs[re].test(elem)){return true}}return false};Registry.prototype.setRuleCallback=function(ruleName,ruleRegs,rsi){var typeObj,regType,rt,callbacks,func,args,elem;for(regType in ruleRegs){func=ruleRegs[regType];if(typeof func!=="function"){this._info(`Rule ${ruleName} : registered '${regType}' is not a function`);continue}rt=elem=regType;if(regType.charAt(0)==="<"){rt=regType.substring(1,regType.length-1).trim();args=rt.split(" ");if(args.length>1){attrib=args[args.length-1];if(attrib.endsWith("=")){rt=args[0]+"|"+attrib.substring(0,attrib.length-1)}elem=args[0]}else{elem=rt.endsWith("=")?null:rt}regType=`<${rt}>`}if(!elem||!_isRE(elem)){if(!(typeObj=this._registry[regType])){this._registry[regType]=typeObj={}}}else{if(!(typeObj=this._regexps[rt])){this._regexps[rt]=typeObj={}}if(!this._reObjs[rt]){this._reObjs[rt]=new RegExp(rt)}}if(!(callbacks=typeObj[ruleName])){typeObj[ruleName]=callbacks=[]}callbacks.push({cb:func,rsi:rsi})}};Registry.prototype.XXsetRuleCallback=function(ruleName,ruleRegs,rsi){var typeObj,callbackType,ruleCallbacks,func;if(Array.isArray(ruleRegs)){var jj=this._setRuleCallback2(ruleName,ruleRegs)}else if(typeof ruleRegs!=="object"){return}else if(ruleRegs.cb){let regs=this._setExtended(ruleName,ruleRegs,rsi);if(regs){ruleRegs=regs}}for(callbackType in ruleRegs){func=ruleRegs[callbackType];if(typeof func!=="function"){this._info("Rule "+ruleName+" : registered '"+callbackType+"' is not a function");continue}typeObj=this._registry[callbackType];if(!typeObj){this._registry[callbackType]=typeObj={}}ruleCallbacks=typeObj[ruleName];if(!ruleCallbacks){typeObj[ruleName]=ruleCallbacks=[]}ruleCallbacks.push({cb:func,rsi:rsi})}};Registry.prototype.XXsetRuleCallback2=function(ruleName,regs,rsi){var a,i,j,props,prop,reg,val;for(i=0;i<regs.length;i++){reg=regs[i];if(!reg.cb){if(!a){a=[]}a.push(reg);continue}props=Object.keys(reg);if(props.length===2){for(j=0;j<props.length;j++){prop=props[j];if(prop!=="cb"){val=reg[prop];if(typeof val==="boolean"&&val){a.push({prop:val});break}}}continue}}};Registry.prototype.dump=function(){var type,rule,vals,tagWidth,tagLen=0,indent,isFirst,s="";var list2={},ruleWidth,ruleLen=0,source,i;for(type in this._registry){if(type.length>tagLen){tagLen=type.length}}for(type in this._regexps){if(type.length>tagLen){tagLen=type.length}}tagWidth=tagLen+3;indent=" ".repeat(tagWidth);s="\n"+ljustify("--- Tags ---",indent.length,indent)+"----- rules -----";source=this._registry;for(i=0;i<2;i++){for(type in source){s+="\n"+ljustify(type,tagWidth,indent);vals=source[type];isFirst=true;for(rule in vals){s+=(isFirst?"":indent)+rule+"\n";isFirst=false;if(!list2[rule]){list2[rule]=[]}list2[rule].push(type);if(rule.length>ruleLen){ruleLen=rule.length}}}source=this._regexps}ruleWidth=ruleLen+2;indent=" ".repeat(ruleWidth);s+="\n"+ljustify("----- Rules -----",indent.length,indent)+"--- Tags ---";for(rule in list2){vals=list2[rule];s+="\n"+ljustify(rule,ruleWidth,indent);isFirst=true;for(i=0;i<vals.length;i++){s+=(isFirst?"":indent)+vals[i]+"\n";isFirst=false}}return s+"\n"};function ljustify(n,w,blanks){var s=n.toString();var l=s.length;return s+blanks.substr(0,w-l)};function _isRE(s){return RULE_RE.test(s)};module.exports=Registry;
|
|
6
|
+
const RULE_RE=new RegExp(/[~`!#$%\^&*+\[\]\\';,/{}|\\"\?]/);var Registry=function(appCtx){this._registry={};this._regexps={};this._reObjs={};this._appCtx=appCtx;this._info=appCtx.info;this._assert=appCtx.assert};Registry.prototype.getRegisteredCallbacks=function(type){var reo,ret;ret=this._registry[type];if(!type.startsWith("css-")&&type.indexOf("-")>0&&type.indexOf("|")<0){ret={...ret};type=type.substring(1,type.length-1).trim();for(re in this._regexps){reo=this._reObjs[re];if(reo&&reo.test(type)){if(!ret){ret={}}for(x in this._regexps[re]){ret[x]=this._regexps[re][x]}}};}return ret};Registry.prototype.isRegisteredCallback=function(type){return!!this._registry[type]};Registry.prototype.isRegisteredCallbackRE=function(elem){var ret,i;if(ret=this.isRegisteredCallback(elem)){return ret}elem=elem.startsWith("<")?elem.substring(1,elem.length-1):elem;for(re in this._regexps){if(this._reObjs[re].test(elem)){return true}}return false};Registry.prototype.setRuleCallback=function(ruleName,ruleRegs,rsi){var typeObj,regType,rt,callbacks,func,args,elem;for(regType in ruleRegs){func=ruleRegs[regType];if(typeof func!=="function"){this._info(`Rule ${ruleName} : registered '${regType}' is not a function`);continue}rt=elem=regType;if(regType.charAt(0)==="<"){rt=regType.substring(1,regType.length-1).trim();args=rt.split(" ");if(args.length>1){attrib=args[args.length-1];if(attrib.endsWith("=")){rt=args[0]+"|"+attrib.substring(0,attrib.length-1)}elem=args[0]}else{elem=rt.endsWith("=")?null:rt}regType=`<${rt}>`}if(!elem||!_isRE(elem)){if(!(typeObj=this._registry[regType])){this._registry[regType]=typeObj={}}}else{if(!(typeObj=this._regexps[rt])){this._regexps[rt]=typeObj={}}if(!this._reObjs[rt]){this._reObjs[rt]=new RegExp(rt)}}if(!(callbacks=typeObj[ruleName])){typeObj[ruleName]=callbacks=[]}callbacks.push({cb:func,rsi:rsi})}};Registry.prototype.XXsetRuleCallback=function(ruleName,ruleRegs,rsi){var typeObj,callbackType,ruleCallbacks,func;if(Array.isArray(ruleRegs)){var jj=this._setRuleCallback2(ruleName,ruleRegs)}else if(typeof ruleRegs!=="object"){return}else if(ruleRegs.cb){let regs=this._setExtended(ruleName,ruleRegs,rsi);if(regs){ruleRegs=regs}}for(callbackType in ruleRegs){func=ruleRegs[callbackType];if(typeof func!=="function"){this._info("Rule "+ruleName+" : registered '"+callbackType+"' is not a function");continue}typeObj=this._registry[callbackType];if(!typeObj){this._registry[callbackType]=typeObj={}}ruleCallbacks=typeObj[ruleName];if(!ruleCallbacks){typeObj[ruleName]=ruleCallbacks=[]}ruleCallbacks.push({cb:func,rsi:rsi})}};Registry.prototype.XXsetRuleCallback2=function(ruleName,regs,rsi){var a,i,j,props,prop,reg,val;for(i=0;i<regs.length;i++){reg=regs[i];if(!reg.cb){if(!a){a=[]}a.push(reg);continue}props=Object.keys(reg);if(props.length===2){for(j=0;j<props.length;j++){prop=props[j];if(prop!=="cb"){val=reg[prop];if(typeof val==="boolean"&&val){a.push({prop:val});break}}}continue}}};Registry.prototype.isEmpty=function(){return!this._appCtx.utils.hasAnyProps(this._registry)};Registry.prototype.dump=function(){var type,rule,vals,tagWidth,tagLen=0,indent,isFirst,s="";var list2={},ruleWidth,ruleLen=0,source,i;for(type in this._registry){if(type.length>tagLen){tagLen=type.length}}for(type in this._regexps){if(type.length>tagLen){tagLen=type.length}}if(!tagLen){return"\n-- No rules enabled - nothing to report --\n"}tagWidth=tagLen+3;indent=" ".repeat(tagWidth);s="\n"+ljustify("--- Tags ---",indent.length,indent)+"----- rules -----";source=this._registry;for(i=0;i<2;i++){for(type in source){s+="\n"+ljustify(type,tagWidth,indent);vals=source[type];isFirst=true;for(rule in vals){s+=(isFirst?"":indent)+rule+"\n";isFirst=false;if(!list2[rule]){list2[rule]=[]}list2[rule].push(type);if(rule.length>ruleLen){ruleLen=rule.length}}}source=this._regexps}ruleWidth=ruleLen+2;indent=" ".repeat(ruleWidth);s+="\n"+ljustify("----- Rules -----",indent.length,indent)+"--- Tags ---";for(rule in list2){vals=list2[rule];s+="\n"+ljustify(rule,ruleWidth,indent);isFirst=true;for(i=0;i<vals.length;i++){s+=(isFirst?"":indent)+vals[i]+"\n";isFirst=false}}return s+"\n"};function ljustify(n,w,blanks){var s=n.toString();var l=s.length;return s+blanks.substr(0,w-l)};function _isRE(s){return RULE_RE.test(s)};module.exports=Registry;
|
package/lib/RuleSet.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const REG=require("./RegTypes");const FILETYPE=require("./filetypes");const RULE_FILE="rules.json";const BUILTIN_RULES_PATH="../rules/";const BUILTIN_RULEPACK_PATH="../rulepacks/";const JAF_BUILTIN_RULES_PATH=BUILTIN_RULES_PATH+"jaf";const JET_BUILTIN_RULES_PATH=BUILTIN_RULES_PATH+"jet";const SPOC_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"spoc";const CSP_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"csp";const JETWC_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"jetwc";const JETWCO_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"jetwco";const VCOMPMIG_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"ojcmig";const WEBDRIVER_TEST_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"wdt";const JET_MIN_VERSION="5.2.0";const TEMP_FILE_TEMPLATE="@@rpziptmp-XXXXXX";const PROP_$BUILTIN="$builtin";const PROP_$REQUIRED="$required";const RESERVED_RULE_PREFIX=["oj-","jaf-","csp-","spoc-","jetwc-","jetwco-","exch-","demo-"];const RESERVED_PACK_PREFIX=["JAF","JET","SPOC","CSP","JETWC","JETWCO","DEMO"];const NO_MSGID_PACKS=[];const RULE_STATUS=["prod","production","ready","beta","alpha","deprecated"];const FUNCTION="function";const COLON=":";const RULE_RE=new RegExp(/[~`!#$%\^&*+\[\]\\';,/{}|\\"\?]/,"g");const RulePack=require("./RulePack");const Registry=require("./Registry");const SemVer=require("./SemVer");const CssUtils=require("./CssUtils");const AstNodeTypes=require("./AstNodeTypes");const clone=require("./clone");var RuleSet=function(config,nodeDeps,appCtx,AMDRulePacks){this._config=config;this._ruleSets=config.getRulePacks();this._ruleMods=config.getRuleMods();this._ruleCount=0;this._AmdPacks=AMDRulePacks;this._appCtx=appCtx;this._nodeDeps=nodeDeps;this._isAMD=!!nodeDeps.AmdRulePackLoader;this._isCLI=appCtx.runMode==="cli";this._isCliOrApi=!this._isAMD;this._metaLib=appCtx.metaLib;this._utils=appCtx.utils;this._severity=appCtx.severity;this._tmpDir=appCtx.tmpDir;this._semVer=new SemVer;this._targFiletypes=[];this._useBuiltinRules=config._config.builtinJetRules;this._rulePacks=null;this._shadowRulePacks=null;this._rulesetSummary=[];this._registerCtx={sysOpts:{verboseMode:this._appCtx.verboseMode,debugMode:this._appCtx.debugMode}};this._registerCtx.utils={};this._registerCtx.utils.metaLib=this._metaLib;this._registerCtx.runMode=appCtx.runMode;this._registerCtx.VsCodeExtHint=appCtx.VsCodeExtHint;this._registerCtx.utils.semVerUtils=this._semVer;this._registerCtx.utils.utils=this._utils;this._registerCtx.utils.CssUtils=CssUtils;this._registerCtx.config=JSON.parse(JSON.stringify(this._config._config));this._registerCtx.error=appCtx.error;this._registerCtx.info=appCtx.info;this._registerCtx.msg=appCtx.msg;this._registerCtx.utils.msgLib={msg:appCtx.msg,error:appCtx.error,info:appCtx.info,debug:appCtx.debug,assert:appCtx.assert};this._registerCtx.utils.sevLib=this._severity.getSevLib();this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._assert=appCtx.assert;this._debugMode=appCtx.debugMode;this._verboseMode=appCtx.verboseMode;if(!this._ruleSets){this._ruleSets=[]}let rsi=0;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,JAF_BUILTIN_RULES_PATH):null,"builtin":true});if(config._config.builtinJetRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,JET_BUILTIN_RULES_PATH):null,"builtin":true})}if(config._config.builtinCspRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,CSP_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinJetWcRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,JETWC_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinJetWcOracleRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,JETWCO_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinSpocRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,SPOC_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinOjcMigrationRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,VCOMPMIG_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinWebDriverTestRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,WEBDRIVER_TEST_BUILTIN_RULES_PATH),"builtin":true})}if(this._isAMD&&this._AmdPacks){let i,apack;for(i=0;i<this._AmdPacks.length;i++){apack=this._AmdPacks[i];this._ruleSets.splice(rsi++,0,{enabled:true,path:null,builtin:false,amdpack:apack})}}};RuleSet.prototype.loadRulePacks=function(config,isDryRun,isRuleDump){var ruleSet,rulePath,rulesJson,rulePack,rsi,rule,prefix,groups,gname,arules,j,k,s="",rulesetSummaryIndex=-1,spocFound,demoFound,errors=false,rc,ruleName,jetVersion;this._config=config;this._confSeverity=config._sev;this._confNamedRules=config.ruleNames;jetVersion=this._metaLib.getRevisionInfo().jetVersion;if(!this._semVer.setReference(jetVersion,JET_MIN_VERSION)){this._error(`JET metadata version ${jetVersion} not supported (less than ${JET_MIN_VERSION})`);return false}if(this._debugMode){this._debug(this._ruleSets?"Processing "+this._ruleSets.length+" Rule Sets":"No Rule Sets defined")}if(!this._ruleSets){return false}this._rulePacks=[];this._shadowRulePacks=[];for(rsi=0;rsi<this._ruleSets.length;rsi++){ruleSet=this._ruleSets[rsi];groups=null;try{if(typeof ruleSet.enabled==="boolean"&&!ruleSet.enabled){s+=(rsi?"\n":"")+" "+(rsi+1)+") "+"Disabled ruleSet at '"+ruleSet.path;continue}if(!ruleSet.status){ruleSet.status=["all"]}if(!this._isAMD){if(this._debugMode){let rname=ruleSet.path.endsWith("jaf")?"JAF":ruleSet.path.endsWith("jet")?"JET":ruleSet.name;this._debug("Ruleset '"+rname+"' path->'"+ruleSet.path+"'")}if(ruleSet.path.endsWith(".zip")){ruleSet.container=ruleSet.path;let tmpFile=this._nodeDeps.fsUtils.getUniqueFileName(TEMP_FILE_TEMPLATE);let tmpDir=this._nodeDeps.path.join(this._tmpDir,tmpFile);rc=this._nodeDeps.fsUtils.createFolder(tmpDir);if(typeof rc!=="boolean"){this._error(`Unable to create folder ${rc.message}`);break}var zipUtils=new this._nodeDeps.zipUtils;;rc=zipUtils.extractAll(tmpDir,ruleSet.container,true);if(typeof rc!=="boolean"){this._error(`Unable to extract from zip ('${rc.message}') : "${ruleSet.container}"`);break}ruleSet.path=tmpDir}rulePath=this._nodeDeps.path.join(ruleSet.path,RULE_FILE);rulesJson=this._loadJson(rulePath)}else{if(ruleSet.builtin){rulesJson=this._nodeDeps.AmdRulePackLoader(this._nodeDeps,rsi,ruleSet,this._error)}else if(ruleSet.amdpack){rulesJson=ruleSet.amdpack.rulesJson}}if(!rulesJson){continue}if(!rulesJson.title){rulesJson.title="unknown"}if(!rulesJson.version){rulesJson.version="0.0.0"}prefix=rulesJson.prefix;ruleSet.prefix=prefix;s+=(rsi?"\n":"")+" "+(rsi+1)+") "+rulesJson.title+"\n "+rulesJson.version+" : "+prefix+(ruleSet.builtin||ruleSet.amdpack?"":" -> "+(ruleSet.container?ruleSet.container:ruleSet.path));if(this._appCtx.isUnitTest&&!spocFound&&prefix==="SPOC"){ruleSet.builtin=true;if(prefix==="SPOC"){spocFound=true}if(prefix==="DEMO"){demoFound=true}}if(!demoFound&&prefix==="DEMO"){ruleSet.builtin=true;if(prefix==="DEMO"){demoFound=true}}if(!ruleSet.builtin){if(RESERVED_PACK_PREFIX.includes(prefix)){this._error("Rule pack at '"+rulePath+"' cannot use use reserved prefix '"+prefix+"'!");break}}for(j=0;j<this._rulesetSummary.length;j++){if(this._rulesetSummary[j].prefix===prefix){this._error("Rule pack prefix '"+prefix+"' at '"+rulePath+"' ignored - previously defined at '"+rulePack.path+"'");break}}if(j<this._rulesetSummary.length){continue}this._rulesetSummary.push({title:rulesJson.title,path:ruleSet.path,version:rulesJson.version,prefix:rulesJson.prefix,status:ruleSet.status,packData:ruleSet.packData});++rulesetSummaryIndex;var reorder,nonReq,reqList=[];reorder=nonReq=false;reqList.length=0;for(ruleName in rulesJson.rules){rule=rulesJson.rules[ruleName];rule._rsi=rulesetSummaryIndex;if(this._ruleSets[rulesetSummaryIndex].builtin){rule[PROP_$BUILTIN]=true}if(rule[PROP_$REQUIRED]){if(!reorder){reorder=nonReq}reqList.push(ruleName)}else{nonReq=true}if(rule.group){groups=groups||{};let rg=rule.group;if(typeof rg==="string"){arules=groups[rg];if(!arules){groups[rg]=arules=[]}arules.push(ruleName)}else if(Array.isArray(rg)){for(k=0;k<rg.length;k++){gname=rg[k];arules=groups[gname];if(!arules){groups[gname]=arules=[]}arules.push(ruleName)}}}}if(reorder){rulesJson.rules=this._promoteRequired(rulesJson.rules,rulesJson.prefix,reqList)}this._rulePacks.push({path:ruleSet.path,rulesJson:rulesJson});ruleSet.groupMap=groups;this._mergeRuleOptions(rulesJson,ruleSet.builtin)}catch(e){this._error(`Failure processing ruleset at '${rulePath}' (${e.message})`);errors=true}}if(s.length){this._info("[info]: ------ Rulepacks found: --------");this._info(s)}if(this._debugMode){this._debug("------ group mappings : --------");let self=this;this._ruleSets.forEach(s=>{self._debug(s.prefix+": "+(s.groupMap?JSON.stringify(s.groupMap,null,3):"none"))})}if(errors){return false}this._registry=new Registry(this._appCtx);this._postProcess_RuleMods();this._postProcess_RuleNames();if(!this._processRuleSets()){return false}if(config.options.debug&&!isRuleDump||config.options.verbose&&!isRuleDump||isDryRun){var f=isDryRun||config.options.verbose?this._info:this._debug;var rules,opts;if(this._ruleCount){f("\n-------- Active Rule Summmary --------");for(rsi=0;rsi<this._rulePacks.length;rsi++){rulePack=this._rulePacks[rsi];f("\n ["+(rsi+1)+"] Rule Set '"+rulePack.rulesJson.title+"'");rules=rulePack.rulesJson.rules;let n=0;for(ruleName in rules){opts=rules[ruleName];if(opts.enabled){f("\n "+ruleName+" : "+JSON.stringify(this._utils.extend(opts)));n++}}if(!n){f("\n "+"No rules enabled in pack.")}}}}return!errors};RuleSet.prototype._postProcess_RuleMods=function(){var rs,rm,are,ard,count=0,n;rm=this._config.ruleMods;if(rm&&(rm.enable||rm.disable)){rs=this._ruleSets;are=rm.enable;if(are){n=_replaceGroups(are,rs);if(n){are=_removeDups(are);count+=n}}ard=rm.disable;if(ard){n=_replaceGroups(ard,rs);if(n){ard=_removeDups(ard);count+=n}}this._enableDisableGroupRules(are,ard)}return count};RuleSet.prototype._enableDisableGroupRules=function(are,ard){var ar,rname,packs,rules,rule,enable,m1,i,j,k;if(this._verboseMode||this._debugMode){this._info("\n[Info]: --- Enabling rules found in ruleMods.enable ---");if(!are){this._info("* None found")}}packs=this._rulePacks;i=2;ar=are;enable=true;m1="enabled";while(i){if(ar){for(j=0;j<ar.length;j++){rname=ar[j];for(k=0;k<packs.length;k++){rules=packs[k];if(rules){rules=rules.rulesJson;if(rules){rule=rules.rules[rname];if(rule){if(!enable&&rule.$required){this._error(`rule '${rname}' is mandatory and cannot be disabled using config 'ruleMods.disable' property.`);continue}rule.enabled=enable;if(this._verboseMode||this._debugMode){this._info(` Rule ${rname} ${m1}`)}break}}}}}}if(enable){ar=ard;if(this._verboseMode||this._debugMode){this._info("\n[Info]: --- Disabling rules found in ruleMods.disable ---");m1="disabled";if(!ard){this._info("* None found")}}if(!ard){return}}enable=false;i--}};RuleSet.prototype._postProcess_RuleNames=function(){var ret=0;if(this._verboseMode||this._debugMode){this._info("\n[Info]: --- Processing config ruleNames entries ---")}if(this._config.ruleNames){ret=_replaceGroups(this._config.ruleNames,this._ruleSets);this._config.ruleNames=_removeDups(this._config.ruleNames)}if(this._verboseMode||this._debugMode){this._info(`\n[Info]: ${ret} ruleNames group entr${ret===1?"y":"ies"} replaced ---`)}return ret};function _replaceGroups(ar,rs){var val,o,group,grules,rc=0,rsi,i;var replaced=[];for(i=0;i<ar.length;i++){val=ar[i];replaced.length=0;for(rsi=0;rsi<rs.length;rsi++){o=rs[rsi];if(o.groupMap){for(group in o.groupMap){if(group===val){grules=o.groupMap[group];replaced.push(...grules);break}}}}if(replaced.length){ar.splice(i,1,...replaced);i+=replaced.length-1;rc++}}return rc};RuleSet.prototype._promoteRequired=function(rules,prefix,reqList){var ret={},keys,rule,n;for(rule of reqList){ret[rule]=rules[rule]}keys=Object.keys(rules);for(rule of keys){if(!rules[rule][PROP_$REQUIRED]){ret[rule]=rules[rule]}}if(this._debugMode||this._verboseMode){this._info(`\n[Info]: Rulepack '${prefix}' - ${reqList.length} rule${reqList.length===1?"":"s"} promoted to top for early $required loading`);let s="";for(n=0;n<reqList.length;n++){s+=" "+(n+1)+"] "+reqList[n]+"\n"}this._info(s+"\n");if(this._debugMode){this._info(`\n[Info]: Rulepack '${prefix}' - Loading Order`);n=0;s="";for(rule in ret){s+=" "+(n+1)+"] "+rule+"\n";n++}this._info(s+"\n")}}return ret?ret:rules};function _removeDups(ar){return[...new Set(ar)]};RuleSet.prototype.dumpRegistry=function(){console.log("\n-------- Active Rule Type Listener Types --------");console.log(this._registry.dump())};RuleSet.prototype.getRulePacks=function(){return this._rulePacks};RuleSet.prototype.getRuleSets=function(){return this._ruleSets};RuleSet.prototype.getRulePacksSummary=function(){return this._rulesetSummary};RuleSet.prototype.getShadowRulePacks=function(){return this._shadowRulePacks};RuleSet.prototype.getActiveRuleCount=function(){return this._ruleCount};RuleSet.prototype.getActiveFiletypes=function(){return this._targFiletypes?this._targFiletypes:[]};RuleSet.prototype.getRegistry=function(){return this._registry};RuleSet.prototype.getRulesetSummary=function(){return this._rulesetSummary};RuleSet.prototype.getRsiFromMsgId=function(msgId){var i,prefix,ret=-1;i=msgId.indexOf("-");prefix=i>=0?msgId.substring(0,i):msgId;if(this._rulesetSummary){for(i=0;i<this._rulesetSummary.length;i++){if(this._rulesetSummary[i].prefix===prefix){ret=i;break}}}return ret};RuleSet.prototype.loadMsgIds=function(){var msgObj,rp,rs,o,rsi,fpath,err;if(this._rulePacks&&this._rulePacks.length){for(rsi=0;rsi<this._rulePacks.length;rsi++){rp=this._rulePacks[rsi];rs=this._ruleSets[rsi];if(rs.builtin&&NO_MSGID_PACKS.includes(rs.prefix)){continue}if(rs.enabled){if(!msgObj){msgObj={}}o=null;try{if(this._isCliOrApi){fpath=this._nodeDeps.path.join(rp.path,"msgid.json");if(rs.builtin||this._nodeDeps.fsUtils.fileExists(fpath)){o=this._nodeDeps.msgidLoader(fpath,this._nodeDeps,this._appCtx)}}else{if(rs.builtin){o=this._nodeDeps.msgidLoader(this._nodeDeps,rsi,this._ruleSets[rsi],this._error)}else if(rs.amdpack&&rs.amdpack.msgid){o=rs.amdpack.msgid}}}catch(e){this._error(`'Failed to load ${rs.builtin?"built-in":"external"} rulepack msgid file : ${e.message}`);err=true;o=null}msgObj[rp.rulesJson.prefix]=o}}}return err?-1:msgObj};RuleSet.prototype.getLoadedRule=function(rsi,ruleName){return this._shadowRulePacks[rsi][ruleName]};RuleSet.prototype.getSemVer=function(){return this._semVer};RuleSet.prototype._processRuleSets=function(){var ruleName,ruleNamesWild,rulePack,rules,opts,ruleJS,rule,rulePath,packStat,rset,callbacks,callback,atLine,rn,rsi,temp,s,i,j;for(rsi=0;rsi<this._rulePacks.length;rsi++){rulePack=this._rulePacks[rsi];rules=rulePack.rulesJson.rules;rulePack.rulePack=new RulePack(this._rulesetSummary,this._rulePacks,this._shadowRulePacks,rsi,this._appCtx);this._registerCtx.rulePack=rulePack.rulePack;packStat=this._rulesetSummary[rsi].status;for(ruleName in rules){opts=rules[ruleName];if(this._debugMode){this._debug(`Loading rule '${ruleName}'`)}if(opts.hasOwnProperty("inservice")){if(!opts.inservice){this._showIgnoredRule(`rule '${ruleName}' is not in service - ignored`);opts.enabled=false;continue}}try{if(this._isAMD){if(!_isAMDRule(opts)){this._showIgnoredRule(`rule '${ruleName}' is not supported in AMD mode - ignored`);opts.enabled=false;continue}}opts.enabled=typeof opts.enabled==="boolean"?opts.enabled:true;if(!opts.enabled){this._showIgnoredRule(`rule '${ruleName}' is disabled - ignored`);continue}if(opts._rsi===undefined){this._showIgnoredRule(`rule '${ruleName}' does not belong to an active ruleset - ignored`);opts.enabled=false;continue}if(opts.severity){if(typeof opts.severity!=="string"||!this._severity.isValidRuleSeverity(opts.severity)){this._showIgnoredRule(`rule '${ruleName}' has invalid 'severity' of ${opts.severity} - assuming default of '${this._severity.DEFAULT}'`,true);opts.severity=this._severity.DEFAULT;opts.enabled=false}}else{opts.severity=this._severity.DEFAULT}if(opts.group){if(rsi&&!this._isGroupActive(opts.group)){this._showIgnoredRule(`rule '${ruleName}' ignored by group`);opts.enabled=false;continue}}if(!opts.status){opts.status="production"}if(!RULE_STATUS.includes(opts.status)){this._showIgnoredRule(`rule '${ruleName}' invalid 'status' (i.e. not 'production', 'prod', 'ready', 'deprecated', 'beta', 'alpha'`,true);opts.enabled=false;continue}if(!_isStatEnabledByPack(packStat,opts.status)){this._showIgnoredRule(`rule '${ruleName}' status does not match rulepack status - ignored`);opts.enabled=false;continue}if(opts.filetype){if(Array.isArray(opts.filetype)){for(j=0;j<opts.filetype.length;j++){opts.filetype[j]=opts.filetype[j].toLowerCase();if(!FILETYPE.isFileTypeSupported(opts.filetype[j])){this._showIgnoredRule(`rule '${ruleName}' ignored by 'filetype' value '${opts.filetype[j]}'`);opts.enabled=false;continue}}}else{if(!FILETYPE.isFileTypeSupported(opts.filetype)){this._showIgnoredRule(`rule '${ruleName}' ignored by 'filetype' value '${opts.filetype}'`);opts.enabled=false;continue}}}if(!ruleName.startsWith("jaf-")&&this._confNamedRules&&this._confNamedRules.length){if(!ruleNamesWild){ruleNamesWild=[];for(j=0;j<this._confNamedRules.length;j++){rn=this._confNamedRules[j];ruleNamesWild.push(_isRE(rn)?new RegExp(rn):null)}}for(j=0;j<this._confNamedRules.length;j++){if(this._confNamedRules.includes(ruleName)){break}rn=ruleNamesWild[j];if(rn){if(rn.test(ruleName)){break}}}if(j>=this._confNamedRules.length){if(opts.$required){this._showIgnoredRule(`rule '${ruleName}' not excluded by config 'ruleNames'- rule is mandatory`)}else{this._showIgnoredRule(`rule '${ruleName}' ignored - excluded by config 'ruleNames'`);opts.enabled=false}continue}}if(opts.jetver){if(!this._semVer.match(opts.jetver)){this._showIgnoredRule(`rule '${ruleName}' ignored : 'jetVer' option is '${opts.jetver}' but metadata is '${this._semVer.getReference()}'`);opts.enabled=false;continue}}if(opts.theme){temp=opts.theme;if(typeof temp==="string"){temp=opts.theme.toLowerCase();if(temp==="redwood"||temp==="alta"){opts.theme=temp.charAt(0).toUpperCase()+temp.substring(1);if(this._config.theme!==opts.theme){this._showIgnoredRule(`rule '${ruleName}' ignored : 'theme' option '${opts.theme}' excluded by config '${this._config.theme}'`);opts.enabled=false;continue}}else{this._showIgnoredRule(`rule '${ruleName}' theme option '${opts.theme}' - must be 'Redwood' or 'Alta'`,true);opts.enabled=false}}else{if(!Array.isArray(temp)){this._showIgnoredRule(`rule '${ruleName}' theme option - must be a string or a string array`,true);opts.enabled=false;continue}temp.forEach((theme,idx)=>{theme=theme.toLowerCase();if(theme==="redwood"||theme==="alta"){theme=theme.charAt(0).toUpperCase()+theme.substring(1);temp[idx]=theme}else{this._showIgnoredRule(`rule '${ruleName}' theme option '${theme}' - must be 'Redwood' or 'Alta'`,true);opts.enabled=false}});if(opts.enabled&&!opts.theme.includes(this._config.theme)){this._showIgnoredRule(`rule '${ruleName}' ignored : 'theme' option '${opts.theme}' excluded by config '${this._config.theme}'`);opts.enabled=false}}}if(this._isCliOrApi){rulePath=this._rulesetSummary[opts._rsi].path;rulePath=this._nodeDeps.path.join(rulePath,ruleName+".js");ruleJS=this._nodeDeps.ruleLoader(rulePath)}else{rset=this._ruleSets[opts._rsi];if(rset.builtin){ruleJS=this._nodeDeps.ruleLoader(ruleName,opts._rsi,this._error)}else if(rset.amdpack){ruleJS=rset.amdpack.rules[ruleName]}}if(!ruleJS){continue}rule=ruleJS;if(rset&&rset.amdpack){try{rule=new ruleJS.default}catch(e){this._showIgnoredRule(`AMD rule '${ruleName}' ${e.message}`,true);rule=null;continue}}else{if(ruleJS.prototype||!ruleJS.getName){try{rule=new ruleJS}catch(e){this._showIgnoredRule(`rule '${ruleName}' ${e.message}`,true);rule=null;continue}}}if(!opts.$internal){if(typeof rule.register!==FUNCTION){this._showIgnoredRule(`rule '${ruleName}' ignored - has no register() method`,true);opts.enabled=false;continue}}if(typeof rule.getName!==FUNCTION){this._showIgnoredRule(`rule '${ruleName}' ignored - has no getName() method`,true);opts.enabled=false;continue}if(typeof rule.getDescription!==FUNCTION){this._showIgnoredRule(`rule '${ruleName}' ignored - has no getDescription() method`,true);opts.enabled=false;continue}if(typeof rule.getShortDescription!==FUNCTION){this._showIgnoredRule(`rule '${ruleName}' ignored - has no getShortDescription() method`,true);opts.enabled=false;continue}if(ruleName!==rule.getName()){this._showIgnoredRule(`rule '${ruleName}' ignored - name '${rule.getName()}' does not match external name '${ruleName}`,true);opts.enabled=false;continue}if(!opts.$internal){this._registerCtx.ruleOpts=clone.cloneOptions(opts);if(opts.filetype){if(typeof opts.filetype==="string"&&opts.filetype==="js"||opts.filetype.includes("js")){this._registerCtx.jsNodeTypes=AstNodeTypes}else if(typeof opts.filetype==="string"&&opts.filetype==="ts"||opts.filetype.includes("ts")){this._registerCtx.tsNodeTypes=AstNodeTypes}}if(this._isCliOrApi){this._registerCtx.utils.fsUtils=this._nodeDeps.fsUtils;if(ruleName==="oj-html-cspexpr"){this._registerCtx.decache=this._nodeDeps.decache}}this._registerCtx.ruleName=ruleName;this._registerCtx.rulePack._setCBCtx(this._registerCtx);callbacks=rule.register(this._registerCtx);if(!callbacks){this._showIgnoredRule(`rule '${ruleName}' has disabled itself during registration`);opts.enabled=false;continue}for(callback in callbacks){if(callbacks[callback]){callbacks[callback]=callbacks[callback].bind(rule)}else{s=`rule '${ruleName}': listener for '${callback}' in register() is not defined - rule is disabled`;this._error(s);this._showIgnoredRule(s);opts.enabled=false;continue}}if(_isHookRule(callbacks)){opts.$hook=true}else{if(!this._checkRuleSeverity(opts)){this._showIgnoredRule(`rule '${ruleName}' ignored by severity`);opts.enabled=false;continue}}}this._addToShadowRulePacks(ruleName,rule,opts);if(!opts.$internal){this._registry.setRuleCallback(ruleName,callbacks,opts._rsi)}this._ruleCount++;this._updateTargetFiletypes(opts)}catch(e){atLine=e.stack.replace(rulePath,"").trim();i=NaN;if(atLine.startsWith(COLON)){i=parseInt(atLine.substr(1))}if(!isNaN(i)){atLine=" line "+i+": "}else{i=atLine.indexOf(COLON);if(i<0){atLine=""}else{atLine=this._utils.eatLine(atLine,i);i=atLine.indexOf(COLON);if(i>=0){atLine=atLine.substring(i+1);i=atLine.indexOf(")");if(i>=0){atLine="("+atLine.substring(0,i).replace(COLON,",")+") - "}}else{atLine=""}};}this._showIgnoredRule(`Cannot load rule ${ruleName} [${atLine} '${e.message}']`,true)}}}this._showIgnoredRule(null);return true};RuleSet.prototype._showIgnoredRule=function(msg,isError){if(msg){if(!this._ignoredRulesShown){this._info("\n--------- Start-up Rule analysis ---------");this._ignoredRulesShown=true}isError?this._error(msg):this._info(msg)}else if(this._ignoredRulesShown){this._info("------------ End Rule analysis -------------")}};RuleSet.prototype._mergeRuleOptions=function(rulesJson,isBuiltinRules){var prefix,rules,overrides,ruleName,opts,error,x;this._debug("Augmenting config defined rules in rulePack from ruleMods...");prefix=rulesJson.prefix;rules=rulesJson.rules;overrides=this._getRuleModsByPrefix(prefix);for(ruleName in rules){error=false;if(!isBuiltinRules){x=RESERVED_RULE_PREFIX.indexOf(ruleName.toLowerCase());if(x>=0){this._showIgnoredRule(`rule '${ruleName}' in rulepack (prefix: '${prefix}') must not use JET reserved prefix '${RESERVED_RULE_PREFIX[x]}'`,true);error=true}}if(overrides){if(error){continue}if(overrides.hasOwnProperty(ruleName)&&rules[ruleName]){if(this._isAMD){opts=rules[ruleName];if(!_isAMDRule(opts)){if(this._debugMode){this._debug(`Rule options override ignored for non-AMD ${ruleName} in AMD mode`)}continue}if(!this._nodeDeps.ruleLoader(ruleName,opts._rsi,this._error)){continue}}if(this._debugMode){this._debug(`Merging rule props of ${ruleName}`)}this._mergeOverrideProps(ruleName,overrides[ruleName],rules[ruleName],isBuiltinRules)}}}};RuleSet.prototype._mergeOverrideProps=function(ruleName,configOpts,ruleOpts){var prop;for(prop in configOpts){if(prop.charAt(0)==="$"){delete configOpts[prop];this._showIgnoredRule(`rule '${ruleName}' : '${prop}' in config 'rulesMod' cannot use reserved '$' prefix`,true);continue}if(prop==="enabled"&&!configOpts[prop]&&ruleOpts["$required"]){this._showIgnoredRule(`rule '${ruleName}' is mandatory and cannot be disabled using config 'ruleMods' property.`,true);continue}ruleOpts[prop]=configOpts[prop]}};RuleSet.prototype._addToShadowRulePacks=function(ruleName,loadedRule,ruleOpts){var rsi=ruleOpts._rsi;var srp=this._shadowRulePacks;while(rsi>=srp.length){srp.push({})}srp[rsi][ruleName]=loadedRule};RuleSet.prototype._updateTargetFiletypes=function(opts){var ft=opts.filetype;if(ft){if(typeof ft==="string"){ft=[ft]}ft.forEach(t=>{if(!opts.$internal){if(!this._targFiletypes.includes(t)){this._targFiletypes.push(t)}}},this)}};RuleSet.prototype._getRuleModsByPrefix=function(prefix){var modPrefix,ret;if(this._ruleMods){prefix=prefix.toLowerCase();for(modPrefix in this._ruleMods){if(prefix===modPrefix.toLowerCase()){ret=this._ruleMods[modPrefix];break}}}return ret};RuleSet.prototype._isGroupActive=function(group){var groups,defs,def,i;groups=this._config.groups;defs=this._config.defGroups;if(this._checkGroups(groups,group)){return true}if(!defs){return false}for(i=0;i<groups.length;i++){def=groups[i];if(this._checkDefGroup(defs,def,group)){return true}}return false};RuleSet.prototype._checkGroups=function(cfgGroups,ruleGroup){var theGroup,i;if(Array.isArray(ruleGroup)){for(i=0;i<ruleGroup.length;i++){theGroup=ruleGroup[i];if(this._checkGroup(cfgGroups,theGroup)){return true}}}else if(this._checkGroup(cfgGroups,ruleGroup)){return true}return false};RuleSet.prototype._checkGroup=function(cfgGroups,group){return!cfgGroups||cfgGroups.includes(group)||cfgGroups.includes(this._severity.ALL)};RuleSet.prototype._isJetInRuleSet=function(jetPrefix){var i,ret=false;if(this._ruleSets&&this._ruleSets.length){for(i=0;i<this._ruleSets.length;i++){if(this._ruleSets[i].prefix===jetPrefix){ret=true;break}}}return ret};RuleSet.prototype._checkRuleSeverity=function(opts){var severities,severity,_sev,i,ret=false;severities=this._config.severity;severity=opts.severity;if(typeof severities==="string"){_sev=this._severity.getConfigSevExpr();if(_sev){ret=true}else{ret=severity===severities||severities===this._severity.ALL}}else{for(var i=0;i<severities.length;i++){if(severity===severities[i]||severities[i]===this._severity.ALL){ret=true;break}}}return ret};RuleSet.prototype._loadJson=function(filepath){var data,stats,msg;try{stats=this._nodeDeps.fs.lstatSync(filepath);if(!stats.isFile()){this._error(`RuleSet '${filepath}' not found!`);return null}else{data=this._nodeDeps.fs.readFileSync(filepath,"utf8");data=JSON.parse(this._nodeDeps.decomment(data))}}catch(e){if(e.code){if(e.message.startsWith("ENOENT:")){this._error(`RuleSet error - '${filepath}' not found!`)}}else if(e.toString().startsWith("SyntaxError")){msg=_convertMsgToRowCol(e.message,data,this._utils)}else{msg=e.message}if(msg){this._error(`JSON load error '${filepath}' - ${msg}`)}data=null}return data};function _isStatEnabledByPack(pstat,rstat){var ret=false;if(pstat.includes("all")||pstat.includes(rstat)){ret=true}else{if(rstat==="ready"||rstat.startsWith("prod")){ret=pstat.includes("ready")||pstat.includes("production")||pstat.includes("prod")}}return ret};function _isHookRule(callbacks){return callbacks[REG.PHASE_STARTUP]||callbacks[REG.PHASE_CLOSEDOWN]||callbacks[REG.PHASE_FILE]?true:false};function _isAMDRule(opts){return opts.hasOwnProperty("amd")?!!opts.amd:true};function _convertMsgToRowCol(msg,data,utils){var x,n,rc;x=msg.indexOf("position");if(x<0){return msg}n=parseInt(msg.substr(x+8).trim());rc=utils.getRowColFromIndex(data,n);return msg.substr(0,x)+"line "+rc.row+", col "+rc.col};function _isRE(s){return RULE_RE.test(s)};module.exports=RuleSet;
|
|
6
|
+
const REG=require("./RegTypes");const FILETYPE=require("./filetypes");const RULE_FILE="rules.json";const BUILTIN_RULES_PATH="../rules/";const BUILTIN_RULEPACK_PATH="../rulepacks/";const JAF_BUILTIN_RULES_PATH=BUILTIN_RULES_PATH+"jaf";const JET_BUILTIN_RULES_PATH=BUILTIN_RULES_PATH+"jet";const SPOC_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"spoc";const CSP_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"csp";const JETWC_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"jetwc";const JETWCO_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"jetwco";const VCOMPMIG_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"ojcmig";const WEBDRIVER_TEST_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"wdt";const JET_MIN_VERSION="5.2.0";const TEMP_FILE_TEMPLATE="@@rpziptmp-XXXXXX";const PROP_$BUILTIN="$builtin";const PROP_$REQUIRED="$required";const RESERVED_RULE_PREFIX=["oj-","jaf-","csp-","spoc-","jetwc-","jetwco-","exch-","demo-"];const RESERVED_PACK_PREFIX=["JAF","JET","SPOC","CSP","JETWC","JETWCO","DEMO"];const NO_MSGID_PACKS=[];const RULE_STATUS=["prod","production","ready","beta","alpha","deprecated"];const FUNCTION="function";const COLON=":";const RULE_RE=new RegExp(/[~`!#$%\^&*+\[\]\\';,/{}|\\"\?]/,"g");const RulePack=require("./RulePack");const Registry=require("./Registry");const SemVer=require("./SemVer");const CssUtils=require("./CssUtils");const AstNodeTypes=require("./AstNodeTypes");const clone=require("./clone");var RuleSet=function(config,nodeDeps,appCtx,AMDRulePacks){this._config=config;this._ruleSets=config.getRulePacks();this._ruleMods=config.getRuleMods();this._ruleCount=0;this._AmdPacks=AMDRulePacks;this._appCtx=appCtx;this._nd=nodeDeps;this._isAMD=!!nodeDeps.AmdRulePackLoader;this._isCLI=appCtx.runMode==="cli";this._isCliOrApi=!this._isAMD;this._metaLib=appCtx.metaLib;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._severity=appCtx.severity;this._tmpDir=appCtx.tmpDir;this._semVer=new SemVer;this._targFiletypes=[];this._msgIds=null;this._useBuiltinRules=config._config.builtinJetRules;this._rulePacks=null;this._shadowRulePacks=null;this._rulesetSummary=[];this._registerCtx={sysOpts:{verboseMode:this._appCtx.verboseMode,debugMode:this._appCtx.debugMode}};this._registerCtx.utils={};this._registerCtx.utils.metaLib=this._metaLib.getPublicInterface();this._registerCtx.runMode=appCtx.runMode;this._registerCtx.VsCodeExtHint=appCtx.VsCodeExtHint;this._registerCtx.utils.semVerUtils=this._semVer;this._registerCtx.utils.utils=this._utils;this._registerCtx.utils.CssUtils=CssUtils;this._registerCtx.config=JSON.parse(JSON.stringify(this._config._config));this._registerCtx.error=appCtx.error;this._registerCtx.info=appCtx.info;this._registerCtx.msg=appCtx.msg;this._registerCtx.utils.msgLib={msg:appCtx.msg,error:appCtx.error,info:appCtx.info,debug:appCtx.debug,assert:appCtx.assert};this._registerCtx.utils.sevLib=this._severity.getSevLib();this._registerCtx.utils.OjetLib=appCtx.ojetLib;this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._assert=appCtx.assert;this._debugMode=appCtx.debugMode;this._verboseMode=appCtx.verboseMode;if(!this._ruleSets){this._ruleSets=[]}let rsi=0;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,JAF_BUILTIN_RULES_PATH):null,"builtin":true});if(config._config.builtinJetRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,JET_BUILTIN_RULES_PATH):null,"builtin":true})}if(config._config.builtinCspRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,CSP_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinJetWcRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,JETWC_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinJetWcOracleRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,JETWCO_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinSpocRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,SPOC_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinOjcMigrationRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,VCOMPMIG_BUILTIN_RULES_PATH),"builtin":true})}if(!this._isAMD&&config._config.builtinWebDriverTestRules){this._ruleSets.splice(rsi++,0,{"enabled":true,"path":nodeDeps.path.join(__dirname,WEBDRIVER_TEST_BUILTIN_RULES_PATH),"builtin":true})}if(this._isAMD&&this._AmdPacks){let i,apack;for(i=0;i<this._AmdPacks.length;i++){if(apack=this._AmdPacks[i]){this._ruleSets.splice(rsi++,0,{enabled:true,path:null,builtin:false,amdpack:apack})}}}};RuleSet.prototype.loadRulePacks=function(config,isDryRun,isRuleDump){var ruleSet,rulePath,rulesJson,rulePack,rsi,rule,prefix,groups,gname,arules,j,k,s="",rulesetSummaryIndex=-1,spocFound,demoFound,errors=false,rc,ruleName,jetVersion;this._config=config;this._confSeverity=config._sev;this._confNamedRules=config.ruleNames;jetVersion=this._metaLib.getRevisionInfo().jetVersion;if(!this._semVer.setReference(jetVersion,JET_MIN_VERSION)){this._error(`JET metadata version ${jetVersion} not supported (less than ${JET_MIN_VERSION})`);return false}if(this._debugMode){this._debug(this._ruleSets?"Processing "+this._ruleSets.length+" Rule Sets":"No Rule Sets defined")}if(!this._ruleSets){return false}this._rulePacks=[];this._shadowRulePacks=[];for(rsi=0;rsi<this._ruleSets.length;rsi++){ruleSet=this._ruleSets[rsi];groups=null;try{if(typeof ruleSet.enabled==="boolean"&&!ruleSet.enabled){s+=(rsi?"\n":"")+" "+(rsi+1)+") "+"Disabled ruleSet at '"+ruleSet.path;continue}if(!ruleSet.status){ruleSet.status=["all"]}if(!this._isAMD){if(this._debugMode){let rname=this._nd.path.basename(ruleSet.path);switch(rname){case"jaf":case"jet":case"spoc":rname=rname.toUpperCase();break;default:rname=ruleSet.name;break;}this._debug(`Ruleset ${rname?"'rname'":""}path->'${ruleSet.path}'`)}if(ruleSet.path.endsWith(".zip")){ruleSet.container=ruleSet.path;let tmpFile=this._fsUtils.getUniqueFileName(TEMP_FILE_TEMPLATE);let tmpDir=this._nd.path.join(this._tmpDir,tmpFile);rc=this._fsUtils.createFolder(tmpDir);if(typeof rc!=="boolean"){this._error(`Unable to create folder ${rc.message}`);break}var zipUtils=new this._nd.zipUtils;;rc=zipUtils.extractAll(tmpDir,ruleSet.container,true);if(typeof rc!=="boolean"){this._error(`Unable to extract from zip ('${rc.message}') : "${ruleSet.container}"`);break}ruleSet.path=tmpDir}rulePath=this._nd.path.join(ruleSet.path,RULE_FILE);rulesJson=this._loadJson(rulePath)}else{if(ruleSet.builtin){rulesJson=this._nd.AmdRulePackLoader(this._nd,rsi,ruleSet,this._error)}else if(ruleSet.amdpack){rulesJson=ruleSet.amdpack.rulesJson;rulesJson=JSON.parse(JSON.stringify(rulesJson))}}if(!rulesJson){continue}if(!rulesJson.title){rulesJson.title="unknown"}if(!rulesJson.version){rulesJson.version="0.0.0"}prefix=rulesJson.prefix;ruleSet.prefix=prefix;s+=(rsi?"\n":"")+" "+(rsi+1)+") "+rulesJson.title+"\n "+rulesJson.version+" : "+prefix+(ruleSet.builtin||ruleSet.amdpack?"":" -> "+(ruleSet.container?ruleSet.container:ruleSet.path));if(this._appCtx.isUnitTest&&!spocFound&&prefix==="SPOC"){ruleSet.builtin=true;if(prefix==="SPOC"){spocFound=true}if(prefix==="DEMO"){demoFound=true}}if(!demoFound&&prefix==="DEMO"){ruleSet.builtin=true;if(prefix==="DEMO"){demoFound=true}}if(!ruleSet.builtin){if(RESERVED_PACK_PREFIX.includes(prefix)){this._error("Rule pack at '"+rulePath+"' cannot use use reserved prefix '"+prefix+"'!");break}}for(j=0;j<this._rulesetSummary.length;j++){if(this._rulesetSummary[j].prefix===prefix){this._error("Rule pack prefix '"+prefix+"' at '"+rulePath+"' ignored - previously defined at '"+rulePack.path+"'");break}}if(j<this._rulesetSummary.length){continue}this._rulesetSummary.push({title:rulesJson.title,path:ruleSet.path,version:rulesJson.version,prefix:rulesJson.prefix,status:ruleSet.status,packData:ruleSet.packData});++rulesetSummaryIndex;var reorder,nonReq,reqList=[];reorder=nonReq=false;reqList.length=0;for(ruleName in rulesJson.rules){rule=rulesJson.rules[ruleName];rule._rsi=rulesetSummaryIndex;if(this._ruleSets[rulesetSummaryIndex].builtin){rule[PROP_$BUILTIN]=true;if(!rule.hasOwnProperty("inservice")||rule.inservice){if(!Array.isArray(rule.group)){rule.group=[rule.group]}rule.group.push("jet-inservice")}}if(rule[PROP_$REQUIRED]){if(!reorder){reorder=nonReq}reqList.push(ruleName)}else{nonReq=true}if(rule.group){groups=groups||{};let rg=rule.group;if(typeof rg==="string"){arules=groups[rg];if(!arules){groups[rg]=arules=[]}arules.push(ruleName)}else if(Array.isArray(rg)){for(k=0;k<rg.length;k++){gname=rg[k];arules=groups[gname];if(!arules){groups[gname]=arules=[]}arules.push(ruleName)}}}}if(reorder){rulesJson.rules=this._promoteRequired(rulesJson.rules,rulesJson.prefix,reqList)}this._rulePacks.push({path:ruleSet.path,rulesJson:rulesJson});ruleSet.groupMap=groups;this._mergeRuleOptions(rulesJson,ruleSet.builtin)}catch(e){this._error(`Failure processing ruleset at '${rulePath}' (${e.message})`);errors=true}}if(s.length){this._info("[info]: ------ Built-in Rulepacks loaded: --------");this._info(s)}if(this._debugMode){this._debug("------ group mappings : --------");let self=this;this._ruleSets.forEach(s=>{self._debug(s.prefix+": "+(s.groupMap?JSON.stringify(s.groupMap,null,3):"none"))})}if(errors){return false}this._registry=new Registry(this._appCtx);this._postProcess_RuleMods();this._postProcess_RuleNames();if(!this._processRuleSets()){return false}if(config.options.debug&&!isRuleDump||config.options.verbose&&!isRuleDump||isDryRun){var f=isDryRun||config.options.verbose?this._info:this._debug;var rules,opts;if(this._ruleCount){f("\n-------- Active Rule Summmary --------");for(rsi=0;rsi<this._rulePacks.length;rsi++){rulePack=this._rulePacks[rsi];f("\n ["+(rsi+1)+"] Rule Set '"+rulePack.rulesJson.title+"'");rules=rulePack.rulesJson.rules;let n=0;for(ruleName in rules){opts=rules[ruleName];if(opts.enabled){f("\n "+ruleName+" : "+JSON.stringify(this._utils.extend(opts)));n++}}if(!n){f("\n "+"No rules enabled in pack.")}}}}return!errors};RuleSet.prototype._postProcess_RuleMods=function(){var rs,rm,are,ard,count=0,n;rm=this._config.ruleMods;if(rm&&(rm.enable||rm.disable)){rs=this._ruleSets;are=rm.enable;if(are){n=_replaceGroups(are,rs);if(n){are=_removeDups(are);count+=n}}ard=rm.disable;if(ard){n=_replaceGroups(ard,rs);if(n){ard=_removeDups(ard);count+=n}}this._enableDisableGroupRules(are,ard)}return count};RuleSet.prototype._enableDisableGroupRules=function(are,ard){var ar,rname,packs,rules,rule,enable,m1,i,j,k;if(this._verboseMode||this._debugMode){this._info("\n[Info]: --- Enabling rules found in ruleMods.enable ---");if(!are){this._info("* None found")}}packs=this._rulePacks;i=2;ar=are;enable=true;m1="enabled";while(i){if(ar){for(j=0;j<ar.length;j++){rname=ar[j];for(k=0;k<packs.length;k++){rules=packs[k];if(rules){rules=rules.rulesJson;if(rules){rule=rules.rules[rname];if(rule){if(!enable&&rule.$required){this._error(`rule '${rname}' is mandatory and cannot be disabled using config 'ruleMods.disable' property.`);continue}rule.enabled=enable;if(this._verboseMode||this._debugMode){this._info(` Rule ${rname} ${m1}`)}break}}}}}}if(enable){ar=ard;if(this._verboseMode||this._debugMode){this._info("\n[Info]: --- Disabling rules found in ruleMods.disable ---");m1="disabled";if(!ard){this._info("* None found")}}if(!ard){return}}enable=false;i--}};RuleSet.prototype._postProcess_RuleNames=function(){var ret=0;if(this._verboseMode||this._debugMode){this._info("\n[Info]: --- Processing config ruleNames entries ---")}if(this._config.ruleNames){ret=_replaceGroups(this._config.ruleNames,this._ruleSets);this._config.ruleNames=_removeDups(this._config.ruleNames)}if(this._verboseMode||this._debugMode){this._info(`\n[Info]: ${ret} ruleNames group entr${ret===1?"y":"ies"} replaced ---`)}return ret};function _replaceGroups(ar,rs){var val,o,group,grules,rc=0,rsi,i;var replaced=[];for(i=0;i<ar.length;i++){val=ar[i];replaced.length=0;for(rsi=0;rsi<rs.length;rsi++){o=rs[rsi];if(o.groupMap){for(group in o.groupMap){if(group===val){grules=o.groupMap[group];replaced.push(...grules);break}}}}if(replaced.length){ar.splice(i,1,...replaced);i+=replaced.length-1;rc++}}return rc};RuleSet.prototype._promoteRequired=function(rules,prefix,reqList){var ret={},keys,rule,n;for(rule of reqList){ret[rule]=rules[rule]}keys=Object.keys(rules);for(rule of keys){if(!rules[rule][PROP_$REQUIRED]){ret[rule]=rules[rule]}}if(this._debugMode||this._verboseMode){this._info(`\n[Info]: Rulepack '${prefix}' - ${reqList.length} rule${reqList.length===1?"":"s"} promoted to top for early $required loading`);let s="";for(n=0;n<reqList.length;n++){s+=" "+(n+1)+"] "+reqList[n]+"\n"}this._info(s+"\n");if(this._debugMode){this._info(`\n[Info]: Rulepack '${prefix}' - Loading Order`);n=0;s="";for(rule in ret){s+=" "+(n+1)+"] "+rule+"\n";n++}this._info(s+"\n")}}return ret?ret:rules};function _removeDups(ar){return[...new Set(ar)]};RuleSet.prototype.dumpRegistry=function(){if(this._registry.isEmpty()){console.log("\n--reg : Nothing to report, no rules active")}else{console.log("\n-------- Active Rule Type Listener Types --------");console.log(this._registry.dump())}};RuleSet.prototype.getRulePacks=function(){return this._rulePacks};RuleSet.prototype.getRuleSets=function(){return this._ruleSets};RuleSet.prototype.getRulePacksSummary=function(){return this._rulesetSummary};RuleSet.prototype.getShadowRulePacks=function(){return this._shadowRulePacks};RuleSet.prototype.getActiveRuleCount=function(){return this._ruleCount};RuleSet.prototype.getActiveFiletypes=function(){return this._targFiletypes?this._targFiletypes:[]};RuleSet.prototype.getRegistry=function(){return this._registry};RuleSet.prototype.getRulesetSummary=function(){return this._rulesetSummary};RuleSet.prototype.getRsiFromMsgId=function(msgId){var i,prefix,ret=-1;i=msgId.indexOf("-");prefix=i>=0?msgId.substring(0,i):msgId;if(this._rulesetSummary){for(i=0;i<this._rulesetSummary.length;i++){if(this._rulesetSummary[i].prefix===prefix){ret=i;break}}}return ret};RuleSet.prototype.loadMsgIds=function(){var msgObj,rp,rs,o,rsi,fpath,err;if(this._msgIds){return this._msgIds}if(this._rulePacks&&this._rulePacks.length){for(rsi=0;rsi<this._rulePacks.length;rsi++){rp=this._rulePacks[rsi];rs=this._ruleSets[rsi];if(rs.builtin&&NO_MSGID_PACKS.includes(rs.prefix)){continue}if(rs.enabled){if(!msgObj){msgObj={}}o=null;try{if(this._isCliOrApi){fpath=this._nd.path.join(rp.path,"msgid.json");if(rs.builtin||this._fsUtils.fileExists(fpath)){o=this._nd.msgidLoader(fpath,this._nd,this._appCtx)}}else{if(rs.builtin){o=this._nd.msgidLoader(this._nd,rsi,this._ruleSets[rsi],this._error)}else if(rs.amdpack&&rs.amdpack.msgid){o=rs.amdpack.msgid}}}catch(e){this._error(`'Failed to load ${rs.builtin?"built-in":"external"} rulepack msgid file : ${e.message}`);err=true;o=null}msgObj[rp.rulesJson.prefix]=o}}}return err?-1:this._msgIds=msgObj};RuleSet.prototype.getMsgIds=function(){return this._msgIds};RuleSet.prototype.getLoadedRule=function(rsi,ruleName){return this._shadowRulePacks[rsi][ruleName]};RuleSet.prototype.getSemVer=function(){return this._semVer};RuleSet.prototype._processRuleSets=function(){var ruleName,ruleNamesWild,rulePack,rules,opts,ruleJS,rule,rulePath,packStat,rset,callbacks,callback,atLine,rn,rsi,temp,s,i,j;for(rsi=0;rsi<this._rulePacks.length;rsi++){rulePack=this._rulePacks[rsi];rules=rulePack.rulesJson.rules;rulePack.rulePack=new RulePack(this._rulesetSummary,this._rulePacks,this._shadowRulePacks,rsi,this._appCtx);this._registerCtx.rulePack=rulePack.rulePack;packStat=this._rulesetSummary[rsi].status;for(ruleName in rules){opts=rules[ruleName];if(this._debugMode){this._debug(`Loading rule '${ruleName}'`)}if(opts.hasOwnProperty("inservice")){if(!opts.inservice){this._showIgnoredRule(`rule '${ruleName}' is not in service - ignored`);opts.enabled=false;continue}}try{if(this._isAMD){if(!_isAMDRule(opts)){this._showIgnoredRule(`rule '${ruleName}' is not supported in AMD mode - ignored`);opts.enabled=false;continue}}opts.enabled=typeof opts.enabled==="boolean"?opts.enabled:true;if(!opts.enabled){this._showIgnoredRule(`rule '${ruleName}' is disabled - ignored`);continue}if(opts._rsi===undefined){this._showIgnoredRule(`rule '${ruleName}' does not belong to an active ruleset - ignored`);opts.enabled=false;continue}if(opts.severity){if(typeof opts.severity!=="string"||!this._severity.isValidRuleSeverity(opts.severity)){this._showIgnoredRule(`rule '${ruleName}' has invalid 'severity' of ${opts.severity} - assuming default of '${this._severity.DEFAULT}'`,true);opts.severity=this._severity.DEFAULT;opts.enabled=false}}else{opts.severity=this._severity.DEFAULT}if(opts.group){if(rsi&&!this._isGroupActive(opts.group)){this._showIgnoredRule(`rule '${ruleName}' ignored by group`);opts.enabled=false;continue}}if(!opts.status){opts.status="production"}if(!RULE_STATUS.includes(opts.status)){this._showIgnoredRule(`rule '${ruleName}' invalid 'status' (i.e. not 'production', 'prod', 'ready', 'deprecated', 'beta', 'alpha'`,true);opts.enabled=false;continue}if(!_isStatEnabledByPack(packStat,opts.status)){this._showIgnoredRule(`rule '${ruleName}' status does not match rulepack status - ignored`);opts.enabled=false;continue}if(opts.filetype){if(Array.isArray(opts.filetype)){for(j=0;j<opts.filetype.length;j++){opts.filetype[j]=opts.filetype[j].toLowerCase();if(!FILETYPE.isFileTypeSupported(opts.filetype[j])){this._showIgnoredRule(`rule '${ruleName}' ignored by 'filetype' value '${opts.filetype[j]}'`);opts.enabled=false;continue}}}else{if(!FILETYPE.isFileTypeSupported(opts.filetype)){this._showIgnoredRule(`rule '${ruleName}' ignored by 'filetype' value '${opts.filetype}'`);opts.enabled=false;continue}}}if(!ruleName.startsWith("jaf-")&&this._confNamedRules&&this._confNamedRules.length){if(!ruleNamesWild){ruleNamesWild=[];for(j=0;j<this._confNamedRules.length;j++){rn=this._confNamedRules[j];ruleNamesWild.push(_isRE(rn)?new RegExp(rn):null)}}for(j=0;j<this._confNamedRules.length;j++){if(this._confNamedRules.includes(ruleName)){break}rn=ruleNamesWild[j];if(rn){if(rn.test(ruleName)){break}}}if(j>=this._confNamedRules.length){if(opts.$required){this._showIgnoredRule(`rule '${ruleName}' not excluded by config 'ruleNames'- rule is mandatory`)}else{this._showIgnoredRule(`rule '${ruleName}' ignored - excluded by config 'ruleNames'`);opts.enabled=false}continue}}if(opts.jetver){if(!this._semVer.match(opts.jetver)){this._showIgnoredRule(`rule '${ruleName}' ignored : 'jetVer' option is '${opts.jetver}' but metadata is '${this._semVer.getReference()}'`);opts.enabled=false;continue}}if(opts.theme){temp=opts.theme;if(typeof temp==="string"){temp=opts.theme.toLowerCase();if(temp==="redwood"||temp==="alta"){opts.theme=temp.charAt(0).toUpperCase()+temp.substring(1);if(this._config.theme!==opts.theme){this._showIgnoredRule(`rule '${ruleName}' ignored : 'theme' option '${opts.theme}' excluded by config '${this._config.theme}'`);opts.enabled=false;continue}}else{this._showIgnoredRule(`rule '${ruleName}' theme option '${opts.theme}' - must be 'Redwood' or 'Alta'`,true);opts.enabled=false}}else{if(!Array.isArray(temp)){this._showIgnoredRule(`rule '${ruleName}' theme option - must be a string or a string array`,true);opts.enabled=false;continue}temp.forEach((theme,idx)=>{theme=theme.toLowerCase();if(theme==="redwood"||theme==="alta"){theme=theme.charAt(0).toUpperCase()+theme.substring(1);temp[idx]=theme}else{this._showIgnoredRule(`rule '${ruleName}' theme option '${theme}' - must be 'Redwood' or 'Alta'`,true);opts.enabled=false}});if(opts.enabled&&!opts.theme.includes(this._config.theme)){this._showIgnoredRule(`rule '${ruleName}' ignored : 'theme' option '${opts.theme}' excluded by config '${this._config.theme}'`);opts.enabled=false}}}if(this._isCliOrApi){rulePath=this._rulesetSummary[opts._rsi].path;rulePath=this._nd.path.join(rulePath,ruleName+".js");ruleJS=this._nd.ruleLoader(rulePath)}else{rset=this._ruleSets[opts._rsi];if(rset.builtin){ruleJS=this._nd.ruleLoader(ruleName,opts._rsi,this._error)}else if(rset.amdpack){ruleJS=rset.amdpack.rules[ruleName]}}if(!ruleJS){continue}rule=ruleJS;if(rset&&rset.amdpack){try{rule=new ruleJS.default}catch(e){this._showIgnoredRule(`AMD rule '${ruleName}' ${e.message}`,true);rule=null;continue}}else{if(ruleJS.prototype||!ruleJS.getName){try{rule=new ruleJS}catch(e){this._showIgnoredRule(`rule '${ruleName}' ${e.message}`,true);rule=null;continue}}}if(!opts.$internal){if(typeof rule.register!==FUNCTION){this._showIgnoredRule(`rule '${ruleName}' ignored - has no register() method`,true);opts.enabled=false;continue}}if(typeof rule.getName!==FUNCTION){this._showIgnoredRule(`rule '${ruleName}' ignored - has no getName() method`,true);opts.enabled=false;continue}if(typeof rule.getDescription!==FUNCTION){this._showIgnoredRule(`rule '${ruleName}' ignored - has no getDescription() method`,true);opts.enabled=false;continue}if(typeof rule.getShortDescription!==FUNCTION){this._showIgnoredRule(`rule '${ruleName}' ignored - has no getShortDescription() method`,true);opts.enabled=false;continue}if(ruleName!==rule.getName()){this._showIgnoredRule(`rule '${ruleName}' ignored - name '${rule.getName()}' does not match external name '${ruleName}`,true);opts.enabled=false;continue}if(!opts.$internal){this._registerCtx.ruleOpts=clone.cloneOptions(opts);if(opts.filetype){if(typeof opts.filetype==="string"&&opts.filetype==="js"||opts.filetype.includes("js")){this._registerCtx.jsNodeTypes=AstNodeTypes}else if(typeof opts.filetype==="string"&&opts.filetype==="ts"||opts.filetype.includes("ts")){this._registerCtx.tsNodeTypes=AstNodeTypes}}if(this._isCliOrApi){this._registerCtx.utils.fsUtils=this._fsUtils;if(ruleName==="oj-html-cspexpr"){this._registerCtx.decache=this._nd.decache}}this._registerCtx.ruleName=ruleName;this._registerCtx.rulePack._setCBCtx(this._registerCtx);callbacks=rule.register(this._registerCtx);if(!callbacks){this._showIgnoredRule(`rule '${ruleName}' has disabled itself during registration`);opts.enabled=false;continue}for(callback in callbacks){if(callbacks[callback]){callbacks[callback]=callbacks[callback].bind(rule)}else{s=`rule '${ruleName}': listener for '${callback}' in register() is not defined - rule is disabled`;this._error(s);this._showIgnoredRule(s);opts.enabled=false;continue}}if(_isHookRule(callbacks)){opts.$hook=true}else{if(!this._checkRuleSeverity(opts)){this._showIgnoredRule(`rule '${ruleName}' ignored by severity`);opts.enabled=false;continue}}}this._addToShadowRulePacks(ruleName,rule,opts);if(!opts.$internal){this._registry.setRuleCallback(ruleName,callbacks,opts._rsi)}this._ruleCount++;this._updateTargetFiletypes(opts)}catch(e){atLine=e.stack.replace(rulePath,"").trim();i=NaN;if(atLine.startsWith(COLON)){i=parseInt(atLine.substr(1))}if(!isNaN(i)){atLine=" line "+i+": "}else{i=atLine.indexOf(COLON);if(i<0){atLine=""}else{atLine=this._utils.eatLine(atLine,i);i=atLine.indexOf(COLON);if(i>=0){atLine=atLine.substring(i+1);i=atLine.indexOf(")");if(i>=0){atLine="("+atLine.substring(0,i).replace(COLON,",")+") - "}}else{atLine=""}};}this._showIgnoredRule(`Cannot load rule ${ruleName} [${atLine} '${e.message}']`,true)}}}this._showIgnoredRule(null);return true};RuleSet.prototype._showIgnoredRule=function(msg,isError){if(msg){if(!this._ignoredRulesShown){this._info("\n--------- Start-up Rule analysis ---------");this._ignoredRulesShown=true}isError?this._error(msg):this._info(msg)}else if(this._ignoredRulesShown){this._info("------------ End Rule analysis -------------")}};RuleSet.prototype._mergeRuleOptions=function(rulesJson,isBuiltinRules){var prefix,rules,overrides,ruleName,opts,error,x;this._debug("Augmenting config defined rules in rulePack from ruleMods...");prefix=rulesJson.prefix;rules=rulesJson.rules;overrides=this._getRuleModsByPrefix(prefix);for(ruleName in rules){error=false;if(!isBuiltinRules){x=RESERVED_RULE_PREFIX.indexOf(ruleName.toLowerCase());if(x>=0){this._showIgnoredRule(`rule '${ruleName}' in rulepack (prefix: '${prefix}') must not use JET reserved prefix '${RESERVED_RULE_PREFIX[x]}'`,true);error=true}}if(overrides){if(error){continue}if(overrides.hasOwnProperty(ruleName)&&rules[ruleName]){if(this._isAMD){opts=rules[ruleName];if(!_isAMDRule(opts)){if(this._debugMode){this._debug(`Rule options override ignored for non-AMD ${ruleName} in AMD mode`)}continue}if(!this._nd.ruleLoader(ruleName,opts._rsi,this._error)){continue}}if(this._debugMode){this._debug(`Merging rule props of ${ruleName}`)}this._mergeOverrideProps(ruleName,overrides[ruleName],rules[ruleName],isBuiltinRules)}}}};RuleSet.prototype._mergeOverrideProps=function(ruleName,configOpts,ruleOpts){var prop;for(prop in configOpts){if(prop.charAt(0)==="$"){delete configOpts[prop];this._showIgnoredRule(`rule '${ruleName}' : '${prop}' in config 'rulesMod' cannot use reserved '$' prefix`,true);continue}if(prop==="enabled"&&!configOpts[prop]&&ruleOpts["$required"]){this._showIgnoredRule(`rule '${ruleName}' is mandatory and cannot be disabled using config 'ruleMods' property.`,true);continue}ruleOpts[prop]=configOpts[prop]}};RuleSet.prototype._addToShadowRulePacks=function(ruleName,loadedRule,ruleOpts){var rsi=ruleOpts._rsi;var srp=this._shadowRulePacks;while(rsi>=srp.length){srp.push({})}srp[rsi][ruleName]=loadedRule};RuleSet.prototype._updateTargetFiletypes=function(opts){var ft=opts.filetype;if(ft){if(typeof ft==="string"){ft=[ft]}ft.forEach(t=>{if(!opts.$internal){if(!this._targFiletypes.includes(t)){this._targFiletypes.push(t)}}},this)}};RuleSet.prototype._getRuleModsByPrefix=function(prefix){var modPrefix,ret;if(this._ruleMods){prefix=prefix.toLowerCase();for(modPrefix in this._ruleMods){if(prefix===modPrefix.toLowerCase()){ret=this._ruleMods[modPrefix];break}}}return ret};RuleSet.prototype._isGroupActive=function(group){var groups,defs,def,i;groups=this._config.groups;defs=this._config.defGroups;if(this._checkGroups(groups,group)){return true}if(!defs){return false}for(i=0;i<groups.length;i++){def=groups[i];if(this._checkDefGroup(defs,def,group)){return true}}return false};RuleSet.prototype._checkGroups=function(cfgGroups,ruleGroup){var theGroup,i;if(Array.isArray(ruleGroup)){for(i=0;i<ruleGroup.length;i++){theGroup=ruleGroup[i];if(this._checkGroup(cfgGroups,theGroup)){return true}}}else if(this._checkGroup(cfgGroups,ruleGroup)){return true}return false};RuleSet.prototype._checkGroup=function(cfgGroups,group){return!cfgGroups||cfgGroups.includes(group)||cfgGroups.includes(this._severity.ALL)};RuleSet.prototype._isJetInRuleSet=function(jetPrefix){var i,ret=false;if(this._ruleSets&&this._ruleSets.length){for(i=0;i<this._ruleSets.length;i++){if(this._ruleSets[i].prefix===jetPrefix){ret=true;break}}}return ret};RuleSet.prototype._checkRuleSeverity=function(opts){var severities,severity,_sev,i,ret=false;severities=this._config.severity;severity=opts.severity;if(typeof severities==="string"){_sev=this._severity.getConfigSevExpr();if(_sev){ret=true}else{ret=severity===severities||severities===this._severity.ALL}}else{for(var i=0;i<severities.length;i++){if(severity===severities[i]||severities[i]===this._severity.ALL){ret=true;break}}}return ret};RuleSet.prototype._loadJson=function(filepath){var data,stats,msg;try{stats=this._nd.fs.lstatSync(filepath);if(!stats.isFile()){this._error(`RuleSet '${filepath}' not found!`);return null}else{data=this._nd.fs.readFileSync(filepath,"utf8");data=JSON.parse(this._nd.decomment(data))}}catch(e){if(e.code){if(e.message.startsWith("ENOENT:")){this._error(`RuleSet error - '${filepath}' not found!`)}}else if(e.toString().startsWith("SyntaxError")){msg=_convertMsgToRowCol(e.message,data,this._utils)}else{msg=e.message}if(msg){this._error(`JSON load error '${filepath}' - ${msg}`)}data=null}return data};function _isStatEnabledByPack(pstat,rstat){var ret=false;if(pstat.includes("all")||pstat.includes(rstat)){ret=true}else{if(rstat==="ready"||rstat.startsWith("prod")){ret=pstat.includes("ready")||pstat.includes("production")||pstat.includes("prod")}}return ret};function _isHookRule(callbacks){return callbacks[REG.PHASE_STARTUP]||callbacks[REG.PHASE_CLOSEDOWN]||callbacks[REG.PHASE_FILE]?true:false};function _isAMDRule(opts){return opts.hasOwnProperty("amd")?!!opts.amd:true};function _convertMsgToRowCol(msg,data,utils){var x,n,rc;x=msg.indexOf("position");if(x<0){return msg}n=parseInt(msg.substr(x+8).trim());rc=utils.getRowColFromIndex(data,n);return msg.substr(0,x)+"line "+rc.row+", col "+rc.col};function _isRE(s){return RULE_RE.test(s)};module.exports=RuleSet;
|
package/lib/Rules.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const RuleContext=require("./RuleContext");const REG=require("../lib/RegTypes");const PROP_FILETYPE="filetype";const FILETYPE_CSS="css";var _builtinJetRules=null;var Rules=function(ruleSets,nodeDeps,config,fnMsgId,appCtx){this._appCtx=appCtx;this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._assert=appCtx.assert;this._metaLib=appCtx.metaLib;this._reporter=appCtx.reporter;this._Issue=appCtx.Issue;this._semVer=ruleSets.getSemVer();this._utils=appCtx.utils;this._sevLib=appCtx.severity.getSevLib();this._registry=ruleSets.getRegistry();this._ruleCount=ruleSets.getActiveRuleCount();this._rulesetSummary=ruleSets.getRulesetSummary();this._rulePacks=ruleSets.getRulePacks();this._common=this._createCommon();this._shadowRulePacks=ruleSets.getShadowRulePacks();this._ruleSets=ruleSets;this._Stats=appCtx.Stats;this._isUnitTest=appCtx.isUnitTest;if(this._isUnitTest||config.rulesFired){this._Stats.packRulesFired=[];for(let i=0;i<ruleSets._ruleSets.length;i++)this._Stats.packRulesFired.push({pack:ruleSets._ruleSets[i].prefix,rules:{}})}this._useBuiltinJetRules=true;this._config=config;this._nodeDeps=nodeDeps;this._isNode=!!nodeDeps.fs;this._curFile=null;this._getMsgId=fnMsgId;this._sysOpts={verboseMode:appCtx.verboseMode,debugMode:appCtx.debugMode};this._message={msg:this._msg,info:this._info,debug:this._debug,error:this._error,assert:this._assert}};Rules.prototype.fireRules=function(ruleCtx,arg1,filepath,filetype,arg2,isEmbeddedCss){var ruleName,callbacks,typeObj;if(this._curFile!==filepath){this._curFile=filepath;this._fileType=filetype}typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type);if(typeObj){for(ruleName in typeObj){if(this._isRuleDisabledByComment&&this._isRuleDisabledByComment(ruleName)){continue}callbacks=typeObj[ruleName];this._fireRulePreTest(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks)}}};Rules.prototype.setJafLib=function(jl){this._jafLib=jl};Rules.prototype._fireRulePreTest=function(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks){var opts,callback,fileType,i;if(!callbacks){return}for(i=0;i<callbacks.length;i++){callback=callbacks[i];opts=this._getRuleOptionsByName(ruleName,callback.rsi);if(!opts.enabled){return}fileType=opts[PROP_FILETYPE];if(fileType){if(isEmbeddedCss&&!this._isFileTypeOk(fileType,FILETYPE_CSS)){return}if(!this._isFileTypeOk(fileType,this._fileType)){return}}ruleCtx._rsi=callback.rsi;ruleCtx.getMsgId=this._getMsgId;this._fireRule(ruleCtx,ruleName,arg1,arg2,filepath,fileType,callback.cb)}};Rules.prototype._fireRule=function(ruleCtx,ruleName,name,value,filepath,filetype,callback){var rule,msg,ctxType,oFired;ctxType=ruleCtx.type;this._debug("Firing rule "+ruleName+" type="+ctxType+" name="+name+" value="+value);rule=this._getRuleByName(ruleName,ruleCtx._rsi);if(!rule){return}ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;ruleCtx.filepath=filepath;ruleCtx.filename=filepath;ruleCtx.filetype=filetype;ruleCtx.utils=ruleCtx.utils?ruleCtx.utils:{};ruleCtx.msgLib=this._message;ruleCtx.message=this._message;ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[ruleCtx._rsi].rulePack;ruleCtx.sysOpts=this._sysOpts;ruleCtx.common=this._common[ruleCtx._rsi];ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._nodeDeps.fsUtils;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.sevLib=this._sevLib;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.jafLib=this._jafLib.getJafLib();this._curCtx=ruleCtx;try{if(callback){ruleCtx.rulePack._setCBCtx(ruleCtx);if((ctxType==="attr"||ctxType==="attrexpr"||ctxType.indexOf("|")>0||ctxType==="class"||ctxType==="style"||ctxType.startsWith("<")&&ctxType.includes("="))&&typeof value!=="string"){if(ctxType==="style"){callback(ruleCtx,name,_extractStyles(value.val),value.rawval)}else{callback(ruleCtx,name,value.val,value.rawval)}}else if(ctxType.startsWith("compjson")||ctxType==="comment"){callback(ruleCtx,value)}else{callback(ruleCtx,name,value)}this._Stats.rulesFired++;if(this._isUnitTest||this._config.rulesFired){if(oFired=this._Stats.packRulesFired[ruleCtx._rsi]){oFired=oFired.rules;if(oFired[ruleName]){oFired[ruleName]++}else{oFired[ruleName]=1}}}}else{rule.run(ruleCtx,name,value)}}catch(e){msg=!e||!e.message?"Unknown error (rule "+this._getFileSuffix(ruleCtx.filepath)+" syntax issue?)":e.message;this._error("** running rule "+ruleName+" ["+msg+"]"+"\n - "+ruleCtx.filepath);this._error(e.stack)}};Rules.prototype.makeRuleContext=function(){return new RuleContext};Rules.prototype.isTypeRegistered=function(regType){return this._registry.isRegisteredCallback(regType)};Rules.prototype.isTypeRegisteredAsElemName=function(elem){return this._registry.isRegisteredCallbackRE(elem)};Rules.prototype.setJSCommentCallback=function(fnCB){this._isRuleDisabledByComment=fnCB};Rules.prototype.filterHtmlCallbacks=function(htmlCB){return htmlCB};Rules.prototype.getRulesProse=function(isInternal){var rulePacks,rulePack,rules,rule,ruleName,rsi,opts,haveRules;this._nodeDeps.exportRules.setupRulesToProse(this._config.severity,this._utils);rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson;this._nodeDeps.exportRules.packToProse(rules,rulePack.path,rsi);haveRules=false;rules=rules.rules;for(ruleName in rules){if(!rules[ruleName].enabled){continue}opts=this._utils.extend(rules[ruleName],isInternal);rule=this._shadowRulePacks[rsi][ruleName];this._nodeDeps.exportRules.ruleToProse(ruleName,rule,opts);haveRules=true}if(!haveRules){this._nodeDeps.exportRules.packToProse()}}return this._nodeDeps.exportRules.getProse()};Rules.prototype.getRulesJson=function(obj){var rulePacks,rulePack,rulesJson,ruleName,rule,ruleOpts,opts,rsi;rulePacks=this._rulePacks;this._nodeDeps.exportRules.setupRulesToJson(obj,this._config.severity,this._utils);for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];this._nodeDeps.exportRules.packToJson(rulePack);rulesJson=rulePack.rulesJson;for(ruleName in rulesJson.rules){ruleOpts=rulesJson.rules[ruleName];if(!ruleOpts.enabled){continue}opts=this._utils.extend(ruleOpts);rule=this._shadowRulePacks[rsi][ruleName];this._nodeDeps.exportRules.ruleToJson(ruleName,rule,opts)}}return this._nodeDeps.exportRules.getJson()};Rules.prototype.getRulesSonar=function(){var rulePacks,rulePack,ruleName,rules,rule,opts,rsi;this._nodeDeps.exportRules.setupRulesToXml(this._utils);rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson.rules;for(ruleName in rules){if(!rules[ruleName].enabled){continue}rule=this._shadowRulePacks[rsi][ruleName];opts=rules[ruleName];this._nodeDeps.exportRules.ruleToXml(ruleName,rule,opts)}}return this._nodeDeps.exportRules.getXml()};Rules.prototype.getRuleOptions=function(ruleName,rsi){return this._getRuleOptionsByName(ruleName,rsi)};Rules.prototype.getActiveRuleCount=function(){return this._ruleCount};Rules.prototype.getRuleSetSummaryByIndex=function(rsi){return this._rulesetSummary[rsi]};Rules.prototype.getRulePack=function(rsi){return this._rulePacks[rsi].rulePack};Rules.prototype.getRSIByPrefix=function(prefix){var i,rsi=-1;;for(i=0;i<this._rulesetSummary.length;i++){if(this._rulesetSummary[i].prefix===prefix){rsi=i;break}}return rsi};Rules.prototype.isRuleEnabled=function(ruleName,rsi){if(rsi===undefined){rsi=this.getRSIByRuleName(ruleName);if(rsi<0){return false}}var opts=this._getRuleOptionsByName(ruleName,rsi);return!!(opts&&opts.enabled)};Rules.prototype.getRSIByRuleName=function(ruleName){var rsi,rp,len;len=this._shadowRulePacks.length;for(rsi=0;rsi<len;rsi++){rp=this._shadowRulePacks[rsi];if(rp[ruleName]){break}}return rsi<len?rsi:-1};Rules.prototype.getRuleDescription=function(prefix,ruleName,isShort){var rule,rsi,ret="";rsi=this.getRSIByPrefix(prefix);if(rsi>=0){rule=this._shadowRulePacks[rsi][ruleName];if(rule){ret=isShort?rule.getShortDescription():rule.getDescription()}}return ret};Rules.prototype.getRuleDescriptionEx=function(msgId,ruleName,isShort){var descrip,rule,prefix,msgNum,rsi,msgTab,msgIds,mid,sev,x;var idList=[];if(ruleName){var rp=this._shadowRulePacks;for(rsi=0;rsi<rp.length;rsi++){rule=rp[rsi][ruleName];if(rule){descrip=isShort?rule.getShortDescription():rule.getDescription();if(descrip){msgTab=this._ruleSets.loadMsgIds();if(prefix=this._rulesetSummary[rsi]){prefix=prefix.prefix;if(msgIds=msgTab[prefix]){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}}}break}}}}if(msgId){rsi=this._ruleSets.getRsiFromMsgId(msgId);if(rsi>=0){x=msgId.indexOf("-");prefix=msgId.substring(0,x);msgNum=msgId.substring(x+1);msgTab=this._ruleSets.loadMsgIds();msgIds=msgTab[prefix];if(msgNum.length<4){msgNum="0".repeat(4-msgNum.length)+msgNum}for(mid in msgIds){if(msgIds[mid]===msgNum){x=mid.lastIndexOf("_");ruleName=x>0?mid.substring(0,x):mid;if(descrip=this.getRuleDescription(prefix,ruleName,isShort)){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}break}}}}}if(ruleName){sev=this._getRuleOptionsByName(ruleName,rsi);sev=sev?sev.severity:""}return{descrip:descrip,rule:ruleName,prefix:prefix,sev:sev,idList:idList}};Rules.prototype._showIgnoredRule=function(msg,isError){if(msg){if(!this._ignoredRulesShown){this._info("\n--------- Start-up Rule analysis ---------");this._ignoredRulesShown=true}isError?this._error(msg):this._info(msg)}else if(this._ignoredRulesShown){this._info("------------ End Rule analysis -------------")}};Rules.prototype.fireHookRules=function(ruleCtx,rsi){var ruleName,typeObj,callbacks,callback,opts,rc,i;var _rsi;ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;ruleCtx.metaLib=this._metaLib;ruleCtx.msgLib=this._message;ruleCtx.message=this._message;_rsi=rsi;typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type);if(!typeObj){return}for(ruleName in typeObj){callbacks=typeObj[ruleName];if(!callbacks){continue}for(i=0;i<callbacks.length;i++){callback=callbacks[i];if(rsi===undefined){_rsi=callback.rsi}else{if(rsi!==callback.rsi){continue}_rsi=rsi}opts=this._getRuleOptionsByName(ruleName,_rsi);if(ruleCtx.type==="file"||ruleCtx.type==="startscript"){if(opts&&opts.filetype){if(!this._isFileTypeOk(opts.filetype,ruleCtx.filetype)){continue}}}ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[_rsi].rulePack;ruleCtx._rsi=_rsi;ruleCtx.common=this._common[_rsi];ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._nodeDeps.fsUtils;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.sysOpts=this._sysOpts;ruleCtx.getMsgId=this._getMsgId;this._debug("Firing hook rule "+ruleName+" type="+ruleCtx.type);ruleCtx.rulePack._setCBCtx(ruleCtx);rc=callback.cb(ruleCtx);this._Stats.hooksFired++;if((ruleCtx.phase===REG.PHASE_STARTUP||ruleCtx.phase===REG.PHASE_START_AUDIT||ruleCtx.phase===REG.PHASE_FILE)&&typeof rc==="boolean"&&!rc){this._info("Hook rule ('"+ruleCtx.type+"') veto! by '"+ruleName+"'");return rc}}}return true};Rules.prototype._getRuleByName=function(ruleName,rsi){var rs=this._shadowRulePacks[rsi];return rs[ruleName]};Rules.prototype._getRuleOptionsByName=function(ruleName,rsi){var rulePack=this._rulePacks[rsi];return rulePack.rulesJson.rules[ruleName]};Rules.prototype._isGroupActive=function(group){var groups,defs,def,i;groups=this._config.groups;defs=this._config.defGroups;if(this._checkGroups(groups,group)){return true}if(!defs){return false}for(i=0;i<groups.length;i++){def=groups[i];if(this._checkDefGroup(defs,def,group)){return true}}return false};Rules.prototype._loadBuiltinJetRulesDescriptions=function(){var ruleName,rules;try{if(!_builtinJetRules){_builtinJetRules=require("../rules/jet/rules.json")}}catch(e){this._error("Unable to load builtin rule definition file "+e)}if(_builtinJetRules&&_builtinJetRules.rules){rules=_builtinJetRules.rules;for(ruleName in rules){rules[ruleName].$builtin=true}}return _builtinJetRules};Rules.prototype._isFileTypeOk=function(ruleFileType,fileType){var ret=false;if(Array.isArray(ruleFileType)){ret=ruleFileType.indexOf(fileType)>=0}else{ret=ruleFileType===fileType}return ret};Rules.prototype._createCommon=function(){var i,a=[];for(i=0;i<this._rulesetSummary.length;i++){a.push({})}return a};Rules.prototype._getFileSuffix=function(fp){var s="";if(fp){s=this._nodeDeps.path.extname(fp)}return s.length?s:"?"};function _extractStyles(s){var a,isExpr,i,sc=";";s=s.trim();isExpr=_isExpr(s);s=s.replace(/[\'\"\[\]\{\}]/g,"").trim();if(!s.includes(";")){if(isExpr){if(s.includes(",")){sc=","}}}a=s.split(sc);for(i=0;i<a.length;i++){a[i]=a[i].trim();if(!a[i].length){a.splice(i,1);i--}}return a};function _isExpr(s){s=s.trim();return s.startsWith("[[")||s.startsWith("{{")};module.exports=Rules;
|
|
6
|
+
const RuleContext=require("./RuleContext");const REG=require("../lib/RegTypes");const PROP_FILETYPE="filetype";const FILETYPE_CSS="css";var Rules=function(ruleSets,nodeDeps,config,fnMsgId,appCtx){this._appCtx=appCtx;this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._assert=appCtx.assert;this._metaLib=appCtx.metaLib;this._reporter=appCtx.reporter;this._Issue=appCtx.Issue;this._semVer=ruleSets.getSemVer();this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._sevLib=appCtx.severity.getSevLib();this._ojetLib=appCtx.ojetLib;this._registry=ruleSets.getRegistry();this._ruleCount=ruleSets.getActiveRuleCount();this._rulesetSummary=ruleSets.getRulesetSummary();this._rulePacks=ruleSets.getRulePacks();this._common=this._createCommon();this._shadowRulePacks=ruleSets.getShadowRulePacks();this._ruleSets=ruleSets;this._Stats=appCtx.Stats;this._isUnitTest=appCtx.isUnitTest;if(this._isUnitTest||config.rulesFired){this._Stats.packRulesFired=[];for(let i=0;i<ruleSets._ruleSets.length;i++)this._Stats.packRulesFired.push({pack:ruleSets._ruleSets[i].prefix,rules:{}})}this._builtinJetRules=null;this._useBuiltinJetRules=true;this._config=config;this._nd=nodeDeps;this._isNode=!!nodeDeps.fs;this._curFile=null;this._getMsgId=fnMsgId;this._sysOpts={verboseMode:appCtx.verboseMode,debugMode:appCtx.debugMode};this._message={msg:this._msg,info:this._info,debug:this._debug,error:this._error,assert:this._assert}};Rules.prototype.fireRules=function(ruleCtx,arg1,filepath,filetype,arg2,isEmbeddedCss){var ruleName,callbacks,typeObj;if(this._curFile!==filepath){this._curFile=filepath;this._fileType=filetype}typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type);if(typeObj){for(ruleName in typeObj){if(this._isRuleDisabledByComment&&this._isRuleDisabledByComment(ruleName)){continue}callbacks=typeObj[ruleName];this._fireRulePreTest(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks)}}};Rules.prototype.setJafLib=function(jl){this._jafLib=jl};Rules.prototype._fireRulePreTest=function(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks){var opts,callback,fileType,i;if(!callbacks){return}for(i=0;i<callbacks.length;i++){callback=callbacks[i];opts=this._getRuleOptionsByName(ruleName,callback.rsi);if(!opts.enabled){return}fileType=opts[PROP_FILETYPE];if(fileType){if(isEmbeddedCss&&!this._isFileTypeOk(fileType,FILETYPE_CSS)){return}if(!this._isFileTypeOk(fileType,this._fileType)){return}}ruleCtx._rsi=callback.rsi;ruleCtx.getMsgId=this._getMsgId;this._fireRule(ruleCtx,ruleName,arg1,arg2,filepath,fileType,callback.cb)}};Rules.prototype._fireRule=function(ruleCtx,ruleName,name,value,filepath,filetype,callback){var rule,msg,ctxType,oFired;ctxType=ruleCtx.type;this._debug("Firing rule "+ruleName+" type="+ctxType+" name="+name+" value="+value);rule=this._getRuleByName(ruleName,ruleCtx._rsi);if(!rule){return}ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;ruleCtx.filepath=filepath;ruleCtx.filetype=filetype;ruleCtx.utils=ruleCtx.utils?ruleCtx.utils:{};ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[ruleCtx._rsi].rulePack;ruleCtx.sysOpts=this._sysOpts;ruleCtx.common=this._common[ruleCtx._rsi];ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.sevLib=this._sevLib;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.jafLib=this._jafLib.getJafLib();ruleCtx.utils.OjetLib=this._ojetLib;this._curCtx=ruleCtx;try{if(callback){ruleCtx.rulePack._setCBCtx(ruleCtx);if((ctxType==="attr"||ctxType==="attrexpr"||ctxType.indexOf("|")>0||ctxType==="class"||ctxType==="style"||ctxType.startsWith("<")&&ctxType.includes("="))&&typeof value!=="string"){if(ctxType==="style"){callback(ruleCtx,name,_extractStyles(value.val),value.rawval)}else{callback(ruleCtx,name,value.val,value.rawval)}}else if(ctxType.startsWith("compjson")||ctxType==="comment"){callback(ruleCtx,value)}else if(ruleCtx.type==="json"){callback(ruleCtx,value.ast)}else{callback(ruleCtx,name,value)}this._Stats.rulesFired++;if(this._isUnitTest||this._config.rulesFired){if(oFired=this._Stats.packRulesFired[ruleCtx._rsi]){oFired=oFired.rules;if(oFired[ruleName]){oFired[ruleName]++}else{oFired[ruleName]=1}}}}else{rule.run(ruleCtx,name,value)}}catch(e){msg=!e||!e.message?"Unknown error (rule "+this._getFileSuffix(ruleCtx.filepath)+" syntax issue?)":e.message;this._error("** running rule "+ruleName+" ["+msg+"]"+"\n - "+ruleCtx.filepath);this._error(e.stack)}};Rules.prototype.makeRuleContext=function(){return new RuleContext};Rules.prototype.isTypeRegistered=function(regType){return this._registry.isRegisteredCallback(regType)};Rules.prototype.isTypeRegisteredAsElemName=function(elem){return this._registry.isRegisteredCallbackRE(elem)};Rules.prototype.setJSCommentCallback=function(fnCB){this._isRuleDisabledByComment=fnCB};Rules.prototype.filterHtmlCallbacks=function(htmlCB){return htmlCB};Rules.prototype.getRulesProse=function(isInternal){var rulePacks,rulePack,rules,rule,ruleName,names,rsi,opts,haveRules,prefix,msgIds,ids;this._nd.exportRules.setupRulesToProse(this._nd,this._config.severity,this._appCtx);msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson;prefix=rules.prefix;this._nd.exportRules.packToProse(rules,rulePack.path,rsi);haveRules=false;rules=rules.rules;names=_getSortedRuleNames(rules);for(ruleName of names){opts=rules[ruleName];if(!opts.enabled||opts.hasOwnProperty("inservice")&&!opts.inservice){continue}opts=this._utils.extend(opts,isInternal);rule=this._shadowRulePacks[rsi][ruleName];ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);this._nd.exportRules.ruleToProse(ruleName,rule,opts,ids);haveRules=true}if(!haveRules){this._nd.exportRules.packToProse()}}return this._nd.exportRules.getProse()};Rules.prototype.getRulesJson=function(active,obj){var rulePacks,rulePack,rulesJson,ruleName,rule,ruleOpts,opts,pack,rsi,prefix,msgIds,ids;msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;this._nd.exportRules.setupRulesToJson(obj,this._config.severity,this._appCtx);for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];this._nd.exportRules.packToJson(rulePack);rulesJson=rulePack.rulesJson;prefix=rulesJson.prefix;for(ruleName in rulesJson.rules){ruleOpts=rulesJson.rules[ruleName];if(ruleOpts.hasOwnProperty("inservice")&&!ruleOpts.inservice){continue}if(active&&!ruleOpts.enabled){continue}opts=this._utils.extend(ruleOpts);ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);if(pack=this._shadowRulePacks[rsi]){rule=pack[ruleName]}else{rule=null}if(!active||rule){this._nd.exportRules.ruleToJson(ruleName,rule,opts,ids,active)}}}return this._nd.exportRules.getJson()};Rules.prototype.getRulesSonar=function(){var rulePacks,rulePack,ruleName,rules,rule,opts,prefix,msgIds,ids,rsi;this._nd.exportRules.setupRulesToXml(this._appCtx);msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson.rules;prefix=rulePack.rulesJson.prefix;for(ruleName in rules){opts=rules[ruleName];if(!opts.enabled||opts.hasOwnProperty("inservice")&&!opts.inservice){continue}opts=this._utils.extend(opts);rule=this._shadowRulePacks[rsi][ruleName];ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);this._nd.exportRules.ruleToXml(ruleName,rule,opts,ids)}}return this._nd.exportRules.getXml()};Rules.prototype.getRuleOptions=function(ruleName,rsi){return this._getRuleOptionsByName(ruleName,rsi)};Rules.prototype.getActiveRuleCount=function(){return this._ruleCount};Rules.prototype.getRuleSetSummaryByIndex=function(rsi){return this._rulesetSummary[rsi]};Rules.prototype.getRulePack=function(rsi){return this._rulePacks[rsi].rulePack};Rules.prototype.getRSIByPrefix=function(prefix){var i,rsi=-1;;for(i=0;i<this._rulesetSummary.length;i++){if(this._rulesetSummary[i].prefix===prefix){rsi=i;break}}return rsi};Rules.prototype.isRuleEnabled=function(ruleName,rsi){if(rsi===undefined){rsi=this.getRSIByRuleName(ruleName);if(rsi<0){return false}}var opts=this._getRuleOptionsByName(ruleName,rsi);return!!(opts&&opts.enabled)};Rules.prototype.getRSIByRuleName=function(ruleName){var rsi,rp,len;len=this._shadowRulePacks.length;for(rsi=0;rsi<len;rsi++){rp=this._shadowRulePacks[rsi];if(rp[ruleName]){break}}return rsi<len?rsi:-1};Rules.prototype.getRuleDescription=function(prefix,ruleName,isShort){var rule,rsi,ret="";rsi=this.getRSIByPrefix(prefix);if(rsi>=0){rule=this._shadowRulePacks[rsi][ruleName];if(rule){ret=isShort?rule.getShortDescription():rule.getDescription()}}return ret};Rules.prototype.getRuleDescriptionEx=function(msgId,ruleName,isShort){var descrip,rule,prefix,msgNum,rsi,msgTab,msgIds,mid,sev,x;var idList=[];if(ruleName){var rp=this._shadowRulePacks;for(rsi=0;rsi<rp.length;rsi++){rule=rp[rsi][ruleName];if(rule){descrip=isShort?rule.getShortDescription():rule.getDescription();if(descrip){msgTab=this._ruleSets.loadMsgIds();if(prefix=this._rulesetSummary[rsi]){prefix=prefix.prefix;if(msgIds=msgTab[prefix]){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}}}break}}}}if(msgId){rsi=this._ruleSets.getRsiFromMsgId(msgId);if(rsi>=0){x=msgId.indexOf("-");prefix=msgId.substring(0,x);msgNum=msgId.substring(x+1);msgTab=this._ruleSets.loadMsgIds();msgIds=msgTab[prefix];if(msgNum.length<4){msgNum="0".repeat(4-msgNum.length)+msgNum}for(mid in msgIds){if(msgIds[mid]===msgNum){x=mid.lastIndexOf("_");ruleName=x>0?mid.substring(0,x):mid;if(descrip=this.getRuleDescription(prefix,ruleName,isShort)){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}break}}}}}if(ruleName){sev=this._getRuleOptionsByName(ruleName,rsi);sev=sev?sev.severity:""}return{descrip:descrip,rule:ruleName,prefix:prefix,sev:sev,idList:idList}};Rules.prototype._getMsgIdsForRule=function(rname,ids,prefix){var r,list=[];prefix=prefix?prefix+"-":"";for(r in ids){if(r.startsWith(rname)){list.push(prefix+ids[r])}}return list};Rules.prototype._showIgnoredRule=function(msg,isError){if(msg){if(!this._ignoredRulesShown){this._info("\n--------- Start-up Rule analysis ---------");this._ignoredRulesShown=true}isError?this._error(msg):this._info(msg)}else if(this._ignoredRulesShown){this._info("------------ End Rule analysis -------------")}};Rules.prototype.fireHookRules=function(ruleCtx,rsi){var ruleName,typeObj,callbacks,callback,opts,rc,i;var _rsi;ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;_rsi=rsi;typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type);if(!typeObj){return}ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.OjetLib=this._ojetLib;ruleCtx.sysOpts=this._sysOpts;ruleCtx.getMsgId=this._getMsgId;for(ruleName in typeObj){callbacks=typeObj[ruleName];if(!callbacks){continue}for(i=0;i<callbacks.length;i++){callback=callbacks[i];if(rsi===undefined){_rsi=callback.rsi}else{if(rsi!==callback.rsi){continue}_rsi=rsi}opts=this._getRuleOptionsByName(ruleName,_rsi);if(ruleCtx.type==="file"||ruleCtx.type==="startscript"){if(opts&&opts.filetype){if(!this._isFileTypeOk(opts.filetype,ruleCtx.filetype)){continue}}}ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[_rsi].rulePack;ruleCtx._rsi=_rsi;ruleCtx.common=this._common[_rsi];this._debug("Firing hook rule "+ruleName+" type="+ruleCtx.type);ruleCtx.rulePack._setCBCtx(ruleCtx);rc=callback.cb(ruleCtx);this._Stats.hooksFired++;if((ruleCtx.phase===REG.PHASE_STARTUP||ruleCtx.phase===REG.PHASE_START_AUDIT||ruleCtx.phase===REG.PHASE_FILE)&&typeof rc==="boolean"&&!rc){this._info("Hook rule ('"+ruleCtx.type+"') veto! by '"+ruleName+"'");return rc}}}return true};Rules.prototype._getRuleByName=function(ruleName,rsi){var rs=this._shadowRulePacks[rsi];return rs[ruleName]};Rules.prototype._getRuleOptionsByName=function(ruleName,rsi){var rulePack=this._rulePacks[rsi];return rulePack.rulesJson.rules[ruleName]};Rules.prototype._isGroupActive=function(group){var groups,defs,def,i;groups=this._config.groups;defs=this._config.defGroups;if(this._checkGroups(groups,group)){return true}if(!defs){return false}for(i=0;i<groups.length;i++){def=groups[i];if(this._checkDefGroup(defs,def,group)){return true}}return false};Rules.prototype._loadBuiltinJetRulesDescriptions=function(){var ruleName,rules;try{if(!this._builtinJetRules){this._builtinJetRules=require("../rules/jet/rules.json")}}catch(e){this._error("Unable to load builtin rule definition file "+e)}if(this._builtinJetRules&&this._builtinJetRules.rules){rules=this._builtinJetRules.rules;for(ruleName in rules){rules[ruleName].$builtin=true}}return this._builtinJetRules};Rules.prototype._isFileTypeOk=function(ruleFileType,fileType){var ret=false;if(Array.isArray(ruleFileType)){ret=ruleFileType.indexOf(fileType)>=0}else{ret=ruleFileType===fileType}return ret};Rules.prototype._createCommon=function(){var i,a=[];for(i=0;i<this._rulesetSummary.length;i++){a.push({})}return a};Rules.prototype._getFileSuffix=function(fp){var s="";if(fp){s=this._nd.path.extname(fp)}return s.length?s:"?"};Rules.prototype.dumpRegistry=function(){return this._registry.dump()};function _extractStyles(s){var a,isExpr,i,sc=";";s=s.trim();isExpr=_isExpr(s);s=s.replace(/[\'\"\[\]\{\}]/g,"").trim();if(!s.includes(";")){if(isExpr){if(s.includes(",")){sc=","}}}a=s.split(sc);for(i=0;i<a.length;i++){a[i]=a[i].trim();if(!a[i].length){a.splice(i,1);i--}}return a};function _isExpr(s){s=s.trim();return s.startsWith("[[")||s.startsWith("{{")};function _getSortedRuleNames(rules){var rule,names=[];for(rule in rules){names.push(rule)}names.sort();return names};module.exports=Rules;
|
package/lib/Scope.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
var walker=require('./scopewalker');const TS_ANY='TSAnyKeyword';const TS_TYPEREF='TSTypeReference';const TS_ARRAY='TSArrayType';const STRING='string';const NUMBER='number';const BOOLEAN='boolean';const NULL='null';const OBJECT='Object';const FUNCTION='function';const ANY='any';const UNKNOWN='unknown';const PROGRAM='Program';const GLOBAL_SCOPE='_@global';const ANON='$anon';const DOCUMENT_METHODS={createElement:'Element',createTextNode:'Element',getElementById:'Element',getElementsByClassName:'HTMLCollection',getElementsByName:'HTMLCollection',getElementsByTagName:'HTMLCollection',getElementsByTagNameNS:'HTMLCollecion',hasFocus:'boolean',querySelector:'Element',querySelectorAll:'NodeList'};const DOCUMENT_MEMBERS={activeElement:'Element',anchors:'HTMLCollection',body:'Element',childElementCount:'number',dir:'string',documentElement:'Element',documentURI:'string',docType:'DTD',forms:'HTMLCollection',getElementById:'Element',head:'Element',hidden:'boolean',links:'HTMLCollection',scrollingElement:'Element',visibilityState:'string'};const INDENT=3;var _level=-INDENT;function _trace(t,n){function _rj(s,w){s=''+s;if(s.length<w){s=' '.repeat(w-s.length)+s}return s}_level+=t==='E'?INDENT:0;if(t==='E')console.log(`${_rj(n.loc.start.line,4)}] ${' '.repeat(_level)} ${n.type}`);else console.log(`${' '.repeat(4)} ${' '.repeat(_level)} ${n.type}`);_level-=t==='L'?INDENT:0};class Scope{constructor(msgCtx,config){this._msgCtx=msgCtx;this._config=config;this.reset()}reset(){this._fStack=[];this._bStack=[];this._imports=[];this._funcStack=[];this._idxStack=0;this._parents=[];this._blockStack=[];this._idxBlkStack=0;this._blkParents=[];this._nextAnonId=0;this._varKind;this._level=-INDENT}build(ast){this.reset();try{walker.traverse(ast,{enter:this._enter.bind(this),leave:this._leave.bind(this)})}catch(e){console.log(e.stack)}return{funcs:this._fStack,blocks:this._bStack}}_buildFuncIndexesToBlocks(){var i,j;for(i=0;i<this._fStack.length;i++){for(j=0;j<this._bStack.length;j++){if(this._bStack[j].func==i){this._fStack[i].blocks.push(j)}}}}getAccessor(){return new _scope(this._fStack,this._bStack)}_enter(node){var type;if(this._msgCtx.isDebug){_trace('E',node)}type=node.type;if(this._isNewScope(node)){this._addNewFunc(node)}else if(type==='VariableDeclarator'||type==='ClassProperty'){this._varDecl(node)}else if(type==='VariableDeclaration'){this._varKind=node.kind}else if(type==='BlockStatement'){this._addNewBlock(node)}else if(type==='ClassDeclaration'){this._inClass=true;this._className=node.id.name}else if(type==='ImportDeclaration'){this._addImport(node)}}_leave(node){if(this._msgCtx.isDebug){_trace('L',node)}if(this._isNewScope(node)){if(this._parents.length){this._parents.pop()}this._funcStack.pop()}else if(node.type==='BlockStatement'){if(this._blkParents.length){this._blkParents.pop()}this._blockStack.pop()}else if(node.type==='ClassDeclaration'){this._inClass=false;this._className=null}}_addNewFunc(node){var type,func,curParent,x;type=node.type;if(type===PROGRAM){func=GLOBAL_SCOPE}else if(node.kind==='method'||node.kind==='constructor'){func=node.key.name}else if(node.id){func=node.id.name}else if(type==='ClassBody'){func=this._className}else{this._getNextAnon()}if(this._parents.length){curParent=this._fStack[this._parents[this._parents.length-1]]}x=this._fStack.push({func:func,node:node,vars:{},args:{},blocks:[],children:[],parent:this._parents.length?this._parents[this._parents.length-1]:-1});x--;this._parents.push(x);if(curParent){curParent.children.push(x)}this._funcStack.push(x);this._addFuncArgs(node)}_addNewBlock(node){var func,curParent,x;var func=this._fStack[this._getCurFunc()];let n=this._fStack[this._getCurFunc()].node;if((n.kind==='method'||n.kind==='constructor')&&this._isMethodRange(n,node)||n.kind!=='method'&&n.kind!=='constructor'&&node.range===n.body.range){return}if(this._blkParents.length){curParent=this._bStack[this._blkParents[this._blkParents.length-1]]}x=this._bStack.push({func:this._getCurFunc(),node:node,lets:{},children:[],parent:this._blkParents.length?this._blkParents[this._blkParents.length-1]:-1});x--;this._blkParents.push(x);if(curParent){curParent.children.push(x)}this._blockStack.push(x);func.blocks.push(x)}_addImport(node){var src,local,o;src=node.source.value;if(!src.startsWith('ojs/')){return}o={src:src};if(node.specifiers.length){node.specifiers.forEach(s=>{if(!local)local=[];local.push(s.local.name)});if(local){o.local=local}}this._imports.push(o)}_getCurFunc(){return this._funcStack[this._funcStack.length-1]}_getCurBlock(){return this._blockStack[this._blockStack.length-1]}_addFuncArgs(node){var vt,curScope;if(node.params){curScope=this._fStack[this._getCurFunc()];node.params.forEach(function(n){if(n.type==='Identifier'){vt=this._getVarType(n);curScope.args[n.name]={type:vt}}else{if(n.type==='AssignmentPattern'){if(n.left&&n.left.name){curScope.args[n.left.name]={type:'???'}}else{console.log('scopes nt = n.type')}}}},this)}}_isNewScope(node){var type=node.type;return type==='FunctionDeclaration'||type==='MethodDefinition'||type==='FunctionExpression'&&!this._inClass||type==='ClassBody'||type==='Program'}_varDecl(node){var curScope,vt,name;function _declVar(vt,self){curScope=self._fStack[self._getCurFunc()];if(node.id){name=node.id.name}else{name=node.key.name}curScope.vars[name]={type:vt,node:node}};vt=this._getVarType(node);if(this._varKind==='let'||this._varKind==='const'){if(this._blockStack.length===0){this._varKind='var'}}if(this._varKind==='var'||node.type==='ClassProperty'){_declVar(vt,this)}else if(this._varKind==='let'||this._varKind==='const'){let b=this._getCurBlock();if(b>=0){let block=this._bStack[b];let br=block.node.range;let start=node.range;if(start[0]>=br[0]&&start[1]<=br[1]){block.lets[node.id.name]={type:vt,node:node}}}else{_declVar(vt,this)}}}_getVarType(node){var vt,ta,et,ty;if(node.type==='ClassProperty'){if(node.value){if(node.value.type==='ArrowFunctionExpression'){return'function'}else if(node.value.type==='CallExpression'){if(node.value.callee.object.name==='ko'){if(node.value.callee.property.name==='observable'){return'KO_Observable'}else if(node.value.callee.property.name==='computed'){return'KO_computed'}else{return'KO_Unknown'}}}}}ta=node.id&&node.id.typeAnnotation?node.id.typeAnnotation:node.typeAnnotation;if(!ta){ty=node.init?this._getInitType(node.init):ANY}else{vt=ta.typeAnnotation.type;if(vt===TS_TYPEREF){if(ta.typeAnnotation.typeName.name){ty=ta.typeAnnotation.typeName.name}else{if(ta.typeAnnotation.typeName.left){if(ta.typeAnnotation.typeName.left.name){ty=ta.typeAnnotation.typeName.left.name;if(ta.typeAnnotation.typeName.right&&ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}else if(ta.typeAnnotation.typeName.left.left.name){ty+='.'+ta.typeAnnotation.typeName.left.left.name;if(ta.typeAnnotation.typeName.left.right.name){ty+='.'+ta.typeAnnotation.typeName.left.right.name}if(ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}}}}else if(vt===TS_ARRAY){et=ta.typeAnnotation.elementType.type;if(et===TS_TYPEREF){ty=ta.typeAnnotation.elementType.typeName.name+'[]'}else{ty=et+'[]'}}else{ty=vt}}if(ty){ty=_transformType(ty)}if(!ty){console.log('[ASSERT]: scopes: ty not defined')}return ty}_getInitType(init){var vt,raw;if(init.type==='Literal'&&init.raw){raw=init.raw;if(raw.charAt(0)==='"'||raw.charAt(0)==='\''){vt=STRING}else if(raw==='true'||raw==='false'){vt=BOOLEAN}else if(!isNaN(raw)){vt=NUMBER}else if(raw==='null'){vt=NULL}else{console.log('[ASSERT]: SCOPES - UNKNOWN VAR INIT LITERAL = '+raw);vt=UNKNOWN}}else if(init.type==='ObjectExpression'){vt=OBJECT}else if(init.type==='NewExpression'){if(init.callee&&init.callee.name){vt=init.callee.name}}else if(init.type==='CallExpression'){if(init.callee&&init.callee.object){let o=init.callee.object;if(o.type==='Identifier'&&o.name==='document'){o=init.callee.property;if(o=DOCUMENT_METHODS[o.name]){return o}else{return'unknown document function'}}if(o.type==='MemberExpression'){vt=this._unravelCallME(o)}if(init.callee&&init.callee.object&&init.callee.object.type==='FunctionExpression'){vt='function'}}}else if(init.type==='MemberExpression'){if(init.object.type==='TSAsExpression'){vt=UNKNOWN}}else if(init.type==='TSAsExpression'){if(init.typeAnnotation&&init.typeAnnotation.type==='TSTypeReference'){vt=init.typeAnnotation.typeName.name}else{vt=UNKNOWN}}else if(init.type==='TSTypeAssertion'){if(init.typeAnnotation){vt=init.typeAnnotation.type}}else{vt=init.type}if(!vt){vt=UNKNOWN}return vt}_isMethodRange(n,node){return n.value&&n.value.body&&n.value.body.range===node.range}_unravelCallME(o){var prop;if(o.object.type==='ThisExpression'){prop=o.property.name;return this._getClassPropType(o,prop)}}_getClassPropType(o,prop){var c,ret;c=this._getContainingClass(o);if(c&&c.vars){ret=c.vars[prop];if(ret){ret=ret.type}}return ret}_getContainingClass(node){var c=this._getCurFunc(node);if(c<0){return}do{c=this._fStack[c];if(c.node.type==='ClassBody'){break}c=c.parent}while(c>=0);return c}_dumpEnter(node){let funcName=node.id?node.id.name:'anon';console.log(`ENTER=${funcName} ${node.type}`)}_dumpLeave(node){let funcName=node.id?node.id.name:'anon';console.log(`LEAVE=${funcName} ${node.type}`)}dumpStacks(){this.dumpFuncStack();this.dumpBlockStack()}dumpFuncStack(){var st,v,o,s,i,title;console.log('\n-------- Function/Class Scope Map --------');st=this._fStack;for(i=0;i<st.length;i++){o=st[i];s=(o.children.length?'children='+_dumpArrayIndices(o.children):'')+' blocks='+_dumpArrayIndices(o.blocks);console.log(`\n[${i}] "${o.func}" ${_dumpStackType(o)} parent=${o.parent} ${s}`);title=false;if(_hasProps(o.args)){for(v in o.args){console.log((!title?' Args: ':' ')+v+': '+o.args[v].type);title=true}}else{console.log(' Args: none')}title=false;if(_hasProps(o.vars)){for(v in o.vars){console.log((!title?' Vars: ':' ')+v+': '+o.vars[v].type+' ('+(o.vars[v].node.type==='ClassProperty'?'class prop':'var')+')');title=true}}else{console.log(' Vars: none')}}}dumpBlockStack(){var st,v,o,ch,i,title;console.log('\n-------- Internal Block Scope Map --------');st=this._bStack;if(!st.length){console.log('\nNo blocks.');return''}for(i=0;i<st.length;i++){o=st[i];ch=o.children.length?'children='+_dumpArrayIndices(o.children):'';console.log(`\n[${i}] ${this._dumpBlkOwner(o)}="${this._fStack[o.func].func}" parent=${o.parent} ${ch}`);title=false;if(_hasProps(o.lets)){for(v in o.lets){console.log((!title?' Lets: ':' ')+v+': '+o.lets[v].type);title=true}}else{console.log(' Lets: none')}}}_dumpBlkOwner(o){var f=this._fStack[o.func];return f.node.type==='FunctionDeclaration'?'func':'meth'}_getNextAnon(){return ANON+ ++this._nextAnonId}};function _hasProps(obj){var ret=false;for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}return ret};function _dumpArrayIndices(a){var ret='[';a.forEach(function(v,i){ret+=(i?', ':'')+v});return ret+']'}function _dumpStackType(o){var s='';switch(o.node.type){case'ClassBody':s='class';break;case'MethodDefinition':s='method';break;case'FunctionDeclaration':s='func';break;}return s.length?'('+s+')':s};function _transformType(ty){const list={TSStringKeyword:'string',TSNumberKeyword:'number',TSBooleanKeyword:'boolean',TSNullKeyword:'null',TSObjectKeyword:'object',TSUnknownKeyword:'unknown',TSAnyKeyword:'any'};return list[ty]||ty};class _scope{constructor(fs,bs){this._fstk=fs;this._bstk=bs}getVarType(node){var name,func,block,v;name=node.name;if(!node.name){return null}block=this.getContainingBlock(node);if(block){v=block.lets[name];if(v){return v.type}while(block.parent>=0){block=this._bstk[block.parent];if(block){v=block.lets[name];if(v){return v.type}}}}func=this.getContainingFunc(node);do{if(func.vars&&func.vars[name]){v=func.vars[name].type}else if(func.args&&func.args[name]){v=func.args[name].type}if(v){break}if(func.parent>=0){func=this._fstk[func.parent]}else{func=null}}while(func);return v}getContainingFunc(node){var start,fnRange,fnIndex,func,fr,i;start=node.range[0];for(i=0;i<this._fstk.length;i++){func=this._fstk[i];fr=func.node.range;if(start>=fr[0]&&start<=fr[1]){if(fnRange){if(fr[0]>=fnRange[0]&&fr[1]<=fnRange[1]){fnRange=fr;fnIndex=i}}else{fnRange=fr;fnIndex=i}}}return typeof fnIndex==='number'?this._fstk[fnIndex]:null}getContainingBlock(node){var nrange,brange,range,bindex,blocks,block,i;if(!this._bstk.length)return;var blocks=this.getContainingFunc(node).blocks;nrange=node.range;for(i=0;i<blocks.length;i++){block=this._bstk[i];brange=block.node.range;if(nrange[0]>=brange[0]&&nrange[1]<=brange[1]){if(range){if(brange[0]>=range[0]&&brange[1]<=range[1]){range=nrange;bindex=i}}else{range=brange;bindex=i}}}return typeof bindex==='number'?this._bstk[bindex]:null}getContainingClass(node){}getGlobals(){return this._fstk[0]}getFuncStack(){return this._fstk}getBlockStack(){return this._bstk}};module.exports=Scope;
|
|
6
|
+
var walker=require('./scopewalker');const TS_ANY='TSAnyKeyword';const TS_TYPEREF='TSTypeReference';const TS_ARRAY='TSArrayType';const STRING='string';const NUMBER='number';const BOOLEAN='boolean';const NULL='null';const OBJECT='Object';const FUNCTION='function';const ANY='any';const UNKNOWN='unknown';const PROGRAM='Program';const GLOBAL_SCOPE='_@global';const ANON='$anon';const DOCUMENT_METHODS={createElement:'Element',createTextNode:'Element',getElementById:'Element',getElementsByClassName:'HTMLCollection',getElementsByName:'HTMLCollection',getElementsByTagName:'HTMLCollection',getElementsByTagNameNS:'HTMLCollecion',hasFocus:'boolean',querySelector:'Element',querySelectorAll:'NodeList'};const DOCUMENT_MEMBERS={activeElement:'Element',anchors:'HTMLCollection',body:'Element',childElementCount:'number',dir:'string',documentElement:'Element',documentURI:'string',docType:'DTD',forms:'HTMLCollection',getElementById:'Element',head:'Element',hidden:'boolean',links:'HTMLCollection',scrollingElement:'Element',visibilityState:'string'};const INDENT=3;var _level=-INDENT;function _trace(t,n){function _rj(s,w){s=''+s;if(s.length<w){s=' '.repeat(w-s.length)+s}return s}_level+=t==='E'?INDENT:0;if(t==='E')console.log(`${_rj(n.loc.start.line,4)}] ${' '.repeat(_level)} ${n.type}`);else console.log(`${' '.repeat(4)} ${' '.repeat(_level)} ${n.type}`);_level-=t==='L'?INDENT:0};class Scope{constructor(msgCtx,config,file){this._msgCtx=msgCtx;this._config=config;this._file=file;this.reset()}reset(){this._fStack=[];this._bStack=[];this._imports=[];this._funcStack=[];this._idxStack=0;this._parents=[];this._blockStack=[];this._idxBlkStack=0;this._blkParents=[];this._nextAnonId=0;this._varKind;this._level=-INDENT}build(ast){this.reset();try{walker.traverse(ast,{enter:this._enter.bind(this),leave:this._leave.bind(this)})}catch(e){let stk=e.stack;let x=stk.indexOf('\n');stk=x>=0?stk.substring(x+1):stk;stk=`${'-'.repeat(10)}\n${stk}\n${'-'.repeat(10)}`;this._msgCtx.jafMsg('jaf-ts-walk',`TS walk exception: ${e.message} File: ${this._file}\n\n${stk}`)}return{funcs:this._fStack,blocks:this._bStack}}_buildFuncIndexesToBlocks(){var i,j;for(i=0;i<this._fStack.length;i++){for(j=0;j<this._bStack.length;j++){if(this._bStack[j].func==i){this._fStack[i].blocks.push(j)}}}}getAccessor(){return new _scope(this._fStack,this._bStack)}_enter(node){var type;if(this._msgCtx.isDebug){_trace('E',node)}type=node.type;if(this._isNewScope(node)){this._addNewFunc(node)}else if(type==='VariableDeclarator'||type==='ClassProperty'){this._varDecl(node)}else if(type==='VariableDeclaration'){this._varKind=node.kind}else if(type==='BlockStatement'){this._addNewBlock(node)}else if(type==='ClassDeclaration'){this._inClass=true;this._className=node.id.name}else if(type==='ImportDeclaration'){this._addImport(node)}}_leave(node){if(this._msgCtx.isDebug){_trace('L',node)}if(this._isNewScope(node)){if(this._parents.length){this._parents.pop()}this._funcStack.pop()}else if(node.type==='BlockStatement'){if(this._blkParents.length){this._blkParents.pop()}this._blockStack.pop()}else if(node.type==='ClassDeclaration'){this._inClass=false;this._className=null}}_addNewFunc(node){var type,func,curParent,x;type=node.type;if(type===PROGRAM){func=GLOBAL_SCOPE}else if(node.kind==='method'||node.kind==='constructor'){func=node.key.name}else if(node.id){func=node.id.name}else if(type==='ClassBody'){func=this._className}else{this._getNextAnon()}if(this._parents.length){curParent=this._fStack[this._parents[this._parents.length-1]]}x=this._fStack.push({func:func,node:node,vars:{},args:{},blocks:[],children:[],parent:this._parents.length?this._parents[this._parents.length-1]:-1});x--;this._parents.push(x);if(curParent){curParent.children.push(x)}this._funcStack.push(x);this._addFuncArgs(node)}_addNewBlock(node){var func,curParent,x;var func=this._fStack[this._getCurFunc()];let n=this._fStack[this._getCurFunc()].node;if((n.kind==='method'||n.kind==='constructor')&&this._isMethodRange(n,node)||n.kind!=='method'&&n.kind!=='constructor'&&node.range===n.body.range){return}if(this._blkParents.length){curParent=this._bStack[this._blkParents[this._blkParents.length-1]]}x=this._bStack.push({func:this._getCurFunc(),node:node,lets:{},children:[],parent:this._blkParents.length?this._blkParents[this._blkParents.length-1]:-1});x--;this._blkParents.push(x);if(curParent){curParent.children.push(x)}this._blockStack.push(x);func.blocks.push(x)}_addImport(node){var src,local,o;src=node.source.value;if(!src.startsWith('ojs/')){return}o={src:src};if(node.specifiers.length){node.specifiers.forEach(s=>{if(!local)local=[];local.push(s.local.name)});if(local){o.local=local}}this._imports.push(o)}_getCurFunc(){return this._funcStack[this._funcStack.length-1]}_getCurBlock(){return this._blockStack[this._blockStack.length-1]}_addFuncArgs(node){var vt,curScope;if(node.params){curScope=this._fStack[this._getCurFunc()];node.params.forEach(function(n){if(n.type==='Identifier'){vt=this._getVarType(n);curScope.args[n.name]={type:vt}}else{if(n.type==='AssignmentPattern'){if(n.left&&n.left.name){curScope.args[n.left.name]={type:'???'}}else{console.log('scopes nt = n.type')}}}},this)}}_isNewScope(node){var type=node.type;return type==='FunctionDeclaration'||type==='MethodDefinition'||type==='FunctionExpression'&&!this._inClass||type==='ClassBody'||type==='Program'}_varDecl(node){var curScope,vt,name;function _declVar(vt,self){curScope=self._fStack[self._getCurFunc()];if(node.id){name=node.id.name}else{name=node.key.name}curScope.vars[name]={type:vt,node:node}};vt=this._getVarType(node);if(this._varKind==='let'||this._varKind==='const'){if(this._blockStack.length===0){this._varKind='var'}}if(this._varKind==='var'||node.type==='ClassProperty'){_declVar(vt,this)}else if(this._varKind==='let'||this._varKind==='const'){let b=this._getCurBlock();if(b>=0){let block=this._bStack[b];let br=block.node.range;let start=node.range;if(start[0]>=br[0]&&start[1]<=br[1]){block.lets[node.id.name]={type:vt,node:node}}}else{_declVar(vt,this)}}}_getVarType(node){var vt,ta,et,ty;if(node.type==='ClassProperty'){if(node.value){if(node.value.type==='ArrowFunctionExpression'){return'function'}else if(node.value.type==='CallExpression'){if(node.value.callee.object.name==='ko'){if(node.value.callee.property.name==='observable'){return'KO_Observable'}else if(node.value.callee.property.name==='computed'){return'KO_computed'}else{return'KO_Unknown'}}}}}ta=node.id&&node.id.typeAnnotation?node.id.typeAnnotation:node.typeAnnotation;if(!ta){ty=node.init?this._getInitType(node.init):ANY}else{vt=ta.typeAnnotation.type;if(vt===TS_TYPEREF){if(ta.typeAnnotation.typeName.name){ty=ta.typeAnnotation.typeName.name}else{if(ta.typeAnnotation.typeName.left){if(ta.typeAnnotation.typeName.left.name){ty=ta.typeAnnotation.typeName.left.name;if(ta.typeAnnotation.typeName.right&&ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}else if(ta.typeAnnotation.typeName.left.left.name){ty+='.'+ta.typeAnnotation.typeName.left.left.name;if(ta.typeAnnotation.typeName.left.right.name){ty+='.'+ta.typeAnnotation.typeName.left.right.name}if(ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}}}}else if(vt===TS_ARRAY){et=ta.typeAnnotation.elementType.type;if(et===TS_TYPEREF){ty=ta.typeAnnotation.elementType.typeName.name+'[]'}else{ty=et+'[]'}}else{ty=vt}}if(ty){ty=_transformType(ty)}if(!ty){console.log('[ASSERT]: scopes: ty not defined')}return ty}_getInitType(init){var vt,raw;if(init.type==='Literal'&&init.raw){raw=init.raw;if(raw.charAt(0)==='"'||raw.charAt(0)==='\''){vt=STRING}else if(raw==='true'||raw==='false'){vt=BOOLEAN}else if(!isNaN(raw)){vt=NUMBER}else if(raw==='null'){vt=NULL}else{console.log('[ASSERT]: SCOPES - UNKNOWN VAR INIT LITERAL = '+raw);vt=UNKNOWN}}else if(init.type==='ObjectExpression'){vt=OBJECT}else if(init.type==='NewExpression'){if(init.callee&&init.callee.name){vt=init.callee.name}}else if(init.type==='CallExpression'){if(init.callee&&init.callee.object){let o=init.callee.object;if(o.type==='Identifier'&&o.name==='document'){o=init.callee.property;if(o=DOCUMENT_METHODS[o.name]){return o}else{return'unknown document function'}}if(o.type==='MemberExpression'){vt=this._unravelCallME(o)}if(init.callee&&init.callee.object&&init.callee.object.type==='FunctionExpression'){vt='function'}}}else if(init.type==='MemberExpression'){if(init.object.type==='TSAsExpression'){vt=UNKNOWN}}else if(init.type==='TSAsExpression'){if(init.typeAnnotation&&init.typeAnnotation.type==='TSTypeReference'){vt=init.typeAnnotation.typeName.name}else{vt=UNKNOWN}}else if(init.type==='TSTypeAssertion'){if(init.typeAnnotation){vt=init.typeAnnotation.type}}else if(init.type==='AwaitExpression'){vt=ANY}else{vt=init.type}if(!vt){vt=UNKNOWN}return vt}_isMethodRange(n,node){return n.value&&n.value.body&&n.value.body.range===node.range}_unravelCallME(o){var prop;if(o.object.type==='ThisExpression'){prop=o.property.name;return this._getClassPropType(o,prop)}}_getClassPropType(o,prop){var c,ret;c=this._getContainingClass(o);if(c&&c.vars){ret=c.vars[prop];if(ret){ret=ret.type}}return ret}_getContainingClass(node){var c=this._getCurFunc(node);if(c<0){return}do{c=this._fStack[c];if(c.node.type==='ClassBody'){break}c=c.parent}while(c>=0);return c}_dumpEnter(node){let funcName=node.id?node.id.name:'anon';console.log(`ENTER=${funcName} ${node.type}`)}_dumpLeave(node){let funcName=node.id?node.id.name:'anon';console.log(`LEAVE=${funcName} ${node.type}`)}dumpStacks(){this.dumpFuncStack();this.dumpBlockStack()}dumpFuncStack(){var st,v,o,s,i,title;console.log('\n-------- Function/Class Scope Map --------');st=this._fStack;for(i=0;i<st.length;i++){o=st[i];s=(o.children.length?'children='+_dumpArrayIndices(o.children):'')+' blocks='+_dumpArrayIndices(o.blocks);console.log(`\n[${i}] "${o.func}" ${_dumpStackType(o)} parent=${o.parent} ${s}`);title=false;if(_hasProps(o.args)){for(v in o.args){console.log((!title?' Args: ':' ')+v+': '+o.args[v].type);title=true}}else{console.log(' Args: none')}title=false;if(_hasProps(o.vars)){for(v in o.vars){console.log((!title?' Vars: ':' ')+v+': '+o.vars[v].type+' ('+(o.vars[v].node.type==='ClassProperty'?'class prop':'var')+')');title=true}}else{console.log(' Vars: none')}}}dumpBlockStack(){var st,v,o,ch,i,title;console.log('\n-------- Internal Block Scope Map --------');st=this._bStack;if(!st.length){console.log('\nNo blocks.');return''}for(i=0;i<st.length;i++){o=st[i];ch=o.children.length?'children='+_dumpArrayIndices(o.children):'';console.log(`\n[${i}] ${this._dumpBlkOwner(o)}="${this._fStack[o.func].func}" parent=${o.parent} ${ch}`);title=false;if(_hasProps(o.lets)){for(v in o.lets){console.log((!title?' Lets: ':' ')+v+': '+o.lets[v].type);title=true}}else{console.log(' Lets: none')}}}_dumpBlkOwner(o){var f=this._fStack[o.func];return f.node.type==='FunctionDeclaration'?'func':'meth'}_getNextAnon(){return ANON+ ++this._nextAnonId}};function _hasProps(obj){var ret=false;for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}return ret};function _dumpArrayIndices(a){var ret='[';a.forEach(function(v,i){ret+=(i?', ':'')+v});return ret+']'}function _dumpStackType(o){var s='';switch(o.node.type){case'ClassBody':s='class';break;case'MethodDefinition':s='method';break;case'FunctionDeclaration':s='func';break;}return s.length?'('+s+')':s};function _transformType(ty){const list={TSStringKeyword:'string',TSNumberKeyword:'number',TSBooleanKeyword:'boolean',TSNullKeyword:'null',TSObjectKeyword:'object',TSUnknownKeyword:'unknown',TSAnyKeyword:'any'};return list[ty]||ty};class _scope{constructor(fs,bs){this._fstk=fs;this._bstk=bs}getVarType(node){var name,func,block,v;if(!(name=node.name)){return null};block=this.getContainingBlock(node);if(block){v=block.lets[name];if(v){return v.type}while(block.parent>=0){block=this._bstk[block.parent];if(block){v=block.lets[name];if(v){return v.type}}}}func=this.getContainingFunc(node);do{if(func.vars&&func.vars[name]){v=func.vars[name].type}else if(func.args&&func.args[name]){v=func.args[name].type}if(v){break}if(func.parent>=0){func=this._fstk[func.parent]}else{func=null}}while(func);return v}getContainingFunc(node){var start,fnRange,fnIndex,func,fr,i;start=node.range[0];for(i=0;i<this._fstk.length;i++){func=this._fstk[i];fr=func.node.range;if(start>=fr[0]&&start<=fr[1]){if(fnRange){if(fr[0]>=fnRange[0]&&fr[1]<=fnRange[1]){fnRange=fr;fnIndex=i}}else{fnRange=fr;fnIndex=i}}}return typeof fnIndex==='number'?this._fstk[fnIndex]:null}getContainingBlock(node){var nrange,brange,range,bindex,blocks,block,i;if(!this._bstk.length)return;var blocks=this.getContainingFunc(node).blocks;nrange=node.range;for(i=0;i<blocks.length;i++){block=this._bstk[i];brange=block.node.range;if(nrange[0]>=brange[0]&&nrange[1]<=brange[1]){if(range){if(brange[0]>=range[0]&&brange[1]<=range[1]){range=nrange;bindex=i}}else{range=brange;bindex=i}}}return typeof bindex==='number'?this._bstk[bindex]:null}getContainingClass(node){}getGlobals(){return this._fstk[0]}getFuncStack(){return this._fstk}getBlockStack(){return this._bstk}};module.exports=Scope;
|
package/lib/Utils.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const daysOfWeek=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];const WHITESPACE=" \t\n\r\x0B";const NL="\n";const CR="\r";const DOT=".";function Utils(nd){this._nd=nd;this._tabHandler=null};Utils.prototype.isObject=function(value){return typeof value==="object"&&!Array.isArray(value)};Utils.prototype.isArrayContentsType=function(ar,type){var i,elemType,ret=true;var isAr=Array.isArray(type);for(i=0;i<ar.length;i++){elemType=this.getType(ar[i]);if(isAr&&!type.includes(elemType)||!isAr&&elemType!==type){ret=false;break}}return ret};Utils.prototype.extend=function(from,internal,to){var prop,what;to=to||{};for(prop in from){if(!internal&&(prop.startsWith("_")||prop==="$builtin")){continue}what=from[prop];if(Array.isArray(what)){to[prop]=what.slice()}else{to[prop]=what}}return to};Utils.prototype.hasAnyProps=function(obj){var ret=false;if(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}}return ret};Utils.prototype.isProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length};Utils.prototype.getProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length?obj:undefined};Utils.prototype.splitString=function(s,sep){var a=s.split(sep);a.forEach(function(val,index){a[index]=a[index].trim()});return a};Utils.prototype.getType=function(val){var t=typeof val;if(val===undefined){t="undefined"}else if(val===null){t="null"}else if(t==="object"){if(Array.isArray(val)){t="array"}else if(this.isObject(val)){t="object"}else{console.log("[ASSERT] unknown object type' "+t+"'");t="?"}}return t};Utils.prototype.format=function(msg,vars){var v,k,k2,i;for(v in vars){k="${"+v+"}";k2=new RegExp("\\$\\{"+v+"\\}","g");i=msg.indexOf(k);if(i>=0){msg=msg.replace(k2,vars[v])}}return msg};Utils.prototype.removeMarkup=function(m){var s;if(!m){return m}s=m.replace(/<[^>]+>/g,"");s=s.replace(/\s\s+/g," ");return s};Utils.prototype.getRowColFromIndex=function(data,disp,fileType,tabs){var row=1,col=1,i,c,len=data.length;var oTabs=tabs?tabs:this._tabHandler;for(i=0;i<len;i++){if(i===disp)break;c=data.charAt(i);if(c==="\n"){row++;col=1}else if(c==="\t"){if(oTabs){col=oTabs.getTabCol(col,fileType)}else{col++}}else if(c!=="\r"){col++}}return{row:row,col:col}};Utils.prototype.decommentJson=function(text){return this._nd.decomment(text)};Utils.prototype.parseJson=function(data,comments){var obj,ret;comments=typeof comments!=="undefined"?!!comments:true;if(comments){data=this._nd.decomment(data)}let x=this.eatWhitespace(data);if(x>=0){let c=data.charAt(x);if(c!=="{"&&c!=="["){return this._convertJsonPosToRowCol(
|
|
6
|
+
const daysOfWeek=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];const WHITESPACE=" \t\n\r\x0B";const NL="\n";const CR="\r";const DOT=".";const SP=" ";function Utils(nd){this._nd=nd;this._tabHandler=null};Utils.prototype.isObject=function(value){return typeof value==="object"&&!Array.isArray(value)};Utils.prototype.isArrayContentsType=function(ar,type){var i,elemType,ret=true;var isAr=Array.isArray(type);for(i=0;i<ar.length;i++){elemType=this.getType(ar[i]);if(isAr&&!type.includes(elemType)||!isAr&&elemType!==type){ret=false;break}}return ret};Utils.prototype.extend=function(from,internal,to){var prop,what;to=to||{};for(prop in from){if(!internal&&(prop.startsWith("_")||prop==="$builtin")){continue}what=from[prop];if(Array.isArray(what)){to[prop]=what.slice()}else{to[prop]=what}}return to};Utils.prototype.hasAnyProps=function(obj){var ret=false;if(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}}return ret};Utils.prototype.isProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length};Utils.prototype.getProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length?obj:undefined};Utils.prototype.splitString=function(s,sep){var a=s.split(sep);a.forEach(function(val,index){a[index]=a[index].trim()});return a};Utils.prototype.getType=function(val){var t=typeof val;if(val===undefined){t="undefined"}else if(val===null){t="null"}else if(t==="object"){if(Array.isArray(val)){t="array"}else if(this.isObject(val)){t="object"}else{console.log("[ASSERT] unknown object type' "+t+"'");t="?"}}return t};Utils.prototype.format=function(msg,vars){var v,k,k2,i;for(v in vars){k="${"+v+"}";k2=new RegExp("\\$\\{"+v+"\\}","g");i=msg.indexOf(k);if(i>=0){msg=msg.replace(k2,vars[v])}}return msg};Utils.prototype.removeMarkup=function(m){var s;if(!m){return m}s=m.replace(/<[^>]+>/g,"");s=s.replace(/\s\s+/g," ");return s};Utils.prototype.getRowColFromIndex=function(data,disp,fileType,tabs){var row=1,col=1,i,c,len=data.length;var oTabs=tabs?tabs:this._tabHandler;for(i=0;i<len;i++){if(i===disp)break;c=data.charAt(i);if(c==="\n"){row++;col=1}else if(c==="\t"){if(oTabs){col=oTabs.getTabCol(col,fileType)}else{col++}}else if(c!=="\r"){col++}}return{row:row,col:col}};Utils.prototype.decommentJson=function(text){return this._nd.decomment(text)};Utils.prototype.parseJson=function(data,comments){var obj,ret;comments=typeof comments!=="undefined"?!!comments:true;if(comments){data=this._nd.decomment(data)}let x=this.eatWhitespace(data);if(x>=0){let c=data.charAt(x);if(c!=="{"&&c!=="["){return this._convertJsonPosToRowCol(`Invalid JSON - unexpected start character '${c}' at position ${x}`,data)}}try{obj=JSON.parse(data);ret={obj:obj,msg:null,startIndex:undefined,endIndex:undefined}}catch(e){if(e.toString().startsWith("SyntaxError")){ret=this._convertJsonPosToRowCol(e.message,data)}else{ret.msg=e.message}ret.obj=null}return ret};Utils.prototype._convertJsonPosToRowCol=function(msg,data){var x,n,rc;x=msg.indexOf("position");if(x<0){if(msg.startsWith("Unexpected end of JSON")){msg+=` at position ${data.length-1}`;x=msg.indexOf("position")}else{n=data.length-1;return{msg:msg,line:0,row:0,startIndex:0,endIndex:0}}}n=parseInt(msg.substring(x+8).trim());rc=this.getRowColFromIndex(data,n);x=msg.indexOf("at");if(x>=0){msg=msg.substring(0,x).trimRight()}x=msg.indexOf("token");if(x>=0){x+=6;let c=msg.charAt(x);let q=c==="'"?"\"":"'";msg=msg.substring(0,x)+q+c+q+msg.substring(x+1)}return{msg:msg,line:rc.row,col:rc.col,startIndex:n,endIndex:n}};Utils.prototype.eatLine=function(str,index){var ret,i,c;index=index||0;if(index>str.length){ret=""}for(i=index;i<str.length;i++){c=str.charAt(i);if(c=="\n"){ret=str.substring(i+1);break}}return ret};Utils.prototype.getLineStart=function(data,index){var c;if(data.length&&index>0&&index<data.length){while(--index){c=data.charAt(index);if(c===NL||c===CR){return index+1}}}return 0};Utils.prototype.getIndexToWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(this.isWhitespace(str.charAt(i))){ret=i;break}}return ret};Utils.prototype.eatWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(WHITESPACE.indexOf(str[i])<0){ret=i;break}}return ret};Utils.prototype.isWhitespace=function(c){return WHITESPACE.indexOf(c)>=0};Utils.prototype.isAlpha=function(c){return c>="a"&&c<="z"||c>="A"&&c<="Z"};Utils.prototype.isDigit=function(c){return c>="0"&&c<="9"};Utils.prototype.isAlphaNum=function(c){return this.isAlpha(c)||this.isDigit(c)};Utils.prototype.getCurrentDate=function(dateObj){var date,dayOfweek,tmp;date=dateObj?dateObj:new Date;dayOfweek=daysOfWeek[date.getDay()];date=date.toString();tmp=date.split(" ");tmp[0]=dayOfweek;return dayOfweek+" "+tmp[1]+" "+tmp[2]+", "+tmp[3]};Utils.prototype.getCurrentTime=function(dateObj){var time,hours,mins,zone;var ampm="am";time=dateObj?dateObj:new Date;hours=time.getHours();mins=time.getMinutes();if(hours>12){hours-=12;ampm="pm"}zone=time.toLocaleTimeString("en-us",{timeZoneName:"short"}).split(" ")[2];return hours+":"+(mins<=9?"0":"")+mins+ampm+" "+zone};Utils.prototype.lineWrap=function(text,width=95,clean=true){if(Array.isArray(text)){let i;for(i=0;i<text.length;i++){let s=text[i];let c=s[s.length-1];if(c!==NL&&c!==SP){text[i]=s+SP}}text=text.join("")}if(clean){text=text.replace(/\<p\>/g,NL);text=text.replace(/\<br\>/g,NL);text=text.replace(/\<b\>/g,"");text=text.replace(/\<i\>/g,"");text=text.replace(/\<\/b\>/g,"");text=text.replace(/\<\/i\>/g,"");text=text.replace(/</g,"<");text=text.replace(/>/g,">")}return this.breakLines(text,width)};Utils.prototype.breakLines=function(s,width){var lines=[];var line,start,end,c,x,y;var len=s.length;s=s.trimRight();len=s.length;if(len<width||len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}if(len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}start=0;while(start<len){x=this.eatWhitespace(s,start);if(x>0){start=x}end=start+width;line=s.substring(start,end+1);if(end>=len){if((x=line.indexOf(NL))>=0){lines.push(line.substring(0,x));start+=x+1;continue}lines.push(line);return lines}if(this.isWhitespace(line.charAt(line.length-1))){for(x=line.length-1;this.isWhitespace(s.charAt(x));x--){}x+=start}else{x=end;c=s.charAt(end+1);if(this.isAlphaNum(c)){for(;x>=start;x--){if(this.isWhitespace(s.charAt(x))){break}}}}x++;if(start<x){line=s.substring(start,x).trimRight()}else{line=s.substring(start,end).trimRight();x=end++}if((y=line.indexOf(NL))>=0){line=line.substring(0,y);x=start+y}lines.push(line);start=x}return lines};Utils.prototype.setTabHandler=function(oTabs){this._tabHandler=oTabs};module.exports=Utils;
|
package/lib/ZipUtils.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const TEMP_ZIP_TEMPLATE='@@ziptmp-XXXXXX.zip';
|
|
6
|
+
const TEMP_ZIP_TEMPLATE='@@ziptmp-XXXXXX.zip';var ZipUtils=function(nd,fsUtils){if(!this._unzipper){this._unzipper=require('adm-zip')}this._zip=null;this._nd=nd;this._fsUtils=fsUtils};ZipUtils.prototype.loadZip=function(zipPath){var ret;this._assertNoCurrentZip();this._zip=null;try{this._zip=new this._unzipper(zipPath);ret=true}catch(e){ret=e}return ret};ZipUtils.prototype.extractAll=function(to,zipPath,overwrite){var ret=false;try{this._assertNoCurrentZip();this._zip=null;this._zip=new this._unzipper(zipPath);if(this._zip){this._zip.extractAllTo(to,!!overwrite);ret=true}}catch(e){ret={message:e}}this._zip=null;return ret};ZipUtils.prototype.extractFileFromZip=function(filePath,zipPath){var text;try{if(zipPath){this._assertNoCurrentZip();this._zip=null;this._zip=new this._unzipper(zipPath)}if(this._zip){text=this._zip.readAsText(filePath);text=text?text.trim():''}}catch(e){text=e}return text};ZipUtils.prototype.getContents=function(zipPath){var entries,ret=[];if(typeof zipPath==='string'){try{this._assertNoCurrentZip();this._zip=null;this._zip=new this._unzipper(zipPath)}catch(e){ret=e}}if(this._zip){ret=[];entries=this._zip.getEntries();this._hierIndex=0;this._createHierarchy(entries,'',ret)}return ret};ZipUtils.prototype._createHierarchy=function(entries,subdir,ar){var entry,arDir,temp,x;for(;this._hierIndex<entries.length;this._hierIndex++){entry=entries[this._hierIndex];if(entry.isDirectory){if(entry.entryName.startsWith(subdir)||!subdir){arDir=[];temp=entry.entryName.substr(0,entry.entryName.length-1);x=temp.lastIndexOf('/');temp=x>=0?temp.substring(x+1):temp;ar.push({name:temp,path:entry.entryName,isFile:false,files:arDir});this._hierIndex++;this._createHierarchy(entries,entry.entryName,arDir)}else{this._hierIndex--;return}}else{if(entry.entryName.startsWith(subdir)||!subdir){ar.push({name:entry.name,isFile:true})}else{this._hierIndex--;return}}}};ZipUtils.prototype.writeBufferToFile=function(buffer,fpath){var ret;try{this._lastFile=fpath;this._nd.fs.writeFileSync(fpath,buffer);ret=true}catch(e){this._lastFile=null;ret=e}return ret};ZipUtils.prototype.deleteFile=function(fpath){var ret=null;try{fpath=fpath?fpath:this._lastFile;if(fpath){this._nd.fs.unlinkSync(fpath)}}catch(e){ret=e}this._zip=null;return ret};ZipUtils.prototype.getLastFilepath=function(){return this._lastFile};ZipUtils.prototype.createTempZipFilename=function(){return this._fsUtils.getUniqueFileName(TEMP_ZIP_TEMPLATE)};ZipUtils.prototype._assertNoCurrentZip=function(){if(this._zip){this._assert('loadZip but Zip EXISTS')}};module.exports=ZipUtils;
|
package/lib/amdlist.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2022, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const AVAIL_TITLE="---- Available in AMD mode ----";const UNAVAIL_TITLE="---- Unavailable in AMD mode ----";function show(nd,arg,appCtx){var packs;if(packs=nd.builtinpacks.getPackMetadata(nd,appCtx)){let prefixes=nd.builtinpacks.getPrefixes();arg=arg?arg.toLowerCase():arg;for(let pack of prefixes){if(!arg||arg===pack)_display(packs[pack],appCtx.colors)}}};function _display(pack,clr){var rules,rule,opts;let sorted=[],avail=[],unavail=[],max=0;console.log(`\n\n${clr.BRIGHTRED("\u25CF")} ${clr.CYAN("Pack")} ${clr.BRIGHTRED(`${pack.prefix}`)} ${clr.CYAN(" - Rules Available/Unavailable in AMD mode by default")}\n`);rules=pack.rules;_getSortedRulesByName(rules,sorted);for(rule of sorted){let ar;opts=rules[rule];ar=opts.hasOwnProperty("amd")&&!opts.amd?unavail:avail;ar.push(rule);ar.push(opts.hasOwnProperty("inservice")?opts.inservice:true);ar.push(opts.hasOwnProperty("enabled")?opts.enabled:true);max=rule.length>max?rule.length:max}console.log(clr.BRIGHTYELLOW(`● Available in AMD mode - ${avail.length/3}`));console.log(clr.BRIGHTYELLOW(`● Unavailable in AMD mode - ${unavail.length/3}\n`));if(!avail.length){return}_displayRules(unavail,false,max,clr);_displayRules(avail,true,max,clr);console.log("")};function _displayRules(list,avail,max,clr){if(!list.length){return}let rule,inserv,enabled,inserv_s,enabled_s,i;console.log(" "+clr.BRIGHTCYAN(avail?AVAIL_TITLE:UNAVAIL_TITLE));for(i=0;i<list.length;i++){rule=list[i++];inserv=list[i++];enabled=list[i];inserv_s=inserv?clr.BRIGHTGREEN(`${inserv}`):clr.RED(`${inserv}`);enabled_s=enabled?clr.BRIGHTGREEN(`${enabled}`):clr.RED(`${enabled}`);console.log(clr.BRIGHTYELLOW(`● ${rule}`)+_spacer(rule,max)+" "+clr.BRIGHTCYAN("In service:")+" "+inserv_s+" "+(inserv?" ":"")+clr.BRIGHTCYAN("Enabled:")+enabled_s)}};function _getSortedRulesByName(rules,sorted){var rule;for(rule in rules){sorted.push(rule)}sorted.sort()};function _spacer(s,max){return" ".repeat(max-s.length+2)};module.exports.show=show;
|
package/lib/api.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const OUTFMT=require("./outFormat");const UNDEF="undefined";
|
|
6
|
+
const OUTFMT=require("./outFormat");const UNDEF="undefined";function Api(nodeDeps,JafCore){this._core=JafCore;this._stats=JafCore.getStats();this._nd=nodeDeps};Api.prototype.startSync=function(apiContext){var core=this._core;core._ctxCB=apiContext;if(apiContext.config){let t=typeof apiContext.config;if(t==="string"){core._configPath=this._nd.path.join(core._curDir,apiContext.config)}else if(t==="object"){core._configPath=apiContext.config}else{core._error("Invalid config argument in init() : type is "+t);return 1}}if(apiContext.format&&apiContext.format!==OUTFMT.PROSE){apiContext.format=OUTFMT.PROSE}return core.start()};Api.prototype.start=function(apiContext,AmdMeta,AmdRulePacks){var t,_self,rc;this._core._isAsync=true;this._core._ctxCB=apiContext;_self=this;return new Promise(function(resolve,reject){let core=_self._core;setTimeout(()=>{try{if(apiContext.config){t=typeof apiContext.config;if(t==="string"){core._configPath=_self._nd.path.join(core._curDir,apiContext.config)}else if(t==="object"){core._configPath=apiContext.config}else{core._error("Invalid config argument in init() : type is "+t);reject(1)}}if(!core._isAMD){core._isAsync=false;core._isAsyncTemp=true;rc=_self.startSync(apiContext);core._isAsync=true;rc===0?resolve(rc):reject(core._messageStack)}else{if(apiContext.format&&apiContext.format!==OUTFMT.PROSE){apiContext.format=OUTFMT.PROSE}core._isAsync=false;core._isAsyncTemp=true;core._AmdMeta=AmdMeta;core._AmdRulePacks=AmdRulePacks;if(AmdRulePacks&&!Array.isArray(AmdRulePacks)){core._error("init() : AMD rule packs must be specified as an array!");reject(1);return}rc=_self.startSync(apiContext);core._isAsync=true;rc===0?resolve(rc):reject(core._messageStack)}}catch(e){reject(core._messageStack)}},0)})};Api.prototype.auditSync=function(filespec){var core=this._core;core._isAsync=false;this._stats.clearAll();if(core._regListenerTypesSet||core._rules&&core._rules.getActiveRuleCount()===0){if(core._rules){core._emitApiRunSummary()}return}if(filespec){if(!Array.isArray(filespec)){filespec=[filespec]}core._fileSet.setFiles(filespec,core._config.getExclude(),core._getMsgCtx())}core._startLifeCycle();core._emitApiRunSummary()};Api.prototype.audit=function(filespec){var rc,_self,core=this._core;core._isAsync=true;this._stats.clearAll();if(filespec){if(!Array.isArray(filespec)){filespec=[filespec]}core._fileSet.setFiles(filespec,core._config.getExclude(),core._getMsgCtx())}_self=this;return new Promise((resolve,reject)=>{setTimeout(()=>{try{_self._core._isAsync=false;rc=_self._core._startLifeCycle();_self._core._isAsync=true;_self._core._emitApiRunSummary();rc?resolve(0):reject(1)}catch(e){let m=`[JAF-9010] Internal Error:\n${_shortStackMsg(e)}`;core._error(m);reject(m)}},0)})};Api.prototype.on=function(evName,fn,obj){if(this._core._listenerSetup()){this._core._events.setListener(evName,fn,obj)}};Api.prototype.removeListener=function(evName,fn){if(this._core._listenerSetup()){this._core._events.removeListener(evName,fn)}};Api.prototype.removeAllListeners=function(evName){if(this._core._listenerSetup()){this._core._events.removeAllListeners(evName)}};Api.prototype.getDescription=function(arg1,arg2,arg3){var issue,short,ruleName,sig=0,ret="";var core=this._core;var arg1Type=core._Utils.getType(arg1);var arg2Type=core._Utils.getType(arg2);if(arg1Type==="object"){issue=arg1;if(arg2==="boolean"||arg2Type===UNDEF){short=arg2;sig=1;ruleName=issue.rule;msgId=issue.msgId}}else if(arg1Type==="string"){if(arg2Type==="string"){msgId=arg1;ruleName=arg2;short=!!arg3;sig=2}}var loadedRule,rsi,msgId,fn;if(sig){rsi=core._ruleSets.getRsiFromMsgId(msgId);if(rsi<0){return""}loadedRule=core._ruleSets.getLoadedRule(rsi,ruleName);fn=short?loadedRule.getShortDescription.bind(loadedRule):loadedRule.getDescription.bind(loadedRule);ret=fn()}return ret};Api.prototype.getRulesetInfo=function(fmt,active){var ret,core=this._core;active=typeof active==="undefined"?true:active;if(fmt===OUTFMT.JSON)ret=core._rules.getRulesJson(active);else if(fmt===OUTFMT.PROSE||fmt===OUTFMT.LINE)ret=core._rules.getRulesProse(active);else ret=core._rules.getRulesSonar(active);return ret};Api.prototype.enableMsgId=function(msgid,state){var ret=false;var core=this._core;if(core._config.setMessages(msgid,state)){core._reporter.setMessageFilter(core._config._config.messages);ret=true}return ret};Api.prototype.getConfig=function(){return this._core._config.getConfig()};Api.prototype.getSevLib=function(){return this._core._severity.getSevLib()};Api.prototype.getInfo=function(){return this._core._getInfo()};Api.prototype.setMarker=function(mark){return this._core.setMarker(mark)};Api.prototype.getMarker=function(){return this._core.getMarker()};Api.prototype.setVsCodeExtHint=function(isVsCodeExt){this._core._VsCodeExtHint=isVsCodeExt};function _shortStackMsg(e){let x,x2=0,m=e.stack||e;if((x=m.indexOf("\n"))>0){if((x2=m.indexOf("\n",x+1))<0){x2=x}}if(x2){m=m.substring(0,x2)}return m};module.exports=Api;
|
package/lib/betalist.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2022, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const PRODUCTION="production";const OOS="Not in service";const DISABLED="disabled";function show(nd,arg,appCtx){var packs;if(packs=nd.builtinpacks.getPackMetadata(nd,appCtx)){let prefixes=nd.builtinpacks.getPrefixes();arg=arg?arg.toLowerCase():arg;for(let pack of prefixes){if(!arg||arg===pack)_display(packs[pack],appCtx.colors)}}};function _display(pack,clr){var rules,rule,opts;let sorted=[],list=[],max=0;console.log(`\n\n${clr.BRIGHTRED("\u25CF")} ${clr.CYAN("Pack")} ${clr.BRIGHTRED(`${pack.prefix}`)} ${clr.CYAN(" - Rules Not in Production Status")}\n`);rules=pack.rules;_getSortedRulesByName(rules,sorted);for(rule of sorted){opts=rules[rule];if(opts.status!==undefined&&opts.status!==PRODUCTION){list.push(rule);list.push(opts.status);max=rule.length>max?rule.length:max;list.push(opts.hasOwnProperty("inservice")?opts.inservice:true);list.push(opts.hasOwnProperty("enabled")?opts.enabled:true)}}_displayRules(list,max,clr);console.log("")};function _displayRules(list,max,clr){console.log(" "+clr.BRIGHTCYAN("--- Non-Production Rules : ")+clr.BRIGHTGREEN(""+list.length/4));for(let i=0;i<list.length;i++){let rule,status,insrvc,enabled,avail;rule=list[i++];status=list[i++];insrvc=list[i++];enabled=list[i];if(!(insrvc&&enabled)){avail=" ("+(!insrvc?clr.BRIGHTRED(OOS):"")+(!insrvc&&!enabled?", ":"")+(!enabled?DISABLED:"")+")"}else{avail=""}console.log(clr.BRIGHTYELLOW(`● ${rule}`)+_spacer(rule,max)+" "+clr.BRIGHTCYAN(status)+avail)}};function _getSortedRulesByName(rules,sorted){for(let rule in rules){sorted.push(rule)}sorted.sort()};function _spacer(s,max){return" ".repeat(max-s.length+2)};module.exports.show=show;
|
package/lib/builtinpacks.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const PREFIX=["jet","jaf","jetwc","jetwco","csp","wdt"];const RP_PREFIX=["csp","jetwc","jetwco","spoc","wdt"];const RULES_JSON="rules.json";var
|
|
6
|
+
const PREFIX=["jet","jaf","jetwc","jetwco","csp","wdt","spoc"];const RP_PREFIX=["csp","jetwc","jetwco","spoc","wdt"];const RULES_JSON="rules.json";var _rDir;var _rpDir;function getPackMetadata(nd,appCtx){var prefix,o,i;var _packs={};_init(nd,appCtx);for(i=0;i<PREFIX.length;i++){prefix=PREFIX[i];if(o=_loadRulesJson(RP_PREFIX.includes(prefix)?_rpDir:_rDir,prefix,nd,appCtx)){_packs[o.prefix]=o.rjson}else{_packs=null;break}}return _packs};function getPrefixes(){return PREFIX};function getRulepackFolderPrefixes(){return RP_PREFIX};function _loadRulesJson(dir,prefix,nd,appCtx){var rjson,fp;fp=nd.path.join(dir,prefix,RULES_JSON);if(appCtx.fsUtils.fileExists(fp)){rjson=nd.jsonLoader.load(fp,nd,m=>{appCtx.error(m)},true,appCtx.utils)}else{appCtx.error(`Internal error: rule manifest for ${prefix} not found`);return null}if(rjson){return{prefix:prefix,rjson:rjson}}};function _init(nd){_rDir=nd.path.join(__dirname,"../rules");_rpDir=nd.path.join(__dirname,"../rulepacks")};module.exports={getPackMetadata,getPrefixes,getRulepackFolderPrefixes};
|
package/lib/checkage.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2022, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const BUILT="2022-07-12T01:49:42.958Z";function CheckAge(msgCtx){this._jetRels=-1;this._msgCtx=msgCtx}CheckAge.prototype.checkAge=function(){var ret=true;var monthsToRelease=0;var curDate=new Date;var buildDate=BUILT!=="@BUILT@"?new Date(BUILT):curDate;var buildMonth=buildDate.getMonth()+1;var months=_getElapsedMonths(buildDate,curDate);this._jetRels=_getReleases(buildMonth,months);if(months&&months<7){if(buildMonth<2){monthsToRelease=1}else{monthsToRelease=8-buildMonth}}if(months>monthsToRelease){this._emitMsg(months);ret=false}return ret};CheckAge.prototype.getJetReleaseCount=function(){return this._jetRels};CheckAge.prototype._emitMsg=function(old){var INDENT=" ".repeat(8);var s,h,p;if(this._jetRels){s=""+this._jetRels;if(this._jetRels===1){h="has";p=""}else{h="have";p="s"}}else{s="at least one";h="has";p=""}var s=`\nThis version of JAF is ${old} months old, and there ${h} been ${s} scheduled public\n`+`${INDENT}major JET release${p}, together with JAF updates and fixes. It is strongly\n`+INDENT+"recommended that you install the latest version of JAF. [JAF-9100]\n";this._msgCtx.warn(s,true)};function _getElapsedMonths(start,end){return end.getMonth()-start.getMonth()+12*(end.getFullYear()-start.getFullYear())};function _getReleases(buildMonth,months){var toNextRel,releases=0;if(buildMonth===1){toNextRel=0}else if(buildMonth>1&&buildMonth<7){toNextRel=7-buildMonth}else if(buildMonth===7){toNextRel=0}else{toNextRel=13-buildMonth}if((releases=months-toNextRel)>=0){releases=1+Math.floor(releases/6)}else{releases=0}return releases};module.exports=CheckAge;
|
package/lib/cliStats.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const Histo=require("./Histo");
|
|
6
|
+
const Histo=require("./Histo");class cliStats{constructor(nd,stats,severity,oConsole,info,isUnitTest,appCtx,useStdErr){this._nd=nd;this._severity=severity;this._clr=appCtx.colors;this._isColor=this._clr.isColor();this._console=oConsole;this._info=info;this._isUnitTest=isUnitTest;this._useStdErr=useStdErr;this._stats=stats}displayStatsAndHisto(elapsed){var clr=this._clr;var msg,msg2,sevs,n,m,l;var stats=this._stats;n=stats.errorFiles||stats.parseErrors;m=stats.totalIssues;msg="JET Audit: "+m+" issue"+(m!==1?"s":"")+(m!==1?" were":" was")+" found"+(m?" in "+stats.totalIssueFiles+" file"+(stats.totalIssueFiles!==1?"s":""):"")+".";msg="\n"+(m?clr.BLACKONRED(msg):clr.GREEN(msg));if(n){n=stats.errorFiles;m=stats.parseErrors;msg2=(n?" "+n+" file"+(n!==1?"s":"")+" could not be read.":"")+(m?" "+m+" parse error"+(m!==1?"s":"")+" "+(m===1?"was":"were")+" found.":"");msg+=clr.BLACKONRED(msg2)}this._console(msg);if(this._useStdErr){process.stderr.write(msg+"\n")}n=stats.totalFilesSelected;msg=_right(n,6)+" file"+(n===1?" ":"s ")+(n===1?"was":"were")+" selected.";n=stats.totalFilesAudited;msg+="\n"+_right(n,6)+" file"+(n===1?" ":"s ")+(n===1?"was":"were")+" audited.";n=stats.totalUrlsAudited;msg+="\n"+_right(n,6)+" URL"+(n===1?" ":"s ")+(n===1?"was":"were")+" audited.";n=stats.rulesFired;msg+="\n"+_right(n,6)+" rule"+(n===1?" ":"s ")+(n===1?"was":"were")+" fired.";n=stats.hooksFired;msg+="\n"+_right(n,6)+" hook rule"+(n===1?" ":"s ")+(n===1?"was":"were")+" fired.";sevs=this._severity.getMappedArray()||this._severity.getSevList();sevs=sevs.filter((val,x)=>sevs.indexOf(val)===x);l=0;sevs.forEach(v=>{n=v.length;l=n>l?n:l});l+=2;let sev,sevTotals;sevTotals=this._getSevTotals(stats.totalSevStats);var histo=new Histo(sevTotals,40,clr);msg+="\n\n"+"-".repeat(10)+"Severities"+"-".repeat(10);for(sev in sevTotals){n=sevTotals[sev];msg+="\n"+_left(sev,l)+": "+_right(n,6)+" |"+histo.bar(n)}msg+="\n"+"-".repeat(30);if(elapsed){msg+="\n[Elapsed: "+elapsed[0]+(elapsed[1]/1000000000).toString().substr(1,3)+"s]"}this._console(msg)}displayErrorsAndAsserts(){var clr=this._clr;var stats=this._stats;var msg="";if(stats.errors){msg+="[Error]: "+stats.errors+" error";msg+=(stats.errors===1?" was":"s were")+" found."}if(stats.warnings){if(msg.length){msg+="\n"}msg+="[Warn]: "+stats.warnings+" warning";msg+=(stats.warnings===1?" was":"s were")+" found."}if(stats.asserts){if(msg.length){msg+="\n"}msg+="[Warn]: "+stats.asserts+" assert";msg+=(stats.asserts===1?" was":"s were")+" found."}msg+="\n";if(!this._isUnitTest){this._info("\n"+clr.BLACKONRED(msg))}else{this._nd.fs.writeSync(process.stdout.fd,"\n"+clr.BLACKONRED(msg))}if(this._useStderr){process.stderr.write(msg+"\n")}}_getSevTotals(totalSevStats){var sevMap,sevTotals,sev,val,n=0;var sevTotals={};if(sevMap=this._severity.getInvertedSevMap()){for(sev in sevMap){val=sevMap[sev];if(!Array.isArray(val)){n+=totalSevStats[val]}else{val.forEach(v=>{n+=totalSevStats[v]})}sevTotals[sev]=n;n=0}}else{sevTotals=totalSevStats}return sevTotals}};function _right(num,len){var s=""+num;return len>s.length?" ".repeat(len-s.length)+s:s};function _left(num,len){var s=""+num;return len>s.length?s+" ".repeat(len-s.length):s};module.exports=cliStats;
|
package/lib/cmdline.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const OUTFMT=require("../lib/outFormat");const MACROS=require("../lib/macros");const ARG_CONFIG="--config";const ARG_CONFIG_SHORT="-c";const ARG_BASE="--base";const ARG_BASE_SHORT="-b";const ARG_SEVERITY="--severity";const ARG_SEVERITY_SHORT="-s";const ARG_FORMAT="--format";const ARG_FORMAT_SHORT="-t";const ARG_FOLLOWLINKS="--followlinks";const ARG_FOLLOWLINKS_SHORT="-fl";const ARG_NOFOLLOWLINKS="--nofollowlinks";const ARG_NOFOLLOWLINKS_SHORT="-nfl";const ARG_SHOWRULES="--rules";const ARG_SHOWRULES_SHORT="-r";const ARG_SHOWRULESJSON="--rulesjson";const ARG_SHOWRULESJSON_SHORT="-rj";const ARG_SHOWRULESSONAR="--rulessonar";const ARG_SHOWRULESSONAR_SHORT="-rs";const ARG_SHOWRULES_INTERNAL="-rx";const ARG_OUTPATH="--outpath";const ARG_OUTPATH_SHORT="-o";const ARG_NO_OUT="--noout";const ARG_NO_OUT_SHORT="-no";const ARG_NOCOLOR="--nocolor";const ARG_NOCOLOR_SHORT="-nc";const ARG_GROUPS="--groups";const ARG_GROUPS_SHORT="-g";const ARG_GROUPS_EQ="--groups=";const ARG_GROUPS_EQ_SHORT="-g=";const ARG_MSGID="--msgid";const ARG_MSGID_SHORT="-id";const ARG_WATCH="--watch";const ARG_WATCH_SHORT="-w";const ARG_VERSION="--version";const ARG_VERSION_SHORT="-v";const ARG_JETLIST="--jetlist";const ARG_JETLIST_SHORT="-jl";const ARG_DEFLIST="--default";const ARG_DEFLIST_ALT="--deflist";const ARG_DEFLIST_SHORT="-def";const ARG_GROUPLIST="--grouplist";const ARG_GROUPLIST_SHORT="-gl";const ARG_XGROUPLIST="--xgrouplist";const ARG_XGROUPLIST_SHORT="-xgl";const ARG_DISLIST="--dislist";const ARG_DISLIST_SHORT="-dl";const ARG_JETVER="--jetver";const ARG_JETVER_SHORT="-jv";const ARG_NAMESPACE_LIST="--nslist";const ARG_NAMESPACE_LIST_SHORT="-nsl";const ARG_METAHIST="--metahist";const ARG_METAHIST_SHORT="-mh";const ARG_RC="--retcode";const ARG_RC_EQ="--retcode=";const ARG_RC_SHORT="-rc";const ARG_RC_EQ_SHORT="-rc=";const ARG_DRYRUN="--dryrun";const ARG_DRYRUN_SHORT="-dr";const ARG_DAC="--daconfig";const ARG_DAC_SHORT="-dac";const ARG_REG="--reg";const ARG_REG_SHORT="-reg";const ARG_HELP="--help";const ARG_HELP_SHORT="-h";const ARG_HELP_SHORT_S="-hs";const ARG_EXTRA="--extra";const ARG_EXTRA_SHORT="-e";const ARG_DEBUG="--debug";const ARG_DEBUG_SHORT="-d";const ARG_SCAFFOLD="--init";const ARG_SCAFFOLD_SHORT="-i";const ARG_SCAFFOLD_RULE="--initrule";const ARG_SCAFFOLD_RULE_SHORT="-ir";const ARG_UNIT_TEST="-ut";const ARG_OJET="--ojet";const ARG_OJET_SHORT="-ojet";const ARG_EXPERIMENTAL="--x";const ARG_EXPERIMENTAL_SHORT="-x";module.exports.checkArgs=function(nodeDeps,rtf,showHelp,showVersion,msgCtx){var argLen,argOrig,arg,dontRun,temp,x,bArgsOk=true,bWantHelp=false,debugTitle;rtf.jetauditdir=nodeDeps.process.argv[1];rtf.jetauditdir=nodeDeps.path.dirname(rtf.jetauditdir);_checkBaseOptions(rtf,nodeDeps);if(rtf.debugSet){_dumpCmdLine()}argLen=process.argv.length;for(var i=2;i<argLen;i++){argOrig=process.argv[i];arg=argOrig.toLowerCase().trim();if(arg.length===0){continue}if(arg.charAt(0)!=="-"){if(!rtf.srcStack){rtf.srcStack=[]}arg=process.argv[i];arg=_handleQuotes(arg);arg=nodeDeps.path.normalize(arg);arg=nodeDeps.path.resolve(arg);rtf.srcStack.push(arg);if(rtf.debugMode||rtf.verboseMode){if(!debugTitle){msgCtx.info("Command line files specified:");debugTitle=true}msgCtx.info(" "+arg)}continue}if(_isBaseOption(arg)){continue}else if(arg===ARG_MSGID||arg===ARG_MSGID_SHORT){rtf.msgIdMode=rtf.msgIdModeSet=true}else if(arg===ARG_VERSION||arg===ARG_VERSION_SHORT){showVersion();dontRun=true}else if(arg===ARG_HELP||arg===ARG_HELP_SHORT||arg===ARG_HELP_SHORT_S){if(i+1<argLen){temp=process.argv[i+1];if(temp.charAt(0)==="-"){showHelp();dontRun=true;if(!_isBaseOption(temp))msgCtx.error(`Unexpected '${temp}'`);break}i++;if(arg===ARG_HELP||arg===ARG_HELP_SHORT){rtf.manCheckL=temp}else{rtf.manCheckS=temp}rtf.isManual=true;if(rtf.st_configSet){break}}else{showHelp();dontRun=true;break}}else if(arg===ARG_JETLIST||arg===ARG_JETLIST_SHORT){rtf.jetverList=true;break}else if(arg.startsWith(ARG_DEFLIST)||arg.startsWith(ARG_DEFLIST_SHORT)||arg.startsWith(ARG_DEFLIST_ALT)){rtf.defList=true;break}else if(arg===ARG_NAMESPACE_LIST||arg===ARG_NAMESPACE_LIST_SHORT){rtf.cmdNSList=true;break}else if(arg===ARG_DISLIST||arg===ARG_DISLIST_SHORT){rtf.disList=true;rtf.cmdArg=checkPackArg(i,argLen,msgCtx.error);break}else if(arg===ARG_GROUPLIST||arg===ARG_GROUPLIST_SHORT){rtf.groupList=true;rtf.cmdArg=checkPackArg(i,argLen,msgCtx.error);break}else if(arg===ARG_XGROUPLIST||arg===ARG_XGROUPLIST_SHORT){rtf.xgroupList=true;rtf.cmdArg=checkPackArg(i,argLen,msgCtx.error)}else if(arg===ARG_METAHIST||arg===ARG_METAHIST_SHORT){rtf.cmdMetaHist=true;break}else if(arg===ARG_CONFIG||arg===ARG_CONFIG_SHORT){i++;if(i<argLen){arg=process.argv[i];rtf.configPath=nodeDeps.path.normalize(arg);rtf.configPath=nodeDeps.path.resolve(rtf.configPath);rtf.st_configSet=true;if(rtf.isManual||rtf.xgroupList){break}}else{msgCtx.error("Invalid --config option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_BASE||arg===ARG_BASE_SHORT){i++;if(i<argLen){rtf.base=process.argv[i];if(rtf.base===MACROS.cwd||nodeDeps.fsUtils.getFileType(rtf.base)==="d"){rtf.st_baseSet=true}else{msgCtx.error(`'--base' ${rtf.base} is not a directory or the '$jafcwd' macro!!`);bArgsOk=false;bWantHelp=true}}else{msgCtx.error("Invalid --base option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_SEVERITY||arg===ARG_SEVERITY_SHORT){i++;if(i<argLen){rtf.severitySet=true;rtf.cliSev=process.argv[i]}else{msgCtx.error("Invalid --severity option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_JETVER||arg===ARG_JETVER_SHORT){i++;argOrig=i<argLen?process.argv[i]:null;arg=nodeDeps.jetver.validate(argOrig);if(arg){msgCtx.error(arg);bArgsOk=false;break}arg=nodeDeps.jetver.getBestVersion(argOrig);if(!arg){msgCtx.error(`'${argOrig}' is not a valid JET version`);bArgsOk=false;break}rtf.jetverSet=arg;if((rtf.verboseMode||rtf.debugMode)&&arg!==argOrig){msgCtx._info(`[Info]: JET version '${argOrig}' was promoted to '${arg}'`)}}else if(arg===ARG_FORMAT||arg===ARG_FORMAT_SHORT){i++;if(i<argLen){argOrig=process.argv[i];arg=argOrig.toLowerCase();if(arg!==OUTFMT.JSON&&arg!==OUTFMT.PROSE&&arg!==OUTFMT.LINE){msgCtx.error(`Invalid --format(-t) option '${argOrig}'`);bArgsOk=false;bWantHelp=true}else{rtf.outFormat=arg;rtf.st_formatSet=true}}else{msgCtx.error("Invalid --format option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_OUTPATH||arg===ARG_OUTPATH_SHORT){i++;if(rtf.st_outPathSet){msgCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{if(i<argLen){arg=process.argv[i];arg=nodeDeps.path.normalize(arg);rtf.outPath=nodeDeps.path.resolve(arg);rtf.st_outPathSet=true}else{msgCtx.error("Invalid --outPath option");bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_NO_OUT||arg===ARG_NO_OUT_SHORT){if(rtf.st_outPathSet){msgCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{rtf.outPath="$noout";rtf.st_outPathSet=true}}else if(arg===ARG_FOLLOWLINKS||arg===ARG_FOLLOWLINKS_SHORT){rtf.followLinks=rtf.followLinksSet=true}else if(arg===ARG_NOFOLLOWLINKS||arg===ARG_NOFOLLOWLINKS_SHORT){rtf.followLinks=false;rtf.followLinksSet=true}else if(arg.startsWith(ARG_GROUPS_EQ)||arg.startsWith(ARG_GROUPS_EQ_SHORT)){x=arg.indexOf("=");if(temp=_convertToArray(argOrig.substring(x+1))){rtf.groupsSet=temp}else{msgCtx.error(`Invalid 'groups' declaration '${argOrig}`);bArgsOk=false;bWantHelp=true}}else if(arg===ARG_GROUPS||arg===ARG_GROUPS_SHORT){rtf.groupsSet=_checkGroups(process.argv,i+1);if(!rtf.groupsSet.groups||rtf.groupsSet.groups.length===0){msgCtx.error(!rtf.groupsSet.groups?`groups missing after flag ${argOrig}`:`Invalid ${argOrig} specification`);bArgsOk=false;bWantHelp=true}i=rtf.groupsSet.next;rtf.groupsSet=rtf.groupsSet.groups}else if(arg.startsWith(ARG_RC_EQ)||arg.startsWith(ARG_RC_EQ_SHORT)||arg===ARG_RC||arg===ARG_RC_SHORT){arg=argOrig;x=arg.indexOf("=");if(x>0){temp=argOrig.substring(0,x);arg=argOrig.substring(x+1)}else{temp=arg;i++;if(i<argLen){arg=process.argv[i]}else{msgCtx.error(`missing arguments after '${argOrig}'`);bArgsOk=false;bWantHelp=true}}if(bArgsOk){temp=_processRetCode(temp,arg);if(temp||typeof temp==="number"){rtf.retCode=temp;rtf.st_retCodeSet=true}else{msgCtx.error(`'${argOrig}' : ${arg.length?"'${arg}' is invalid":"missing argument?"}`);bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_SHOWRULES||arg===ARG_SHOWRULES_SHORT){rtf.dumpRulesSet=true}else if(arg===ARG_SHOWRULESJSON||arg===ARG_SHOWRULESJSON_SHORT){rtf.dumpRulesJsonSet=true}else if(arg===ARG_SHOWRULESSONAR||arg===ARG_SHOWRULESSONAR_SHORT){rtf.dumpRulesSonarSet=true}else if(arg===ARG_SHOWRULES_INTERNAL){rtf.dumpRulesInternalSet=true}else if(arg===ARG_DRYRUN||arg===ARG_DRYRUN_SHORT){rtf.dryRunSet=rtf.dacSet=rtf.verboseMode=rtf.verboseSet=rtf.dumpRulesSet=true}else if(arg===ARG_DAC||arg===ARG_DAC_SHORT){rtf.dacSet=true}else if(arg===ARG_REG||arg===ARG_REG_SHORT){rtf.regListenerTypesSet=true}else if(arg===ARG_UNIT_TEST){rtf.unitTest=true}else if(arg===ARG_OJET||arg===ARG_OJET_SHORT){rtf.isOJETCLI=true}else if(arg===ARG_EXPERIMENTAL||arg===ARG_EXPERIMENTAL_SHORT){rtf.experimentalSet=true}else if(arg===ARG_WATCH||arg===ARG_WATCH_SHORT){if(rtf.experimentalSet){rtf.watchSet=true}}else if(arg===ARG_SCAFFOLD||arg===ARG_SCAFFOLD_SHORT){rtf.scaffoldSet=true}else if(arg===ARG_SCAFFOLD_RULE||arg===ARG_SCAFFOLD_RULE_SHORT){i++;if(i<argLen){rtf.scaffoldRuleSet=process.argv[i]}else{msgCtx.error("Invalid --initrule argument: rule name missing ");bArgsOk=false;bWantHelp=true}}else if(arg==="-z"){}else{msgCtx.error(`Invalid command flag '${argOrig}'`);bArgsOk=false;bWantHelp=true}}if(!dontRun&&bWantHelp){showHelp()}return dontRun?"end":bArgsOk};module.exports.displayCmdLineOptionsSet=function(rtf,msgCtx){var s="\n** Command line options:\n";if(rtf.dryRunSet){s+=" - Dry run ON\n"}if(rtf.dacSet){s+=" - Display active config ON\n"}if(rtf.verboseMode){s+=" - Verbose mode ON\n"}if(rtf.debugMode){s+=" - Debug mode ON\n"}if(rtf.watchSet){s+=" - watch mode ON\n"}if(rtf.groupsSet){s+=` - Groups set to ${rtf.groupsSet}\n`}if(rtf.st_retCodeSet){s+=` - retCode set to ${rtf.retCode}\n`}if(rtf.colorSet){s+=` - Color mode ${rtf.colorMode}? "ON" : "OFF"}\n`}if(rtf.msgIdModeSet){s+=` - Show msg ID's(${rtf.msgIdModeSet}? "ON" : "OFF"}\n`}if(rtf.st_formatSet){s+=` - Output in ${rtf.outFormat.toUpperCase()} format\n`}if(rtf.st_configSet){s+=` - Config set to ${rtf.configPath}\n`}if(rtf.severitySet){s+=` - Severity set to '${rtf.severity}'\n`}if(rtf.st_outPathSet){s+=` - Outpath set to ${rtf.outPath==="$noout"?"'none'":rtf.outPath}\n`}if(rtf.st_baseSet){s+=` - Base set to ${rtf.base}\n`}if(rtf.jetverSet){s+=` - JET version set to ${rtf.jetverSet}\n`}if(rtf.followLinksSet){s+=` - following stylesheet links is ${rtf.followLinks?"ON":"OFF"}\n`}if(rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumRulesSonarSet){s+=" - Dump Rules ON\n"}msgCtx.console(s+"\n")};module.exports.isCmdLineOptionsSet=function(rtf){return rtf.verboseMode||rtf.debugMode||rtf.colorSet||rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumpRulesSonarSet||rtf.dumpRulesInternalSet||rtf.msgIdModeSet||rtf.severitySet||rtf.watchSet||rtf.jetverSet||rtf.followLinksSet||rtf.dryRunSet||rtf.jetverList||rtf.cmdNSList||rtf.groupList||rtf.xgroupList||rtf.disList||rtf.cmdMetaHist||rtf.st_baseSet||rtf.st_formatSet||rtf.st_configSet||rtf.st_outPathSet||rtf.st_retCodeSet};function _checkBaseOptions(rtf,nd){var i,arg,argLen=process.argv.length;for(i=2;i<argLen;i++){arg=process.argv[i];if(arg.length===0||arg.charAt(0)!=="-"){continue}arg=arg.toLowerCase();if(arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT){rtf.verboseMode=rtf.verboseSet=true}else if(arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT){rtf.debugMode=rtf.debugSet=true}else if(arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT){rtf.colorMode=false;rtf.colorSet=true;nd.colors.enable(false)}}};function _isBaseOption(arg){return arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT||arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT||arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT};function _checkGroups(args,i){var arg,a,x,last,bound,groups;x=i;for(;;i++){if(i>=args.length||args[i].charAt(0)==="-"||last){break}arg=args[i].trim();if(x===i){bound=arg.startsWith("[")||arg.startsWith("(")}last=bound&&(arg.endsWith("]")||arg.endsWith(")"));arg=arg.replace(/[\[\(\)\]]/g,"").trim();if(!arg.length){break}arg=arg.replace(/,/g," ");arg=arg.replace(/ +(?= )/g,"").trim();if(!groups){groups=[]}a=arg.split(" ");groups=groups.concat(a)}return{next:bound?i:x,groups:groups}};function _processRetCode(arg,val){var temp,ret;if(val==="auto"||val==="errors"){ret=val}else{temp=parseInt(val);if(!isNaN(temp)){ret=temp}else{if(temp=_convertToArray(val)){ret=temp}}}return ret};function checkPackArg(i,argLen,error){var temp,lcTemp;if(i+1<argLen){temp=process.argv[i+1];lcTemp=temp.toLowerCase();if(temp.charAt(0)==="-"){if(!_isBaseOption(temp)&&lcTemp!==ARG_CONFIG&&lcTemp!==ARG_CONFIG_SHORT){error(`Unexpected '${temp}' - expected nothing, or a built-in pack prefix`)}temp=undefined}}return temp};function _convertToArray(s){var a,n,i;if(s.charAt(0)==="["){s=s.substring(1);if(!s.length){return null}}if(s.charAt(s.length-1)==="]"){s=s.substring(0,s.length-1)}s=s.trim();if(!s.length){return null}s=s.replace(/\,/g," ");s=s.replace(/\s\s+/g," ").trim();a=s.split(" ");n=0;for(i=0;i<a.length;i++){if(a[i].length){n++}else{a=a.splice(i,1);i--}}return n?a:null};function _handleQuotes(s){return s.replace(/[\"\']/g,"")};function _dumpCmdLine(){var s="";for(var i=0;i<process.argv.length;i++){s+=`[${i}]: |${process.argv[i]}|\n`}console.log(s)}
|
|
6
|
+
const OUTFMT=require("../lib/outFormat");const MACROS=require("../lib/macros");const ARG_CONFIG="--config";const ARG_CONFIG_SHORT="-c";const ARG_BASE="--base";const ARG_BASE_SHORT="-b";const ARG_SEVERITY="--severity";const ARG_SEVERITY_SHORT="-s";const ARG_FORMAT="--format";const ARG_FORMAT_SHORT="-t";const ARG_FOLLOWLINKS="--followlinks";const ARG_FOLLOWLINKS_SHORT="-fl";const ARG_NOFOLLOWLINKS="--nofollowlinks";const ARG_NOFOLLOWLINKS_SHORT="-nfl";const ARG_SHOWRULES="--rules";const ARG_SHOWRULES_SHORT="-r";const ARG_SHOWRULESJSON="--rulesjson";const ARG_SHOWRULESJSON_SHORT="-rj";const ARG_SHOWRULESSONAR="--rulessonar";const ARG_SHOWRULESSONAR_SHORT="-rs";const ARG_SHOWRULES_INTERNAL="-rx";const ARG_OUTPATH="--outpath";const ARG_OUTPATH_SHORT="-o";const ARG_NO_OUT="--noout";const ARG_NO_OUT_SHORT="-no";const ARG_NOCOLOR="--nocolor";const ARG_NOCOLOR_SHORT="-nc";const ARG_GROUPS="--groups";const ARG_GROUPS_SHORT="-g";const ARG_GROUPS_EQ="--groups=";const ARG_GROUPS_EQ_SHORT="-g=";const ARG_MSGID="--msgid";const ARG_MSGID_SHORT="-id";const ARG_WATCH="--watch";const ARG_WATCH_SHORT="-w";const ARG_VERSION="--version";const ARG_VERSION_SHORT="-v";const ARG_JETLIST="--jetlist";const ARG_JETLIST_SHORT="-jl";const ARG_DEFLIST="--default";const ARG_DEFLIST_ALT="--deflist";const ARG_DEFLIST_SHORT="-def";const ARG_GROUPLIST="--grouplist";const ARG_GROUPLIST_SHORT="-gl";const ARG_XGROUPLIST="--xgrouplist";const ARG_XGROUPLIST_SHORT="-xgl";const ARG_DISLIST="--dislist";const ARG_DISLIST_SHORT="-dl";const ARG_JETVER="--jetver";const ARG_JETVER_SHORT="-jv";const ARG_NAMESPACE_LIST="--nslist";const ARG_NAMESPACE_LIST_SHORT="-nsl";const ARG_PROFILES_LIST="--profiles";const ARG_PROFILES_LIST_SHORT="-prof";const ARG_AMDLIST="--amdlist";const ARG_AMDLIST_SHORT="-amd";const ARG_RLOLIST="--loadorder";const ARG_RLOLIST_SHORT="-rlo";const ARG_BETALIST="--betalist";const ARG_BETALIST_SHORT="-bl";const ARG_METAHIST="--metahist";const ARG_METAHIST_SHORT="-mh";const ARG_RC="--retcode";const ARG_RC_EQ="--retcode=";const ARG_RC_SHORT="-rc";const ARG_RC_EQ_SHORT="-rc=";const ARG_DRYRUN="--dryrun";const ARG_DRYRUN_SHORT="-dr";const ARG_DAC="--daconfig";const ARG_DAC_SHORT="-dac";const ARG_REG="--reg";const ARG_REG_SHORT="-reg";const ARG_HELP="--help";const ARG_HELP_SHORT="-h";const ARG_HELP_SHORT_S="-hs";const ARG_EXTRA="--extra";const ARG_EXTRA_SHORT="-e";const ARG_DEBUG="--debug";const ARG_DEBUG_SHORT="-d";const ARG_SCAFFOLD="--init";const ARG_SCAFFOLD_SHORT="-i";const ARG_SCAFFOLD_RULE="--initrule";const ARG_SCAFFOLD_RULE_SHORT="-ir";const ARG_UNIT_TEST="-ut";const ARG_OJET="--ojet";const ARG_OJET_SHORT="-ojet";const ARG_EXPERIMENTAL="--x";const ARG_EXPERIMENTAL_SHORT="-x";module.exports.checkArgs=function(nodeDeps,rtf,showHelp,showVersion,appCtx){var argLen,argOrig,arg,dontRun,temp,x,bArgsOk=true,bWantHelp=false,debugTitle;rtf.jetauditdir=nodeDeps.process.argv[1];rtf.jetauditdir=nodeDeps.path.dirname(rtf.jetauditdir);_checkBaseOptions(rtf,appCtx.colors);if(rtf.debugSet){_dumpCmdLine()}argLen=process.argv.length;for(var i=2;i<argLen;i++){argOrig=process.argv[i];arg=argOrig.toLowerCase().trim();if(arg.length===0){continue}if(arg.charAt(0)!=="-"){if(!rtf.srcStack){rtf.srcStack=[]}arg=process.argv[i];arg=_handleQuotes(arg);arg=nodeDeps.path.normalize(arg);arg=nodeDeps.path.resolve(arg);rtf.srcStack.push(arg);if(rtf.debugMode||rtf.verboseMode){if(!debugTitle){appCtx.info("Command line files specified:");debugTitle=true}appCtx.info(" "+arg)}continue}if(arg.endsWith("?")){temp=arg.replace(/[\-\?]/g,"");rtf.manCheckL=temp;rtf.isManual=true;rtf.isManPage=true;break}if(_isBaseOption(arg)){continue}else if(arg===ARG_MSGID||arg===ARG_MSGID_SHORT){rtf.msgIdMode=rtf.msgIdModeSet=true}else if(arg===ARG_VERSION||arg===ARG_VERSION_SHORT){showVersion();dontRun=true}else if(arg===ARG_HELP||arg===ARG_HELP_SHORT||arg===ARG_HELP_SHORT_S){if(i+1<argLen){temp=process.argv[i+1];if(temp.charAt(0)==="-"){showHelp();dontRun=true;if(!_isBaseOption(temp))appCtx.error(`Unexpected '${temp}'`);break}i++;if(arg===ARG_HELP||arg===ARG_HELP_SHORT){rtf.manCheckL=temp}else{rtf.manCheckS=temp}rtf.isManual=true;if(rtf.st_configSet){break}}else{showHelp();dontRun=true;break}}else if(arg===ARG_JETLIST||arg===ARG_JETLIST_SHORT){rtf.jetverList=true;break}else if(arg.startsWith(ARG_DEFLIST)||arg.startsWith(ARG_DEFLIST_SHORT)||arg.startsWith(ARG_DEFLIST_ALT)){rtf.defList=true;break}else if(arg===ARG_NAMESPACE_LIST||arg===ARG_NAMESPACE_LIST_SHORT){rtf.cmdNSList=true;break}else if(arg===ARG_PROFILES_LIST||arg===ARG_PROFILES_LIST_SHORT){rtf.profList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,false);break}else if(arg===ARG_DISLIST||arg===ARG_DISLIST_SHORT){rtf.disList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_AMDLIST||arg===ARG_AMDLIST_SHORT){rtf.amdList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_RLOLIST||arg===ARG_RLOLIST_SHORT){rtf.rloList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_BETALIST||arg===ARG_BETALIST_SHORT){rtf.betaList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_GROUPLIST||arg===ARG_GROUPLIST_SHORT){rtf.groupList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_XGROUPLIST||arg===ARG_XGROUPLIST_SHORT){rtf.xgroupList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true)}else if(arg===ARG_METAHIST||arg===ARG_METAHIST_SHORT){rtf.cmdMetaHist=true;break}else if(arg===ARG_CONFIG||arg===ARG_CONFIG_SHORT){i++;if(i<argLen){arg=process.argv[i];rtf.configPath=nodeDeps.path.normalize(arg);rtf.configPath=nodeDeps.path.resolve(rtf.configPath);rtf.st_configSet=true;if(rtf.isManual||rtf.xgroupList){break}}else{appCtx.error("Invalid --config option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_BASE||arg===ARG_BASE_SHORT){i++;if(i<argLen){rtf.base=process.argv[i];if(rtf.base===MACROS.cwd||appCtx.utils.getFileType(rtf.base)==="d"){rtf.st_baseSet=true}else{appCtx.error(`'--base' ${rtf.base} is not a directory or the '$jafcwd' macro!!`);bArgsOk=false;bWantHelp=true}}else{appCtx.error("Invalid --base option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_SEVERITY||arg===ARG_SEVERITY_SHORT){i++;if(i<argLen){rtf.severitySet=true;rtf.cliSev=process.argv[i]}else{appCtx.error("Invalid --severity option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_JETVER||arg===ARG_JETVER_SHORT){i++;argOrig=i<argLen?process.argv[i]:null;arg=nodeDeps.jetver.validate(argOrig);if(arg){appCtx.error(arg);bArgsOk=false;break}arg=nodeDeps.jetver.getBestVersion(argOrig);if(!arg){appCtx.error(`'${argOrig}' is not a valid JET version`);bArgsOk=false;break}rtf.jetverSet=arg;if((rtf.verboseMode||rtf.debugMode)&&arg!==argOrig){appCtx._info(`[Info]: JET version '${argOrig}' was promoted to '${arg}'`)}}else if(arg===ARG_FORMAT||arg===ARG_FORMAT_SHORT){i++;if(i<argLen){argOrig=process.argv[i];arg=argOrig.toLowerCase();if(arg!==OUTFMT.JSON&&arg!==OUTFMT.PROSE&&arg!==OUTFMT.LINE){appCtx.error(`Invalid --format(-t) option '${argOrig}'`);bArgsOk=false;bWantHelp=true}else{rtf.outFormat=arg;rtf.st_formatSet=true}}else{appCtx.error("Invalid --format option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_OUTPATH||arg===ARG_OUTPATH_SHORT){i++;if(rtf.st_outPathSet){appCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{if(i<argLen){arg=process.argv[i];arg=nodeDeps.path.normalize(arg);rtf.outPath=nodeDeps.path.resolve(arg);rtf.st_outPathSet=true}else{appCtx.error("Invalid --outPath option");bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_NO_OUT||arg===ARG_NO_OUT_SHORT){if(rtf.st_outPathSet){appCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{rtf.outPath="$noout";rtf.st_outPathSet=true}}else if(arg===ARG_FOLLOWLINKS||arg===ARG_FOLLOWLINKS_SHORT){rtf.followLinks=rtf.followLinksSet=true}else if(arg===ARG_NOFOLLOWLINKS||arg===ARG_NOFOLLOWLINKS_SHORT){rtf.followLinks=false;rtf.followLinksSet=true}else if(arg.startsWith(ARG_GROUPS_EQ)||arg.startsWith(ARG_GROUPS_EQ_SHORT)){x=arg.indexOf("=");if(temp=_convertToArray(argOrig.substring(x+1))){rtf.groupsSet=temp}else{appCtx.error(`Invalid 'groups' declaration '${argOrig}`);bArgsOk=false;bWantHelp=true}}else if(arg===ARG_GROUPS||arg===ARG_GROUPS_SHORT){rtf.groupsSet=_checkGroups(process.argv,i+1);if(!rtf.groupsSet.groups||rtf.groupsSet.groups.length===0){appCtx.error(!rtf.groupsSet.groups?`groups missing after flag ${argOrig}`:`Invalid ${argOrig} specification`);bArgsOk=false;bWantHelp=true}i=rtf.groupsSet.next;rtf.groupsSet=rtf.groupsSet.groups}else if(arg.startsWith(ARG_RC_EQ)||arg.startsWith(ARG_RC_EQ_SHORT)||arg===ARG_RC||arg===ARG_RC_SHORT){arg=argOrig;x=arg.indexOf("=");if(x>0){temp=argOrig.substring(0,x);arg=argOrig.substring(x+1)}else{temp=arg;i++;if(i<argLen){arg=process.argv[i]}else{appCtx.error(`missing arguments after '${argOrig}'`);bArgsOk=false;bWantHelp=true}}if(bArgsOk){temp=_processRetCode(temp,arg);if(temp||typeof temp==="number"){rtf.retCode=temp;rtf.st_retCodeSet=true}else{appCtx.error(`'${argOrig}' : ${arg.length?"'${arg}' is invalid":"missing argument?"}`);bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_SHOWRULES||arg===ARG_SHOWRULES_SHORT){rtf.dumpRulesSet=true}else if(arg===ARG_SHOWRULESJSON||arg===ARG_SHOWRULESJSON_SHORT){rtf.dumpRulesJsonSet=true}else if(arg===ARG_SHOWRULESSONAR||arg===ARG_SHOWRULESSONAR_SHORT){rtf.dumpRulesSonarSet=true}else if(arg===ARG_SHOWRULES_INTERNAL){rtf.dumpRulesInternalSet=true}else if(arg===ARG_DRYRUN||arg===ARG_DRYRUN_SHORT){rtf.dryRunSet=rtf.dacSet=rtf.verboseMode=rtf.verboseSet=rtf.dumpRulesSet=true}else if(arg===ARG_DAC||arg===ARG_DAC_SHORT){rtf.dacSet=true}else if(arg===ARG_REG||arg===ARG_REG_SHORT){rtf.regListenerTypesSet=true}else if(arg===ARG_UNIT_TEST){rtf.unitTest=true}else if(arg===ARG_OJET||arg===ARG_OJET_SHORT){rtf.isOJETCLI=true}else if(arg===ARG_EXPERIMENTAL||arg===ARG_EXPERIMENTAL_SHORT){rtf.experimentalSet=true}else if(arg===ARG_WATCH||arg===ARG_WATCH_SHORT){if(rtf.experimentalSet){rtf.watchSet=true}}else if(arg===ARG_SCAFFOLD||arg===ARG_SCAFFOLD_SHORT){rtf.scaffoldSet=true}else if(arg===ARG_SCAFFOLD_RULE||arg===ARG_SCAFFOLD_RULE_SHORT){i++;if(i<argLen){rtf.scaffoldRuleSet=process.argv[i]}else{appCtx.error("Invalid --initrule argument: rule name missing ");bArgsOk=false;bWantHelp=true}}else if(arg==="-z"){}else{console.log("");appCtx.error(`Invalid command flag '${argOrig}' (Use ojaf -h to get help)`);bArgsOk=false;dontRun=true}}return dontRun?"end":bArgsOk};module.exports.displayCmdLineOptionsSet=function(rtf,appCtx){var s="\n** Command line options:\n";if(rtf.dryRunSet){s+=" - Dry run ON\n"}if(rtf.dacSet){s+=" - Display active config ON\n"}if(rtf.verboseMode){s+=" - Verbose mode ON\n"}if(rtf.debugMode){s+=" - Debug mode ON\n"}if(rtf.watchSet){s+=" - watch mode ON\n"}if(rtf.groupsSet){s+=` - Groups set to ${rtf.groupsSet}\n`}if(rtf.st_retCodeSet){s+=` - retCode set to ${rtf.retCode}\n`}if(rtf.colorSet){s+=` - Color mode ${rtf.colorMode}? "ON" : "OFF"}\n`}if(rtf.msgIdModeSet){s+=` - Show msg ID's(${rtf.msgIdModeSet}? "ON" : "OFF"}\n`}if(rtf.st_formatSet){s+=` - Output in ${rtf.outFormat.toUpperCase()} format\n`}if(rtf.st_configSet){s+=` - Config set to ${rtf.configPath}\n`}if(rtf.severitySet){s+=` - Severity set to '${rtf.severity}'\n`}if(rtf.st_outPathSet){s+=` - Outpath set to ${rtf.outPath==="$noout"?"'none'":rtf.outPath}\n`}if(rtf.st_baseSet){s+=` - Base set to ${rtf.base}\n`}if(rtf.jetverSet){s+=` - JET version set to ${rtf.jetverSet}\n`}if(rtf.followLinksSet){s+=` - following stylesheet links is ${rtf.followLinks?"ON":"OFF"}\n`}if(rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumRulesSonarSet){s+=" - Dump Rules ON\n"}appCtx.console(s+"\n")};module.exports.isCmdLineOptionsSet=function(rtf){return rtf.verboseMode||rtf.debugMode||rtf.colorSet||rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumpRulesSonarSet||rtf.dumpRulesInternalSet||rtf.msgIdModeSet||rtf.severitySet||rtf.watchSet||rtf.jetverSet||rtf.followLinksSet||rtf.dryRunSet||rtf.jetverList||rtf.cmdNSList||rtf.groupList||rtf.xgroupList||rtf.disList||rtf.cmdMetaHist||rtf.amdList||rtf.rloList||rtf.betaList||rtf.profList||rtf.st_baseSet||rtf.st_formatSet||rtf.st_configSet||rtf.st_outPathSet||rtf.st_retCodeSet};function _checkBaseOptions(rtf,clr){var i,arg,argLen=process.argv.length;for(i=2;i<argLen;i++){arg=process.argv[i];if(arg.length===0||arg.charAt(0)!=="-"){continue}arg=arg.toLowerCase();if(arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT){rtf.verboseMode=rtf.verboseSet=true}else if(arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT){rtf.debugMode=rtf.debugSet=true;rtf.debugMode=rtf.debugSet=rtf.verboseMode=true}else if(arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT){rtf.colorMode=false;rtf.colorSet=true;clr.enable(false)}}};function _isBaseOption(arg){return arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT||arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT||arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT};function _checkGroups(args,i){var arg,a,x,last,bound,groups;x=i;for(;;i++){if(i>=args.length||args[i].charAt(0)==="-"||last){break}arg=args[i].trim();if(x===i){bound=arg.startsWith("[")||arg.startsWith("(")}last=bound&&(arg.endsWith("]")||arg.endsWith(")"));arg=arg.replace(/[\[\(\)\]]/g,"").trim();if(!arg.length){break}arg=arg.replace(/,/g," ");arg=arg.replace(/ +(?= )/g,"").trim();if(!groups){groups=[]}a=arg.split(" ");groups=groups.concat(a)}return{next:bound?i:x,groups:groups}};function _processRetCode(arg,val){var temp,ret;if(val==="auto"||val==="errors"){ret=val}else{temp=parseInt(val);if(!isNaN(temp)){ret=temp}else{if(temp=_convertToArray(val)){ret=temp}}}return ret};function checkNextArg(i,argLen,error,argType){var temp,lcTemp;if(i+1<argLen){temp=process.argv[i+1];lcTemp=temp.toLowerCase();if(temp.charAt(0)==="-"){if(!_isBaseOption(temp)&&lcTemp!==ARG_CONFIG&&lcTemp!==ARG_CONFIG_SHORT){error(`Unexpected '${temp}' - expected nothing, or a ${argType?"built-in pack prefix":"profile name"}`)}temp=undefined}}return temp};function _convertToArray(s){var a,n,i;if(s.charAt(0)==="["){s=s.substring(1);if(!s.length){return null}}if(s.charAt(s.length-1)==="]"){s=s.substring(0,s.length-1)}s=s.trim();if(!s.length){return null}s=s.replace(/\,/g," ");s=s.replace(/\s\s+/g," ").trim();a=s.split(" ");n=0;for(i=0;i<a.length;i++){if(a[i].length){n++}else{a=a.splice(i,1);i--}}return n?a:null};function _handleQuotes(s){return s.replace(/[\"\']/g,"")};function _dumpCmdLine(){var s="";for(var i=0;i<process.argv.length;i++){s+=`[${i}]: |${process.argv[i]}|\n`}console.log(s)}
|
package/lib/defaults.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const defaults={JETVER:'
|
|
6
|
+
const defaults={JETVER:'13.0.0'.replace(/(\d*\.\d*)(\.\d*)+$/g,'$1')+'.0',THEME:'Alta',ECMAVER:11};module.exports=defaults;
|